From d69c2d1f198ab08a26a2b3bad07ccfa6f31d37da Mon Sep 17 00:00:00 2001 From: Nick Martin Date: Thu, 17 Nov 2011 18:35:20 -0800 Subject: [PATCH] Initial import from old busted repo. --- .gitignore | 4 + LICENSE.txt | 661 ++ README.md | 64 + admin/cut-release.sh | 96 + admin/generate-dev-bundle.sh | 144 + admin/increment-version.js | 64 + admin/install-s3.sh | 76 + admin/manifest.json | 4 + app/lib/app.html.in | 16 + app/lib/bundler.js | 460 + app/lib/files.js | 257 + app/lib/packages.js | 69 + app/lib/project.js | 68 + app/lib/third/underscore.js | 839 ++ app/lib/updater.js | 57 + app/server/server.js | 131 + app/server/underscore.js | 839 ++ app/skybreak/deploy.js | 18 + app/skybreak/run.js | 384 + app/skybreak/skel/.skybreak/.gitignore | 1 + app/skybreak/skel/.skybreak/packages | 4 + app/skybreak/skel/client/~name~.css | 10 + app/skybreak/skel/client/~name~.html | 36 + app/skybreak/skel/client/~name~.js | 16 + app/skybreak/skel/model.js | 3 + .../skel/public/4201645142_ec2e3bb3f8_b.jpg | Bin 0 -> 48284 bytes app/skybreak/skybreak.js | 576 ++ app/skybreak/update.js | 90 + install.sh | 23 + packages/backbone/backbone.js | 1159 +++ packages/backbone/package.js | 5 + packages/basics/basics.js | 216 + packages/basics/package.js | 7 + packages/class/class.js | 465 + packages/class/package.js | 5 + packages/code-prettify/lang-apollo.js | 2 + packages/code-prettify/lang-clj.js | 18 + packages/code-prettify/lang-css.js | 2 + packages/code-prettify/lang-go.js | 1 + packages/code-prettify/lang-hs.js | 2 + packages/code-prettify/lang-lisp.js | 3 + packages/code-prettify/lang-lua.js | 2 + packages/code-prettify/lang-ml.js | 2 + packages/code-prettify/lang-n.js | 4 + packages/code-prettify/lang-proto.js | 1 + packages/code-prettify/lang-scala.js | 2 + packages/code-prettify/lang-sql.js | 2 + packages/code-prettify/lang-tex.js | 1 + packages/code-prettify/lang-vb.js | 2 + packages/code-prettify/lang-vhdl.js | 3 + packages/code-prettify/lang-wiki.js | 2 + packages/code-prettify/lang-xq.js | 3 + packages/code-prettify/lang-yaml.js | 2 + packages/code-prettify/package.js | 15 + packages/code-prettify/prettify.css | 1 + packages/code-prettify/prettify.js | 28 + packages/code-prettify/styles/desert.css | 34 + packages/code-prettify/styles/sunburst.css | 51 + packages/coffeescript/package.js | 20 + packages/deps/deps.js | 111 + packages/deps/package.js | 8 + packages/handlebars/evaluate.js | 172 + packages/handlebars/package.js | 20 + packages/handlebars/parse.js | 127 + packages/htmljs/html.js | 110 + packages/htmljs/package.js | 8 + packages/jquery-history/jquery.history.js | 1 + packages/jquery-history/package.js | 6 + packages/jquery-layout/jquery.layout.js | 2507 +++++ packages/jquery-layout/package.js | 9 + packages/jquery-waypoints/package.js | 5 + packages/jquery-waypoints/waypoints.js | 633 ++ packages/jquery/jquery.js | 8981 +++++++++++++++++ packages/jquery/package.js | 5 + packages/less/package.js | 25 + packages/livedata/livedata_client.js | 248 + packages/livedata/livedata_server.js | 302 + packages/livedata/mongo_driver.js | 171 + packages/livedata/package.js | 28 + packages/liveui/liveui.js | 305 + packages/liveui/package.js | 8 + packages/minimongo/NOTES | 83 + packages/minimongo/genid.js | 232 + packages/minimongo/minimongo.js | 357 + packages/minimongo/modify.js | 292 + packages/minimongo/package.js | 10 + packages/minimongo/selector.js | 534 + packages/minimongo/sort.js | 52 + packages/session/package.js | 7 + packages/session/session.js | 151 + packages/showdown/license.txt | 34 + packages/showdown/package.js | 14 + packages/showdown/showdown.js | 1302 +++ packages/showdown/template-integration.js | 4 + packages/templating/deftemplate.js | 232 + packages/templating/html_scanner.js | 107 + packages/templating/package.js | 55 + packages/underscore/package.js | 7 + packages/underscore/underscore-min.js | 27 + packages/underscore/underscore.js | 839 ++ skybreak | 75 + tests/minimongo/.skybreak/.gitignore | 1 + tests/minimongo/.skybreak/packages | 6 + tests/minimongo/client/main.js | 3 + tests/minimongo/client/test.js | 780 ++ tests/minimongo/test.html | 11 + tests/selenium/run-tests.sh | 32 + tests/selenium/todo-basic.py | 294 + 108 files changed, 26401 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE.txt create mode 100644 README.md create mode 100755 admin/cut-release.sh create mode 100755 admin/generate-dev-bundle.sh create mode 100644 admin/increment-version.js create mode 100755 admin/install-s3.sh create mode 100644 admin/manifest.json create mode 100644 app/lib/app.html.in create mode 100644 app/lib/bundler.js create mode 100644 app/lib/files.js create mode 100644 app/lib/packages.js create mode 100644 app/lib/project.js create mode 100644 app/lib/third/underscore.js create mode 100644 app/lib/updater.js create mode 100644 app/server/server.js create mode 100644 app/server/underscore.js create mode 100644 app/skybreak/deploy.js create mode 100644 app/skybreak/run.js create mode 100644 app/skybreak/skel/.skybreak/.gitignore create mode 100644 app/skybreak/skel/.skybreak/packages create mode 100644 app/skybreak/skel/client/~name~.css create mode 100644 app/skybreak/skel/client/~name~.html create mode 100644 app/skybreak/skel/client/~name~.js create mode 100644 app/skybreak/skel/model.js create mode 100644 app/skybreak/skel/public/4201645142_ec2e3bb3f8_b.jpg create mode 100644 app/skybreak/skybreak.js create mode 100644 app/skybreak/update.js create mode 100755 install.sh create mode 100644 packages/backbone/backbone.js create mode 100644 packages/backbone/package.js create mode 100644 packages/basics/basics.js create mode 100644 packages/basics/package.js create mode 100644 packages/class/class.js create mode 100644 packages/class/package.js create mode 100644 packages/code-prettify/lang-apollo.js create mode 100644 packages/code-prettify/lang-clj.js create mode 100644 packages/code-prettify/lang-css.js create mode 100644 packages/code-prettify/lang-go.js create mode 100644 packages/code-prettify/lang-hs.js create mode 100644 packages/code-prettify/lang-lisp.js create mode 100644 packages/code-prettify/lang-lua.js create mode 100644 packages/code-prettify/lang-ml.js create mode 100644 packages/code-prettify/lang-n.js create mode 100644 packages/code-prettify/lang-proto.js create mode 100644 packages/code-prettify/lang-scala.js create mode 100644 packages/code-prettify/lang-sql.js create mode 100644 packages/code-prettify/lang-tex.js create mode 100644 packages/code-prettify/lang-vb.js create mode 100644 packages/code-prettify/lang-vhdl.js create mode 100644 packages/code-prettify/lang-wiki.js create mode 100644 packages/code-prettify/lang-xq.js create mode 100644 packages/code-prettify/lang-yaml.js create mode 100644 packages/code-prettify/package.js create mode 100644 packages/code-prettify/prettify.css create mode 100644 packages/code-prettify/prettify.js create mode 100644 packages/code-prettify/styles/desert.css create mode 100644 packages/code-prettify/styles/sunburst.css create mode 100644 packages/coffeescript/package.js create mode 100644 packages/deps/deps.js create mode 100644 packages/deps/package.js create mode 100644 packages/handlebars/evaluate.js create mode 100644 packages/handlebars/package.js create mode 100644 packages/handlebars/parse.js create mode 100644 packages/htmljs/html.js create mode 100644 packages/htmljs/package.js create mode 100644 packages/jquery-history/jquery.history.js create mode 100644 packages/jquery-history/package.js create mode 100644 packages/jquery-layout/jquery.layout.js create mode 100644 packages/jquery-layout/package.js create mode 100644 packages/jquery-waypoints/package.js create mode 100644 packages/jquery-waypoints/waypoints.js create mode 100644 packages/jquery/jquery.js create mode 100644 packages/jquery/package.js create mode 100644 packages/less/package.js create mode 100644 packages/livedata/livedata_client.js create mode 100644 packages/livedata/livedata_server.js create mode 100644 packages/livedata/mongo_driver.js create mode 100644 packages/livedata/package.js create mode 100644 packages/liveui/liveui.js create mode 100644 packages/liveui/package.js create mode 100644 packages/minimongo/NOTES create mode 100644 packages/minimongo/genid.js create mode 100644 packages/minimongo/minimongo.js create mode 100644 packages/minimongo/modify.js create mode 100644 packages/minimongo/package.js create mode 100644 packages/minimongo/selector.js create mode 100644 packages/minimongo/sort.js create mode 100644 packages/session/package.js create mode 100644 packages/session/session.js create mode 100644 packages/showdown/license.txt create mode 100644 packages/showdown/package.js create mode 100644 packages/showdown/showdown.js create mode 100644 packages/showdown/template-integration.js create mode 100644 packages/templating/deftemplate.js create mode 100644 packages/templating/html_scanner.js create mode 100644 packages/templating/package.js create mode 100644 packages/underscore/package.js create mode 100644 packages/underscore/underscore-min.js create mode 100644 packages/underscore/underscore.js create mode 100755 skybreak create mode 100644 tests/minimongo/.skybreak/.gitignore create mode 100644 tests/minimongo/.skybreak/packages create mode 100644 tests/minimongo/client/main.js create mode 100644 tests/minimongo/client/test.js create mode 100644 tests/minimongo/test.html create mode 100755 tests/selenium/run-tests.sh create mode 100644 tests/selenium/todo-basic.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000000..ccaf105f2ae --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.DS_Store +*~ +/dev_bundle +/dev_bundle*.tar.gz diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 00000000000..dba13ed2ddf --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + 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. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 00000000000..4d72e819898 --- /dev/null +++ b/README.md @@ -0,0 +1,64 @@ +# Skybreak + +Skybreak is an ultra-simple framework for building modern websites and web applications. What once took weeks, now takes hours in Skybreak. + +With Skybreak you write apps: + +* in pure Javascript +* that send data over the wire, rather than HTML +* using your choice of popular open-source libraries + +**Have a look at the main Skybreak documentation here:** + +http://preview.skybreakplatform.com + +**This is still pre-release software. If you use it please, PLEASE sign up on the website above. Especially if you deploy a web site with ```skybreak deploy```** + +## Quick Start (normal install process) + +Install Skybreak (only OS X, for now): + + curl -sL bit.ly/n122Iu | /bin/sh + +Create a project: + + skybreak create try-skybreak + +Run it: + + cd try-skybreak + skybreak + +Deploy it to the world, for free: + + skybreak deploy try-skybreak.skybreakplatform.com + + +## Slow Start (for developers) + +If you want to run on the bleeding edge, or help develop Skybreak, you can run Skybreak directly from a git checkout. + + git clone git@github.com:honeycomb/skybreak.git + cd skybreak + +If you're the sort of person who likes to build everything from scratch, you can build all the Skybreak dependencies (node.js, npm, mongodb, etc) with the provided script. If you do not run this script, Skybreak will automatically download pre-compiled binaries when you first run it. + + ./admin/generate-dev-bundle.sh # OPTIONAL + +Now you can run skybreak directly from the checkout (if you did not build the dev bundle above, this will take a few moments to download dependencies). + + ./skybreak --help + +Or install to ```/usr/local``` like the normal install process. This will cause ```skybreak``` to be in your ```PATH```. + + ./install.sh + skybreak --help + + + +## Developer Resources + +- XXX google group +- XXX irc channel + + diff --git a/admin/cut-release.sh b/admin/cut-release.sh new file mode 100755 index 00000000000..8a27d14718d --- /dev/null +++ b/admin/cut-release.sh @@ -0,0 +1,96 @@ +#!/bin/bash + +set -e + +# cd to top level dir +cd `dirname $0` +cd .. + +# Check for MacOS +if [ `uname` != "Darwin" ] ; then + echo "Skybreak only support MacOS X right now." + exit 1 +fi + +# make sure we're clean +# http://stackoverflow.com/questions/2657935/checking-for-a-dirty-index-or-untracked-files-with-git +function warn_and_exit { echo $1 ; return 1; } +git diff-files --quiet || \ + warn_and_exit "Local changes. Aborting." +git diff-index --quiet --cached HEAD || \ + warn_and_exit "Local changes staged. Aborting." +test -z "$(git ls-files --others --exclude-standard)" || \ + warn_and_exit "Uncommitted files. Aborting." + +# Make sure we have an up to date dev bundle by re-downloading. +for i in dev_bundle_*.tar.gz ; do + test -f $i && warn_and_exit "Local dev_bundle tarball. Aborting." +done +if [ -d dev_bundle ] ; then + echo "Removing old dev_bundle." + rm -rf dev_bundle +fi + +# Force dev_bundle re-creation +./skybreak --version || \ + warn_and_exit "dev_bundle installation failed." + + +# increment the version number +export NODE_PATH="$(pwd)/dev_bundle/lib/node_modules" +./dev_bundle/bin/node admin/increment-version.js + +echo "Installing." + +# install it. +./install.sh + +# get the version number. +VERSION="$(/usr/local/bin/skybreak --version | sed 's/.* //')" + +# tar it up +TARBALL=~/skybreak-package-${VERSION}.tar.gz +echo "Tarring to: $TARBALL" + +tar -C /usr/local --exclude .skybreak/local -czf "$TARBALL" skybreak + +# commit to git +echo +echo "//////////////////////" +echo "//////////////////////" +git diff + +echo +echo "//////////////////////" +echo "// Commit to git? Press enter to continue. Hit C-c to abort." +read anykey + +git commit -a -m "Bump to version $VERSION" +git push origin master + + +echo +echo "//////////////////////" + +# prompt are you sure +echo "// Result tarball:" +ls -l "$TARBALL" +md5 "$TARBALL" + +cat </dev/null 2>&1' 0 + +echo BUILDING IN "$DIR" + +cd "$DIR" +mkdir build +cd build + +git clone git://github.com/joyent/node.git +cd node +git checkout v0.6.1 + +# Disable obnoxious print. No easy way to disable that I found. +patch -p1 < .bundle_version.txt +rm -rf build + +tar czf "${TARGET_DIR}/dev_bundle_${UNAME}_${BUNDLE_VERSION}.tar.gz" . + +echo DONE diff --git a/admin/increment-version.js b/admin/increment-version.js new file mode 100644 index 00000000000..cc53f3d4a52 --- /dev/null +++ b/admin/increment-version.js @@ -0,0 +1,64 @@ + +var fs = require('fs'); +var path = require('path'); +var semver = require('semver'); + + +var optimist = require('optimist') + +var updater = require('../app/lib/updater.js'); +var _ = require('../app/lib/third/underscore.js'); + + +// What files to update. Relative to project root. +var UPDATE_FILES = ['app/lib/updater.js', 'admin/install-s3.sh', + ['admin/manifest.json', 'g']]; + +// Files to update for dev_bundle +var BUNDLE_FILES = ['admin/generate-dev-bundle.sh', 'skybreak']; + + +var opt = require('optimist') + .alias('dev_bundle', 'd') + .boolean('dev_bundle') + .describe('dev_bundle', 'Update the dev_bundle version, not the main version.') + .alias('new_version', 'n') + .describe('new_version', 'A new version number. Default is to increment patch number.') + .usage('Usage: $0 [options]') +; +var argv = opt.argv; +if (argv.help) { + process.stdout.write(opt.help()); + process.exit(1); +} + +var CURRENT_VERSION = updater.CURRENT_VERSION; +var files = UPDATE_FILES; + +if (argv.dev_bundle) { + var version_path = path.join(__dirname, '..', 'skybreak'); + var version_data = fs.readFileSync(version_path, 'utf8'); + var version_match = /BUNDLE_VERSION=([\d\.]+)/.exec(version_data); + CURRENT_VERSION = version_match[1]; + files = BUNDLE_FILES; +} + +var NEW_VERSION = argv.new_version || semver.inc(CURRENT_VERSION, 'patch'); + +console.log("Updating from " + CURRENT_VERSION + " to " + NEW_VERSION); + +_.each(files, function (file) { + var flags = ''; + if (file instanceof Array) { + flags = file[1]; + file = file[0]; + } + var fp = path.join(__dirname, '..', file); + var text = fs.readFileSync(fp, 'utf8'); + var new_text = text.replace(new RegExp(CURRENT_VERSION, flags), NEW_VERSION); + fs.writeFileSync(fp, new_text, 'utf8'); + + console.log("updated file: " + fp); +}); + +console.log("Complete"); diff --git a/admin/install-s3.sh b/admin/install-s3.sh new file mode 100755 index 00000000000..7264167f541 --- /dev/null +++ b/admin/install-s3.sh @@ -0,0 +1,76 @@ +#!/bin/bash + +URL="http://d377jur38fl888.cloudfront.net/skybreak-package-0.0.31.tar.gz" +TARGET="/usr/local/skybreak" +PARENT="/usr/local" + +set -e +trap "echo Installation FAILED" INT TERM EXIT + +# Check for MacOS +if [ `uname` != "Darwin" ] ; then + echo "Skybreak only support MacOS X right now." + exit 1 +fi + + +echo "Installing Skybreak to $TARGET" + +# if /usr/local doesn't exist or isn't writable, fix it with sudo. +if [ ! -d "$PARENT" ] ; then + echo + echo "'$PARENT' does not exist. creating it." + echo "This may prompt for your password." + echo "sudo /bin/mkdir \"$PARENT\"" + sudo /bin/mkdir "$PARENT" + echo "sudo /usr/bin/chgrp admin \"$PARENT\"" + sudo /usr/bin/chgrp admin "$PARENT" + echo "sudo /bin/chmod 775 \"$PARENT\"" + sudo /bin/chmod 775 "$PARENT" +elif [ ! -w "$PARENT" -o ! -w "$PARENT/bin" ] ; then + echo + echo "'$PARENT' is not writable to you. changing it." + echo "This may prompt for your password." + echo "sudo /usr/bin/chgrp -f admin \"$PARENT\" \"$PARENT/bin\"" + sudo /usr/bin/chgrp -f admin "$PARENT" "$PARENT/bin" + echo "sudo chmod -f g+rwx \"$PARENT\" \"$PARENT/bin\"" + sudo /bin/chmod -f g+rwx "$PARENT" "$PARENT/bin" +fi + + +# remove old version +if [ -e "$TARGET" ] ; then + echo "found existing install. removing $TARGET." + rm -rf "$TARGET" +fi + +# make sure target exists and is directory +mkdir -p "$TARGET" || true +if [ ! -d "$TARGET" -o ! -w "$TARGET" ] ; then + echo "can't write to $TARGET" + exit 1 +fi + +# download and untar +echo "... downloading" +curl --progress-bar $URL | tar -C "$PARENT" -xzf - + + +# add to $PATH +mkdir -p "$PARENT/bin" +rm -f "$PARENT/bin/skybreak" +ln -s "$TARGET/bin/skybreak" "$PARENT/bin/skybreak" + +cat < + + +{{#each stylesheets}} +{{/each}} + +{{{head_extra}}} + +{{#each scripts}} +{{/each}} + + +{{{body_extra}}} + + diff --git a/app/lib/bundler.js b/app/lib/bundler.js new file mode 100644 index 00000000000..53745f279f5 --- /dev/null +++ b/app/lib/bundler.js @@ -0,0 +1,460 @@ +// Bundle contents: +// main.js [run to start the server] +// /static [served by node for now] +// /server +// server.js, db.js, .... [contents of app/server] +// node_modules [for now, contents of (skybreak_root)/lib/node_modules] +// /app.html +// /app [user code] +// /app.json: [data for server.js] +// - load [list of files to load, relative to root, presumably under /app] +// /dependencies.json: +// - extensions +// +// The application launcher is expected to execute /main.js with node, +// setting the PORT and MONGO_URL environment variables. The enclosed +// node application is expected to do the rest, including serving +// /static. + +var files = require('./files.js'); +var crypto = require('crypto'); +var path = require('path'); +var fs = require('fs'); +var uglify = require('uglify-js'); +var cleanCSS = require('clean-css'); +var _ = require('./third/underscore.js'); + +var Bundle = function () { + var self = this; + + self.loading = null; + self.loaded = {}; + self.extensions = {}; + + // Map from path name (server relative) to contents of file as buffer. + self.client_files = {}; + self.server_files = {}; + + // list of files to load on the server + self.server_load = []; + + // list of javascript files to tell the client to load + self.serve_js = []; + + // list of css files to tell the client to load + self.serve_css = []; + + // extra HTML to add to and + self.head_extra = ''; + self.body_extra = ''; + + self.api = { + describe: function () {}, + + require: function (name) { + if (name in self.loaded) + return; + + var was_loading = self.loading; + self.loading = name; + try { + var fullpath = path.join(files.get_package_dir(), name, 'package.js'); + var code = fs.readFileSync(fullpath).toString(); + // \n is necessary in case final line is a //-comment + var wrapped = "(function(Package,require){" + code + "\n})"; + // XXX it'd be nice to runInNewContext so that the package + // setup code can't mess with our globals, but objects that + // come out of runInNewContext have bizarro antimatter + // prototype chains and break 'instanceof Array'. for now, + // steer clear + var func = require('vm').runInThisContext(wrapped, fullpath, true); + // XXX would be nice to eliminate require. packages like + // 'templating' use this to load other code to run at + // bundle-time. and to pull in, eg, 'fs' and 'path' to access + // the file system + func(self.api, require); + // XXX catch circular dependencies + self.loaded[name] = true; + } finally { + self.loading = was_loading; + } + }, + + // XXX probably unify this into a much smaller number of routines + // that take more complicated parameters. eg, a hash with keys + // filename, data (if you want to provide the data yourself rather + // than have it be read from the filename), type (defaulting to + // js.) and maybe call it Package.serve for the client and + // Package.load for the server? + + // XXX should rename to something like client_js_file + client_file: function (file) { + var name = path.join("/packages", self.loading, file); + var fullpath = path.join(__dirname, '../..', name); + self.serve_js.push(name); + self.client_files[name] = fs.readFileSync(fullpath); + }, + + // XXX should rename to something like server_js_file + server_file: function (file) { + var name = path.join("/packages", self.loading, file); + var fullpath = path.join(__dirname, '../..', name); + self.server_files[name] = fs.readFileSync(fullpath); + self.server_load.push(name); + }, + + register_extension: function (extension, callback) { + if (extension in self.extensions) + // XXX improve error message (eg, name the packages in conflict) + // XXX do something more graceful than printing a stack trace and + // exiting! this isn't javaland! + throw new Error("Conflict: two packages are both trying " + + "to handle ." + extension); + self.extensions[extension] = callback; + }, + + // XXX figure out what the hell we're doing with encodings (and get + // consistent about the use of strings vs buffers) + + server_js_buffer: function (path, contents) { + // XXX raise error if there is already a file at that path + // XXX raise error if contents is not a buffer .. or .. something + self.server_files[path] = contents; + self.server_load.push(path); + }, + + client_js_buffer: function (path, contents) { + // XXX raise error if there is already a file at that path + // XXX raise error if contents is not a buffer .. or .. something + self.client_files[path] = contents; + self.serve_js.push(path); + }, + + client_css_buffer: function (path, contents) { + // XXX raise error if there is already a file at that path + // XXX raise error if contents is not a buffer .. or .. something + self.client_files[path] = contents; + self.serve_css.push(path); + }, + + client_css_file: function (file) { + var name = path.join("/packages", self.loading, file); + var fullpath = path.join(__dirname, '../..', name); + self.serve_css.push(name); + self.client_files[name] = fs.readFileSync(fullpath); + }, + + append_head: function (buffer, comment) { + // XXX raise error if contents is not a buffer .. or .. something + if (self.head_extra) self.head_extra += "\n"; + self.head_extra += "\n"; + self.head_extra += buffer; + }, + + append_body: function (buffer, comment) { + // XXX raise error if contents is not a buffer .. or .. something + if (self.body_extra) self.body_extra += "\n"; + self.body_extra += "\n"; + self.body_extra += buffer; + } + }; + + self.api.register_extension( + "js", function (filename, rel_filename, is_client, is_server) { + var contents = fs.readFileSync(filename); + if (is_client) + self.api.client_js_buffer(rel_filename, contents); + if (is_server) + self.api.server_js_buffer(rel_filename, contents); + }); + + self.api.register_extension( + "css", function (filename, rel_filename, is_client, is_server) { + if (!is_client) return; // only for the client. + self.api.client_css_buffer(rel_filename, fs.readFileSync(filename)); + }); +}; + +_.extend(Bundle.prototype, { + // XXX note that this includes dots + registeredExtensions: function () { + var ret = []; + for (var ext in this.extensions) + ret.push("." + ext); + return ret; + }, + + add_standard_packages: function () { + // XXX if we need underscore on the client for our internal use, + // we should still send it in such a way that '_' doesn't get in + // the global namespace unless the user specifically asks for the + // underscore package + this.api.require('underscore'); + + // XXX this is some kind of legacy crap that someone might need + // but I don't know the details. it should go away. + this.api.require('basics'); + + // standard client packages (for now), for the classic skybreak stack + this.api.require('deps'); + this.api.require('session'); + this.api.require('livedata'); + this.api.require('liveui'); + this.api.require('templating'); + + // these should really be something that users have to add manually + this.api.require('coffeescript'); + }, + + // returns paths relative to app_dir + compute_user_files: function (app_dir) { + // find everything in tree, sorted depth-first alphabetically. + var file_list = files.file_list_sync(app_dir, + this.registeredExtensions()); + file_list.sort(files.sort); + + // (Note: we used to have some functionality to let users push + // some files to the front of the load order. It was removed + // because once we had packages, no app seemed to need it. But you + // could fish it out of version control if you wanted to bring it + // back.) + + // now push html (template) files ahead of everything else. this + // is important because the user wants to be able to say + // Template.foo.events = { ... } + // + // XXX this is kind of hacky. maybe all of the templates should go + // in one file? packages should probably have a way to request + // this treatment (load order depedency tags?) .. who knows. + var htmls = []; + _.each(file_list, function (filename) { + if (path.extname(filename) === '.html') { + htmls.push(filename); + file_list = _.reject(file_list, function (f) { return f === filename;}); + } + }); + file_list = htmls.concat(file_list); + + // now make everything relative to app_dir + var prefix = app_dir; + if (prefix[prefix.length - 1] !== '/') + prefix += '/'; + file_list = file_list.map(function (abs) { + if (app_dir.length >= abs.length || + abs.substr(0, app_dir.length) !== app_dir) + // XXX audit to make sure it works in all possible symlink + // scenarios + throw new Error("internal error: source file outside of app_dir?"); + return abs.substr(app_dir.length); + }); + + return file_list; + }, + + generate_app_html: function () { + var template = fs.readFileSync(path.join(__dirname, "app.html.in")); + var f = require('handlebars').compile(template.toString()); + return f({ + scripts: this.serve_js, + head_extra: this.head_extra, + body_extra: this.body_extra, + stylesheets: this.serve_css + }); + } +}); + +/** + * Take the Skybreak application in app_dir, and compile it into a + * bundle at output_path. output_path will be created if it doesn't + * exist (it will be a directory), and removed if it does exist. + * + * options include: + * - no_minify : don't minify the assets + * - skip_dev_bundle : don't put any node_modules in the bundle. + * - symlink_dev_bundle : symlink bundle's node_modules to prebuilt + * local installation (to save startup time when running locally, + * used by skybreak run). + */ +exports.bundle = function (app_dir, output_path, options) { + options = options || {}; + var bundle = new Bundle; + var base = Date.now(); + + ////////// Packages ////////// + + // has to come before user packages, because we don't (presently) + // require packages to declare dependencies on 'standard skybreak + // stuff' like minimongo + bundle.add_standard_packages(); + + require('./project.js').get_packages(app_dir).forEach(function (p) { + bundle.api.require(p); + }); + + ////////// User source ////////// + + var user_files = bundle.compute_user_files(app_dir); + + user_files.forEach(function (rel_path) { + var full_path = path.join(app_dir, rel_path); + + // XXX at some point we should re-work our directory structure and + // how we determine which files are for the client and which are for + // the server. + var is_client = (full_path.indexOf('/server/') === -1); + var is_server = (full_path.indexOf('/client/') === -1); + + var ext = path.extname(full_path).substr(1); + + if (!(ext in bundle.extensions)) + // huh? we used bundle.extensions to build the file list .. + throw new Error("internal error: don't have handler for extension?"); + + bundle.extensions[ext](full_path, rel_path, is_client, is_server); + + }); + + ////////// Minify and bundle files ////////// + + if (!options.no_minify) { + /// Javascript + var js_concat = ""; + _.each(bundle.serve_js, function (js_path) { + var js_data = bundle.client_files[js_path]; + js_concat = js_concat + "\n;\n" + js_data.toString('utf8'); + + delete bundle.client_files[js_path]; + }); + + var ast = uglify.parser.parse(js_concat); + ast = uglify.uglify.ast_mangle(ast); + ast = uglify.uglify.ast_squeeze(ast); + var final_code = uglify.uglify.gen_code(ast); + + var hash = crypto.createHash('sha1'); + hash.update(final_code); + var digest = hash.digest('hex'); + var name = digest + ".js"; + + bundle.client_files[name] = new Buffer(final_code); + bundle.serve_js = [name]; + + /// CSS + var css_concat = ""; + _.each(bundle.serve_css, function (css_path) { + var css_data = bundle.client_files[css_path]; + css_concat = css_concat + "\n" + css_data.toString('utf8'); + + delete bundle.client_files[css_path]; + }); + + var final_css = cleanCSS.process(css_concat); + + hash = crypto.createHash('sha1'); + hash.update(final_css); + digest = hash.digest('hex'); + name = digest + ".css"; + + bundle.client_files[name] = new Buffer(final_css); + bundle.serve_css = [name]; + } + + // Socket.io is an exceptional file. Push it in manually after + // minification (it doesn't like being minified). But still serve it + // ourselves instead of letting socket.io do it, so we get gzip and + // such (potentially CDN later). + bundle.serve_js.unshift('/socketio.static.js'); + bundle.client_files['/socketio.static.js'] = + fs.readFileSync(path.join( + files.get_dev_bundle(), 'lib/node_modules', + 'socket.io/node_modules/socket.io-client/dist/socket.io.min.js')); + + ////////// Generate bundle ////////// + + var app_json = {}; + var dependencies_json = {}; + + // foo/bar => foo/.build.bar + var build_path = path.join(path.dirname(output_path), + '.build.' + path.basename(output_path)); + + // XXX cleaner error handling. don't make the humans read an + // exception (and, make suitable for use in automated systems) + files.rm_recursive(build_path); + files.mkdir_p(build_path, 0755); + + files.cp_r(path.join(__dirname, '../server'), + path.join(build_path, 'server')); + + if (options.skip_dev_bundle) + ; + else if (options.symlink_dev_bundle) + fs.symlinkSync(path.join(files.get_dev_bundle(), 'lib/node_modules'), + path.join(build_path, 'server/node_modules')); + else + files.cp_r(path.join(files.get_dev_bundle(), 'lib/node_modules'), + path.join(build_path, 'server/node_modules')); + + // XXX should filter out foo~, etc, from public? (server too?) + if (path.existsSync(path.join(app_dir, 'public'))) { + files.cp_r(path.join(app_dir, 'public'), + path.join(build_path, 'static')); + } + for (var rel_path in bundle.client_files) { + var full_path = path.join(build_path, 'static', rel_path); + files.mkdir_p(path.dirname(full_path), 0755); + fs.writeFileSync(full_path, bundle.client_files[rel_path]); + } + + app_json.load = []; + files.mkdir_p(path.join(build_path, 'app'), 0755); + bundle.server_load.forEach(function (rel_path) { + var path_in_bundle = path.join('app', rel_path); + var full_path = path.join(build_path, path_in_bundle); + app_json.load.push(path_in_bundle); + files.mkdir_p(path.dirname(full_path), 0755); + fs.writeFileSync(full_path, bundle.server_files[rel_path]); + }); + + fs.writeFileSync(path.join(build_path, 'app.html'), + bundle.generate_app_html()); + + fs.writeFileSync(path.join(build_path, 'main.js'), +"require(require('path').join(__dirname, 'server/server.js'));\n"); + + // XXX XXX we need to rejigger this a bit to make it true (letting + // the user bring their own fibers -- which is necessary, if we want + // the package to be portable. same goes for any other binary + // package we use..) (also, we need to not require keepalives when + // the app is run this way.) + fs.writeFileSync(path.join(build_path, 'README'), +"This is a Skybreak application bundle. It has only one dependency,\n" + +"node.js (with the 'fibers' package). To run the application:\n" + +"\n" + +" $ npm install fibers\n" + +" $ export MONGO_URL='mongodb://user:password@host:port/databasename'\n" + +" $ node main.js\n" + +"\n" + +"Use the PORT environment variable to set the port where the\n" + +"application will listen. The default is 80, but that will require\n" + +"root on most systems.\n" + +"\n" + +"Find out more about Skybreak at skybreakplatform.com.\n"); + + // XXX enhance dependencies to include all dependencies, not just + // user code, so we can get reload behavior when developing packages + // or skybreak itself. that includes (1) any file that went in the + // bundle (from 'static', 'app/server', or a package), (2) + // package.js for each package that was included. also conceptually + // we need to restart on 'skybreak add'. + dependencies_json.extensions = bundle.registeredExtensions(); + + fs.writeFileSync(path.join(build_path, 'app.json'), + JSON.stringify(app_json)); + fs.writeFileSync(path.join(build_path, 'dependencies.json'), + JSON.stringify(dependencies_json)); + + // XXX cleaner error handling (no exceptions) + files.rm_recursive(output_path); + fs.renameSync(build_path, output_path); +}; diff --git a/app/lib/files.js b/app/lib/files.js new file mode 100644 index 00000000000..ec83da00c34 --- /dev/null +++ b/app/lib/files.js @@ -0,0 +1,257 @@ +var fs = require("fs"); +var path = require('path'); +var _ = require('./third/underscore.js'); + +var files = module.exports = { + // A sort comparator to order files into load order. + sort: function (a, b) { + // main.* loaded last + ismain_a = (path.basename(a).indexOf('main.') === 0); + ismain_b = (path.basename(b).indexOf('main.') === 0); + if (ismain_a !== ismain_b) { + return (ismain_a ? 1 : -1); + } + + // /lib/ loaded first + islib_a = (a.indexOf('/lib/') !== -1); + islib_b = (b.indexOf('/lib/') !== -1); + if (islib_a !== islib_b) { + return (islib_a ? -1 : 1); + } + + // deeper paths loaded first. + len_a = a.split('/').length; + len_b = b.split('/').length; + if (len_a !== len_b) { + return (len_a < len_b ? 1 : -1); + } + + // otherwise alphabetical + return (a < b ? -1 : 1); + }, + + // Returns true if this is a file we should maybe care about (stat it, + // descend if it is a directory, etc). + pre_filter: function (filename) { + if (!filename) { return false; } + // no . files + var base = path.basename(filename); + if (base && base[0] === '.') { return false; } + + // XXX + // first, we only want to exclude APP_ROOT/public, not some deeper public + // second, we don't really like this at all + // third, we don't update the app now if anything here changes + if (filename.indexOf('/public/') !== -1) { return false; } + + return true; + }, + + // Returns true if this is a file we should monitor. + // Iterate over all the interesting files, applying 'func' to each + // file path. 'extensions' is an array of extensions to include (eg + // ['.html', '.js']) + file_list_async: function (filepath, extensions, func) { + if (!files.pre_filter(filepath)) { return; } + fs.stat(filepath, function(err, stats) { + if (err) { + // XXX! + return; + } + + if (stats.isDirectory()) { + fs.readdir(filepath, function(err, fileNames) { + if(err) { + // XXX! + return; + } + + fileNames.forEach(function (fileName) { + files.file_list_async(path.join(filepath, fileName), + extensions, func); + }); + }); + } else if (extensions.indexOf(path.extname(filepath)) !== -1) { + func(filepath); + } + }); + }, + + file_list_sync: function (filepath, extensions) { + var ret = []; + if (!files.pre_filter(filepath)) { return ret; } + var stats = fs.statSync(filepath); + if (stats.isDirectory()) { + var fileNames = fs.readdirSync(filepath); + fileNames.forEach(function (fileName) { + ret = ret.concat(files.file_list_sync( + path.join(filepath, fileName), extensions)); + }); + } else if (extensions.indexOf(path.extname(filepath)) !== -1) { + ret.push(filepath); + } + + return ret; + }, + + // given a path, traverse upwards until we find a .skybreak + // directory that contains a 'packages' file. returns either the + // path to a top-level app or null for no app found. if filepath + // isn't given, use cwd. + find_app_dir: function (filepath) { + var test_dir = filepath || process.cwd(); + while (test_dir) { + if (path.existsSync(path.join(test_dir, '.skybreak/packages'))) { + break; + } + var new_dir = path.dirname(test_dir); + if (new_dir === test_dir) { + test_dir = null; + } else { + test_dir = new_dir; + } + } + if (!test_dir) + return null; + + return test_dir; + }, + + // create a .gitignore file in dir_path if one doesn't exist. add + // 'entry' to the .gitignore on its own line at the bottom of the + // file, if the exact line does not already exist in the file. + // XXX unused. remove? + add_to_gitignore: function (dir_path, entry) { + var filepath = path.join(dir_path, ".gitignore"); + if (path.existsSync(filepath)) { + var data = fs.readFileSync(filepath, 'utf8'); + var lines = data.split(/\n/); + if (_.any(lines, function (x) { return x === entry })) { + // already there do nothing + } else { + // rewrite file w/ new entry. + if (data.substr(-1) !== "\n") data = data + "\n"; + data = data + entry + "\n"; + fs.writeFileSync(filepath, data, 'utf8'); + } + } else { + // doesn't exist, just write it. + fs.writeFileSync(filepath, entry + "\n", 'utf8'); + } + }, + + // True if we're in a git checkout of Skybreak, else false (we're in + // an installation.) + in_checkout: function () { + try { + if (path.existsSync(path.join(__dirname, "../../.git"))) + return true; + } catch (e) { console.log(e);} + + return false; + }, + + // Return the root of dev_bundle (probably /usr/local/skybreak in an + // install, or (checkout root)/dev_bundle in a checkout..) + get_dev_bundle: function () { + if (files.in_checkout()) { + return path.join(__dirname, '../../dev_bundle'); + } + else + return path.join(__dirname, '../..'); + }, + + // Return where the packages are stored + get_package_dir: function () { + return path.join(__dirname, '../../packages'); + }, + + // Try to find the prettiest way to present a path to the + // user. Presently, the main thing it does is replace $HOME with ~. + pretty_path: function (path) { + path = fs.realpathSync(path); + var home = process.env.HOME; + if (home && path.substr(0, home.length) === home) + path = "~" + path.substr(home.length); + return path; + }, + + // Like rm -r. + rm_recursive: function (p) { + try { + // the l in lstat is critical -- we want to remove symbolic + // links, not what they point to + var stat = fs.lstatSync(p); + } catch (e) { + if (e.code == "ENOENT") + return; + throw e; + } + + if (stat.isDirectory()) { + fs.readdirSync(p).forEach(function (file) { + file = path.join(p, file); + files.rm_recursive(file); + }); + fs.rmdirSync(p) + } else + fs.unlinkSync(p); + }, + + // like mkdir -p. if it returns true, the item is a directory (even + // if it was already created). if it returns false, the item is not + // a directory and we couldn't make it one. + mkdir_p: function (dir, mode) { + var p = path.resolve(dir); + var ps = path.normalize(p).split('/'); + + if (path.existsSync(p)) { + if (fs.statSync(p).isDirectory()) { return true;} + return false; + } + + // doesn't exist. recurse to build parent. + var success = files.mkdir_p(ps.slice(0,-1).join('/'), mode); + // parent is not a directory. + if (!success) { return false; } + + fs.mkdirSync(p, mode); + + // double check we exist now + if (!path.existsSync(p) || + !fs.statSync(p).isDirectory()) + return false; // wtf + return true; + }, + + // Roughly like cp -R. 'from' should be a directory. 'to' can either + // be a directory, or it can not exist (in which case it will be + // created with mkdir_p.) Doesn't think about file mode at all. + // + // If options.transformer_{filename, contents} is present, it should + // be a function, and the contents (as a buffer) or filename will be + // passed through the function. Use this to, eg, fill templates. + cp_r: function (from, to, options) { + options = options || {}; + files.mkdir_p(to, 0755); + fs.readdirSync(from).forEach(function (f) { + var full_from = path.join(from, f); + if (options.transform_filename) + f = options.transform_filename(f); + var full_to = path.join(to, f); + if (fs.statSync(full_from).isDirectory()) + files.cp_r(full_from, full_to, options); + else { + if (!options.transform_contents) { + // XXX reads full file into memory.. lame. + fs.writeFileSync(full_to, fs.readFileSync(full_from)) + } else { + var contents = fs.readFileSync(full_from); + contents = options.transform_contents(contents, f); + fs.writeFileSync(full_to, contents); + } + } + }); + } + +}; diff --git a/app/lib/packages.js b/app/lib/packages.js new file mode 100644 index 00000000000..260e0bc543c --- /dev/null +++ b/app/lib/packages.js @@ -0,0 +1,69 @@ +var _ = require('./third/underscore.js'); +var files = require('./files.js'); +var fs = require('fs'); +var path = require('path'); + +var packages = module.exports = { + // get the description info out of a package + describe: function (name) { + // XXX this is a huge nasty hack. this whole thing will need to be + // rethought going forward + var Package = {}; + _.each(['require', 'client_file', 'register_extension', + 'server_js_buffer', 'client_js_buffer', 'client_css_buffer', + 'client_css_file', 'append_head', 'append_body', 'server_file'], + function (f) { + Package[f] = function () {}; + }); + var ret = {}; + Package.describe = function (x) { + _.extend(ret, x); + }; + ret.name = name; + var fullpath = path.join(files.get_package_dir(), name, 'package.js'); + var init = fs.readFileSync(fullpath).toString(); + (function () { eval(init); })(); + return ret; + }, + + // get all packages, in a map from package name to description + // info. description info will also contain a key 'name' which is + // the package name. + list: function () { + var ret = {}; + var dir = files.get_package_dir(); + _.each(fs.readdirSync(dir), function (pkg) { + ret[pkg] = packages.describe(pkg); + }); + + return ret; + }, + + // returns a pretty list suitable for showing to the user. input is + // a list of descriptions as returned by describe(). + format_list: function (descrs) { + var longest = ''; + _.each(descrs, function (d) { + if (d.name.length > longest.length) + longest = d.name; + }); + var pad = longest.replace(/./g, ' '); + // it'd be nice to read the actual terminal width, but I tried + // several methods and none of them work (COLUMNS isn't set in + // node's environment; `tput cols` returns a constant 80.) maybe + // node is doing something weird with ptys. + var width = 80; + + var out = ''; + _.each(descrs, function (d) { + if (d.internal) + return; + var name = d.name + pad.substr(d.name.length); + var summary = d.summary || 'No description'; + out += (name + " " + + summary.substr(0, width - 2 - pad.length) + "\n"); + }); + + return out; + } +} diff --git a/app/lib/project.js b/app/lib/project.js new file mode 100644 index 00000000000..cd0994d5318 --- /dev/null +++ b/app/lib/project.js @@ -0,0 +1,68 @@ +var fs = require('fs'); +var path = require('path'); +var _ = require('./third/underscore.js'); + +var project = module.exports = { + + _get_lines: function (app_dir) { + var raw = fs.readFileSync(path.join(app_dir, '.skybreak/packages'), 'utf8'); + var lines = raw.split(/\r*\n\r*/); + + // strip blank lines at the end + while (lines.length) { + var line = lines[lines.length - 1]; + if (line.match(/\S/)) + break; + lines.pop(); + } + + return lines; + }, + + _trim_line: function (line) { + var match = line.match(/^([^#]*)#/); + if (match) + line = match[1]; + line = line.replace(/^\s+|\s+$/g, ''); // leading/trailing whitespace + return line; + }, + + _write_packages: function (app_dir, lines) { + fs.writeFileSync(path.join(app_dir, '.skybreak/packages'), + lines.join('\n') + '\n', 'utf8'); + }, + + // Packages used by this project. + get_packages: function (app_dir) { + var ret = []; + + project._get_lines(app_dir).forEach(function (line) { + line = project._trim_line(line); + if (line !== '') + ret.push(line); + }); + + return ret; + }, + + add_package: function (app_dir, name) { + var lines = project._get_lines(app_dir); + + // detail: if the file starts with a comment, try to keep a single + // blank line after the comment (unless the user removes it) + var current = project.get_packages(app_dir); + if (!current.length && lines.length) + lines.push(''); + lines.push(name); + project._write_packages(app_dir, lines); + }, + + remove_package: function (app_dir, name) { + // XXX assume no special regexp characters + var lines = _.reject(project._get_lines(app_dir), function (line) { + return project._trim_line(line) === name; + }); + project._write_packages(app_dir, lines); + } + +}; diff --git a/app/lib/third/underscore.js b/app/lib/third/underscore.js new file mode 100644 index 00000000000..4f56013259b --- /dev/null +++ b/app/lib/third/underscore.js @@ -0,0 +1,839 @@ +// Underscore.js 1.1.7 +// (c) 2011 Jeremy Ashkenas, DocumentCloud Inc. +// Underscore is freely distributable under the MIT license. +// Portions of Underscore are inspired or borrowed from Prototype, +// Oliver Steele's Functional, and John Resig's Micro-Templating. +// For all details and documentation: +// http://documentcloud.github.com/underscore + +(function() { + + // Baseline setup + // -------------- + + // Establish the root object, `window` in the browser, or `global` on the server. + var root = this; + + // Save the previous value of the `_` variable. + var previousUnderscore = root._; + + // Establish the object that gets returned to break out of a loop iteration. + var breaker = {}; + + // Save bytes in the minified (but not gzipped) version: + var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; + + // Create quick reference variables for speed access to core prototypes. + var slice = ArrayProto.slice, + unshift = ArrayProto.unshift, + toString = ObjProto.toString, + hasOwnProperty = ObjProto.hasOwnProperty; + + // All **ECMAScript 5** native function implementations that we hope to use + // are declared here. + var + nativeForEach = ArrayProto.forEach, + nativeMap = ArrayProto.map, + nativeReduce = ArrayProto.reduce, + nativeReduceRight = ArrayProto.reduceRight, + nativeFilter = ArrayProto.filter, + nativeEvery = ArrayProto.every, + nativeSome = ArrayProto.some, + nativeIndexOf = ArrayProto.indexOf, + nativeLastIndexOf = ArrayProto.lastIndexOf, + nativeIsArray = Array.isArray, + nativeKeys = Object.keys, + nativeBind = FuncProto.bind; + + // Create a safe reference to the Underscore object for use below. + var _ = function(obj) { return new wrapper(obj); }; + + // Export the Underscore object for **CommonJS**, with backwards-compatibility + // for the old `require()` API. If we're not in CommonJS, add `_` to the + // global object. + if (typeof module !== 'undefined' && module.exports) { + module.exports = _; + _._ = _; + } else { + // Exported as a string, for Closure Compiler "advanced" mode. + root['_'] = _; + } + + // Current version. + _.VERSION = '1.1.7'; + + // Collection Functions + // -------------------- + + // The cornerstone, an `each` implementation, aka `forEach`. + // Handles objects with the built-in `forEach`, arrays, and raw objects. + // Delegates to **ECMAScript 5**'s native `forEach` if available. + var each = _.each = _.forEach = function(obj, iterator, context) { + if (obj == null) return; + if (nativeForEach && obj.forEach === nativeForEach) { + obj.forEach(iterator, context); + } else if (obj.length === +obj.length) { + for (var i = 0, l = obj.length; i < l; i++) { + if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return; + } + } else { + for (var key in obj) { + if (hasOwnProperty.call(obj, key)) { + if (iterator.call(context, obj[key], key, obj) === breaker) return; + } + } + } + }; + + // Return the results of applying the iterator to each element. + // Delegates to **ECMAScript 5**'s native `map` if available. + _.map = function(obj, iterator, context) { + var results = []; + if (obj == null) return results; + if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); + each(obj, function(value, index, list) { + results[results.length] = iterator.call(context, value, index, list); + }); + return results; + }; + + // **Reduce** builds up a single result from a list of values, aka `inject`, + // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. + _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { + var initial = memo !== void 0; + if (obj == null) obj = []; + if (nativeReduce && obj.reduce === nativeReduce) { + if (context) iterator = _.bind(iterator, context); + return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); + } + each(obj, function(value, index, list) { + if (!initial) { + memo = value; + initial = true; + } else { + memo = iterator.call(context, memo, value, index, list); + } + }); + if (!initial) throw new TypeError("Reduce of empty array with no initial value"); + return memo; + }; + + // The right-associative version of reduce, also known as `foldr`. + // Delegates to **ECMAScript 5**'s native `reduceRight` if available. + _.reduceRight = _.foldr = function(obj, iterator, memo, context) { + if (obj == null) obj = []; + if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { + if (context) iterator = _.bind(iterator, context); + return memo !== void 0 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); + } + var reversed = (_.isArray(obj) ? obj.slice() : _.toArray(obj)).reverse(); + return _.reduce(reversed, iterator, memo, context); + }; + + // Return the first value which passes a truth test. Aliased as `detect`. + _.find = _.detect = function(obj, iterator, context) { + var result; + any(obj, function(value, index, list) { + if (iterator.call(context, value, index, list)) { + result = value; + return true; + } + }); + return result; + }; + + // Return all the elements that pass a truth test. + // Delegates to **ECMAScript 5**'s native `filter` if available. + // Aliased as `select`. + _.filter = _.select = function(obj, iterator, context) { + var results = []; + if (obj == null) return results; + if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); + each(obj, function(value, index, list) { + if (iterator.call(context, value, index, list)) results[results.length] = value; + }); + return results; + }; + + // Return all the elements for which a truth test fails. + _.reject = function(obj, iterator, context) { + var results = []; + if (obj == null) return results; + each(obj, function(value, index, list) { + if (!iterator.call(context, value, index, list)) results[results.length] = value; + }); + return results; + }; + + // Determine whether all of the elements match a truth test. + // Delegates to **ECMAScript 5**'s native `every` if available. + // Aliased as `all`. + _.every = _.all = function(obj, iterator, context) { + var result = true; + if (obj == null) return result; + if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); + each(obj, function(value, index, list) { + if (!(result = result && iterator.call(context, value, index, list))) return breaker; + }); + return result; + }; + + // Determine if at least one element in the object matches a truth test. + // Delegates to **ECMAScript 5**'s native `some` if available. + // Aliased as `any`. + var any = _.some = _.any = function(obj, iterator, context) { + iterator = iterator || _.identity; + var result = false; + if (obj == null) return result; + if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); + each(obj, function(value, index, list) { + if (result |= iterator.call(context, value, index, list)) return breaker; + }); + return !!result; + }; + + // Determine if a given value is included in the array or object using `===`. + // Aliased as `contains`. + _.include = _.contains = function(obj, target) { + var found = false; + if (obj == null) return found; + if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; + any(obj, function(value) { + if (found = value === target) return true; + }); + return found; + }; + + // Invoke a method (with arguments) on every item in a collection. + _.invoke = function(obj, method) { + var args = slice.call(arguments, 2); + return _.map(obj, function(value) { + return (method.call ? method || value : value[method]).apply(value, args); + }); + }; + + // Convenience version of a common use case of `map`: fetching a property. + _.pluck = function(obj, key) { + return _.map(obj, function(value){ return value[key]; }); + }; + + // Return the maximum element or (element-based computation). + _.max = function(obj, iterator, context) { + if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj); + var result = {computed : -Infinity}; + each(obj, function(value, index, list) { + var computed = iterator ? iterator.call(context, value, index, list) : value; + computed >= result.computed && (result = {value : value, computed : computed}); + }); + return result.value; + }; + + // Return the minimum element (or element-based computation). + _.min = function(obj, iterator, context) { + if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj); + var result = {computed : Infinity}; + each(obj, function(value, index, list) { + var computed = iterator ? iterator.call(context, value, index, list) : value; + computed < result.computed && (result = {value : value, computed : computed}); + }); + return result.value; + }; + + // Sort the object's values by a criterion produced by an iterator. + _.sortBy = function(obj, iterator, context) { + return _.pluck(_.map(obj, function(value, index, list) { + return { + value : value, + criteria : iterator.call(context, value, index, list) + }; + }).sort(function(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }), 'value'); + }; + + // Groups the object's values by a criterion produced by an iterator + _.groupBy = function(obj, iterator) { + var result = {}; + each(obj, function(value, index) { + var key = iterator(value, index); + (result[key] || (result[key] = [])).push(value); + }); + return result; + }; + + // Use a comparator function to figure out at what index an object should + // be inserted so as to maintain order. Uses binary search. + _.sortedIndex = function(array, obj, iterator) { + iterator || (iterator = _.identity); + var low = 0, high = array.length; + while (low < high) { + var mid = (low + high) >> 1; + iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid; + } + return low; + }; + + // Safely convert anything iterable into a real, live array. + _.toArray = function(iterable) { + if (!iterable) return []; + if (iterable.toArray) return iterable.toArray(); + if (_.isArray(iterable)) return slice.call(iterable); + if (_.isArguments(iterable)) return slice.call(iterable); + return _.values(iterable); + }; + + // Return the number of elements in an object. + _.size = function(obj) { + return _.toArray(obj).length; + }; + + // Array Functions + // --------------- + + // Get the first element of an array. Passing **n** will return the first N + // values in the array. Aliased as `head`. The **guard** check allows it to work + // with `_.map`. + _.first = _.head = function(array, n, guard) { + return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; + }; + + // Returns everything but the first entry of the array. Aliased as `tail`. + // Especially useful on the arguments object. Passing an **index** will return + // the rest of the values in the array from that index onward. The **guard** + // check allows it to work with `_.map`. + _.rest = _.tail = function(array, index, guard) { + return slice.call(array, (index == null) || guard ? 1 : index); + }; + + // Get the last element of an array. + _.last = function(array) { + return array[array.length - 1]; + }; + + // Trim out all falsy values from an array. + _.compact = function(array) { + return _.filter(array, function(value){ return !!value; }); + }; + + // Return a completely flattened version of an array. + _.flatten = function(array) { + return _.reduce(array, function(memo, value) { + if (_.isArray(value)) return memo.concat(_.flatten(value)); + memo[memo.length] = value; + return memo; + }, []); + }; + + // Return a version of the array that does not contain the specified value(s). + _.without = function(array) { + return _.difference(array, slice.call(arguments, 1)); + }; + + // Produce a duplicate-free version of the array. If the array has already + // been sorted, you have the option of using a faster algorithm. + // Aliased as `unique`. + _.uniq = _.unique = function(array, isSorted) { + return _.reduce(array, function(memo, el, i) { + if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el; + return memo; + }, []); + }; + + // Produce an array that contains the union: each distinct element from all of + // the passed-in arrays. + _.union = function() { + return _.uniq(_.flatten(arguments)); + }; + + // Produce an array that contains every item shared between all the + // passed-in arrays. (Aliased as "intersect" for back-compat.) + _.intersection = _.intersect = function(array) { + var rest = slice.call(arguments, 1); + return _.filter(_.uniq(array), function(item) { + return _.every(rest, function(other) { + return _.indexOf(other, item) >= 0; + }); + }); + }; + + // Take the difference between one array and another. + // Only the elements present in just the first array will remain. + _.difference = function(array, other) { + return _.filter(array, function(value){ return !_.include(other, value); }); + }; + + // Zip together multiple lists into a single array -- elements that share + // an index go together. + _.zip = function() { + var args = slice.call(arguments); + var length = _.max(_.pluck(args, 'length')); + var results = new Array(length); + for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i); + return results; + }; + + // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), + // we need this function. Return the position of the first occurrence of an + // item in an array, or -1 if the item is not included in the array. + // Delegates to **ECMAScript 5**'s native `indexOf` if available. + // If the array is large and already in sort order, pass `true` + // for **isSorted** to use binary search. + _.indexOf = function(array, item, isSorted) { + if (array == null) return -1; + var i, l; + if (isSorted) { + i = _.sortedIndex(array, item); + return array[i] === item ? i : -1; + } + if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item); + for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i; + return -1; + }; + + + // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. + _.lastIndexOf = function(array, item) { + if (array == null) return -1; + if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item); + var i = array.length; + while (i--) if (array[i] === item) return i; + return -1; + }; + + // Generate an integer Array containing an arithmetic progression. A port of + // the native Python `range()` function. See + // [the Python documentation](http://docs.python.org/library/functions.html#range). + _.range = function(start, stop, step) { + if (arguments.length <= 1) { + stop = start || 0; + start = 0; + } + step = arguments[2] || 1; + + var len = Math.max(Math.ceil((stop - start) / step), 0); + var idx = 0; + var range = new Array(len); + + while(idx < len) { + range[idx++] = start; + start += step; + } + + return range; + }; + + // Function (ahem) Functions + // ------------------ + + // Create a function bound to a given object (assigning `this`, and arguments, + // optionally). Binding with arguments is also known as `curry`. + // Delegates to **ECMAScript 5**'s native `Function.bind` if available. + // We check for `func.bind` first, to fail fast when `func` is undefined. + _.bind = function(func, obj) { + if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); + var args = slice.call(arguments, 2); + return function() { + return func.apply(obj, args.concat(slice.call(arguments))); + }; + }; + + // Bind all of an object's methods to that object. Useful for ensuring that + // all callbacks defined on an object belong to it. + _.bindAll = function(obj) { + var funcs = slice.call(arguments, 1); + if (funcs.length == 0) funcs = _.functions(obj); + each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); + return obj; + }; + + // Memoize an expensive function by storing its results. + _.memoize = function(func, hasher) { + var memo = {}; + hasher || (hasher = _.identity); + return function() { + var key = hasher.apply(this, arguments); + return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); + }; + }; + + // Delays a function for the given number of milliseconds, and then calls + // it with the arguments supplied. + _.delay = function(func, wait) { + var args = slice.call(arguments, 2); + return setTimeout(function(){ return func.apply(func, args); }, wait); + }; + + // Defers a function, scheduling it to run after the current call stack has + // cleared. + _.defer = function(func) { + return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); + }; + + // Internal function used to implement `_.throttle` and `_.debounce`. + var limit = function(func, wait, debounce) { + var timeout; + return function() { + var context = this, args = arguments; + var throttler = function() { + timeout = null; + func.apply(context, args); + }; + if (debounce) clearTimeout(timeout); + if (debounce || !timeout) timeout = setTimeout(throttler, wait); + }; + }; + + // Returns a function, that, when invoked, will only be triggered at most once + // during a given window of time. + _.throttle = function(func, wait) { + return limit(func, wait, false); + }; + + // Returns a function, that, as long as it continues to be invoked, will not + // be triggered. The function will be called after it stops being called for + // N milliseconds. + _.debounce = function(func, wait) { + return limit(func, wait, true); + }; + + // Returns a function that will be executed at most one time, no matter how + // often you call it. Useful for lazy initialization. + _.once = function(func) { + var ran = false, memo; + return function() { + if (ran) return memo; + ran = true; + return memo = func.apply(this, arguments); + }; + }; + + // Returns the first function passed as an argument to the second, + // allowing you to adjust arguments, run code before and after, and + // conditionally execute the original function. + _.wrap = function(func, wrapper) { + return function() { + var args = [func].concat(slice.call(arguments)); + return wrapper.apply(this, args); + }; + }; + + // Returns a function that is the composition of a list of functions, each + // consuming the return value of the function that follows. + _.compose = function() { + var funcs = slice.call(arguments); + return function() { + var args = slice.call(arguments); + for (var i = funcs.length - 1; i >= 0; i--) { + args = [funcs[i].apply(this, args)]; + } + return args[0]; + }; + }; + + // Returns a function that will only be executed after being called N times. + _.after = function(times, func) { + return function() { + if (--times < 1) { return func.apply(this, arguments); } + }; + }; + + + // Object Functions + // ---------------- + + // Retrieve the names of an object's properties. + // Delegates to **ECMAScript 5**'s native `Object.keys` + _.keys = nativeKeys || function(obj) { + if (obj !== Object(obj)) throw new TypeError('Invalid object'); + var keys = []; + for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key; + return keys; + }; + + // Retrieve the values of an object's properties. + _.values = function(obj) { + return _.map(obj, _.identity); + }; + + // Return a sorted list of the function names available on the object. + // Aliased as `methods` + _.functions = _.methods = function(obj) { + var names = []; + for (var key in obj) { + if (_.isFunction(obj[key])) names.push(key); + } + return names.sort(); + }; + + // Extend a given object with all the properties in passed-in object(s). + _.extend = function(obj) { + each(slice.call(arguments, 1), function(source) { + for (var prop in source) { + if (source[prop] !== void 0) obj[prop] = source[prop]; + } + }); + return obj; + }; + + // Fill in a given object with default properties. + _.defaults = function(obj) { + each(slice.call(arguments, 1), function(source) { + for (var prop in source) { + if (obj[prop] == null) obj[prop] = source[prop]; + } + }); + return obj; + }; + + // Create a (shallow-cloned) duplicate of an object. + _.clone = function(obj) { + return _.isArray(obj) ? obj.slice() : _.extend({}, obj); + }; + + // Invokes interceptor with the obj, and then returns obj. + // The primary purpose of this method is to "tap into" a method chain, in + // order to perform operations on intermediate results within the chain. + _.tap = function(obj, interceptor) { + interceptor(obj); + return obj; + }; + + // Perform a deep comparison to check if two objects are equal. + _.isEqual = function(a, b) { + // Check object identity. + if (a === b) return true; + // Different types? + var atype = typeof(a), btype = typeof(b); + if (atype != btype) return false; + // Basic equality test (watch out for coercions). + if (a == b) return true; + // One is falsy and the other truthy. + if ((!a && b) || (a && !b)) return false; + // Unwrap any wrapped objects. + if (a._chain) a = a._wrapped; + if (b._chain) b = b._wrapped; + // One of them implements an isEqual()? + if (a.isEqual) return a.isEqual(b); + if (b.isEqual) return b.isEqual(a); + // Check dates' integer values. + if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime(); + // Both are NaN? + if (_.isNaN(a) && _.isNaN(b)) return false; + // Compare regular expressions. + if (_.isRegExp(a) && _.isRegExp(b)) + return a.source === b.source && + a.global === b.global && + a.ignoreCase === b.ignoreCase && + a.multiline === b.multiline; + // If a is not an object by this point, we can't handle it. + if (atype !== 'object') return false; + // Check for different array lengths before comparing contents. + if (a.length && (a.length !== b.length)) return false; + // Nothing else worked, deep compare the contents. + var aKeys = _.keys(a), bKeys = _.keys(b); + // Different object sizes? + if (aKeys.length != bKeys.length) return false; + // Recursive comparison of contents. + for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false; + return true; + }; + + // Is a given array or object empty? + _.isEmpty = function(obj) { + if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; + for (var key in obj) if (hasOwnProperty.call(obj, key)) return false; + return true; + }; + + // Is a given value a DOM element? + _.isElement = function(obj) { + return !!(obj && obj.nodeType == 1); + }; + + // Is a given value an array? + // Delegates to ECMA5's native Array.isArray + _.isArray = nativeIsArray || function(obj) { + return toString.call(obj) === '[object Array]'; + }; + + // Is a given variable an object? + _.isObject = function(obj) { + return obj === Object(obj); + }; + + // Is a given variable an arguments object? + _.isArguments = function(obj) { + return !!(obj && hasOwnProperty.call(obj, 'callee')); + }; + + // Is a given value a function? + _.isFunction = function(obj) { + return !!(obj && obj.constructor && obj.call && obj.apply); + }; + + // Is a given value a string? + _.isString = function(obj) { + return !!(obj === '' || (obj && obj.charCodeAt && obj.substr)); + }; + + // Is a given value a number? + _.isNumber = function(obj) { + return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed)); + }; + + // Is the given value `NaN`? `NaN` happens to be the only value in JavaScript + // that does not equal itself. + _.isNaN = function(obj) { + return obj !== obj; + }; + + // Is a given value a boolean? + _.isBoolean = function(obj) { + return obj === true || obj === false; + }; + + // Is a given value a date? + _.isDate = function(obj) { + return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear); + }; + + // Is the given value a regular expression? + _.isRegExp = function(obj) { + return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false)); + }; + + // Is a given value equal to null? + _.isNull = function(obj) { + return obj === null; + }; + + // Is a given variable undefined? + _.isUndefined = function(obj) { + return obj === void 0; + }; + + // Utility Functions + // ----------------- + + // Run Underscore.js in *noConflict* mode, returning the `_` variable to its + // previous owner. Returns a reference to the Underscore object. + _.noConflict = function() { + root._ = previousUnderscore; + return this; + }; + + // Keep the identity function around for default iterators. + _.identity = function(value) { + return value; + }; + + // Run a function **n** times. + _.times = function (n, iterator, context) { + for (var i = 0; i < n; i++) iterator.call(context, i); + }; + + // Add your own custom functions to the Underscore object, ensuring that + // they're correctly added to the OOP wrapper as well. + _.mixin = function(obj) { + each(_.functions(obj), function(name){ + addToWrapper(name, _[name] = obj[name]); + }); + }; + + // Generate a unique integer id (unique within the entire client session). + // Useful for temporary DOM ids. + var idCounter = 0; + _.uniqueId = function(prefix) { + var id = idCounter++; + return prefix ? prefix + id : id; + }; + + // By default, Underscore uses ERB-style template delimiters, change the + // following template settings to use alternative delimiters. + _.templateSettings = { + evaluate : /<%([\s\S]+?)%>/g, + interpolate : /<%=([\s\S]+?)%>/g + }; + + // JavaScript micro-templating, similar to John Resig's implementation. + // Underscore templating handles arbitrary delimiters, preserves whitespace, + // and correctly escapes quotes within interpolated code. + _.template = function(str, data) { + var c = _.templateSettings; + var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' + + 'with(obj||{}){__p.push(\'' + + str.replace(/\\/g, '\\\\') + .replace(/'/g, "\\'") + .replace(c.interpolate, function(match, code) { + return "'," + code.replace(/\\'/g, "'") + ",'"; + }) + .replace(c.evaluate || null, function(match, code) { + return "');" + code.replace(/\\'/g, "'") + .replace(/[\r\n\t]/g, ' ') + "__p.push('"; + }) + .replace(/\r/g, '\\r') + .replace(/\n/g, '\\n') + .replace(/\t/g, '\\t') + + "');}return __p.join('');"; + var func = new Function('obj', tmpl); + return data ? func(data) : func; + }; + + // The OOP Wrapper + // --------------- + + // If Underscore is called as a function, it returns a wrapped object that + // can be used OO-style. This wrapper holds altered versions of all the + // underscore functions. Wrapped objects may be chained. + var wrapper = function(obj) { this._wrapped = obj; }; + + // Expose `wrapper.prototype` as `_.prototype` + _.prototype = wrapper.prototype; + + // Helper function to continue chaining intermediate results. + var result = function(obj, chain) { + return chain ? _(obj).chain() : obj; + }; + + // A method to easily add functions to the OOP wrapper. + var addToWrapper = function(name, func) { + wrapper.prototype[name] = function() { + var args = slice.call(arguments); + unshift.call(args, this._wrapped); + return result(func.apply(_, args), this._chain); + }; + }; + + // Add all of the Underscore functions to the wrapper object. + _.mixin(_); + + // Add all mutator Array functions to the wrapper. + each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { + var method = ArrayProto[name]; + wrapper.prototype[name] = function() { + method.apply(this._wrapped, arguments); + return result(this._wrapped, this._chain); + }; + }); + + // Add all accessor Array functions to the wrapper. + each(['concat', 'join', 'slice'], function(name) { + var method = ArrayProto[name]; + wrapper.prototype[name] = function() { + return result(method.apply(this._wrapped, arguments), this._chain); + }; + }); + + // Start chaining a wrapped Underscore object. + wrapper.prototype.chain = function() { + this._chain = true; + return this; + }; + + // Extracts the result from a wrapped and chained object. + wrapper.prototype.value = function() { + return this._wrapped; + }; + +})(); diff --git a/app/lib/updater.js b/app/lib/updater.js new file mode 100644 index 00000000000..2b99cedd222 --- /dev/null +++ b/app/lib/updater.js @@ -0,0 +1,57 @@ +exports.CURRENT_VERSION = "0.0.31"; + +var fs = require("fs"); +var https = require("https"); +var path = require("path"); +var semver = require("semver"); + +var manifest_options = { + host: 's3.amazonaws.com', + path: '/com.skybreakplatform.static/update/manifest.json' +}; + + +/** + * Downloads the current manifest file and returns it via a callback (or + * null on error) + */ +exports.get_manifest = function (callback) { + var req = https.request(manifest_options, function(res) { + if (res.statusCode !== 200) { + callback(null); + return; + } + res.setEncoding('utf8'); + var manifest = ''; + res.on('data', function (chunk) { + manifest = manifest + chunk; + }); + res.on('end', function () { + var parsed; + try { + parsed = JSON.parse(manifest); + } catch (err) { + parsed = null; + }; + callback(parsed); + }); + }); + req.addListener('error', function () { + // No-op makes node not crash! + // http://rentzsch.tumblr.com/post/664884799/node-js-handling-refused-http-client-connections + }); + req.end(); +}; + +/** + * Takes a version string (or a manifest object) and returns true if + * this copy is out of date. + */ +exports.needs_upgrade = function (version) { + if (version && typeof version !== "string") { + version = version.version; + } + if (!version) return false; + + return semver.lt(exports.CURRENT_VERSION, version); +} diff --git a/app/server/server.js b/app/server/server.js new file mode 100644 index 00000000000..4a9e2e0b2fc --- /dev/null +++ b/app/server/server.js @@ -0,0 +1,131 @@ +////////// Requires ////////// + +require("fibers"); + +var fs = require("fs"); +var path = require("path"); + +var connect = require('connect'); +var gzip = require('connect-gzip'); +var argv = require('optimist').argv; +var mime = require('mime'); +var socketio = require('socket.io'); +var handlebars = require('handlebars'); + +// this is a copy of underscore that will be shipped just for use by +// this file, server.js. +var _ = require('./underscore.js'); + +// Keepalives so that when the outer server dies unceremoniously and +// doesn't kill us, we quit ourselves. A little gross, but better than +// pidfiles. +var init_keepalive = function () { + var keepalive_count = 0; + + process.stdin.on('data', function (data) { + keepalive_count = 0; + }); + + process.stdin.resume(); + + setInterval(function () { + keepalive_count ++; + if (keepalive_count >= 2) { + console.log("Failed to receive keepalive! Exiting."); + process.exit(1); + } + }, 3000); +}; + +var run = function (bundle_dir) { + var bundle_dir = path.join(__dirname, '..'); + + // check environment + var port = process.env.PORT ? parseInt(process.env.PORT) : 80; + var mongo_url = process.env.MONGO_URL; + if (!mongo_url) + throw new Error("MONGO_URL must be set in environment"); + + // webserver + var app = connect.createServer(); + app.use(gzip.gzip()); + app.use(connect.static(path.join(bundle_dir, 'static'))); + var app_html = fs.readFileSync(path.join(bundle_dir, 'app.html')); + app.use(function (req, res) { + res.write(app_html); + res.end(); + }); + + // socket.io setup + var io = socketio.listen(app); + io.configure(function() { + // Don't serve static files from socket.io. We serve them separately + // to get gzip and other fun things. + io.set('browser client', false); + + io.set('log level', 1); + // XXX disable websockets! they break chrome both debugging + // and node-http-proxy (used in outer app) + io.set('transports', _.without(io.transports(), 'websocket')); + }); + + // read bundle config file + var info_raw = + fs.readFileSync(path.join(bundle_dir, 'app.json'), 'utf8'); + var info = JSON.parse(info_raw); + + // start up app + __skybreak_bootstrap__ = {require: require, startup_hooks: []}; + Fiber(function () { + // (put in a fiber to let Sky.db operations happen during loading) + + // pass in database info + __skybreak_bootstrap__.mongo_url = mongo_url; + + // load app code + info.load.forEach(function (filename) { + var code = fs.readFileSync(path.join(bundle_dir, filename)); + // it's tempting to run the code in a new context so we can + // precisely control the enviroment the user code sees. but, + // this is harder than it looks. you get a situation where [] + // created in one runInContext invocation fails 'instanceof + // Array' if tested in another (reusing the same context each + // time fixes it for {} and Object, but not [] and Array.) and + // we have no pressing need to do this, so punt. + // + // the final 'true' is an undocumented argument to + // runIn[Foo]Context that causes it to print out a descriptive + // error message on parse error. it's what require() uses to + // generate its errors. + require('vm').runInThisContext(code, filename, true); + }); + + // connect socket.io to skybreak server libraries + io.sockets.on('connection', function (socket) { + __skybreak_bootstrap__.register_socket(socket); + + socket.on('subscribe', function (data) { + __skybreak_bootstrap__.register_subscription(socket, data); + }); + socket.on('unsubscribe', function (data) { + __skybreak_bootstrap__.unregister_subscription(socket, data); + }); + + socket.on('handle', function (data) { + __skybreak_bootstrap__.run_handler(socket, data, + io.sockets.sockets); + }); + }); + + // run the user startup hooks. + _.each(__skybreak_bootstrap__.startup_hooks, function (x) { x(); }); + + // only start listening after all the startup code has run. + app.listen(port, function() {}); + + }).run(); + + init_keepalive(); +}; + +run(); diff --git a/app/server/underscore.js b/app/server/underscore.js new file mode 100644 index 00000000000..4f56013259b --- /dev/null +++ b/app/server/underscore.js @@ -0,0 +1,839 @@ +// Underscore.js 1.1.7 +// (c) 2011 Jeremy Ashkenas, DocumentCloud Inc. +// Underscore is freely distributable under the MIT license. +// Portions of Underscore are inspired or borrowed from Prototype, +// Oliver Steele's Functional, and John Resig's Micro-Templating. +// For all details and documentation: +// http://documentcloud.github.com/underscore + +(function() { + + // Baseline setup + // -------------- + + // Establish the root object, `window` in the browser, or `global` on the server. + var root = this; + + // Save the previous value of the `_` variable. + var previousUnderscore = root._; + + // Establish the object that gets returned to break out of a loop iteration. + var breaker = {}; + + // Save bytes in the minified (but not gzipped) version: + var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; + + // Create quick reference variables for speed access to core prototypes. + var slice = ArrayProto.slice, + unshift = ArrayProto.unshift, + toString = ObjProto.toString, + hasOwnProperty = ObjProto.hasOwnProperty; + + // All **ECMAScript 5** native function implementations that we hope to use + // are declared here. + var + nativeForEach = ArrayProto.forEach, + nativeMap = ArrayProto.map, + nativeReduce = ArrayProto.reduce, + nativeReduceRight = ArrayProto.reduceRight, + nativeFilter = ArrayProto.filter, + nativeEvery = ArrayProto.every, + nativeSome = ArrayProto.some, + nativeIndexOf = ArrayProto.indexOf, + nativeLastIndexOf = ArrayProto.lastIndexOf, + nativeIsArray = Array.isArray, + nativeKeys = Object.keys, + nativeBind = FuncProto.bind; + + // Create a safe reference to the Underscore object for use below. + var _ = function(obj) { return new wrapper(obj); }; + + // Export the Underscore object for **CommonJS**, with backwards-compatibility + // for the old `require()` API. If we're not in CommonJS, add `_` to the + // global object. + if (typeof module !== 'undefined' && module.exports) { + module.exports = _; + _._ = _; + } else { + // Exported as a string, for Closure Compiler "advanced" mode. + root['_'] = _; + } + + // Current version. + _.VERSION = '1.1.7'; + + // Collection Functions + // -------------------- + + // The cornerstone, an `each` implementation, aka `forEach`. + // Handles objects with the built-in `forEach`, arrays, and raw objects. + // Delegates to **ECMAScript 5**'s native `forEach` if available. + var each = _.each = _.forEach = function(obj, iterator, context) { + if (obj == null) return; + if (nativeForEach && obj.forEach === nativeForEach) { + obj.forEach(iterator, context); + } else if (obj.length === +obj.length) { + for (var i = 0, l = obj.length; i < l; i++) { + if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return; + } + } else { + for (var key in obj) { + if (hasOwnProperty.call(obj, key)) { + if (iterator.call(context, obj[key], key, obj) === breaker) return; + } + } + } + }; + + // Return the results of applying the iterator to each element. + // Delegates to **ECMAScript 5**'s native `map` if available. + _.map = function(obj, iterator, context) { + var results = []; + if (obj == null) return results; + if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); + each(obj, function(value, index, list) { + results[results.length] = iterator.call(context, value, index, list); + }); + return results; + }; + + // **Reduce** builds up a single result from a list of values, aka `inject`, + // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. + _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { + var initial = memo !== void 0; + if (obj == null) obj = []; + if (nativeReduce && obj.reduce === nativeReduce) { + if (context) iterator = _.bind(iterator, context); + return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); + } + each(obj, function(value, index, list) { + if (!initial) { + memo = value; + initial = true; + } else { + memo = iterator.call(context, memo, value, index, list); + } + }); + if (!initial) throw new TypeError("Reduce of empty array with no initial value"); + return memo; + }; + + // The right-associative version of reduce, also known as `foldr`. + // Delegates to **ECMAScript 5**'s native `reduceRight` if available. + _.reduceRight = _.foldr = function(obj, iterator, memo, context) { + if (obj == null) obj = []; + if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { + if (context) iterator = _.bind(iterator, context); + return memo !== void 0 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); + } + var reversed = (_.isArray(obj) ? obj.slice() : _.toArray(obj)).reverse(); + return _.reduce(reversed, iterator, memo, context); + }; + + // Return the first value which passes a truth test. Aliased as `detect`. + _.find = _.detect = function(obj, iterator, context) { + var result; + any(obj, function(value, index, list) { + if (iterator.call(context, value, index, list)) { + result = value; + return true; + } + }); + return result; + }; + + // Return all the elements that pass a truth test. + // Delegates to **ECMAScript 5**'s native `filter` if available. + // Aliased as `select`. + _.filter = _.select = function(obj, iterator, context) { + var results = []; + if (obj == null) return results; + if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); + each(obj, function(value, index, list) { + if (iterator.call(context, value, index, list)) results[results.length] = value; + }); + return results; + }; + + // Return all the elements for which a truth test fails. + _.reject = function(obj, iterator, context) { + var results = []; + if (obj == null) return results; + each(obj, function(value, index, list) { + if (!iterator.call(context, value, index, list)) results[results.length] = value; + }); + return results; + }; + + // Determine whether all of the elements match a truth test. + // Delegates to **ECMAScript 5**'s native `every` if available. + // Aliased as `all`. + _.every = _.all = function(obj, iterator, context) { + var result = true; + if (obj == null) return result; + if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); + each(obj, function(value, index, list) { + if (!(result = result && iterator.call(context, value, index, list))) return breaker; + }); + return result; + }; + + // Determine if at least one element in the object matches a truth test. + // Delegates to **ECMAScript 5**'s native `some` if available. + // Aliased as `any`. + var any = _.some = _.any = function(obj, iterator, context) { + iterator = iterator || _.identity; + var result = false; + if (obj == null) return result; + if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); + each(obj, function(value, index, list) { + if (result |= iterator.call(context, value, index, list)) return breaker; + }); + return !!result; + }; + + // Determine if a given value is included in the array or object using `===`. + // Aliased as `contains`. + _.include = _.contains = function(obj, target) { + var found = false; + if (obj == null) return found; + if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; + any(obj, function(value) { + if (found = value === target) return true; + }); + return found; + }; + + // Invoke a method (with arguments) on every item in a collection. + _.invoke = function(obj, method) { + var args = slice.call(arguments, 2); + return _.map(obj, function(value) { + return (method.call ? method || value : value[method]).apply(value, args); + }); + }; + + // Convenience version of a common use case of `map`: fetching a property. + _.pluck = function(obj, key) { + return _.map(obj, function(value){ return value[key]; }); + }; + + // Return the maximum element or (element-based computation). + _.max = function(obj, iterator, context) { + if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj); + var result = {computed : -Infinity}; + each(obj, function(value, index, list) { + var computed = iterator ? iterator.call(context, value, index, list) : value; + computed >= result.computed && (result = {value : value, computed : computed}); + }); + return result.value; + }; + + // Return the minimum element (or element-based computation). + _.min = function(obj, iterator, context) { + if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj); + var result = {computed : Infinity}; + each(obj, function(value, index, list) { + var computed = iterator ? iterator.call(context, value, index, list) : value; + computed < result.computed && (result = {value : value, computed : computed}); + }); + return result.value; + }; + + // Sort the object's values by a criterion produced by an iterator. + _.sortBy = function(obj, iterator, context) { + return _.pluck(_.map(obj, function(value, index, list) { + return { + value : value, + criteria : iterator.call(context, value, index, list) + }; + }).sort(function(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }), 'value'); + }; + + // Groups the object's values by a criterion produced by an iterator + _.groupBy = function(obj, iterator) { + var result = {}; + each(obj, function(value, index) { + var key = iterator(value, index); + (result[key] || (result[key] = [])).push(value); + }); + return result; + }; + + // Use a comparator function to figure out at what index an object should + // be inserted so as to maintain order. Uses binary search. + _.sortedIndex = function(array, obj, iterator) { + iterator || (iterator = _.identity); + var low = 0, high = array.length; + while (low < high) { + var mid = (low + high) >> 1; + iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid; + } + return low; + }; + + // Safely convert anything iterable into a real, live array. + _.toArray = function(iterable) { + if (!iterable) return []; + if (iterable.toArray) return iterable.toArray(); + if (_.isArray(iterable)) return slice.call(iterable); + if (_.isArguments(iterable)) return slice.call(iterable); + return _.values(iterable); + }; + + // Return the number of elements in an object. + _.size = function(obj) { + return _.toArray(obj).length; + }; + + // Array Functions + // --------------- + + // Get the first element of an array. Passing **n** will return the first N + // values in the array. Aliased as `head`. The **guard** check allows it to work + // with `_.map`. + _.first = _.head = function(array, n, guard) { + return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; + }; + + // Returns everything but the first entry of the array. Aliased as `tail`. + // Especially useful on the arguments object. Passing an **index** will return + // the rest of the values in the array from that index onward. The **guard** + // check allows it to work with `_.map`. + _.rest = _.tail = function(array, index, guard) { + return slice.call(array, (index == null) || guard ? 1 : index); + }; + + // Get the last element of an array. + _.last = function(array) { + return array[array.length - 1]; + }; + + // Trim out all falsy values from an array. + _.compact = function(array) { + return _.filter(array, function(value){ return !!value; }); + }; + + // Return a completely flattened version of an array. + _.flatten = function(array) { + return _.reduce(array, function(memo, value) { + if (_.isArray(value)) return memo.concat(_.flatten(value)); + memo[memo.length] = value; + return memo; + }, []); + }; + + // Return a version of the array that does not contain the specified value(s). + _.without = function(array) { + return _.difference(array, slice.call(arguments, 1)); + }; + + // Produce a duplicate-free version of the array. If the array has already + // been sorted, you have the option of using a faster algorithm. + // Aliased as `unique`. + _.uniq = _.unique = function(array, isSorted) { + return _.reduce(array, function(memo, el, i) { + if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el; + return memo; + }, []); + }; + + // Produce an array that contains the union: each distinct element from all of + // the passed-in arrays. + _.union = function() { + return _.uniq(_.flatten(arguments)); + }; + + // Produce an array that contains every item shared between all the + // passed-in arrays. (Aliased as "intersect" for back-compat.) + _.intersection = _.intersect = function(array) { + var rest = slice.call(arguments, 1); + return _.filter(_.uniq(array), function(item) { + return _.every(rest, function(other) { + return _.indexOf(other, item) >= 0; + }); + }); + }; + + // Take the difference between one array and another. + // Only the elements present in just the first array will remain. + _.difference = function(array, other) { + return _.filter(array, function(value){ return !_.include(other, value); }); + }; + + // Zip together multiple lists into a single array -- elements that share + // an index go together. + _.zip = function() { + var args = slice.call(arguments); + var length = _.max(_.pluck(args, 'length')); + var results = new Array(length); + for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i); + return results; + }; + + // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), + // we need this function. Return the position of the first occurrence of an + // item in an array, or -1 if the item is not included in the array. + // Delegates to **ECMAScript 5**'s native `indexOf` if available. + // If the array is large and already in sort order, pass `true` + // for **isSorted** to use binary search. + _.indexOf = function(array, item, isSorted) { + if (array == null) return -1; + var i, l; + if (isSorted) { + i = _.sortedIndex(array, item); + return array[i] === item ? i : -1; + } + if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item); + for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i; + return -1; + }; + + + // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. + _.lastIndexOf = function(array, item) { + if (array == null) return -1; + if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item); + var i = array.length; + while (i--) if (array[i] === item) return i; + return -1; + }; + + // Generate an integer Array containing an arithmetic progression. A port of + // the native Python `range()` function. See + // [the Python documentation](http://docs.python.org/library/functions.html#range). + _.range = function(start, stop, step) { + if (arguments.length <= 1) { + stop = start || 0; + start = 0; + } + step = arguments[2] || 1; + + var len = Math.max(Math.ceil((stop - start) / step), 0); + var idx = 0; + var range = new Array(len); + + while(idx < len) { + range[idx++] = start; + start += step; + } + + return range; + }; + + // Function (ahem) Functions + // ------------------ + + // Create a function bound to a given object (assigning `this`, and arguments, + // optionally). Binding with arguments is also known as `curry`. + // Delegates to **ECMAScript 5**'s native `Function.bind` if available. + // We check for `func.bind` first, to fail fast when `func` is undefined. + _.bind = function(func, obj) { + if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); + var args = slice.call(arguments, 2); + return function() { + return func.apply(obj, args.concat(slice.call(arguments))); + }; + }; + + // Bind all of an object's methods to that object. Useful for ensuring that + // all callbacks defined on an object belong to it. + _.bindAll = function(obj) { + var funcs = slice.call(arguments, 1); + if (funcs.length == 0) funcs = _.functions(obj); + each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); + return obj; + }; + + // Memoize an expensive function by storing its results. + _.memoize = function(func, hasher) { + var memo = {}; + hasher || (hasher = _.identity); + return function() { + var key = hasher.apply(this, arguments); + return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); + }; + }; + + // Delays a function for the given number of milliseconds, and then calls + // it with the arguments supplied. + _.delay = function(func, wait) { + var args = slice.call(arguments, 2); + return setTimeout(function(){ return func.apply(func, args); }, wait); + }; + + // Defers a function, scheduling it to run after the current call stack has + // cleared. + _.defer = function(func) { + return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); + }; + + // Internal function used to implement `_.throttle` and `_.debounce`. + var limit = function(func, wait, debounce) { + var timeout; + return function() { + var context = this, args = arguments; + var throttler = function() { + timeout = null; + func.apply(context, args); + }; + if (debounce) clearTimeout(timeout); + if (debounce || !timeout) timeout = setTimeout(throttler, wait); + }; + }; + + // Returns a function, that, when invoked, will only be triggered at most once + // during a given window of time. + _.throttle = function(func, wait) { + return limit(func, wait, false); + }; + + // Returns a function, that, as long as it continues to be invoked, will not + // be triggered. The function will be called after it stops being called for + // N milliseconds. + _.debounce = function(func, wait) { + return limit(func, wait, true); + }; + + // Returns a function that will be executed at most one time, no matter how + // often you call it. Useful for lazy initialization. + _.once = function(func) { + var ran = false, memo; + return function() { + if (ran) return memo; + ran = true; + return memo = func.apply(this, arguments); + }; + }; + + // Returns the first function passed as an argument to the second, + // allowing you to adjust arguments, run code before and after, and + // conditionally execute the original function. + _.wrap = function(func, wrapper) { + return function() { + var args = [func].concat(slice.call(arguments)); + return wrapper.apply(this, args); + }; + }; + + // Returns a function that is the composition of a list of functions, each + // consuming the return value of the function that follows. + _.compose = function() { + var funcs = slice.call(arguments); + return function() { + var args = slice.call(arguments); + for (var i = funcs.length - 1; i >= 0; i--) { + args = [funcs[i].apply(this, args)]; + } + return args[0]; + }; + }; + + // Returns a function that will only be executed after being called N times. + _.after = function(times, func) { + return function() { + if (--times < 1) { return func.apply(this, arguments); } + }; + }; + + + // Object Functions + // ---------------- + + // Retrieve the names of an object's properties. + // Delegates to **ECMAScript 5**'s native `Object.keys` + _.keys = nativeKeys || function(obj) { + if (obj !== Object(obj)) throw new TypeError('Invalid object'); + var keys = []; + for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key; + return keys; + }; + + // Retrieve the values of an object's properties. + _.values = function(obj) { + return _.map(obj, _.identity); + }; + + // Return a sorted list of the function names available on the object. + // Aliased as `methods` + _.functions = _.methods = function(obj) { + var names = []; + for (var key in obj) { + if (_.isFunction(obj[key])) names.push(key); + } + return names.sort(); + }; + + // Extend a given object with all the properties in passed-in object(s). + _.extend = function(obj) { + each(slice.call(arguments, 1), function(source) { + for (var prop in source) { + if (source[prop] !== void 0) obj[prop] = source[prop]; + } + }); + return obj; + }; + + // Fill in a given object with default properties. + _.defaults = function(obj) { + each(slice.call(arguments, 1), function(source) { + for (var prop in source) { + if (obj[prop] == null) obj[prop] = source[prop]; + } + }); + return obj; + }; + + // Create a (shallow-cloned) duplicate of an object. + _.clone = function(obj) { + return _.isArray(obj) ? obj.slice() : _.extend({}, obj); + }; + + // Invokes interceptor with the obj, and then returns obj. + // The primary purpose of this method is to "tap into" a method chain, in + // order to perform operations on intermediate results within the chain. + _.tap = function(obj, interceptor) { + interceptor(obj); + return obj; + }; + + // Perform a deep comparison to check if two objects are equal. + _.isEqual = function(a, b) { + // Check object identity. + if (a === b) return true; + // Different types? + var atype = typeof(a), btype = typeof(b); + if (atype != btype) return false; + // Basic equality test (watch out for coercions). + if (a == b) return true; + // One is falsy and the other truthy. + if ((!a && b) || (a && !b)) return false; + // Unwrap any wrapped objects. + if (a._chain) a = a._wrapped; + if (b._chain) b = b._wrapped; + // One of them implements an isEqual()? + if (a.isEqual) return a.isEqual(b); + if (b.isEqual) return b.isEqual(a); + // Check dates' integer values. + if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime(); + // Both are NaN? + if (_.isNaN(a) && _.isNaN(b)) return false; + // Compare regular expressions. + if (_.isRegExp(a) && _.isRegExp(b)) + return a.source === b.source && + a.global === b.global && + a.ignoreCase === b.ignoreCase && + a.multiline === b.multiline; + // If a is not an object by this point, we can't handle it. + if (atype !== 'object') return false; + // Check for different array lengths before comparing contents. + if (a.length && (a.length !== b.length)) return false; + // Nothing else worked, deep compare the contents. + var aKeys = _.keys(a), bKeys = _.keys(b); + // Different object sizes? + if (aKeys.length != bKeys.length) return false; + // Recursive comparison of contents. + for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false; + return true; + }; + + // Is a given array or object empty? + _.isEmpty = function(obj) { + if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; + for (var key in obj) if (hasOwnProperty.call(obj, key)) return false; + return true; + }; + + // Is a given value a DOM element? + _.isElement = function(obj) { + return !!(obj && obj.nodeType == 1); + }; + + // Is a given value an array? + // Delegates to ECMA5's native Array.isArray + _.isArray = nativeIsArray || function(obj) { + return toString.call(obj) === '[object Array]'; + }; + + // Is a given variable an object? + _.isObject = function(obj) { + return obj === Object(obj); + }; + + // Is a given variable an arguments object? + _.isArguments = function(obj) { + return !!(obj && hasOwnProperty.call(obj, 'callee')); + }; + + // Is a given value a function? + _.isFunction = function(obj) { + return !!(obj && obj.constructor && obj.call && obj.apply); + }; + + // Is a given value a string? + _.isString = function(obj) { + return !!(obj === '' || (obj && obj.charCodeAt && obj.substr)); + }; + + // Is a given value a number? + _.isNumber = function(obj) { + return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed)); + }; + + // Is the given value `NaN`? `NaN` happens to be the only value in JavaScript + // that does not equal itself. + _.isNaN = function(obj) { + return obj !== obj; + }; + + // Is a given value a boolean? + _.isBoolean = function(obj) { + return obj === true || obj === false; + }; + + // Is a given value a date? + _.isDate = function(obj) { + return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear); + }; + + // Is the given value a regular expression? + _.isRegExp = function(obj) { + return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false)); + }; + + // Is a given value equal to null? + _.isNull = function(obj) { + return obj === null; + }; + + // Is a given variable undefined? + _.isUndefined = function(obj) { + return obj === void 0; + }; + + // Utility Functions + // ----------------- + + // Run Underscore.js in *noConflict* mode, returning the `_` variable to its + // previous owner. Returns a reference to the Underscore object. + _.noConflict = function() { + root._ = previousUnderscore; + return this; + }; + + // Keep the identity function around for default iterators. + _.identity = function(value) { + return value; + }; + + // Run a function **n** times. + _.times = function (n, iterator, context) { + for (var i = 0; i < n; i++) iterator.call(context, i); + }; + + // Add your own custom functions to the Underscore object, ensuring that + // they're correctly added to the OOP wrapper as well. + _.mixin = function(obj) { + each(_.functions(obj), function(name){ + addToWrapper(name, _[name] = obj[name]); + }); + }; + + // Generate a unique integer id (unique within the entire client session). + // Useful for temporary DOM ids. + var idCounter = 0; + _.uniqueId = function(prefix) { + var id = idCounter++; + return prefix ? prefix + id : id; + }; + + // By default, Underscore uses ERB-style template delimiters, change the + // following template settings to use alternative delimiters. + _.templateSettings = { + evaluate : /<%([\s\S]+?)%>/g, + interpolate : /<%=([\s\S]+?)%>/g + }; + + // JavaScript micro-templating, similar to John Resig's implementation. + // Underscore templating handles arbitrary delimiters, preserves whitespace, + // and correctly escapes quotes within interpolated code. + _.template = function(str, data) { + var c = _.templateSettings; + var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' + + 'with(obj||{}){__p.push(\'' + + str.replace(/\\/g, '\\\\') + .replace(/'/g, "\\'") + .replace(c.interpolate, function(match, code) { + return "'," + code.replace(/\\'/g, "'") + ",'"; + }) + .replace(c.evaluate || null, function(match, code) { + return "');" + code.replace(/\\'/g, "'") + .replace(/[\r\n\t]/g, ' ') + "__p.push('"; + }) + .replace(/\r/g, '\\r') + .replace(/\n/g, '\\n') + .replace(/\t/g, '\\t') + + "');}return __p.join('');"; + var func = new Function('obj', tmpl); + return data ? func(data) : func; + }; + + // The OOP Wrapper + // --------------- + + // If Underscore is called as a function, it returns a wrapped object that + // can be used OO-style. This wrapper holds altered versions of all the + // underscore functions. Wrapped objects may be chained. + var wrapper = function(obj) { this._wrapped = obj; }; + + // Expose `wrapper.prototype` as `_.prototype` + _.prototype = wrapper.prototype; + + // Helper function to continue chaining intermediate results. + var result = function(obj, chain) { + return chain ? _(obj).chain() : obj; + }; + + // A method to easily add functions to the OOP wrapper. + var addToWrapper = function(name, func) { + wrapper.prototype[name] = function() { + var args = slice.call(arguments); + unshift.call(args, this._wrapped); + return result(func.apply(_, args), this._chain); + }; + }; + + // Add all of the Underscore functions to the wrapper object. + _.mixin(_); + + // Add all mutator Array functions to the wrapper. + each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { + var method = ArrayProto[name]; + wrapper.prototype[name] = function() { + method.apply(this._wrapped, arguments); + return result(this._wrapped, this._chain); + }; + }); + + // Add all accessor Array functions to the wrapper. + each(['concat', 'join', 'slice'], function(name) { + var method = ArrayProto[name]; + wrapper.prototype[name] = function() { + return result(method.apply(this._wrapped, arguments), this._chain); + }; + }); + + // Start chaining a wrapped Underscore object. + wrapper.prototype.chain = function() { + this._chain = true; + return this; + }; + + // Extracts the result from a wrapped and chained object. + wrapper.prototype.value = function() { + return this._wrapped; + }; + +})(); diff --git a/app/skybreak/deploy.js b/app/skybreak/deploy.js new file mode 100644 index 00000000000..18564f993b2 --- /dev/null +++ b/app/skybreak/deploy.js @@ -0,0 +1,18 @@ +// accepts www.host.com, defaults domain to skybreakplatform, defaults +// protocol to http. +// +// XXX shared w/ proxy.js +exports.parse_url = function (url) { + if (!url.match(':\/\/')) + url = 'http://' + url; + + var parsed = require('url').parse(url); + + delete parsed.host; // we use hostname + + if (parsed.hostname && !parsed.hostname.match(/\./)) + parsed.hostname += '.skybreakplatform.com'; + + return parsed; +} + diff --git a/app/skybreak/run.js b/app/skybreak/run.js new file mode 100644 index 00000000000..600be07ac3e --- /dev/null +++ b/app/skybreak/run.js @@ -0,0 +1,384 @@ +////////// Requires ////////// + +var fs = require("fs"); +var path = require("path"); +var spawn = require('child_process').spawn; + +var socketio = require('socket.io'); +var httpProxy = require('http-proxy'); + +var files = require('../lib/files.js'); +var updater = require('../lib/updater.js'); + +var _ = require('../lib/third/underscore.js'); + +////////// Globals ////////// + +// list of log objects from the child process. +var server_log = []; + +Status = { + running: false, // is server running now? + crashing: false, // does server crash whenever we start it? + counter: 0, // how many crashes in rapid succession + + reset: function () { + this.crashing = false; + this.counter = 0; + }, + + crashed: function () { + if (this.counter === 0) + setTimeout(function () { + this.counter = 0; + }, 2000); + + this.counter++; + + if (this.counter > 2) { + log_to_clients({'exit': "Your application is crashing. Waiting for file change."}); + this.crashing = true; + } + } +}; + +////////// Outer Proxy Server ////////// + +var start_proxy = function (outer_port, inner_port) { + httpProxy.createServer(function (req, res, proxy) { + if (Status.running) { + // server is running. things are hunky dory! + proxy.proxyRequest(req, res, { + host: '127.0.0.1', + port: inner_port + }); + } else { + // sad face. send error logs. + // XXX formatting! text/plain is bad + res.writeHead(200, {'Content-Type': 'text/plain'}); + + res.write("Your app is crashed. Here's the latest log.\n\n"); + + // XXX this is a hack to look through the error logs until the last + // startup. + var last_logs = _.reduceRight(server_log, function(acc, log) { + if (!_.last(acc) || ! _.last(acc).launch) + return acc.concat([log]); + return acc; + }, []); + last_logs.reverse(); + + _.each(last_logs, function(log) { + _.each(log, function(val, key) { + res.write(val); + // deal with mixed line endings! XXX + if (key !== 'stdout' && key !== 'stderr') + res.write("\n"); + }); + }); + + res.end(); + + } + }).listen(outer_port, function () { + process.stdout.write("Running on: http://localhost:" + outer_port + "/\n"); + }); +}; + +////////// MongoDB ////////// + +var launch_mongo = function (app_dir, port, launch_callback, on_exit_callback) { + launch_callback = launch_callback || function () {}; + on_exit_callback = on_exit_callback || function () {}; + + var mongod_path = path.join(files.get_dev_bundle(), 'mongodb/bin/mongod'); + + // store data in app_dir + var data_path = path.join(app_dir, '.skybreak/local/db'); + files.mkdir_p(data_path, 0755); + var pid_path = path.join(app_dir, '.skybreak/local/mongod.pid'); + var port_path = path.join(app_dir, '.skybreak/local/mongod.port'); + + // read old pid file, kill old process. + var pid; + try { + var pid_data = parseInt(fs.readFileSync(pid_path)); + if (pid_data) { + // found old mongo. killing it. will raise if already dead. + pid = pid_data; + process.kill(pid); + console.log("Killing old mongod " + pid); + } + } catch (e) { + // no pid, or no longer running. no worries. + } + + // We need to wait for mongo to fully die, so define a callback + // function for launch. + var _launch = function () { + var proc = spawn(mongod_path, [ + '--bind_ip', '127.0.0.1', '--port', port, + '--dbpath', data_path + ]); + + // write pid and port file. + fs.writeFileSync(pid_path, proc.pid.toString(), 'ascii'); + fs.writeFileSync(port_path, port.toString(), 'ascii'); + + proc.on('exit', function (code, signal) { + console.log("XXX MONGO DEAD! " + code + " : " + signal); // XXX + on_exit_callback(); + }); + + // proc.stderr.setEncoding('utf8'); + // proc.stderr.on('data', function (data) { + // process.stdout.write(data); + // }); + + proc.stdout.setEncoding('utf8'); + proc.stdout.on('data', function (data) { + // process.stdout.write(data); + if (/ \[initandlisten\] waiting for connections on port/.test(data)) + launch_callback(); + }); + + // XXX deal with unclean death. + }; + + if (!pid) { + // no mongo running, launch new one + _launch(); + } else { + // Ensure mongo is really dead. + // XXX super ugly. + var attempts = 0; + var dead_yet = function () { + setTimeout(function () { + attempts = attempts + 1; + var signal = 0; + // try to kill -9 it twice, once at 1 second, once at 10 seconds + if (attempts === 10 || attempts === 20) + signal = 'SIGKILL'; + try { + process.kill(pid, signal); + } catch (e) { + // it's dead. launch and we're done + _launch(); + return; + } + if (attempts === 30) { + // give up after 3 seconds. + process.stdout.write( + "Can't kill running mongo (pid " + pid + "). Aborting.\n"); + process.exit(1); + } + + // recurse + dead_yet(); + }, 100); + }; + dead_yet(); + } +}; + +////////// Launch server process ////////// + +var log_to_clients = function (msg) { + server_log.push(msg); + if (server_log.length > 100) { + server_log.shift(); + } + + // log to console + // + // XXX this is a mess. some lines have newlines some don't. this + // whole thing should be redone. it is the result of doing it very + // differently and changing over quickly. + _.each(msg, function (val, key) { + if (key === "stdout") + process.stdout.write(val); + else if (key === "stderr") + process.stderr.write(val); + else + console.log(val); + }); +}; + +var start_server = function (bundle_path, port, mongo_url, on_exit) { + // environment + var env = {}; + for (var k in process.env) + env[k] = process.env[k]; + env.PORT = port; + env.MONGO_URL = mongo_url; + + Status.running = true; + proc = spawn(process.execPath, + [path.join(bundle_path, 'main.js')], {env: env}); + + proc.stdout.setEncoding('utf8'); + proc.stdout.on('data', function (data) { + data && log_to_clients({stdout: data}); + }); + + proc.stderr.setEncoding('utf8'); + proc.stderr.on('data', function (data) { + data && log_to_clients({stderr: data}); + }); + + proc.on('exit', function (code, signal) { + if (signal) { + log_to_clients({'exit': 'Exited from signal: ' + signal}); + } else { + log_to_clients({'exit': 'Exited with code: ' + code}); + } + + Status.running = false; + on_exit(); + }); + + // Keepalive so server can detect when we die + var timer = setInterval(function () { + if (proc.pid) { + proc.stdin.write('k'); + } + }, 2000); + + return { + proc: proc, + timer: timer + }; +}; + +var kill_server = function (handle) { + if (handle.proc.pid) { + handle.proc.removeAllListeners('exit'); + handle.proc.kill(); + } + clearInterval(handle.timer); +}; + +////////// Watching dependencies ////////// + +var watch_files = function (app_dir, extensions, on_change) { + var watched_files = {}; + + var file_accessed = function (oldStat, newStat) { + if (newStat.mtime.getTime() !== oldStat.mtime.getTime()) + on_change(); + }; + + var consider_file = function (initial_scan, filepath) { + // XXX maybe exclude some files? + if (filepath in watched_files) { + return; + } + watched_files[filepath] = true; + + fs.watchFile(filepath, + {persistant: true, interval: 500}, // poll a lot! + file_accessed); + + if (!initial_scan) + on_change(); + }; + + // kick off initial watch. + files.file_list_async(app_dir, extensions, + _.bind(consider_file, null, true)); + + // watch for new files. + setInterval(function () { + files.file_list_async(app_dir, extensions, + _.bind(consider_file, null, false)); + }, 5000); + + // XXX doesn't deal with removed files + + // XXX if a file is removed from the project, we will continue to + // restart when it's updated + + // XXX if the initial scan takes more than 5000 ms to complete, it's + // all going to come crashing down on us.. +}; + +////////// Upgrade check ////////// + +// XXX this should move to main skybreak command-line, probably? +var start_update_checks = function () { + var update_check = function () { + updater.get_manifest(function (manifest) { + if (manifest && updater.needs_upgrade(manifest)) { + console.log("////////////////////////////////////////"); + console.log("////////////////////////////////////////"); + console.log(); + console.log("skybreak is out of date. Please run:"); + console.log(); + console.log(" skybreak update"); + console.log(); + console.log("////////////////////////////////////////"); + console.log("////////////////////////////////////////"); + } + }); + }; + setInterval(update_check, 12*60*60*1000); // twice a day + update_check(); // and now. +} + +/////////////////////////////////////////////////////////////////////////////// + +// XXX leave a pidfile and check if we are already running + +exports.run = function (app_dir, bundle_path, port, on_restart) { + var outer_port = port || 3000; + var inner_port = outer_port + 1; + var mongo_port = outer_port + 2; + var mongo_url = "mongodb://localhost:" + mongo_port + "/skybreak"; + on_restart = on_restart || function () {}; + + process.stdout.write("[[[[[ " + files.pretty_path(app_dir) + " ]]]]]\n\n"); + + deps = {}; + try { + var deps_raw = + fs.readFileSync(path.join(bundle_path, 'dependencies.json'), 'utf8'); + var deps = JSON.parse(deps_raw.toString()); + } catch (e) { + process.stdout.write("No dependency info in bundle. " + + "Filesystem monitoring disabled.\n"); + } + + if (!files.in_checkout()) + start_update_checks(); + start_proxy(outer_port, inner_port); + + var server; + var restart_server = function () { + if (server) + kill_server(server); + server = start_server(bundle_path, inner_port, mongo_url, function () { + Status.crashed(); + if (!Status.crashing) + restart_server(app_dir); + }); + }; + + watch_files(app_dir, deps.extensions || [], function () { + log_to_clients({'system': "=> Modified -- restarting."}); + on_restart(); + Status.reset(); + restart_server(); + }); + + var launch = function () { + launch_mongo(app_dir, mongo_port, + function () { // On Mongo startup complete + restart_server(); + }, + function () { // On Mongo dead + // XXX wait a sec to restart. + setTimeout(launch, 1000); + }); + }; + launch(); +}; diff --git a/app/skybreak/skel/.skybreak/.gitignore b/app/skybreak/skel/.skybreak/.gitignore new file mode 100644 index 00000000000..40830374235 --- /dev/null +++ b/app/skybreak/skel/.skybreak/.gitignore @@ -0,0 +1 @@ +local diff --git a/app/skybreak/skel/.skybreak/packages b/app/skybreak/skel/.skybreak/packages new file mode 100644 index 00000000000..abccef56b1e --- /dev/null +++ b/app/skybreak/skel/.skybreak/packages @@ -0,0 +1,4 @@ +# Skybreak packages used by this project, one per line. +# +# 'skybreak add' and 'skybreak remove' will edit this file for you, +# but you can also edit it by hand. diff --git a/app/skybreak/skel/client/~name~.css b/app/skybreak/skel/client/~name~.css new file mode 100644 index 00000000000..30b0f452681 --- /dev/null +++ b/app/skybreak/skel/client/~name~.css @@ -0,0 +1,10 @@ +h1 { + color: red; +} + +img { + display: block; + position: absolute; + top: 0px; + right: 0px; +} diff --git a/app/skybreak/skel/client/~name~.html b/app/skybreak/skel/client/~name~.html new file mode 100644 index 00000000000..c6b232cb453 --- /dev/null +++ b/app/skybreak/skel/client/~name~.html @@ -0,0 +1,36 @@ + + ~name~ + + + +

~name~

+ + Welcome to Skybreak! Here is a button for you to press. + + {{> button_demo }} + + + + + + + + diff --git a/app/skybreak/skel/client/~name~.js b/app/skybreak/skel/client/~name~.js new file mode 100644 index 00000000000..dce7ce1e7a3 --- /dev/null +++ b/app/skybreak/skel/client/~name~.js @@ -0,0 +1,16 @@ +Sky.subscribe('presses'); + +Template.button_demo.events = { + 'click input': function () { + console.log("press"); + Presses.insert({}); + } +}; + +Template.button_demo.press_count = function () { + return Presses.find({}).length; +}; + +Template.button_demo.never_pressed = function (options) { + return Presses.find({}).length === 0; +}; diff --git a/app/skybreak/skel/model.js b/app/skybreak/skel/model.js new file mode 100644 index 00000000000..307887b9685 --- /dev/null +++ b/app/skybreak/skel/model.js @@ -0,0 +1,3 @@ +Presses = Sky.Collection('presses'); + +Sky.publish('presses', {}); diff --git a/app/skybreak/skel/public/4201645142_ec2e3bb3f8_b.jpg b/app/skybreak/skel/public/4201645142_ec2e3bb3f8_b.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e673901a22ea214d9752456384cb574f17b7f509 GIT binary patch literal 48284 zcmbTd1z225(=NIO8=Rnl1Pc%d5Fofi2niZIxCM8c!8K@tJ0S!K!Gee2?k@x##@%+`s3c=bc*B)m7bH>#3@>xSP0J03OIm$w~nr5D1V#et^3jAVS&F z!Px<7>EKAq&He%qcqOZVh6dcXca$I<0QK=xX-X6TKmkxFQ78a3M`}Pe|O#r}^d240wfbswU?ChN( zs?x7$wX}6;!9z%eumB8z699}%ppFV^Qt$3%%D$1Lg(8{$lK*#ylyN!^AbS89VUtm& zrTv@yf87(BI6|BO0Hll@!EI^=H9_JaB(`;PcD$$WBQc4w%{@lBUpEp6Qb8mpzsDAT znN8Wq#Ks6>N-ODLhumuq0QlSH`%wVV{o2wZ7nzS!kdKdz ziygWA|Fr+|;y+yfHMrl~zd4Rn{@ODT*}%VO{~G%*n!|Sh5I8}uP0YV&#$N!SIv4=R zr~XA__yzz3K>$z%`!{>Y?$3**v$LZR2Zx)R8@rX63H$wm{?q)*5{i2#U*gCjCXrYcqCT6s3|LYi?rdiAMfJfm&J6-jgL&-_e@5KwR%J(kJda zbO0M507w7|fEu6&o&jtC7r+k)122I$fE=I%yaTiW1Hc5Z1nd9^;0AaD{y+#24#WV7 zKnjonWCQs?3GfT31{#1?pbO{+egk8`G_U}y09(L5a0*-@Z>wMs9*7u30ippt1+jv- zKms5!&>PTOkSa(U^d4jZvIn_zqwXc4pl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Gs}pL []\n" + +"\n" + +"With no arguments, 'skybreak' runs the project in the current\n" + +"directory in local development mode. You can run it from the root\n" + +"directory of the project or from any subdirectory.\n" + +"\n" + +"Use 'skybreak create ' to create a new Skybreak project.\n" + +"\n" + +"Commands:\n"); + Commands.forEach(function (cmd) { + if (cmd.help) { + var name = cmd.name + " ".substr(cmd.name.length); + process.stdout.write(" " + name + cmd.help + "\n"); + } + }); + process.stdout.write("\n"); +process.stdout.write( +"See 'skybreak help ' for details on a command.\n"); + process.exit(1); +}; + +var require_project = function (cmd) { + var app_dir = files.find_app_dir(); + if (!app_dir) { + // This is where you end up if you type 'skybreak' with no + // args. Be gentle to the noobs.. + process.stdout.write( +cmd + ": You're not in a Skybreak project directory.\n" + +"\n" + +"To create a new Skybreak project:\n" + +" skybreak create \n" + +"For example:\n" + +" skybreak create myapp\n" + +"\n" + +"For more help, see 'skybreak --help'.\n"); + process.exit(1); + } + return app_dir; +}; + +// See if mongo is running already. If so, return the current port. If +// not, return null. +var find_mongo_port = function (cmd) { + var app_dir = require_project(cmd); + + var fs = require("fs"); + var pid_path = path.join(app_dir, '.skybreak/local/mongod.pid'); + var port_path = path.join(app_dir, '.skybreak/local/mongod.port'); + var port; + + try { + var pid_data = parseInt(fs.readFileSync(pid_path)); + process.kill(pid_data, 0); // make sure it is still alive + port = parseInt(fs.readFileSync(port_path)); + } catch (e) { + return null; + } + + return port; +}; + +Commands = []; + +var findCommand = function (name) { + for (var i = 0; i < Commands.length; i++) + if (Commands[i].name === name) + return Commands[i]; + process.stdout.write("'" + name + "' is not a Skybreak command. See " + + "'skybreak --help'.\n"); + process.exit(1); +}; + +// XXX when the pass unexpected argument or unrecognized flags, print +// an error and fail out + +Commands.push({ + name: "run", + help: "[default] Run this project in local development mode", + func: function (argv) { + // reparse args + // This help logic should probably move to run.js eventually + var opt = require('optimist') + .alias('port', 'p').default('port', 3000) + .describe('port', 'Port to listen on. NOTE: Also uses port N+1 and N+2.') + .boolean('production') + .describe('production', 'Run in production mode. Minify and bundle CSS and JS files.') + .usage( +"Usage: skybreak run [options]\n" + +"\n" + +"Searches upward from the current directory for the root directory of a\n" + +"Skybreak project, then runs that project in local development\n" + +"mode. You can use the application by pointing your web browser at\n" + +"localhost:3000. No internet connection is required.\n" + +"\n" + +"Whenever you change any of the application's source files, the changes\n" + +"are automatically detected and applied to the running application.\n" + +"\n" + +"The application's database persists between runs. It's stored under\n" + +"the .skybreak directory in the root of the project.\n" +); + + new_argv = opt.argv; + + if (argv.help) { + process.stdout.write(opt.help()); + process.exit(1); + } + + var app_dir = require_project("run"); + var bundle_path = path.join(app_dir, '.skybreak/local/build'); + var opts = { no_minify: !argv.production, symlink_dev_bundle: true }; + var build = function () { + require('../lib/bundler.js').bundle(app_dir, bundle_path, opts); + }; + build(); + require('./run.js').run(app_dir, bundle_path, new_argv.port, build); + } +}); + +Commands.push({ + name: "help", + func: function (argv) { + if (!argv._.length || argv.help) + usage(); + var cmd = argv._.splice(0,1)[0]; + argv.help = true; + findCommand(cmd).func(argv); + } +}); + +Commands.push({ + name: "create", + help: "Create a new project", + func: function (argv) { + if (argv.help || argv._.length !== 1 || !argv._[0].length) { + process.stdout.write( +"Usage: skybreak create \n" + +"\n" + +"Make a subdirectory named and create a new Skybreak project\n" + +"there. You can also pass an absolute or relative path.\n"); + process.exit(1); + } + + var name = argv._[0]; + if (path.existsSync(name)) { + process.stderr.write(name + ": Already exists\n"); + process.exit(1); + } + + if (files.find_app_dir(name)) { + process.stderr.write( +"You can't create a Skybreak project inside another Skybreak project.\n"); + process.exit(1); + } + + var transform = function (x) { + return x.replace(/~name~/g, path.basename(name)); + }; + files.cp_r(path.join(__dirname, 'skel'), name, { + transform_filename: function (f) { + return transform(f); + }, + transform_contents: function (contents, f) { + if (f.substr(-5) === ".html") { + return new Buffer(transform(contents.toString())); + } else { + return contents; + } + } + }); + } +}); + +Commands.push({ + name: "update", + help: "Upgrade to the latest version of Skybreak", + func: function (argv) { + if (argv.help) { + process.stdout.write( +"Usage: skybreak update\n" + +"\n" + +"Checks to see if a new version of Skybreak is available, and if so,\n" + +"downloads and installs it. You must be connected to the internet.\n"); + process.exit(1); + } + + require('./update.js'); + } +}); + +Commands.push({ + name: "add", + help: "Add a package to this project", + func: function (argv) { + if (argv.help || !argv._.length) { + process.stdout.write( +"Usage: skybreak add [package] [package..]\n" + +"\n" + +"Adds packages to your Skybreak project. You can add multiple\n" + +"packages with one command. For a list of the available packages, see\n" + +"'skybreak packages'.\n"); + process.exit(1); + } + + var app_dir = require_project('add'); + var packages = require('../lib/packages.js'); + var project = require('../lib/project.js'); + var all = packages.list(); + var using = {}; + _.each(project.get_packages(app_dir), function (name) { + using[name] = true; + }); + + _.each(argv._, function (name) { + if (!(name in all)) { + process.stderr.write(name + ": no such package\n"); + } else if (name in using) { + process.stderr.write(name + ": already using\n"); + } else { + project.add_package(app_dir, name); + var note = all[name].summary || ''; + process.stderr.write(name + ": " + note + "\n"); + } + }); + } +}); + +Commands.push({ + name: "remove", + help: "Remove a package from this project", + func: function (argv) { + if (argv.help || !argv._.length) { + process.stdout.write( +"Usage: skybreak remove [package] [package..]\n" + +"\n" + +"Removes a package previously added to your Skybreak project. For a\n" + +"list of the packages that your package is currently using, see\n" + +"'skybreak using'.\n"); + process.exit(1); + } + + var app_dir = require_project('remove'); + var packages = require('../lib/packages.js'); + var project = require('../lib/project.js'); + var using = {}; + _.each(project.get_packages(app_dir), function (name) { + using[name] = true; + }); + + _.each(argv._, function (name) { + if (!(name in using)) { + process.stderr.write(name + ": not in project\n"); + } else { + project.remove_package(app_dir, name); + process.stderr.write(name + ": removed\n"); + } + }); + } +}); + +Commands.push({ + name: "list", + help: "List available packages", + func: function (argv) { + if (argv.help) { + process.stdout.write( +"Usage: skybreak list [--using]\n" + +"\n" + +"Without arguments, lists all available Skybreak packages. To add one\n" + +"of these packages to your project, see 'skybreak add'.\n" + +"\n" + +"With --using, list the packages that you have added to your project.\n"); + process.exit(1); + } + + if (argv.using) { + var app_dir = require_project('list --using'); + var using = require('../lib/project.js').get_packages(app_dir); + + if (using.length) { + _.each(using, function (name) { + process.stdout.write(name + "\n"); + }); + } else { + process.stderr.write( +"This project doesn't use any packages yet. To add some packages:\n" + +" skybreak add ...\n" + +"\n" + +"To see available packages:\n" + +" skybreak packages\n"); + } + return; + } + + var list = require('../lib/packages.js').list(); + var names = _.keys(list); + names.sort(); + var descrs = []; + _.each(names, function (name) { + descrs.push(list[name]); + }); + process.stdout.write("\n" + + require('../lib/packages.js').format_list(descrs) + + "\n"); + } +}); + +Commands.push({ + name: "bundle", + help: "Pack this project up into a tarball", + func: function (argv) { + if (argv.help || argv._.length != 1) { + process.stdout.write( +"Usage: skybreak bundle \n" + +"\n" + +"Package this project up for deployment. The output is a tarball that\n" + +"includes everything necessary to run the application. See README in\n" + +"the tarball for details.\n"); + process.exit(1); + } + + // XXX if they pass a file that doesn't end in .tar.gz or .tgz, + // add the former for them + + // XXX output, to stderr, the name of the file written to (for + // human comfort, especially since we might change the name) + + // XXX name the root directory in the bundle based on the basename + // of the file, not a constant 'bundle' (a bit obnoxious for + // machines, but worth it for humans) + + var app_dir = path.resolve(require_project("bundle")); + var build_dir = path.join(app_dir, '.skybreak/local/build_tar'); + var bundle_path = path.join(build_dir, 'bundle'); + require('../lib/bundler.js').bundle(app_dir, bundle_path); + + var cp = require('child_process'); + cp.execFile('/usr/bin/env', + ['tar', 'czf', argv._[0], 'bundle'], + {cwd: build_dir}, + function (error, stdout, stderr) { + if (error !== null) { + console.log(JSON.stringify(error)); + process.stderr.write("couldn't run tar\n"); + } else { + process.stdout.write(stdout); + process.stderr.write(stderr); + } + files.rm_recursive(build_dir); + }); + } +}); + +Commands.push({ + name: "deploy", + help: "Deploy this project to Skybreak", + func: function (argv) { + if (argv.help || argv._.length < 1 || argv._.length > 2) { + process.stdout.write( +"Usage: skybreak deploy \n" + +"\n" + +"Deploy the current code in your tree to the specified subdomain of\n" + +"skybreakplatform.com.\n"); + process.exit(1); + } + + var deploy = require('./deploy'); + + var url = deploy.parse_url(argv._[0]); + + if (!url.hostname) { + process.stdout.write( +"Please specify a domain to deploy to, such as www.example.com or\n" + +"http://www.example.com/\n"); + process.exit(1); + } + + if (url.pathname != '/' || url.hash || url.query) { + process.stdout.write( +"Sorry, Skybreak does not yet support deploying to a specific path URL, such as\n" + +"http://www.example.com/blog . Please specify the root of a domain.\n"); + process.exit(1); + } + + process.stdout.write('Deploying to ' + url.hostname + ' ...\n'); + + var app_dir = path.resolve(require_project("bundle")); + var build_dir = path.join(app_dir, '.skybreak/local/build_tar'); + var bundle_path = path.join(build_dir, 'bundle'); + var bundle_opts = { skip_dev_bundle: true }; + require('../lib/bundler.js').bundle(app_dir, bundle_path, bundle_opts); + + var cp = require('child_process'); + // curl -# progress meter, -f exit nonzero if HTTP 403, -F form data. + // XXX exec won't let us buffer the output. + cp.exec('tar czf - bundle | curl -f -# -F file=@- http://deploy.skybreakplatform.com/deploy/' + url.hostname, + {cwd: build_dir}, + function (error, stdout, stderr) { + files.rm_recursive(build_dir); + + process.stdout.write(stdout); + process.stderr.write(stderr); + + if (error !== null) { + // XXX better error reporting + process.stderr.write("couldn't deploy\n"); + process.exit(1); + } + + process.stdout.write('Done. Now serving at ' + url.hostname + '\n'); + + if (!url.hostname.match('skybreakplatform.com')) { + var dns = require('dns'); + dns.resolve(url.hostname, 'CNAME', function (err, cnames) { + if (err || cnames[0] !== 'origin.skybreakplatform.com') { + dns.resolve(url.hostname, 'A', function (err, addresses) { + if (err || addresses[0] !== '107.22.210.133') { + process.stdout.write('-------------\n'); + process.stdout.write("You've deployed to a custom domain.\n"); + process.stdout.write("Please be sure to CNAME your hostname to origin.skybreakplatform.com,\n"); + process.stdout.write("or set an A record to 107.22.210.133.\n"); + process.stdout.write('-------------\n'); + } + }); + } + }); + } + }); + } +}); + +Commands.push({ + name: "logs", + help: "Show logs for specified site", + func: function (argv) { + if (argv.help || argv._.length < 1 || argv._.length > 2) { + process.stdout.write( +"Usage: skybreak logs \n" + +"\n" + +"Retrieves the logs for the requested site.\n"); + process.exit(1); + } + + var deploy = require('./deploy'); + var url = deploy.parse_url(argv._[0]); + + var http = require('http'); + + var options = { + host: 'deploy.skybreakplatform.com', + port: 80, + path: '/logs/' + url.hostname, + }; + + var req = http.get(options, function(res) { + res.setEncoding('utf8'); + res.on('data', function (chunk) { + process.stdout.write(chunk); + }); + }); + + req.on('error', function(e) { + console.log("Error connecting to Skybreak: " + e.message); + process.exit(1); + }); + } +}); + +Commands.push({ + name: "mongo", + help: "Open a MongoDB shell on this project's local database", + func: function (argv) { + if (argv.help) { + process.stdout.write( +"Usage: skybreak mongo\n" + +"\n" + +"Open a MongoDB shell on your local development database, so that you\n" + +"can view or manipulate it directly. You must already have your\n" + +"application running locally.\n"); + process.exit(1); + } + + var mongod_port = find_mongo_port("mongo"); + + if (!mongod_port) { + process.stdout.write( +"mongo: Skybreak isn't running.\n" + +"\n" + +"This command only works while Skybreak is running your application\n" + +"locally. Start your application first.\n"); + process.exit(1); + } + + var path_base = path.join(path.dirname(process.execPath), '..'); + var mongo_path = path.join(path_base, 'mongodb/bin/mongo'); + + process.stdout.write("Database: " + + files.pretty_path(files.find_app_dir()) + + "/.skybreak\n\n"); + + var spawn = require('child_process').spawn; + var mongo_proc = spawn(mongo_path,[ + '127.0.0.1:' + mongod_port + '/skybreak', '--shell' + ], { + customFds: [0, 1, 2], // just take the fds! sketch, but works + }); + } +}); + +Commands.push({ + name: "reset", + help: "Reset the project state. Erases the local database.", + func: function (argv) { + if (argv.help) { + process.stdout.write( +"Usage: skybreak reset\n" + +"\n" + +"Reset the current project to a fresh state. Removes all local\n" + +"data and kills any running skybreak development servers.\n"); + process.exit(1); + } + + var app_dir = path.resolve(require_project("reset")); + + var mongod_port = find_mongo_port("reset"); + if (mongod_port) { + process.stdout.write( +"reset: Skybreak is running.\n" + +"\n" + +"This command does not work while Skybreak is running your application.\n" + +"Exit the running skybreak development server.\n"); + process.exit(1); + } + + var local_dir = path.join(app_dir, '.skybreak/local'); + files.rm_recursive(local_dir); + + process.stdout.write("Project reset.\n"); + } +}); + + +var main = function() { + var optimist = require('optimist') + .boolean("h").alias("h", "help") + .boolean("version") + .boolean("debug"); + + var argv = optimist.argv; + + if (argv.help) { + argv._.splice(0, 0, "help"); + delete argv.help; + } + + if (argv.version) { + var updater = require('../lib/updater.js'); + process.stdout.write("Skybreak version " + updater.CURRENT_VERSION + "\n"); + process.exit(0); + } + + var cmd = 'run'; + if (argv._.length) + cmd = argv._.splice(0,1)[0]; + + findCommand(cmd).func(argv); +}; + +main(); + diff --git a/app/skybreak/update.js b/app/skybreak/update.js new file mode 100644 index 00000000000..d916450cf1c --- /dev/null +++ b/app/skybreak/update.js @@ -0,0 +1,90 @@ +var fs = require("fs"); +var https = require("https"); +var path = require("path"); +var spawn = require('child_process').spawn; +var url = require("url"); + +var wrench = require("wrench"); +var ProgressBar = require('progress'); + +var updater = require("../lib/updater.js"); + +updater.get_manifest(function (manifest) { + if (!manifest) { + console.log("Failed to download manifest."); + return; + } + + if (!updater.needs_upgrade(manifest)) { + if (manifest.version === updater.CURRENT_VERSION) { + console.log("Already at current version: " + manifest.version); + } else { + console.log("Not upgrading. Your version: " + updater.CURRENT_VERSION + + ". New version: " + manifest.version + "."); + } + return; + } + + console.log("New version available: " + manifest.version); + var download_url = url.parse(manifest.url); + // XXX why is node's API for url different from http? + download_url.path = download_url.pathname; + + var req = https.request(download_url, function(res) { + if (res.statusCode !== 200) { + console.log("Failed to download: " + manifest.url); + return; + } + var len = parseInt(res.headers['content-length'], 10); + + var bar = new ProgressBar(' downloading [:bar] :percent', { + complete: '=' + , incomplete: ' ' + , width: 30 + , total: len + }); + + // find / make directory paths + var base_dir = path.join(__dirname, "../../"); + var tmp_dir = path.join(base_dir, "tmp"); + try { fs.mkdirSync(tmp_dir, 0755); } catch (err) { } + + // open pipe to tar + // XXX not always /usr/bin/tar !!!. linux is /bin/tar. + var tar_proc = spawn("/usr/bin/tar", ["-C", tmp_dir, "-xzf", "-"]); + + // XXX + tar_proc.stderr.setEncoding('utf8'); + tar_proc.stderr.on('data', function (data) { + console.log(data); + }); + + res.on('data', function (chunk) { + tar_proc.stdin.write(chunk); + bar.tick(chunk.length); + }); + res.on('end', function () { + console.log("... finished download"); + tar_proc.stdin.end(); + tar_proc.on('exit', function (code, signal) { + if (code !== 0 || signal) { + console.log("failed to untar download"); + return; + } + + // untar complete. swap directories + var old_base_dir = base_dir.slice(0,-1) + ".old"; + if (path.existsSync(old_base_dir)) + wrench.rmdirSyncRecursive(old_base_dir); // rm -rf !! + + fs.renameSync(base_dir, old_base_dir); + fs.renameSync(old_base_dir + "/tmp/skybreak", base_dir); + + console.log("Upgrade complete."); + }); + }); + + }); + req.end(); + +}); diff --git a/install.sh b/install.sh new file mode 100755 index 00000000000..5b620aee98a --- /dev/null +++ b/install.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +cd `dirname $0` + +TARGET_DIR=/usr/local/skybreak + +rm -rf "$TARGET_DIR" + +# make sure dev bundle exists before trying to install +./skybreak --version || exit 1 + +cp -a dev_bundle "$TARGET_DIR" + +function CPR { + tar -c --exclude .skybreak/local "$1" | tar -x -C "$2" +} +cp skybreak "$TARGET_DIR/bin" +CPR app "$TARGET_DIR" +CPR packages "$TARGET_DIR" + +mkdir -p /usr/local/bin +rm -f /usr/local/bin/skybreak +ln -s "$TARGET_DIR/bin/skybreak" /usr/local/bin/skybreak diff --git a/packages/backbone/backbone.js b/packages/backbone/backbone.js new file mode 100644 index 00000000000..54efe48a96f --- /dev/null +++ b/packages/backbone/backbone.js @@ -0,0 +1,1159 @@ +// Backbone.js 0.5.3 +// (c) 2010 Jeremy Ashkenas, DocumentCloud Inc. +// Backbone may be freely distributed under the MIT license. +// For all details and documentation: +// http://documentcloud.github.com/backbone + +(function(){ + + // Initial Setup + // ------------- + + // Save a reference to the global object. + var root = this; + + // Save the previous value of the `Backbone` variable. + var previousBackbone = root.Backbone; + + // The top-level namespace. All public Backbone classes and modules will + // be attached to this. Exported for both CommonJS and the browser. + var Backbone; + if (typeof exports !== 'undefined') { + Backbone = exports; + } else { + Backbone = root.Backbone = {}; + } + + // Current version of the library. Keep in sync with `package.json`. + Backbone.VERSION = '0.5.3'; + + // Require Underscore, if we're on the server, and it's not already present. + var _ = root._; + if (!_ && (typeof require !== 'undefined')) _ = require('underscore')._; + + // For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable. + var $ = root.jQuery || root.Zepto || root.ender; + + // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable + // to its previous owner. Returns a reference to this Backbone object. + Backbone.noConflict = function() { + root.Backbone = previousBackbone; + return this; + }; + + // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option will + // fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and set a + // `X-Http-Method-Override` header. + Backbone.emulateHTTP = false; + + // Turn on `emulateJSON` to support legacy servers that can't deal with direct + // `application/json` requests ... will encode the body as + // `application/x-www-form-urlencoded` instead and will send the model in a + // form param named `model`. + Backbone.emulateJSON = false; + + // Backbone.Events + // ----------------- + + // A module that can be mixed in to *any object* in order to provide it with + // custom events. You may `bind` or `unbind` a callback function to an event; + // `trigger`-ing an event fires all callbacks in succession. + // + // var object = {}; + // _.extend(object, Backbone.Events); + // object.bind('expand', function(){ alert('expanded'); }); + // object.trigger('expand'); + // + Backbone.Events = { + + // Bind an event, specified by a string name, `ev`, to a `callback` function. + // Passing `"all"` will bind the callback to all events fired. + bind : function(ev, callback, context) { + var calls = this._callbacks || (this._callbacks = {}); + var list = calls[ev] || (calls[ev] = []); + list.push([callback, context]); + return this; + }, + + // Remove one or many callbacks. If `callback` is null, removes all + // callbacks for the event. If `ev` is null, removes all bound callbacks + // for all events. + unbind : function(ev, callback) { + var calls; + if (!ev) { + this._callbacks = {}; + } else if (calls = this._callbacks) { + if (!callback) { + calls[ev] = []; + } else { + var list = calls[ev]; + if (!list) return this; + for (var i = 0, l = list.length; i < l; i++) { + if (list[i] && callback === list[i][0]) { + list[i] = null; + break; + } + } + } + } + return this; + }, + + // Trigger an event, firing all bound callbacks. Callbacks are passed the + // same arguments as `trigger` is, apart from the event name. + // Listening for `"all"` passes the true event name as the first argument. + trigger : function(eventName) { + var list, calls, ev, callback, args; + var both = 2; + if (!(calls = this._callbacks)) return this; + while (both--) { + ev = both ? eventName : 'all'; + if (list = calls[ev]) { + for (var i = 0, l = list.length; i < l; i++) { + if (!(callback = list[i])) { + list.splice(i, 1); i--; l--; + } else { + args = both ? Array.prototype.slice.call(arguments, 1) : arguments; + callback[0].apply(callback[1] || this, args); + } + } + } + } + return this; + } + + }; + + // Backbone.Model + // -------------- + + // Create a new model, with defined attributes. A client id (`cid`) + // is automatically generated and assigned for you. + Backbone.Model = function(attributes, options) { + var defaults; + attributes || (attributes = {}); + if (defaults = this.defaults) { + if (_.isFunction(defaults)) defaults = defaults.call(this); + attributes = _.extend({}, defaults, attributes); + } + this.attributes = {}; + this._escapedAttributes = {}; + this.cid = _.uniqueId('c'); + this.set(attributes, {silent : true}); + this._changed = false; + this._previousAttributes = _.clone(this.attributes); + if (options && options.collection) this.collection = options.collection; + this.initialize(attributes, options); + }; + + // Attach all inheritable methods to the Model prototype. + _.extend(Backbone.Model.prototype, Backbone.Events, { + + // A snapshot of the model's previous attributes, taken immediately + // after the last `"change"` event was fired. + _previousAttributes : null, + + // Has the item been changed since the last `"change"` event? + _changed : false, + + // The default name for the JSON `id` attribute is `"id"`. MongoDB and + // CouchDB users may want to set this to `"_id"`. + idAttribute : 'id', + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize : function(){}, + + // Return a copy of the model's `attributes` object. + toJSON : function() { + return _.clone(this.attributes); + }, + + // Get the value of an attribute. + get : function(attr) { + return this.attributes[attr]; + }, + + // Get the HTML-escaped value of an attribute. + escape : function(attr) { + var html; + if (html = this._escapedAttributes[attr]) return html; + var val = this.attributes[attr]; + return this._escapedAttributes[attr] = escapeHTML(val == null ? '' : '' + val); + }, + + // Returns `true` if the attribute contains a value that is not null + // or undefined. + has : function(attr) { + return this.attributes[attr] != null; + }, + + // Set a hash of model attributes on the object, firing `"change"` unless you + // choose to silence it. + set : function(attrs, options) { + + // Extract attributes and options. + options || (options = {}); + if (!attrs) return this; + if (attrs.attributes) attrs = attrs.attributes; + var now = this.attributes, escaped = this._escapedAttributes; + + // Run validation. + if (!options.silent && this.validate && !this._performValidation(attrs, options)) return false; + + // Check for changes of `id`. + if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; + + // We're about to start triggering change events. + var alreadyChanging = this._changing; + this._changing = true; + + // Update attributes. + for (var attr in attrs) { + var val = attrs[attr]; + if (!_.isEqual(now[attr], val)) { + now[attr] = val; + delete escaped[attr]; + this._changed = true; + if (!options.silent) this.trigger('change:' + attr, this, val, options); + } + } + + // Fire the `"change"` event, if the model has been changed. + if (!alreadyChanging && !options.silent && this._changed) this.change(options); + this._changing = false; + return this; + }, + + // Remove an attribute from the model, firing `"change"` unless you choose + // to silence it. `unset` is a noop if the attribute doesn't exist. + unset : function(attr, options) { + if (!(attr in this.attributes)) return this; + options || (options = {}); + var value = this.attributes[attr]; + + // Run validation. + var validObj = {}; + validObj[attr] = void 0; + if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false; + + // Remove the attribute. + delete this.attributes[attr]; + delete this._escapedAttributes[attr]; + if (attr == this.idAttribute) delete this.id; + this._changed = true; + if (!options.silent) { + this.trigger('change:' + attr, this, void 0, options); + this.change(options); + } + return this; + }, + + // Clear all attributes on the model, firing `"change"` unless you choose + // to silence it. + clear : function(options) { + options || (options = {}); + var attr; + var old = this.attributes; + + // Run validation. + var validObj = {}; + for (attr in old) validObj[attr] = void 0; + if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false; + + this.attributes = {}; + this._escapedAttributes = {}; + this._changed = true; + if (!options.silent) { + for (attr in old) { + this.trigger('change:' + attr, this, void 0, options); + } + this.change(options); + } + return this; + }, + + // Fetch the model from the server. If the server's representation of the + // model differs from its current attributes, they will be overriden, + // triggering a `"change"` event. + fetch : function(options) { + options || (options = {}); + var model = this; + var success = options.success; + options.success = function(resp, status, xhr) { + if (!model.set(model.parse(resp, xhr), options)) return false; + if (success) success(model, resp); + }; + options.error = wrapError(options.error, model, options); + return (this.sync || Backbone.sync).call(this, 'read', this, options); + }, + + // Set a hash of model attributes, and sync the model to the server. + // If the server returns an attributes hash that differs, the model's + // state will be `set` again. + save : function(attrs, options) { + options || (options = {}); + if (attrs && !this.set(attrs, options)) return false; + var model = this; + var success = options.success; + options.success = function(resp, status, xhr) { + if (!model.set(model.parse(resp, xhr), options)) return false; + if (success) success(model, resp, xhr); + }; + options.error = wrapError(options.error, model, options); + var method = this.isNew() ? 'create' : 'update'; + return (this.sync || Backbone.sync).call(this, method, this, options); + }, + + // Destroy this model on the server if it was already persisted. Upon success, the model is removed + // from its collection, if it has one. + destroy : function(options) { + options || (options = {}); + if (this.isNew()) return this.trigger('destroy', this, this.collection, options); + var model = this; + var success = options.success; + options.success = function(resp) { + model.trigger('destroy', model, model.collection, options); + if (success) success(model, resp); + }; + options.error = wrapError(options.error, model, options); + return (this.sync || Backbone.sync).call(this, 'delete', this, options); + }, + + // Default URL for the model's representation on the server -- if you're + // using Backbone's restful methods, override this to change the endpoint + // that will be called. + url : function() { + var base = getUrl(this.collection) || this.urlRoot || urlError(); + if (this.isNew()) return base; + return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id); + }, + + // **parse** converts a response into the hash of attributes to be `set` on + // the model. The default implementation is just to pass the response along. + parse : function(resp, xhr) { + return resp; + }, + + // Create a new model with identical attributes to this one. + clone : function() { + return new this.constructor(this); + }, + + // A model is new if it has never been saved to the server, and lacks an id. + isNew : function() { + return this.id == null; + }, + + // Call this method to manually fire a `change` event for this model. + // Calling this will cause all objects observing the model to update. + change : function(options) { + this.trigger('change', this, options); + this._previousAttributes = _.clone(this.attributes); + this._changed = false; + }, + + // Determine if the model has changed since the last `"change"` event. + // If you specify an attribute name, determine if that attribute has changed. + hasChanged : function(attr) { + if (attr) return this._previousAttributes[attr] != this.attributes[attr]; + return this._changed; + }, + + // Return an object containing all the attributes that have changed, or false + // if there are no changed attributes. Useful for determining what parts of a + // view need to be updated and/or what attributes need to be persisted to + // the server. + changedAttributes : function(now) { + now || (now = this.attributes); + var old = this._previousAttributes; + var changed = false; + for (var attr in now) { + if (!_.isEqual(old[attr], now[attr])) { + changed = changed || {}; + changed[attr] = now[attr]; + } + } + return changed; + }, + + // Get the previous value of an attribute, recorded at the time the last + // `"change"` event was fired. + previous : function(attr) { + if (!attr || !this._previousAttributes) return null; + return this._previousAttributes[attr]; + }, + + // Get all of the attributes of the model at the time of the previous + // `"change"` event. + previousAttributes : function() { + return _.clone(this._previousAttributes); + }, + + // Run validation against a set of incoming attributes, returning `true` + // if all is well. If a specific `error` callback has been passed, + // call that instead of firing the general `"error"` event. + _performValidation : function(attrs, options) { + var error = this.validate(attrs); + if (error) { + if (options.error) { + options.error(this, error, options); + } else { + this.trigger('error', this, error, options); + } + return false; + } + return true; + } + + }); + + // Backbone.Collection + // ------------------- + + // Provides a standard collection class for our sets of models, ordered + // or unordered. If a `comparator` is specified, the Collection will maintain + // its models in sort order, as they're added and removed. + Backbone.Collection = function(models, options) { + options || (options = {}); + if (options.comparator) this.comparator = options.comparator; + _.bindAll(this, '_onModelEvent', '_removeReference'); + this._reset(); + if (models) this.reset(models, {silent: true}); + this.initialize.apply(this, arguments); + }; + + // Define the Collection's inheritable methods. + _.extend(Backbone.Collection.prototype, Backbone.Events, { + + // The default model for a collection is just a **Backbone.Model**. + // This should be overridden in most cases. + model : Backbone.Model, + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize : function(){}, + + // The JSON representation of a Collection is an array of the + // models' attributes. + toJSON : function() { + return this.map(function(model){ return model.toJSON(); }); + }, + + // Add a model, or list of models to the set. Pass **silent** to avoid + // firing the `added` event for every new model. + add : function(models, options) { + if (_.isArray(models)) { + for (var i = 0, l = models.length; i < l; i++) { + this._add(models[i], options); + } + } else { + this._add(models, options); + } + return this; + }, + + // Remove a model, or a list of models from the set. Pass silent to avoid + // firing the `removed` event for every model removed. + remove : function(models, options) { + if (_.isArray(models)) { + for (var i = 0, l = models.length; i < l; i++) { + this._remove(models[i], options); + } + } else { + this._remove(models, options); + } + return this; + }, + + // Get a model from the set by id. + get : function(id) { + if (id == null) return null; + return this._byId[id.id != null ? id.id : id]; + }, + + // Get a model from the set by client id. + getByCid : function(cid) { + return cid && this._byCid[cid.cid || cid]; + }, + + // Get the model at the given index. + at: function(index) { + return this.models[index]; + }, + + // Force the collection to re-sort itself. You don't need to call this under normal + // circumstances, as the set will maintain sort order as each item is added. + sort : function(options) { + options || (options = {}); + if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); + this.models = this.sortBy(this.comparator); + if (!options.silent) this.trigger('reset', this, options); + return this; + }, + + // Pluck an attribute from each model in the collection. + pluck : function(attr) { + return _.map(this.models, function(model){ return model.get(attr); }); + }, + + // When you have more items than you want to add or remove individually, + // you can reset the entire set with a new list of models, without firing + // any `added` or `removed` events. Fires `reset` when finished. + reset : function(models, options) { + models || (models = []); + options || (options = {}); + this.each(this._removeReference); + this._reset(); + this.add(models, {silent: true}); + if (!options.silent) this.trigger('reset', this, options); + return this; + }, + + // Fetch the default set of models for this collection, resetting the + // collection when they arrive. If `add: true` is passed, appends the + // models to the collection instead of resetting. + fetch : function(options) { + options || (options = {}); + var collection = this; + var success = options.success; + options.success = function(resp, status, xhr) { + collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options); + if (success) success(collection, resp); + }; + options.error = wrapError(options.error, collection, options); + return (this.sync || Backbone.sync).call(this, 'read', this, options); + }, + + // Create a new instance of a model in this collection. After the model + // has been created on the server, it will be added to the collection. + // Returns the model, or 'false' if validation on a new model fails. + create : function(model, options) { + var coll = this; + options || (options = {}); + model = this._prepareModel(model, options); + if (!model) return false; + var success = options.success; + options.success = function(nextModel, resp, xhr) { + coll.add(nextModel, options); + if (success) success(nextModel, resp, xhr); + }; + model.save(null, options); + return model; + }, + + // **parse** converts a response into a list of models to be added to the + // collection. The default implementation is just to pass it through. + parse : function(resp, xhr) { + return resp; + }, + + // Proxy to _'s chain. Can't be proxied the same way the rest of the + // underscore methods are proxied because it relies on the underscore + // constructor. + chain: function () { + return _(this.models).chain(); + }, + + // Reset all internal state. Called when the collection is reset. + _reset : function(options) { + this.length = 0; + this.models = []; + this._byId = {}; + this._byCid = {}; + }, + + // Prepare a model to be added to this collection + _prepareModel: function(model, options) { + if (!(model instanceof Backbone.Model)) { + var attrs = model; + model = new this.model(attrs, {collection: this}); + if (model.validate && !model._performValidation(attrs, options)) model = false; + } else if (!model.collection) { + model.collection = this; + } + return model; + }, + + // Internal implementation of adding a single model to the set, updating + // hash indexes for `id` and `cid` lookups. + // Returns the model, or 'false' if validation on a new model fails. + _add : function(model, options) { + options || (options = {}); + model = this._prepareModel(model, options); + if (!model) return false; + var already = this.getByCid(model); + if (already) throw new Error(["Can't add the same model to a set twice", already.id]); + this._byId[model.id] = model; + this._byCid[model.cid] = model; + var index = options.at != null ? options.at : + this.comparator ? this.sortedIndex(model, this.comparator) : + this.length; + this.models.splice(index, 0, model); + model.bind('all', this._onModelEvent); + this.length++; + if (!options.silent) model.trigger('add', model, this, options); + return model; + }, + + // Internal implementation of removing a single model from the set, updating + // hash indexes for `id` and `cid` lookups. + _remove : function(model, options) { + options || (options = {}); + model = this.getByCid(model) || this.get(model); + if (!model) return null; + delete this._byId[model.id]; + delete this._byCid[model.cid]; + this.models.splice(this.indexOf(model), 1); + this.length--; + if (!options.silent) model.trigger('remove', model, this, options); + this._removeReference(model); + return model; + }, + + // Internal method to remove a model's ties to a collection. + _removeReference : function(model) { + if (this == model.collection) { + delete model.collection; + } + model.unbind('all', this._onModelEvent); + }, + + // Internal method called every time a model in the set fires an event. + // Sets need to update their indexes when models change ids. All other + // events simply proxy through. "add" and "remove" events that originate + // in other collections are ignored. + _onModelEvent : function(ev, model, collection, options) { + if ((ev == 'add' || ev == 'remove') && collection != this) return; + if (ev == 'destroy') { + this._remove(model, options); + } + if (model && ev === 'change:' + model.idAttribute) { + delete this._byId[model.previous(model.idAttribute)]; + this._byId[model.id] = model; + } + this.trigger.apply(this, arguments); + } + + }); + + // Underscore methods that we want to implement on the Collection. + var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect', + 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', + 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size', + 'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty', 'groupBy']; + + // Mix in each Underscore method as a proxy to `Collection#models`. + _.each(methods, function(method) { + Backbone.Collection.prototype[method] = function() { + return _[method].apply(_, [this.models].concat(_.toArray(arguments))); + }; + }); + + // Backbone.Router + // ------------------- + + // Routers map faux-URLs to actions, and fire events when routes are + // matched. Creating a new one sets its `routes` hash, if not set statically. + Backbone.Router = function(options) { + options || (options = {}); + if (options.routes) this.routes = options.routes; + this._bindRoutes(); + this.initialize.apply(this, arguments); + }; + + // Cached regular expressions for matching named param parts and splatted + // parts of route strings. + var namedParam = /:([\w\d]+)/g; + var splatParam = /\*([\w\d]+)/g; + var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g; + + // Set up all inheritable **Backbone.Router** properties and methods. + _.extend(Backbone.Router.prototype, Backbone.Events, { + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize : function(){}, + + // Manually bind a single named route to a callback. For example: + // + // this.route('search/:query/p:num', 'search', function(query, num) { + // ... + // }); + // + route : function(route, name, callback) { + Backbone.history || (Backbone.history = new Backbone.History); + if (!_.isRegExp(route)) route = this._routeToRegExp(route); + Backbone.history.route(route, _.bind(function(fragment) { + var args = this._extractParameters(route, fragment); + callback.apply(this, args); + this.trigger.apply(this, ['route:' + name].concat(args)); + }, this)); + }, + + // Simple proxy to `Backbone.history` to save a fragment into the history. + navigate : function(fragment, triggerRoute) { + Backbone.history.navigate(fragment, triggerRoute); + }, + + // Bind all defined routes to `Backbone.history`. We have to reverse the + // order of the routes here to support behavior where the most general + // routes can be defined at the bottom of the route map. + _bindRoutes : function() { + if (!this.routes) return; + var routes = []; + for (var route in this.routes) { + routes.unshift([route, this.routes[route]]); + } + for (var i = 0, l = routes.length; i < l; i++) { + this.route(routes[i][0], routes[i][1], this[routes[i][1]]); + } + }, + + // Convert a route string into a regular expression, suitable for matching + // against the current location hash. + _routeToRegExp : function(route) { + route = route.replace(escapeRegExp, "\\$&") + .replace(namedParam, "([^\/]*)") + .replace(splatParam, "(.*?)"); + return new RegExp('^' + route + '$'); + }, + + // Given a route, and a URL fragment that it matches, return the array of + // extracted parameters. + _extractParameters : function(route, fragment) { + return route.exec(fragment).slice(1); + } + + }); + + // Backbone.History + // ---------------- + + // Handles cross-browser history management, based on URL fragments. If the + // browser does not support `onhashchange`, falls back to polling. + Backbone.History = function() { + this.handlers = []; + _.bindAll(this, 'checkUrl'); + }; + + // Cached regex for cleaning hashes. + var hashStrip = /^#*/; + + // Cached regex for detecting MSIE. + var isExplorer = /msie [\w.]+/; + + // Has the history handling already been started? + var historyStarted = false; + + // Set up all inheritable **Backbone.History** properties and methods. + _.extend(Backbone.History.prototype, { + + // The default interval to poll for hash changes, if necessary, is + // twenty times a second. + interval: 50, + + // Get the cross-browser normalized URL fragment, either from the URL, + // the hash, or the override. + getFragment : function(fragment, forcePushState) { + if (fragment == null) { + if (this._hasPushState || forcePushState) { + fragment = window.location.pathname; + var search = window.location.search; + if (search) fragment += search; + } else { + fragment = window.location.hash; + } + } + fragment = decodeURIComponent(fragment.replace(hashStrip, '')); + if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length); + return fragment; + }, + + // Start the hash change handling, returning `true` if the current URL matches + // an existing route, and `false` otherwise. + start : function(options) { + + // Figure out the initial configuration. Do we need an iframe? + // Is pushState desired ... is it available? + if (historyStarted) throw new Error("Backbone.history has already been started"); + this.options = _.extend({}, {root: '/'}, this.options, options); + this._wantsPushState = !!this.options.pushState; + this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState); + var fragment = this.getFragment(); + var docMode = document.documentMode; + var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); + if (oldIE) { + this.iframe = $('