This commit is contained in:
Ruben Müller 2014-12-07 20:58:53 +01:00
parent 760c1838ed
commit 1de7efa943
3952 changed files with 0 additions and 552900 deletions

1
node_modules/.bin/browser-sync generated vendored
View file

@ -1 +0,0 @@
../browser-sync/bin/browser-sync

1
node_modules/.bin/gulp generated vendored
View file

@ -1 +0,0 @@
../gulp/bin/gulp.js

596
node_modules/browser-sync/LICENSE-GPL generated vendored
View file

@ -1,596 +0,0 @@
GNU GENERAL PUBLIC LICENSE
==========================
Version 3, 29 June 2007
Copyright &copy; 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;
Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.
## Preamble
The GNU General Public License is a free, copyleft license for software and other
kinds of works.
The licenses for most software and other practical works are designed to take away
your freedom to share and change the works. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change all versions of a
program--to make sure it remains free software for all its users. We, the Free
Software Foundation, use the GNU General Public License for most of our software; it
applies also to any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General
Public Licenses are designed to make sure that you have the freedom to distribute
copies of free software (and charge for them if you wish), that you receive source
code or can get it if you want it, that you can change the software or use pieces of
it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or
asking you to surrender the rights. Therefore, you have certain responsibilities if
you distribute copies of the software, or if you modify it: responsibilities to
respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee,
you must pass on to the recipients the same freedoms that you received. You must make
sure that they, too, receive or can get the source code. And you must show them these
terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert
copyright on the software, and (2) offer you this License giving you legal permission
to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is
no warranty for this free software. For both users' and authors' sake, the GPL
requires that modified versions be marked as changed, so that their problems will not
be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of
the software inside them, although the manufacturer can do so. This is fundamentally
incompatible with the aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we have designed
this version of the GPL to prohibit the practice for those products. If such problems
arise substantially in other domains, we stand ready to extend this provision to
those domains in future versions of the GPL, as needed to protect the freedom of
users.
Finally, every program is threatened constantly by software patents. States should
not allow patents to restrict development and use of software on general-purpose
computers, but in those that do, we wish to avoid the special danger that patents
applied to a free program could make it effectively proprietary. To prevent this, the
GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
## TERMS AND CONDITIONS
### 0. Definitions.
&ldquo;This License&rdquo; refers to version 3 of the GNU General Public License.
&ldquo;Copyright&rdquo; also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
&ldquo;The Program&rdquo; refers to any copyrightable work licensed under this
License. Each licensee is addressed as &ldquo;you&rdquo;. &ldquo;Licensees&rdquo; and
&ldquo;recipients&rdquo; may be individuals or organizations.
To &ldquo;modify&rdquo; 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 &ldquo;modified version&rdquo; of the earlier work or a
work &ldquo;based on&rdquo; the earlier work.
A &ldquo;covered work&rdquo; means either the unmodified Program or a work based on
the Program.
To &ldquo;propagate&rdquo; 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 &ldquo;convey&rdquo; 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 &ldquo;Appropriate Legal Notices&rdquo; 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 &ldquo;source code&rdquo; for a work means the preferred form of the work for
making modifications to it. &ldquo;Object code&rdquo; means any non-source form of a
work.
A &ldquo;Standard Interface&rdquo; 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 &ldquo;System Libraries&rdquo; 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 &ldquo;Major Component&rdquo;, 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 &ldquo;Corresponding Source&rdquo; 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 &ldquo;keep intact all notices&rdquo;.
* **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 &ldquo;aggregate&rdquo; 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 &ldquo;User Product&rdquo; is either (1) a &ldquo;consumer product&rdquo;, 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, &ldquo;normally used&rdquo; 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.
&ldquo;Installation Information&rdquo; 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.
&ldquo;Additional permissions&rdquo; 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 &ldquo;further
restrictions&rdquo; 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 &ldquo;entity transaction&rdquo; 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 &ldquo;contributor&rdquo; 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 &ldquo;contributor version&rdquo;.
A contributor's &ldquo;essential patent claims&rdquo; 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, &ldquo;control&rdquo; 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 &ldquo;patent license&rdquo; 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 &ldquo;grant&rdquo; 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. &ldquo;Knowingly relying&rdquo; 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 &ldquo;discriminatory&rdquo; if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on the
non-exercise of one or more of the rights that are specifically granted under this
License. You may not convey a covered work if you are a party to an arrangement with
a third party that is in the business of distributing software, under which you make
payment to the third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties who would receive
the covered work from you, a discriminatory patent license (a) in connection with
copies of the covered work conveyed by you (or copies made from those copies), or (b)
primarily for and in connection with specific products or compilations that contain
the covered work, unless you entered into that arrangement, or that patent license
was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied
license or other defenses to infringement that may otherwise be available to you
under applicable patent law.
### 12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise)
that contradict the conditions of this License, they do not excuse you from the
conditions of this License. If you cannot convey a covered work so as to satisfy
simultaneously your obligations under this License and any other pertinent
obligations, then as a consequence you may not convey it at all. For example, if you
agree to terms that obligate you to collect a royalty for further conveying from
those to whom you convey the Program, the only way you could satisfy both those terms
and this License would be to refrain entirely from conveying the Program.
### 13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or
combine any covered work with a work licensed under version 3 of the GNU Affero
General Public License into a single combined work, and to convey the resulting work.
The terms of this License will continue to apply to the part which is the covered
work, but the special requirements of the GNU Affero General Public License, section
13, concerning interaction through a network will apply to the combination as such.
### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU
General Public License from time to time. Such new versions will be similar in spirit
to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that
a certain numbered version of the GNU General Public License &ldquo;or any later
version&rdquo; applies to it, you have the option of following the terms and
conditions either of that numbered version or of any later version published by the
Free Software Foundation. If the Program does not specify a version number of the GNU
General Public License, you may choose any version ever published by the Free
Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU
General Public License can be used, that proxy's public statement of acceptance of a
version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no
additional obligations are imposed on any author or copyright holder as a result of
your choosing to follow a later version.
### 15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM &ldquo;AS IS&rdquo; 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 &ldquo;copyright&rdquo; line and a pointer to
where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this
when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type 'show c' for details.
The hypothetical commands 'show w' and 'show c' should show the appropriate parts of
the General Public License. Of course, your program's commands might be different;
for a GUI interface, you would use an &ldquo;about box&rdquo;.
You should also get your employer (if you work as a programmer) or school, if any, to
sign a &ldquo;copyright disclaimer&rdquo; for the program, if necessary. For more
information on this, and how to apply and follow the GNU GPL, see
&lt;<http://www.gnu.org/licenses/>&gt;.
The GNU General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may consider it
more useful to permit linking proprietary applications with the library. If this is
what you want to do, use the GNU Lesser General Public License instead of this
License. But first, please read
&lt;<http://www.gnu.org/philosophy/why-not-lgpl.html>&gt;.

97
node_modules/browser-sync/README.md generated vendored
View file

@ -1,97 +0,0 @@
# BrowserSync [![Build status] (https://ci.appveyor.com/api/projects/status/r5vung2ipn9uj4sy)](https://ci.appveyor.com/project/shakyShane/browser-sync) [![Build Status](http://img.shields.io/travis/shakyShane/browser-sync/master.svg?style=flat)] (https://travis-ci.org/shakyShane/browser-sync) [![Coverage Status](https://img.shields.io/coveralls/shakyShane/browser-sync.svg?style=flat)](https://coveralls.io/r/shakyShane/browser-sync?branch=master) [![NPM version](https://img.shields.io/npm/v/browser-sync.svg?style=flat)](http://npmjs.org/package/browser-sync)
> Keep multiple browsers & devices in sync when building websites.
<a href="http://www.wearejh.com"><img src="http://cl.ly/image/3Y3O0M2z310j/jh-100-red.png" /></a>
BrowserSync is developed and maintained internally at <a href="http://www.wearejh.com">JH</a>, follow <a href="http://www.twitter.com/browsersync">@BrowserSync</a> on twitter for news & updates.
##Features
1. **Scroll** - I can keep your pages in sync when scrolling.
2. **Forms** - You fill out a form in one browser, I'll copy the data to all the others.
3. **Links** - I'll watch your clicks and make all the other browsers follow you.
4. **CSS injecting** - I can even watch your CSS files & inject them when they change.
5. **Live Reload** - I can also watch files like HTML and PHP & when they change I can reload all browsers for you.
6. **Built-in Server** - Yep, I can serve static files too if you need me to (uses Connect).
7. **Use with any back-end setup** - I even have a proxy option so that I can be used with existing PHP, Rails, Python, Node or ASP.net setup.
8. **Public URL** - View your website via a URL that any internet connected device can access & maintain all BrowserSync features.
9. **Browser Stack support** - Use the all of my features when viewing your site through Browser Stack.
##When is it useful?
It's pretty useful when used with a single browser, watching a CSS file for changes & injecting it. But the real power comes when you're building responsive sites and using multiple devices/monitors because it can keep all browsers in sync & make your workflow much faster.
##Requirements
BrowserSync works by injecting an asynchronous script tag (`<script async>...</script>`) right after the `<body>` tag
during initial request. In order for this to work properly the `<body>` tag must be present. Alternatively you
can provide a custom rule for the snippet using [snippetOptions](http://www.browsersync.io/docs/options/#option-snippetOptions)
##Install
```
npm install -g browser-sync
```
##How to use it
1. [Command line](http://www.browsersync.io/docs/command-line/)
2. [API](http://www.browsersync.io/docs/api/)
## Using Grunt?
There's a [separate plugin](https://github.com/shakyShane/grunt-browser-sync) for that
## Using Gulp?
No problem, here's a [setup guide](http://www.browsersync.io/docs/gulp)
## Using Brunch?
Enjoy the [browser-sync-brunch plugin](https://github.com/ocombe/browser-sync-brunch)
## Screencasts
[Some listed here](https://github.com/shakyShane/browser-sync/wiki/Screencasts)
Want any more? Something specific? ask me nicely [@shaneOsbourne](http://www.twitter.com/shaneOsbourne)
##Support
If you've found Browser-sync useful and would like to contribute to its continued development & support, please feel free to send a donation of any size - it would be greatly appreciated!
[![Support via Gittip](https://rawgithub.com/chris---/Donation-Badges/master/gittip.jpeg)](https://www.gittip.com/shakyshane)
[![Support via PayPal](https://rawgithub.com/chris---/Donation-Badges/master/paypal.jpeg)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=shakyshane%40gmail%2ecom&lc=US&item_name=browser%2dsync)
## Contributors
```
778 Shane Osbourne
29 Shinnosuke Watanabe
19 Shane Daniel
13 Hugo Bessa
11 Paul Kinlan
8 shinnn
3 Marek 'saji' Augustynowicz
3 Werner van Deventer
3 Adam Lynch
2 Paul Robertson
2 Dan Tello
2 Hugo Dias
2 Michael Branch
2 Olivier Combe
2 Piotr Kaleta
2 brutaldev
2 chase_chou
1 Dave Hall
1 mericson
1 Robert Vock
1 Craig Morris
1 Cedric Kastner
1 Carl Henderson
1 Sylvain Emery
1 Tony Holdstock-Brown
1 Victor Fernandez de Alba
1 Cameron Spear
1 Yazhong Liu
1 Jory Graham
1 Benjamín Eidelman
1 viktor hesselbom
1 Guillaume Lambert
1 Peter Blazejewicz
```
## License
Copyright (c) 2014 Shane Osbourne
Licensed under the GPL license.

View file

@ -1,28 +0,0 @@
#!/usr/bin/env node
"use strict";
var cli = require("../lib/cli/index");
var pjson = require("../package.json");
var utils = require("../lib/utils");
var init = cli.init;
var info = cli.info;
var BrowserSync = require("../lib/browser-sync");
var browserSync = new BrowserSync();
var argv = process.argv;
var args = require("minimist")(argv.slice(2));
init.parse(pjson.version, args, argv, function (err, data) {
if (err) {
utils.fail(err, {}, true);
}
if (data.config) {
browserSync.init(data.files || [], data.config, pjson.version);
}
if (data.configFile) {
info.makeConfig(browserSync.cwd);
}
});

80
node_modules/browser-sync/index.js generated vendored
View file

@ -1,80 +0,0 @@
#! /usr/bin/env node
"use strict";
/**
* @module BrowserSync
*/
var pjson = require("./package.json");
var BrowserSync = require("./lib/browser-sync");
var browserSync = new BrowserSync();
/**
* @method browserSync
* @param {Object} [config] This is the main configuration for your BrowserSync instance and can contain any of the [available options]({{site.links.options}})
* If you do not pass a config an argument for configuration, BrowserSync will still run; but it will be in the `snippet` mode
* @param {Function} [cb] If you pass a callback function, it will be called when BrowserSync has completed all setup tasks and is ready to use. This
* is useful when you need to wait for information (for example: urls, port etc) or perform other tasks synchronously.
* @returns {BrowserSync}
*/
var publicInit = require("./lib/public/init")(browserSync, pjson);
module.exports = publicInit;
module.exports.init = publicInit;
/**
* The `reload` method will inform all browsers about changed files and will either cause the browser to refresh, or inject the files where possible.
*
* @method reload
* @param {String|Array|Object} [arg] The file or files to be reloaded. For
* details and examples of Streams support, please see the [GulpJS]({{site.links.gulp}}) examples
* @returns {*}
*/
module.exports.reload = require("./lib/public/reload")(browserSync);
/**
* Helper method for browser notifications
*
* @method notify
* @param {String|HTML} msg Can be a simple message such as 'Connected' or HTML
* @param {Number} [timeout] How long the message will remain in the browser. @since 1.3.0
*/
module.exports.notify = require("./lib/public/notify")(browserSync);
/**
* Register a plugin. Must implement at least a 'plugin' method that returns a
* callable function.
*
* @method use
* @param {String} name The name of the plugin
* @param {Object} module The object to be `required`.
* @param {Function} [cb] A callback function that will return any errors.
*/
module.exports.use = browserSync.registerPlugin.bind(browserSync);
/**
* The internal Event Emitter used by the running BrowserSync instance (if there is one).
* You can use this to emit your own events, such as changed files, logging etc.
*
* @property emitter
* @type Events.EventEmitter
*/
module.exports.emitter = browserSync.events;
/**
* This method will close any running server, stop file watching & exit the current process.
*
* @method exit
*/
module.exports.exit = require("./lib/public/exit")(browserSync);
/**
* A simple true/false flag that you can use to determine if there's a currently-running BrowserSync instance.
*
* @property active
*/
Object.defineProperty(module.exports, "active", {
get: function () {
return browserSync.active;
}
});

View file

@ -1,71 +0,0 @@
"use strict";
function isFilesArg (arg) {
return Array.isArray(arg) || typeof arg === "string";
}
/**
* Handle arguments for backwards compatibility
* @param {Object} args
* @returns {{config: {}, cb: *}}
*/
module.exports = function (args) {
var config = {};
var cb;
switch (args.length) {
case 1 :
if (isFilesArg(args[0])) {
config.files = args[0];
} else if (typeof args[0] === "function") {
cb = args[0];
} else {
config = args[0];
}
break;
case 2 :
// if second is a function, first MUST be config
if (typeof args[1] === "function") {
config = args[0] || {};
cb = args[1];
} else {
config = args[1] || {};
if (!config.files) {
config.files = args[0];
}
}
break;
case 3 :
config = args[1] || {};
if (!config.files) {
config.files = args[0];
}
cb = args[2];
}
return {
config: config,
cb: cb
};
};

View file

@ -1,436 +0,0 @@
"use strict";
var services = require("./services");
var hooks = require("./hooks");
var config = require("./config");
var messages = require("./messages");
var utils = require("./utils");
var logger = require("./logger");
var _ = require("lodash");
var EE = require("easy-extender");
var filePath = require("path");
var events = require("events");
var objectPath = require("object-path");
/**
* Required internal plugin, all can be overridden.
*/
var defaultPlugins = {
"logger": logger,
"socket": require("./sockets"),
"file:watcher": require("./file-watcher"),
"server": require("./server"),
"tunnel": require("./tunnel"),
"client:script": require("browser-sync-client")
};
/**
* @constructor
*/
var BrowserSync = function () {
this.cwd = process.cwd();
this.active = false;
this.config = config;
// Events
this.events = new events.EventEmitter();
this.events.setMaxListeners(20);
this._reloadQueue = [];
this._browserReload = false;
// Plugin management
this.pluginManager = new EE(defaultPlugins, hooks);
this._userPlugins = [];
this.clientEvents = [
"scroll",
"input:text",
"input:toggles",
"form:submit",
"form:reset",
"click"
];
};
/**
* @param module
* @param opts
* @param cb
*/
BrowserSync.prototype.registerPlugin = function (module, opts, cb) {
this.pluginManager.registerPlugin(module, opts, cb);
if (module["plugin:name"]) {
this._userPlugins.push(module);
}
};
/**
* @param {Function} [filter]
*/
BrowserSync.prototype.getUserPlugins = function (filter) {
filter = filter || function () {
return true;
};
/**
* Transform Plugins option
*/
this.userPlugins = this._userPlugins.filter(filter).map(function (plugin) {
return {
name: plugin["plugin:name"],
active: plugin._enabled
};
});
return this.userPlugins;
};
/**
* Get middleware
* @returns {*}
*/
BrowserSync.prototype.getMiddleware = function (type) {
var types = {
"connector": messages.socketConnector(this.options.port, this.options, true),
"socket-js": require("./snippet").utils.getSocketScript()
};
if (type in types) {
return function (req, res) {
res.setHeader("Content-Type", "text/javascript");
res.end(types[type]);
};
}
};
/**
* @param {Array} files
* @param {Object} options
* @param {String} version
* @param {Function} cb
* @returns {BrowserSync}
*/
BrowserSync.prototype.init = function (files, options, version, cb) {
var err;
this.version = options.version = version;
this.cb = cb;
this.pluginManager.init();
this.pluginManager.wrap(require("localtunnel"), "tunnel:runner");
this.logger = this.pluginManager.get("logger")(this.events, options);
this.debugger = this.logger.clone({useLevelPrefixes: true});
this.debug = this.debugger.debug;
// Die if both server & proxy options provided
if (options.server && options.proxy) {
err = "Invalid config. You cannot specify both a server & proxy option.";
this.events.emit("config:error", {msg: err});
return utils.fail(true, err, this.cb);
}
this.debug("Looking for an empty port...");
utils.getPorts(options)
.then(this.handleSuccess.bind(this, options))
.catch(this.handleError.bind(this, options));
return this;
};
/**
* @param options
* @param err
*/
BrowserSync.prototype.handleError = function (options, err) {
this.logger.mute(false).error(err);
utils.fail(true, err, this.cb);
};
/**
* @param options
* @param ports
*/
BrowserSync.prototype.handleSuccess = function (options, ports) {
var debug = this.debug;
debug("Using port {magenta:%s", ports[0]);
options.port = ports[0];
var init = function () {
services.init(this)(options);
}.bind(this);
if (_.isUndefined(options.online) && _.isUndefined(process.env.TESTING)) {
debug("Checking if you're online");
require("dns").resolve("www.google.com", function (err) {
if (err) {
debug("Could not resolve www.google.com, setting {magenta:online: false}");
options.online = false;
} else {
debug("Resolved www.google.com, setting {magenta:online: true}");
options.online = true;
}
init();
});
} else {
init();
}
};
/**
* Callback helper
* @param err
* @param [data]
*/
BrowserSync.prototype.callback = function (err, data) {
if (_.isFunction(this.cb)) {
this.cb(err, data, this);
}
this.events.emit("service:ready");
};
/**
* Callback helper
* @param name
* @param [defaultValue]
*/
BrowserSync.prototype.getOption = function (name, defaultValue) {
this.debug("Getting option: {magenta:%s", name);
return objectPath.get(this.options, name, defaultValue);
};
/**
* @returns {BrowserSync.options}
*/
BrowserSync.prototype.getOptions = function () {
return this.options;
};
/**
* @returns {BrowserSync.options}
*/
BrowserSync.prototype.getLogger = logger.getLogger;
/**
* @param {String} name
* @param {*} value
* @returns {BrowserSync.options|*}
*/
BrowserSync.prototype.setOption = function (name, value) {
var objectPath = require("object-path");
if (!_.isUndefined(objectPath.get(this.options, name))) {
this.debug("Setting option: {magenta:%s", name);
objectPath.set(this.options, name, value);
this.events.emit("options:set", {name: name, value: value, options: this.options});
}
return this.options;
};
/**
* Internal Events
* @param {Object} options
*/
BrowserSync.prototype.registerInternalEvents = function (options) {
var events = {
"file:changed": function (data) {
if (data.namespace === "core") {
if (_.isUndefined(data.log)) {
data.log = this.getOption("logFileChanges");
}
this.changeFile(data, options);
}
},
"file:reload": function (data) {
this.doFileReload(data);
},
"browser:reload": function () {
this.doBrowserReload();
},
"browser:notify": function (data) {
this.io.sockets.emit("browser:notify", data);
},
/**
* Things that happened after the service is running
* @param data
*/
"service:running": function (data) {
if (data.type !== "snippet") {
utils.openBrowser(data.url, options);
}
// log about any file watching
if (this.watchers) {
this.events.emit("file:watching", this.watchers);
}
},
"options:set": function (data) {
this.io.sockets.emit("options:set", data);
},
"init": function () {
this.active = true;
},
"plugins:configure": function (data) {
if (data.active) {
this.pluginManager.enablePlugin(data.name);
} else {
this.pluginManager.disablePlugin(data.name);
}
this.options.userPlugins = this.getUserPlugins();
}
};
_.each(events, function (func, event) {
this.events.on(event, func.bind(this));
}, this);
};
/**
* Handle Browser Reloads
*/
BrowserSync.prototype.doBrowserReload = function () {
var bs = this;
if (bs._browserReload) {
return;
}
bs._browserReload = setTimeout(function () {
bs.io.sockets.emit("browser:reload");
clearTimeout(bs._browserReload);
bs._browserReload = false;
}, this.getOption("reloadDelay"));
};
/**
* Handle a queue of reloads
* @param {Object} data
*/
BrowserSync.prototype.doFileReload = function (data) {
var bs = this;
bs._reloadQueue = bs._reloadQueue || [];
bs._reloadQueue.push(data);
if (bs._reloadTimer) {
return;
}
bs._reloadTimer = setTimeout(function () {
if (utils.willCauseReload(bs._reloadQueue.map(function (item) { return item.path; }), bs.getOption("injectFileTypes"))) {
bs.io.sockets.emit("browser:reload");
} else {
bs._reloadQueue.forEach(function (item) {
bs.io.sockets.emit("file:reload", item);
});
}
clearTimeout(bs._reloadTimer);
bs._reloadTimer = undefined;
bs._reloadQueue = [];
}, bs.getOption("reloadDelay"));
};
/**
* Instance Cleanup
*/
BrowserSync.prototype.cleanup = function (cb) {
if (!this.active) {
return;
}
// Close any servers
if (this.server) {
this.debug("Closing server...");
this.server.close();
}
// Stop any file watching
if (this.watchers) {
this.debug("Stopping watchers...");
_.each(this.watchers, function (item) {
item.watcher.end();
});
}
// Remove all event listeners
if (this.events) {
this.debug("Removing event listeners...");
this.events.removeAllListeners();
}
// Reset the flag
this.debug("Setting {magenta:active: false");
this.active = false;
this.pluginManager.plugins = {};
this.pluginManager.pluginOptions = {};
this._userPlugins = [];
this._reloadTimer = undefined;
this._reloadQueue = undefined;
if (_.isFunction(cb)) {
cb(null);
}
};
/**
* @param {Object} data
* @param {Object} options
* @returns {{assetFileName: String}}
*/
BrowserSync.prototype.changeFile = function (data, options) {
var path = data.path;
var fileName = filePath.basename(path);
var fileExtension = utils.getFileExtension(path);
var obj = {
assetFileName: fileName,
fileExtension: fileExtension
};
var message = "inject";
// RELOAD page
if (!_.contains(options.injectFileTypes, fileExtension)) {
obj.url = path;
message = "reload";
}
obj.cwd = this.cwd;
obj.path = path;
obj.type = message;
obj.log = data.log;
// emit the event through socket
this.events.emit("file:reload", obj);
return obj;
};
module.exports = BrowserSync;

View file

@ -1,66 +0,0 @@
"use strict";
var config = require("./../config");
var utils = require("./../utils");
var logger = require("./../logger").logger;
var fs = require("fs");
var _ = require("lodash");
var path = require("path");
var info = {
/**
* Version info
* @param {Object} pjson
* @returns {String}
*/
getVersion: function (pjson) {
console.log(pjson.version);
return pjson.version;
},
/**
* Retrieve the config file
* @returns {*}
* @private
* @param filePath
*/
_getConfigFile: function (filePath) {
var relPath = path.resolve(process.cwd() + "/" + filePath);
if (fs.existsSync(relPath)) {
return require(relPath);
}
return false;
},
/**
* Generate an example Config file.
*/
makeConfig: function (cwd) {
var opts = require(__dirname + "/../" + config.configFile);
var userOpts = {};
var ignore = ["excludedFileTypes", "injectFileTypes"];
Object.keys(opts).forEach(function (key) {
if (!_.contains(ignore, key)) {
userOpts[key] = opts[key];
}
});
var file = fs.readFileSync(__dirname + config.template);
file = file.toString().replace("//OPTS", JSON.stringify(userOpts, null, 4));
var path = cwd + config.userFile;
fs.writeFile(path, file, function () {
logger.info("Config file created {magenta:%s}", utils.resolveRelativeFilePath(path, cwd));
logger.info(
"To use it, in the same directory run: " +
"{cyan:browser-sync start --config bs-config.js}"
);
});
}
};
module.exports = info;

View file

@ -1,91 +0,0 @@
"use strict";
var defaultConfig = require("./../default-config");
var cliOptions = require("./cli-options");
var info = require("./cli-info");
var opts = require("./opts.json");
var tfunk = require("tfunk");
var program = require("commander");
var merge = require("opt-merger").merge;
module.exports.allowedOptions = ["host", "server", "proxy"];
/**
* Handle command-line usage with 'start'
* @param args
* @param cb
*/
module.exports.startFromCommandLine = function (args, cb) {
var userConfig;
// First look for provided --config option
if (args.config) {
userConfig = info._getConfigFile(args.config);
}
var options = merge(defaultConfig, userConfig || {}, cliOptions.callbacks);
cb(null, {
files: options.files || [],
config: options
});
};
/**
* @param {String} version
* @param {Object} args - minimist object
* @param {Object} argv
* @param {Function} cb
*/
module.exports.parse = function (version, args, argv, cb) {
program
.version(version)
.usage("<command> [options]");
Object.keys(opts).forEach(function (key) {
program.option(key, opts[key]);
});
program
.on("--help", exports.help);
program
.command("init")
.description("Creates a default config file")
.action(function () {
cb(null, {configFile: true});
});
program
.command("start")
.description("Start Browser Sync")
.action(exports.startFromCommandLine.bind(null, args, cb));
program.parse(argv);
if (!args._.length) {
program.help();
}
};
/**
* Help screen
*/
module.exports.help = function () {
console.log(tfunk(" {bold:Server Example:"));
console.log(" ---------------");
console.log(" Use current directory as root & watch CSS files");
console.log("");
console.log(tfunk(" {magenta:$}{cyan: browser-sync start --server --files=\"css/*.css\""));
console.log("");
console.log(tfunk(" {bold:Proxy Example:"));
console.log(" --------------");
console.log(" Proxy `localhost:8080` & watch CSS files");
console.log("");
console.log(tfunk(" {magenta:$}{cyan: browser-sync start --proxy=\"localhost:8080\" --files=\"css/*.css\""));
console.log("");
};

View file

@ -1,266 +0,0 @@
"use strict";
var path = require("path");
var _ = require("lodash");
var utils = {
/**
* @param pattern
* @returns {*|string}
* @private
*/
wrapPattern: function (pattern) {
var prefix = "!";
var suffix = "/**";
var lastChar = pattern.charAt(pattern.length - 1);
var extName = path.extname(pattern);
// If there's a file ext, don't append any suffix
if (extName.length) {
suffix = "";
} else {
if (lastChar === "/") {
suffix = "**";
}
if (lastChar === "*") {
suffix = "";
}
}
return [prefix, pattern, suffix].join("");
}
};
module.exports.utils = utils;
module.exports.callbacks = {
/**
* Merge server options
* @param defaultValue
* @param merged
* @param newValue
* @param args
* @returns {*}
*/
server: function (defaultValue, merged, newValue, args) {
// Return if object or array given
if (typeof merged === "undefined" || merged === false) {
return defaultValue;
}
if (newValue.baseDir) {
return newValue;
}
var obj = {
baseDir: "./"
};
if (newValue !== true) {
obj.baseDir = newValue;
}
if (args) {
if (args.index) {
obj.index = args.index;
}
if (args.directory) {
obj.directory = true;
}
}
return obj;
},
/**
* @param defaultValue
* @param newValue
* @returns {*}
*/
proxy: function (defaultValue, newValue) {
var protocol = "http";
var host = "localhost";
var port = 80;
var segs;
var startPath = false;
var returnObj;
if (typeof newValue !== "string") {
return false;
}
var url = newValue.replace(/^(https?):\/\//, function (match, solo) {
protocol = solo;
return "";
});
if (~url.indexOf(":")) {
segs = url.split(":");
host = segs[0];
port = parseInt(segs[1], 10);
} else {
host = url;
}
if (~host.indexOf("/")) {
segs = host.split("/");
host = segs.shift();
startPath = segs.join("/");
}
returnObj = {
protocol: protocol,
host: host,
port: port,
target: protocol + "://" + host + (port > 80 ? ":" + port : "")
};
if (startPath) {
returnObj.startPath = startPath;
}
return returnObj;
},
/**
* @param {Object} defaultValue
* @param {String} newValue
* @returns {String}
* @private
*/
host: function (defaultValue, newValue) {
if (newValue && typeof newValue === "string") {
return newValue;
}
return null;
},
/**
* @param defaultValue
* @param newValue
* @private
*/
ports: function (defaultValue, newValue) {
var segs;
var obj = {};
if (typeof newValue === "string") {
if (~newValue.indexOf(",")) {
segs = newValue.split(",");
obj.min = parseInt(segs[0], 10);
obj.max = parseInt(segs[1], 10);
} else {
obj.min = parseInt(newValue, 10);
obj.max = null;
}
return obj;
} else {
return {
min: newValue.min,
max: newValue.max || null
};
}
},
/**
* @param defaultValue
* @returns {*}
*/
ghostMode: function (defaultValue, merged, newValue, args) {
var def = _.cloneDeep(merged);
var trueAll = {
clicks: true,
scroll: true,
location: false,
forms: {
submit: true,
inputs: true,
toggles: true
}
};
var falseAll = {
clicks: false,
scroll: false,
location: false,
forms: {
submit: false,
inputs: false,
toggles: false
}
};
if (merged === false || merged === "false" || args && args.ghost === false) {
return falseAll;
}
if (merged === true || merged === "true" || args && args.ghost === true) {
return trueAll;
}
if (merged.forms === false || newValue === false || newValue === "false") {
def.forms = {
submit: false,
inputs: false,
toggles: false
};
}
if (merged.forms === true || newValue === true || newValue === "true") {
def.forms = {
submit: true,
inputs: true,
toggles: true
};
}
return def;
},
/**
* @param defaultValue
* @param newValue
* @param args
* @param config
* @returns {*}
*/
files: function (defaultValue, newValue, args, config) {
var merged = [];
var exclude = config && config.exclude ? config.exclude : false;
if (newValue) {
if (typeof newValue === "string") {
if (~newValue.indexOf(",")) {
merged = merged.concat(newValue.split(",").map(function (item) {
return item.trim();
}));
} else {
merged.push(newValue);
}
} else {
merged = newValue;
}
if (typeof exclude === "string") {
merged.push(utils.wrapPattern(exclude));
} else {
if (Array.isArray(exclude)) {
exclude.forEach(function (pattern) {
merged.push(utils.wrapPattern(pattern));
}, this);
}
}
}
return merged;
}
};

View file

@ -1,15 +0,0 @@
/*
|--------------------------------------------------------------------------
| Browser-sync config file
|--------------------------------------------------------------------------
|
| For up-to-date information about the options:
| http://www.browsersync.io/docs/options/
|
| There are more options than you see here, these are just the ones that are
| set internally. See the website for more info.
|
|
*/
module.exports = //OPTS;

View file

@ -1,7 +0,0 @@
"use strict";
module.exports = {
init: require("./cli-init"),
options: require("./cli-options"),
info: require("./cli-info")
};

View file

@ -1,21 +0,0 @@
{
"--files": "File paths to watch",
"--exclude": "File patterns to ignore",
"--server": "Run a Local server (uses your cwd as the web root)",
"--index": "Specify which file should be used as the index page",
"--startPath": "Specify the start path for the opened browser",
"--https": "Enable SSL for local development",
"--directory": "Show a directory listing for the server",
"--proxy": "Proxy an existing server",
"--xip": "Use xip.io domain routing",
"--tunnel": "Use a public URL",
"--open": "Choose which URL is auto-opened (local, external or tunnel)",
"--config": "Specify a path to a bs-config.js file",
"--host": "Specify a hostname to use",
"--logLevel": "Set the logger output level (silent, info or debug)",
"--port": "Specify a port to use",
"--no-notify": "Disable the notify element in browsers",
"--no-open": "Don't open a new browser window",
"--no-ghost": "Disable Ghost Mode",
"--no-online": "Force offline usage"
}

View file

@ -1,23 +0,0 @@
"use strict";
var path = require("path");
/**
* @type {{controlPanel: {jsFile: string, baseDir: *}, socketIoScript: string, configFile: string, client: {shims: string}}}
*/
module.exports = {
controlPanel: {
jsFile: "/js/app.js",
baseDir: path.resolve(__dirname + "/control-panel")
},
templates: {
scriptTag: path.resolve(__dirname + "/templates/script-tags.tmpl"),
connector: path.resolve(__dirname + "/templates/connector.tmpl")
},
socketIoScript: "/public/socket.io.js",
configFile: "/default-config.js",
userFile: "/bs-config.js",
template: "/cli-template.js",
client: {
shims: "/client/client-shims.js"
}
};

View file

@ -1,310 +0,0 @@
"use strict";
/**
* @module BrowserSync.options
*/
module.exports = {
/**
* BrowserSync can watch your files as you work. Changes you make will either
* be injected into the page (CSS & images) or will cause all browsers to do
* a full-page refresh. See [isaacs's minimatch](https://github.com/isaacs/minimatch) for more information on glob patterns.
* @property files
* @type Array|String
* @default false
*/
files: false,
/**
* File watching options that get passed along to [Gaze](https://github.com/shama/gaze). Check out the [properties](https://github.com/shama/gaze#properties)
* section of their docs to see which options they support.
* for availbable options
* @property watchOptions
* @type Object
* @default undefined
* @since 1.3.0
*/
/**
* Use the built-in static server for basic HTML/JS/CSS websites.
* @property server
* @type Object|Boolean
* @default false
*/
server: false,
/**
* Proxy an EXISTING vhost. BrowserSync will wrap your existing url and provide a different one to use.
* @property proxy
* @type String|Boolean
* @default false
*/
proxy: false,
/**
* @property port
* @type Number
* @default 3000
*/
port: 3000,
/**
* Enable https for localhost development. **Note:** Proxy and Tunnel not currently supported.
* @property https
* @type Boolean
* @default undefined
* @since 1.3.0
*/
/**
* @property ghostMode
* @param {Boolean} [clicks=true]
* @param {Boolean} [scroll=true]
* @param {Boolean} [location=false]
* @param {Boolean} [forms=true]
* @param {Boolean} [forms.submit=true]
* @param {Boolean} [forms.inputs=true]
* @param {Boolean} [forms.toggles=true]
* @type Object
*/
ghostMode: {
clicks: true,
scroll: true,
location: false,
forms: {
submit: true,
inputs: true,
toggles: true
}
},
/**
* Can be either "info", "debug", "warn", or "silent"
* @property logLevel
* @type String
* @default info
*/
logLevel: "info",
/**
* Change the console logging prefix. Useful if you're creating your
* own project based on BrowserSync
* @property logPrefix
* @type String
* @default BS
* @since 1.5.1
*/
logPrefix: "BS",
/**
* @property logConnections
* @type Boolean
* @default false
*/
logConnections: false,
/**
* @property logFileChanges
* @type Boolean
* @default true
*/
logFileChanges: true,
/**
* Log the snippet to the console when you're in snippet mode (no proxy/server)
* @property logSnippet
* @type: Boolean
* @default true
* @since 1.5.2
*/
logSnippet: true,
/**
* SINCE 1.7.0! You can control how the snippet is injected
* onto each page via a custom regex + function.
* You can also provide patterns for certain urls
* that should be ignored from the snippet injection.
* @property snippetOptions
* @since 1.7.0
* @param {String|Array} [ignorePaths=undefined]
* @param {RegExp} [rule.match=/&lt;body&#91;^&gt;&#93;*&gt;/i]
* @param {Function} [rule.fn=Function]
* @type Object
*/
snippetOptions: {
rule: {
match: /<body[^>]*>/i,
fn: function (snippet, match) {
return match + snippet;
}
}
},
/**
* @property tunnel
* @type String|Boolean
* @default null
*/
/**
* Some features of BrowserSync (such as `xip` & `tunnel`) require an internet connection, but if you're
* working offline, you can reduce start-up time by setting this option to `false`
* @property online
* @type Boolean
* @default undefined
*/
/**
* Decide which URL to open automatically when BrowserSync starts. Defaults to "local" if none set.
* Can be true, "local", "external" or "tunnel"
* @property open
* @type Boolean|String
* @default true
*/
open: "local",
/**
* @property browser
* @type String|Array
* @default default
*/
browser: "default",
/**
* Requires an internet connection - useful for services such as [Typekit](https://typekit.com/)
* as it allows you to configure domains such as `*.xip.io` in your kit settings
* @property xip
* @type Boolean
* @default false
*/
xip: false,
hostnameSuffix: false,
/**
* The small pop-over notifications in the browser are not always needed/wanted.
* @property notify
* @type Boolean
* @default true
*/
notify: true,
/**
* @property scrollProportionally
* @type Boolean
* @default true
*/
scrollProportionally: true,
/**
* @property scrollThrottle
* @type Number
* @default 0
*/
scrollThrottle: 0,
/**
* @property reloadDelay
* @type Number
* @default 0
*/
reloadDelay: 0,
/**
* @property injectChanges
* @type Boolean
* @default true
*/
injectChanges: true,
/**
* @property startPath
* @type String|Null
* @default null
*/
startPath: null,
/**
* Whether to minify client script, or not.
* @property minify
* @type Boolean
* @default true
*/
minify: true,
/**
* @property host
* @type String
* @default null
*/
host: null,
/**
* @property codeSync
* @type Boolean
* @default true
*/
codeSync: true,
/**
* @property timestamps
* @type Boolean
* @default true
*/
timestamps: true,
/**
* Alter the script path for complete control over where the BrowserSync
* Javascript is served from. Whatever you return from this function
* will be used as the script path.
* @property scriptPath
* @default undefined
* @since 1.5.0
* @type Function
*/
/**
* Configure the Socket.IO path and namespace to avoid collisions. Note: `namespace` can also be a function
* @property socket
* @param {String} [path="/browser-sync/socket.io"]
* @param {String} [clientPath="/browser-sync"]
* @param {String|Function} [namespace="/browser-sync"]
* @since 1.6.2
* @type Object
*/
socket: {
path: "/browser-sync/socket.io",
clientPath: "/browser-sync",
namespace: "/browser-sync"
},
injectFileTypes: ["css", "png", "jpg", "jpeg", "svg", "gif", "webp"],
excludedFileTypes: [
"js",
"css",
"pdf",
"map",
"svg",
"ico",
"woff",
"json",
"eot",
"ttf",
"png",
"jpg",
"jpeg",
"webp",
"gif",
"mp4",
"mp3",
"3gp",
"ogg",
"ogv",
"webm",
"m4a",
"flv",
"wmv",
"avi",
"swf",
"scss"
],
debugInfo: true
};

View file

@ -1,34 +0,0 @@
"use strict";
var globWatcher = require("glob-watcher");
var _ = require("lodash");
/**
* Plugin interface
* @returns {*|function(this:exports)}
*/
module.exports.plugin = function (globs, options, emitter) {
// Options to pass along to Gaze
var watchOptions = options.watchOptions || options.watchoptions || {};
var tempWatcher;
var watchers = {};
_.each(globs, function (glob, namespace) {
tempWatcher = globWatcher(glob, watchOptions, function (data) {
data.namespace = namespace;
emitter.emit("file:changed", data);
});
// Ignore dir-related errors from gaze
tempWatcher.on("error", function () {/*noop*/});
watchers[namespace] = {
glob: glob,
watcher: tempWatcher
};
});
return watchers;
};

View file

@ -1,102 +0,0 @@
"use strict";
var _ = require("lodash");
var snippetUtils = require("./snippet").utils;
module.exports = {
/**
*
* @this {BrowserSync}
* @returns {String}
*/
"client:js": function (hooks, data) {
var js = snippetUtils.getClientJs(data.port, data.options);
return hooks.reduce(function (joined, hook) {
return joined += hook;
}, js);
},
/**
* @this {BrowserSync}
* @returns {Array}
*/
"client:events": function (hooks, clientEvents) {
hooks.forEach(function (hook) {
var result = hook(this);
if (Array.isArray(result)) {
clientEvents = _.union(clientEvents, result);
} else {
clientEvents.push(result);
}
}, this);
return clientEvents;
},
/**
* @returns {Array}
*/
"server:middleware": function (hooks, initial) {
initial = initial || [];
_.each(hooks, function (hook) {
var result = hook(this);
if (Array.isArray(result)) {
result.forEach(function (res) {
if (_.isFunction(res)) {
initial.push(res);
}
});
} else {
if (_.isFunction(result)) {
initial.push(result);
}
}
}, this);
return initial;
},
/**
* Allow plugins to have their own watchers
* @param hooks
* @param bs
* @param obj
* @returns {{core: *}}
*/
"files:watch": function (hooks, bs, obj) {
var added = false;
var namespaces = {};
if (Array.isArray(obj)) {
if (obj.length) {
namespaces["core"] = obj;
if (obj.length === 1) {
added = true;
}
}
}
if (!added && Object.keys(obj).length) {
_.each(obj, function (val, key) {
namespaces[key] = val;
});
}
if (bs.pluginManager.pluginOptions) {
_.each(bs.pluginManager.pluginOptions, function (value, key) {
if (value && value.files) {
namespaces[key] = value.files;
}
}, this);
}
return namespaces;
}
};

View file

@ -1,194 +0,0 @@
"use strict";
var messages = require("./messages");
var utils = require("./utils");
var _ = require("lodash");
var template = "[{blue:%s}] ";
var logger = require("eazy-logger").Logger({
prefix: template.replace("%s", "BS"),
useLevelPrefixes: false
});
module.exports.logger = logger;
/**
* @param name
* @returns {*}
*/
module.exports.getLogger = function (name) {
return logger.clone(function (config) {
config.prefix = config.prefix + template.replace("%s", name);
return config;
});
};
/**
* Logging Callbacks
*/
module.exports.callbacks = {
/**
* Log when file-watching has started
* @param options
* @param data
*/
"file:watching": function (options, data) {
if (Object.keys(data).length) {
logger.info("Watching files...");
}
},
/**
* Log when a file changes
* @param options
* @param data
*/
"file:reload": function (options, data) {
if (data.log) {
var path = utils.resolveRelativeFilePath(data.path, data.cwd);
logger.info("{cyan:File changed: {magenta:%s", path);
}
},
/**
*
*/
"service:exit": function () {
logger.debug("Exiting...");
},
/**
*
*/
"browser:reload": function () {
logger.info("{cyan:Reloading Browsers...");
},
/**
* @param options
* @param data
*/
"config:error": function (options, data) {
logger.setOnce("useLevelPrefixes", true).error(data.msg);
},
/**
* @param options
* @param data
*/
"config:warn": function (options, data) {
logger.setOnce("useLevelPrefixes", true).warn(data.msg);
},
/**
* @param options
* @param data
*/
"stream:changed": function (options, data) {
var changed = data.changed;
logger.info("{cyan:%s %s changed} ({magenta:%s})",
changed.length,
changed.length > 1 ? "files" : "file",
changed.join(", ")
);
},
/**
* Client connected logging
* @param options
* @param data
*/
"client:connected": function (options, data) {
var uaString = utils.getUaString(data.ua);
var msg = "{cyan:Browser Connected: {magenta:%s, version: %s}";
var method = "info";
if (!options.logConnections) {
method = "debug";
}
logger.log(method, msg,
uaString.name,
uaString.version
);
},
/**
* Main logging when the service is running
* @param options
* @param data
*/
"service:running": function (options, data) {
var type = data.type;
var baseDir = options.server.baseDir;
var proxy = options.proxy;
if (type === "server") {
logUrls(options.urls);
if (baseDir) {
if (Array.isArray(baseDir)) {
_.each(baseDir, serveFiles);
} else {
serveFiles(baseDir);
}
}
}
if (type === "proxy") {
logger.info("Proxying: {cyan:%s}", proxy.target);
logger.info("Now you can access your site through the following addresses:");
logUrls(options.urls);
}
if (type === "snippet" && options.logSnippet) {
logger.info(
"Copy the following snippet into your website, " +
"just before the closing {cyan:</body>} tag"
);
logger.unprefixed("info",
messages.scriptTags(options.port, options)
);
}
function serveFiles (base) {
logger.info("Serving files from: {magenta:%s}", base);
}
function logUrls (urls) {
_.each(urls, function (value, key) {
logger.info("%s URL: {magenta:%s}",
utils.ucfirst(key),
value);
});
}
}
};
/**
* Plugin interface - only to be called once to register all events
*/
module.exports.plugin = function (emitter, options) {
// Should set logger level here!
if (options.logLevel === "silent") {
logger.mute(true);
} else {
logger.setLevel(options.logLevel);
}
if (options.logPrefix) {
if (_.isFunction(options.logPrefix)) {
logger.setPrefix(options.logPrefix);
} else {
logger.setPrefix(template.replace("%s", options.logPrefix));
}
}
_.each(exports.callbacks, function (func, event) {
emitter.on(event, func.bind(this, options));
});
return logger;
};

View file

@ -1,99 +0,0 @@
"use strict";
var objectPath = require("object-path");
var _ = require("lodash");
var fs = require("fs");
var config = require("./config");
var messages = {
/**
* @param {Number} port
* @param {Object} options
* @returns {String}
*/
scriptTags: function (port, options) {
function getPath(relative, port) {
return "//HOST:" + port + relative;
}
var template = fs.readFileSync(config.templates.scriptTag, "utf-8");
var scriptPath = this.clientScript(options);
var script;
var override = false;
if (options.scriptPath && _.isFunction(options.scriptPath)) {
script = options.scriptPath(scriptPath, port, options);
override = true;
} else {
script = getPath(scriptPath, port);
}
if (!override && (options.server || options.proxy)) {
script = scriptPath;
}
template = template
.replace("%script%", script);
return template;
},
/**
* @param {String|Number} port
* @param {Object} options
* @returns {String}
*/
socketConnector: function (port, options, external) {
var path = objectPath.get(options, "socket.path");
var namespace = objectPath.get(options, "socket.namespace");
var override = false;
var withPort = "location.hostname + ':%port+ns%'".replace("%port+ns%", port + namespace);
if (_.isFunction(namespace)) {
namespace = "'" + namespace(path, port, options) + "'";
override = true;
}
if (!override) {
// Ensure snippet mode always has PORT
if (!options.server && !options.proxy || external) {
namespace = withPort;
} else {
namespace = "'%ns'".replace("%ns", namespace);
}
}
var template = fs.readFileSync(config.templates.connector, "utf-8");
template = template
.replace("%path%", path)
.replace("%url%", namespace);
return template;
},
/**
* @param {Object} [options]
* @param {Boolean} [both]
*/
clientScript: function (options, both) {
var prefix = options.socket && options.socket.clientPath || "/browser-sync";
var script = prefix + "/browser-sync-client.js";
var template = prefix + "/browser-sync-client.%s.js";
var compiled = template.replace("%s", options.version);
if (both) {
return {
path: script,
versioned: compiled
};
}
return compiled;
}
};
module.exports = messages;

View file

@ -1,20 +0,0 @@
"use strict";
/**
* @param {BrowserSync} browserSync
* @returns {Function}
*/
module.exports = function (browserSync) {
function exit() {
if (browserSync.active) {
browserSync.events.emit("service:exit");
browserSync.cleanup();
}
process.exit();
}
process.on("SIGINT", exit);
return exit;
};

View file

@ -1,28 +0,0 @@
"use strict";
var defaultConfig = require("../default-config");
var cliOptions = require("../cli/cli-options");
var merger = require("opt-merger");
/**
* @param {BrowserSync} browserSync
* @param {Object} pjson
* @returns {Function}
*/
module.exports = function (browserSync, pjson) {
return function () {
var args = Array.prototype.slice.call(arguments);
args = require("../args")(args);
var config = merger.set({ignoreCli: true}).merge(defaultConfig, args.config || {}, cliOptions.callbacks);
if (!config.server && !config.proxy) {
config.open = false;
}
return browserSync.init(config.files || [], config, pjson.version, args.cb);
};
};

View file

@ -1,18 +0,0 @@
"use strict";
/**
* @param {BrowserSync} browserSync
* @returns {Function}
*/
module.exports = function (browserSync) {
return function (msg, timeout) {
if (msg) {
browserSync.events.emit("browser:notify", {
message: msg,
timeout: timeout || 2000
});
}
};
};

View file

@ -1,98 +0,0 @@
"use strict";
var path = require("path");
var utils = require("../utils");
var defaultConfig = require("../default-config");
/**
* @param {BrowserSync} browserSync
* @returns {Function}
*/
module.exports = function (browserSync) {
var events = browserSync.events;
function emitReload(path, log) {
events.emit("file:changed", {
path: path,
log: log,
namespace: "core"
});
}
function emitBrowserReload() {
events.emit("browser:reload");
}
function emitInfo(changed) {
events.emit("stream:changed", {changed: changed});
}
return function (arg) {
if (typeof arg === "string") {
return emitReload(arg, true);
}
if (Array.isArray(arg)) {
if (utils.willCauseReload(arg, defaultConfig.injectFileTypes)) {
return emitBrowserReload();
}
return arg.forEach(function (filepath) {
emitReload(filepath, true);
});
}
if (arg && arg.stream === true) {
// Handle Streams here...
var emitted = false;
var once = arg.once || false;
var Transform = require("stream").Transform;
var reload = new Transform({objectMode:true});
var changed = [];
reload._transform = function (file, encoding, next) {
if (once === true && !emitted) {
emitBrowserReload();
emitted = true;
} else { // handle multiple
if (once === true && emitted) {
} else {
if (file.path) {
emitted = true;
emitReload(file.path, false);
changed.push(path.basename(file.path));
}
}
}
this.push(file); // always send the file down-stream
next();
};
reload._flush = function (next) {
emitInfo(changed);
next();
};
return reload;
}
return emitBrowserReload();
};
};

File diff suppressed because one or more lines are too long

View file

@ -1,18 +0,0 @@
-----BEGIN CERTIFICATE-----
MIIC7zCCAligAwIBAgIJAOku4vmM434TMA0GCSqGSIb3DQEBBQUAMFkxCzAJBgNV
BAYTAkdCMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX
aWRnaXRzIFB0eSBMdGQxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0xNDA3MDgyMDE3
NDZaFw0xNTA3MDgyMDE3NDZaMFkxCzAJBgNVBAYTAkdCMRMwEQYDVQQIEwpTb21l
LVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxEjAQBgNV
BAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAuCoY7Qeo
NtkrLHcXtqIUzfyJIiVthoxtjq58pIFv6es8XWS+gTEUy496TLcuLuAzdRykrPVX
F/UyLPHOfX4AR4LQyopw08vyKoLFLYXq70qH1wcJHe/6a+qjTfVMR6uGNfFGa7Id
ZRVtJUD/mBmR6FQ04YJHiTt2vb30DMWtyW8CAwEAAaOBvjCBuzAdBgNVHQ4EFgQU
5rLnWXk1j1xVQi3iIs+Z7xfuQPcwgYsGA1UdIwSBgzCBgIAU5rLnWXk1j1xVQi3i
Is+Z7xfuQPehXaRbMFkxCzAJBgNVBAYTAkdCMRMwEQYDVQQIEwpTb21lLVN0YXRl
MSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxEjAQBgNVBAMTCWxv
Y2FsaG9zdIIJAOku4vmM434TMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQAD
gYEAOBOI+IWCzL5MB+0AxB6lQz1wa41aQQKkqSN8FrSJ+45yQADEW3IqieTOXgdD
R5/w+EAD+L9BSq9RiVCXq6ACmnBnQUMld3clCEKQfv1T5r4KzvpZF7KDuspVLidu
CUpLCuc3+x0bm45z/cmg2Iy6eYjDLBQksrDTrgXdWU/4X1U=
-----END CERTIFICATE-----

View file

@ -1,15 +0,0 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQC4KhjtB6g22Sssdxe2ohTN/IkiJW2GjG2OrnykgW/p6zxdZL6B
MRTLj3pMty4u4DN1HKSs9VcX9TIs8c59fgBHgtDKinDTy/IqgsUthervSofXBwkd
7/pr6qNN9UxHq4Y18UZrsh1lFW0lQP+YGZHoVDThgkeJO3a9vfQMxa3JbwIDAQAB
AoGAOaeMOCBujAU+2+PIu7dQNhB6SgNXn4i0/7cmdEXFaIDpW/+fGEjqTrPzQLMU
NT6hPWejMjZ4dpqfg6yLzYO1yCTigBZv1n2BzJ2qxb4gILIO2olAI0rb5QOWW07a
2BOgeA/ovwYuUMSIs+Oxaz128vSJjrtBUDVn1U8iHZMYTxkCQQDucj+Bd0xovNap
Ut1emL/uQfHEbheLDO2tY8W1cxdX2Ppu4SmU+Z2u9826DdGCrYQhSHnP+DTVHTjj
SQTE8hLLAkEAxbja9DaRyhgENmLixwi7gUMH4kI6hm1msDLIFNljpzs+BmwCZ6Nv
uRc4Gpx+Px+UR+3ZXlYGODUgMu2m7PU7bQJBAJQjjqjUgTgg+gxAWx/GLpfLiHTN
IPtWkONENTTByCLfvtbcNIVFf12QvtN0elGBk7FJ4cP/JHOysAElAD2LV3kCQHXB
NS2SvlsE2KVnWTY+fiVqvWxEE0TyLOEtLTo1igMT5km+0+PTU3uBV5mJsCp57T61
aeqkAwpAoY+TOAIRvzUCQCUC70C+SHT19mS4L093CsDDows0ww7KOG4IY4d2ZpzD
OgjvCBULqwM1rHdl9oRRI/Utp0vc8ynENRTnTrTqSdU=
-----END RSA PRIVATE KEY-----

View file

@ -1,235 +0,0 @@
"use strict";
var messages = require("./../messages");
var snippetUtils = require("./../snippet").utils;
var utils = require("./utils.js");
var mainUtils = require("./../utils");
var connect = require("connect");
var _ = require("lodash");
var http = require("http");
var https = require("https");
var foxy = require("foxy");
var fs = require("fs");
/**
*
*/
module.exports.plugin = function (bs, scripts) {
var options = bs.options;
var debug = bs.debug;
var proxy = options.proxy || false;
var server = options.server || false;
var snippet = (!server && !proxy);
var baseDir = mainUtils.getBaseDir(server.baseDir || "./");
var type = "snippet";
var events = bs.events;
if (options.server) {
options.server.middleware = bs.pluginManager.hook("server:middleware", server.middleware || null);
}
var bsServer = exports.createServer(options, scripts, bs);
if (server || snippet) {
debug("Static Server running ({magenta:%s}) ...", options.https ? "https" : "http");
type = server ? "server" : "snippet";
}
if (proxy) {
debug("Proxy running, proxing: {magenta:%s}", options.proxy.target);
type = "proxy";
}
if (bsServer) {
bs.server = bsServer.listen(options.port);
}
debug("Running mode: %s", type.toUpperCase());
if (type && (server || proxy)) {
if (options.tunnel && options.online) {
try {
var tunnel = bs.pluginManager.get("tunnel:runner");
if (tunnel) {
bs.pluginManager.get("tunnel")(bs, tunnel(), finished);
}
} catch (e) {
console.log("ERRRRRRRRRRRRR: " + e);
}
} else {
finished(options.urls.local);
}
} else {
finished("n/a");
}
function finished (url, tunnel) {
if (tunnel) {
bs.options.urls.tunnel = url;
}
events.emit("service:running", {
type: type,
options: bs.options,
baseDir: baseDir || null,
port: options.port,
url: url,
tunnel: tunnel ? url : false
});
}
return bsServer;
};
/**
* Launch the server for serving the client JS plus static files
* @param {Object} options
* @param {String} scripts
* @param {BrowserSync} bs
* @returns {{staticServer: (http.Server), proxyServer: (http.Server)}}
*/
module.exports.createServer = function (options, scripts, bs) {
var proxy = options.proxy || false;
var server = options.server || false;
options.snippet = messages.scriptTags(options.port, options);
options.scriptPaths = messages.clientScript(options, true);
if (!proxy && !server) {
return createSnippetServer(options, scripts, bs);
}
if (options.proxy) {
return exports.createProxy(options, scripts, bs);
}
if (options.server) {
return createServer(options, scripts, bs);
}
};
/**
* @param options
* @param scripts
* @param context
* @returns {*}
*/
function createServer (options, scripts, context) {
var server = options.server;
var middleware = server.middleware;
var secure = (options.https !== undefined && options.https !== false);
var secureKey, secureCert;
var index, app;
index = server.index || "index.html";
app = context.app = connect();
context.connect = connect;
utils.addMiddleware(app, middleware);
app.use(function (req, res, next) {
snippetUtils.isOldIe(req);
return next();
})
.use(options.scriptPaths.versioned, scripts)
.use(options.scriptPaths.path, scripts);
if (server.directory) {
utils.addDirectory(app, server.baseDir);
}
app.use(snippetUtils.getSnippetMiddleware(options.snippet, options.snippetOptions));
utils.addBaseDir(app, server.baseDir, index);
if (server.routes) {
utils.addRoutes(app, server.routes);
}
if (secure) {
secureKey = fs.readFileSync(secure.key || __dirname + "/certs/server.key");
secureCert = fs.readFileSync(secure.cert || __dirname + "/certs/server.crt");
return https.createServer({key: secureKey, cert: secureCert}, app);
} else {
return http.createServer(app);
}
}
/**
* @param options
* @param scripts
* @param context
* @returns {*}
*/
function createSnippetServer (options, scripts, context) {
var app = context.app = connect();
context.connect = connect;
app.use(options.scriptPaths.versioned, scripts)
.use(options.scriptPaths.path, scripts);
return http.createServer(app);
}
/**
* @param options
* @param scripts
* @returns {*}
* @param {BrowserSync} bs
*/
module.exports.createProxy = function (options, scripts, bs) {
exports.checkProxyTarget(options.proxy, function (err) {
if (err) {
bs.events.emit("config:warn", {msg: err});
}
});
return foxy(options.proxy.target, {
rules: snippetUtils.getRegex(options.snippet, options.snippetOptions),
ignorePaths: options.snippetOptions.ignorePaths,
middleware: snippetUtils.getProxyMiddleware(scripts, options.scriptPaths.versioned),
errHandler: function () {}
}
);
};
/**
* @param {Object} proxy
* @param {Function} cb
*/
module.exports.checkProxyTarget = function (proxy, cb) {
var chunks = [];
var errored = false;
function logError() {
if (!errored) {
cb("Proxy address not reachable - is your server running?");
errored = true;
}
}
require("http").get(proxy.target, function (res) {
res.on("data", function (data) {
chunks.push(data);
});
}).on("error", function (err) {
if (_.contains(["ENOTFOUND", "ECONNREFUSED"], err.code)) {
logError();
}
}).on("close", function () {
if (!chunks.length) {
logError();
}
});
};

View file

@ -1,134 +0,0 @@
"use strict";
var filePath = require("path");
var serveIndex = require("serve-index");
var serveStatic = require("serve-static");
var _ = require("lodash");
var snippetUtils = require("./../snippet").utils;
module.exports = {
/**
* The middleware that can emit location change events.
* @param {Object} io
* @param {Object} options
* @returns {Function}
*/
navigateCallback: function (io, options) {
var disabled = false;
var navigating = false;
var canNavigate = this.canNavigate;
return function (req, res, next) {
if (canNavigate(req, options, io)) {
var clients = io.sockets.clients();
if (clients.length && !disabled && !navigating) {
navigating = true;
disabled = true;
io.sockets.emit("location", {
url: req.url
});
var timer = setTimeout(function () {
disabled = false;
navigating = false;
clearInterval(timer);
}, 300);
}
}
if (typeof next === "function") {
next();
}
};
},
/**
* All the conditions that determine if we should emit
* a location:change event
* @param {Object} req
* @param {Object} options
* @returns {Boolean}
*/
canNavigate: function (req, options) {
var headers = req.headers || {};
if (req.method !== "GET") {
return false;
}
if (headers["x-requested-with"] !== undefined && headers["x-requested-with"] === "XMLHttpRequest") {
return false;
}
if (!options || !options.ghostMode || !options.ghostMode.location) {
return false;
}
if (snippetUtils.isExcluded(req.url, options.excludedFileTypes)) {
return false;
}
return true;
},
/**
* @param app
* @param middleware
* @returns {*}
*/
addMiddleware: function (app, middleware) {
if (Array.isArray(middleware)) {
middleware.forEach(function (item) {
app.use(item);
});
} else if (typeof middleware === "function") {
app.use(middleware);
}
return app;
},
/**
* @param app
* @param base
* @param index
*/
addBaseDir: function (app, base, index) {
if (Array.isArray(base)) {
base.forEach(function (item) {
app.use(serveStatic(filePath.resolve(item), {index: index}));
});
} else {
if ("string" === typeof base) {
app.use(serveStatic(filePath.resolve(base), {index: index}));
}
}
},
/**
* @param app
* @param base
*/
addDirectory: function (app, base) {
if (Array.isArray(base)) {
base = base[0];
}
app.use(serveIndex(filePath.resolve(base), {icons:true}));
},
/**
* @param app
* @param {Object} routes
*/
addRoutes: function (app, routes) {
Object.keys(routes).forEach(function (key) {
if (_.isString(key) && _.isString(routes[key])) {
app.use(key, serveStatic(filePath.resolve(routes[key])));
}
});
}
};

View file

@ -1,59 +0,0 @@
"use strict";
var utils = require("./utils");
/**
* @param context
* @returns {function(this:*)}
*/
module.exports.init = function (context) {
/**
* @this {BrowserSync}
*/
return function (options) {
this.options = options;
// register internal events
this.registerInternalEvents(options);
// Set global URL options
options.urls = utils.setUrlOptions(options.port, options);
var files = this.pluginManager.hook("files:watch", this, options.files);
// Start file watcher
this.watchers = this.pluginManager.get("file:watcher")(files, options, this.events);
// Get the Client JS + any user-defined
var clientJs = this.clientJs = this.pluginManager.hook("client:js", {
port: options.port,
options: options
});
// Start the server
var server = this.server = this.pluginManager.get("server")(
this,
this.pluginManager.get("client:script")(options, clientJs, options.proxy ? "file" : "middleware")
);
this.clientEvents = this.pluginManager.hook("client:events", this.clientEvents);
// Start the socket, needs an existing server.
this.io = this.pluginManager.get("socket")(
server,
this.clientEvents,
this
);
this.events.emit("init", this);
this.pluginManager.initUserPlugins(this);
this.options.userPlugins = this.getUserPlugins();
this.callback(null, this);
}.bind(context);
};

View file

@ -1,115 +0,0 @@
"use strict";
var messages = require("./messages");
var config = require("./config");
var lrSnippet = require("resp-modifier");
var path = require("path");
var _ = require("lodash");
var fs = require("fs");
/**
* Utils for snippet injection
*/
var utils = {
/**
* @param {String} url
* @param {Array} excludeList
* @returns {boolean}
*/
isExcluded: function (url, excludeList) {
var extension = path.extname(url);
if (extension) {
if (~url.indexOf("?")) {
return true;
}
extension = extension.slice(1);
return _.contains(excludeList, extension);
}
return false;
},
/**
* @param {String} snippet
* @param {Object} options
* @returns {{match: RegExp, fn: Function}}
*/
getRegex: function (snippet, options) {
var fn = options.rule.fn.bind(null, snippet);
return {
match: options.rule.match,
fn: fn
};
},
/**
* @param {String} snippet
* @param {Object} [options]
* @returns {Function}
*/
getSnippetMiddleware: function (snippet, options) {
options = options || {};
return lrSnippet({
rules: [utils.getRegex(snippet, options)],
ignorePaths: options.ignorePaths
});
},
/**
* @param {String} scripts - the client side JS
* @param {String} scriptPath - the URL to match
* @returns {Function}
*/
getProxyMiddleware: function (scripts, scriptPath) {
return function (req, res, next) {
if (req.url.indexOf(scriptPath) > -1) {
res.writeHead(200, {"Content-Type": "text/javascript"});
res.write(scripts);
res.end();
return next(true);
} else {
return next(false);
}
};
},
/**
* @param {Object} req
* @param {Array} [excludeList]
* @returns {Object}
*/
isOldIe: function (req, excludeList) {
var ua = req.headers["user-agent"];
var match = /MSIE (\d)\.\d/.exec(ua);
if (match) {
if (parseInt(match[1], 10) < 9) {
if (!utils.isExcluded(req.url, excludeList)) {
req.headers["accept"] = "text/html";
}
}
}
return req;
},
getNoConflictJs: function () {
return "window.___browserSync___oldSocketIo = window.io;";
},
/**
* @param {Number} port
* @param {BrowserSync.options} options
* @returns {String}
*/
getClientJs: function (port, options) {
var socket = utils.getSocketScript();
return utils.getNoConflictJs() + socket + ";" + messages.socketConnector(port, options);
},
/**
* @returns {String}
*/
getSocketScript: function () {
return fs.readFileSync(path.resolve(__dirname + config.socketIoScript), "utf-8");
}
};
module.exports.utils = utils;

View file

@ -1,81 +0,0 @@
"use strict";
var socket = require("socket.io");
var Steward = require("emitter-steward");
/**
* Plugin interface
* @returns {*|function(this:exports)}
*/
module.exports.plugin = function (server, clientEvents, bs) {
return exports.init(server, clientEvents, bs);
};
/**
* @param {http.Server} server
* @param clientEvents
* @param {BrowserSync} bs
*/
module.exports.init = function (server, clientEvents, bs) {
var emitter = bs.events;
var io = socket.listen(server, {log: false, path: bs.getOption("socket.path")});
// Override default namespace.
io.sockets = io.of(bs.getOption("socket.namespace", "/browser-sync"));
var steward = new Steward(emitter);
/**
* Listen for new connections
*/
io.sockets.on("connection", handleConnection);
/**
* Handle each new connection
* @param {Object} client
*/
function handleConnection (client) {
// set ghostmode callbacks
if (bs.getOption("ghostMode")) {
addGhostMode(client);
}
client.emit("connection", bs.getOptions());
emitter.emit("client:connected", {
ua: client.handshake.headers["user-agent"]
});
}
/**
* @param {string} event
* @param {Socket.client} client
* @param {Object} data
*/
function handleClientEvent(event, client, data) {
if (steward.valid(client.id)) {
client.broadcast.emit(event, data);
}
}
/**
* @param client
*/
function addGhostMode (client) {
clientEvents.forEach(addEvent);
function addEvent(event) {
client.on(event, handleClientEvent.bind(null, event, client));
}
}
return io;
};

View file

@ -1,6 +0,0 @@
window.___browserSync___ = {};
___browserSync___.io = window.io;
window.io = window.___browserSync___oldSocketIo;
window.___browserSync___oldSocketIo=undefined;
___browserSync___.socketConfig = {}; ___browserSync___.socketConfig.path = '%path%';
___browserSync___.socket = ___browserSync___.io(%url%, ___browserSync___.socketConfig);

View file

@ -1,3 +0,0 @@
<script type='text/javascript' id="__bs_script__">//<![CDATA[
document.write("<script async src='%script%'><\/script>".replace(/HOST/g, location.hostname).replace(/PORT/g, location.port));
//]]></script>

View file

@ -1,30 +0,0 @@
"use strict";
var _ = require("lodash");
/**
* @param {BrowserSync} bs
* @param {Function} tunnelRunner
* @param {Function} cb
*/
module.exports.plugin = function (bs, tunnelRunner, cb) {
var opts = {};
var options = bs.options;
var port = bs.options.port;
//var debug = bs.debug;
if (_.isString(options.tunnel)) {
opts.subdomain = options.tunnel;
}
//debug("Trying tunnel connection with: %s ", options.tunnel || "no subdomain specified");
tunnelRunner(port, opts, function (err, tunnel) {
if (err) {
throw err;
}
cb(tunnel.url, true);
});
};

View file

@ -1,271 +0,0 @@
"use strict";
var devIp = require("dev-ip");
var open = require("opn");
var filePath = require("path");
var portScanner = require("portscanner-plus");
var _ = require("lodash");
var UAParser = require("ua-parser-js");
var parser = new UAParser();
var utils = {
/**
* @param {Object} options
* @returns {String|boolean} - the IP address
*/
getHostIp: function (options) {
var returnValue = devIp.getIp(null);
if (options) {
if (options.host && options.host !== "localhost") {
return options.host;
}
if (options.detect === false || !devIp) {
return false;
}
}
if (Array.isArray(returnValue)) {
returnValue = returnValue[0];
}
return returnValue || false;
},
/**
* Take the path provided in options & transform into CWD for serving files
* @param {String} [baseDir]
* @returns {String}
*/
getBaseDir: function (baseDir) {
if (Array.isArray(baseDir)) {
return baseDir;
}
var suffix = "";
var validRoots = ["./", "/", "."];
if (!baseDir || _.contains(validRoots, baseDir)) {
return process.cwd();
}
if (baseDir.charAt(0) === "/") {
suffix = baseDir;
} else {
if (/^.\//.test(baseDir)) {
suffix = baseDir.replace(".", "");
} else {
suffix = "/" + baseDir;
}
}
return process.cwd() + suffix;
},
/**
* Set URL Options
*/
setUrlOptions: function (port, options) {
var urls = {};
var scheme = (options.https && !options.proxy && !options.tunnel) ? "https" : "http";
if (!options.online) {
urls.local = utils.getUrl(scheme + "://localhost:" + port, options);
return urls;
}
var external = utils.xip(utils.getHostIp(options), options);
var localhost = "localhost";
if (options.xip) {
localhost = "127.0.0.1";
}
var local = utils.xip(localhost, options);
options.external = options.host = external;
return utils.getUrls(external, local, scheme, port, options);
},
/**
* Append a start path if given in options
* @param {String} url
* @param {Object} options
* @returns {String}
*/
getUrl: function (url, options) {
var prefix = "/";
var startPath = options.startPath;
if (options.proxy && options.proxy.startPath) {
startPath = options.proxy.startPath;
}
if (startPath) {
if (startPath.charAt(0) === "/") {
prefix = "";
}
url = url + prefix + startPath;
}
return url;
},
/**
* @param {String} external
* @param {String} local
* @param {String} scheme
* @param {number|string} port
* @param {Object} options
* @returns {{local: string, external: string}}
*/
getUrls: function (external, local, scheme, port, options) {
var urls = {
local: utils.getUrl(utils._makeUrl(scheme, local, port), options)
};
if (external !== local) {
urls.external = utils.getUrl(utils._makeUrl(scheme, external, port), options);
}
return urls;
},
/**
* @param {String} scheme
* @param {String} host
* @param {Number} port
* @returns {String}
* @private
*/
_makeUrl: function (scheme, host, port) {
return scheme + "://" + host + ":" + port;
},
/**
* Get ports
* @param {Object} options
* @returns {Q.promise}
*/
getPorts: function (options) {
var port = options.port;
var ports = options.ports; // backwards compatibility
var max;
if (ports) {
port = ports.min;
max = ports.max;
}
return portScanner.getPorts(1, port, max);
},
/**
* @param {String} ua
* @returns {Object}
*/
getUaString: function (ua) {
return parser.setUA(ua).getBrowser();
},
/**
* @param {String} filepath
* @param {String} cwd
* @returns {String}
*/
resolveRelativeFilePath: function (filepath, cwd) {
return filepath.replace(cwd + "/", "");
},
/**
* @param {String} path
* @returns {String}
*/
getFileExtension: function (path) {
return filePath.extname(path).replace(".", "");
},
/**
* Open the page in browser
* @param {String} url
* @param {Object} options
*/
openBrowser: function (url, options) {
if (_.isString(options.open)) {
if (options.urls[options.open]) {
url = options.urls[options.open];
}
}
if (options.open) {
if (options.browser !== "default") {
if (Array.isArray(options.browser)) {
options.browser.forEach(function (browser) {
utils.open(url, browser);
});
} else {
utils.open(url, options.browser); // single
}
} else {
utils.open(url);
}
}
},
/**
* Wrapper for open module - for easier stubbin'
* @param url
* @param name
*/
open: function (url, name) {
open(url, name || null);
},
/**
* @param {Boolean} kill
* @param err
* @param cb
*/
fail: function (kill, err, cb) {
if (kill) {
if (cb && _.isFunction(cb)) {
cb(err);
}
process.exit(1);
}
},
/**
* Add support for xip.io urls
* @param {String} host
* @param {Object} options
* @returns {String}
*/
xip: function (host, options) {
if (options.xip) {
return host + ".xip.io";
}
if (options.hostnameSuffix) {
return host + options.hostnameSuffix;
}
return host;
},
/**
* @param {String} string
* @returns {string}
*/
ucfirst: function (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
},
/**
* Determine if an array of file paths will cause a full page reload.
* @param {Array} needles - filepath such as ["core.css", "index.html"]
* @param {Array} haystack
* @returns {Boolean}
*/
willCauseReload: function (needles, haystack) {
return needles.some(function (needle) {
return !_.contains(haystack, filePath.extname(needle).replace(".", ""));
});
}
};
module.exports = utils;

View file

@ -1 +0,0 @@
../dev-ip/lib/dev-ip.js

View file

@ -1 +0,0 @@
../localtunnel/bin/client

View file

@ -1 +0,0 @@
../opn/cli.js

View file

@ -1 +0,0 @@
browser-sync-client

View file

@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="chai-DefinitelyTyped" level="application" />
<orderEntry type="library" name="lodash-DefinitelyTyped" level="application" />
<orderEntry type="library" name="mocha-DefinitelyTyped" level="application" />
<orderEntry type="library" name="sinon-chai-DefinitelyTyped" level="application" />
<orderEntry type="library" name="browser-sync-client node_modules" level="project" />
<orderEntry type="library" name="browserify-DefinitelyTyped" level="application" />
<orderEntry type="library" name="Node.js v0.10.26 Core Modules" level="application" />
<orderEntry type="library" name="sass-stdlib" level="application" />
</component>
</module>

View file

@ -1,10 +0,0 @@
<component name="ProjectDictionaryState">
<dictionary name="shakyshane">
<words>
<w>browserify</w>
<w>fucntion</w>
<w>minified</w>
<w>minify</w>
</words>
</dictionary>
</component>

View file

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" />
</project>

View file

@ -1,7 +0,0 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0" is_locked="false">
<option name="myName" value="Project Default" />
<option name="myLocal" value="false" />
<inspection_tool class="JSValidateTypes" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
</profile>
</component>

View file

@ -1,7 +0,0 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="PROJECT_PROFILE" value="Project Default" />
<option name="USE_PROJECT_PROFILE" value="true" />
<version value="1.0" />
</settings>
</component>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptLibraryMappings">
<file url="file://$PROJECT_DIR$" libraries="{browser-sync-client node_modules}" />
<includedPredefinedLibrary name="Node.js Globals" />
</component>
</project>

View file

@ -1,14 +0,0 @@
<component name="libraryTable">
<library name="browser-sync-client node_modules" type="javaScript">
<properties>
<option name="frameworkName" value="node_modules" />
<sourceFilesUrls>
<item url="file://$PROJECT_DIR$/node_modules" />
</sourceFilesUrls>
</properties>
<CLASSES>
<root url="file://$PROJECT_DIR$/node_modules" />
</CLASSES>
<SOURCES />
</library>
</component>

View file

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" />
</project>

View file

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/browser-sync-client.iml" filepath="$PROJECT_DIR$/.idea/browser-sync-client.iml" />
</modules>
</component>
</project>

View file

@ -1,5 +0,0 @@
<component name="DependencyValidationManager">
<state>
<option name="SKIP_IMPORT_STATEMENTS" value="false" />
</state>
</component>

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="" />
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

File diff suppressed because it is too large Load diff

View file

@ -1 +0,0 @@
test/

View file

@ -1,7 +0,0 @@
language: node_js
node_js:
- '0.10'
before_script:
- "npm install -g gulp"
- "export DISPLAY=:99.0"
- "sh -e /etc/init.d/xvfb start"

View file

@ -1,22 +0,0 @@
Copyright (c) 2013 Shane Osbourne
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,15 +0,0 @@
# browser-sync-client [![Build Status](https://travis-ci.org/shakyShane/browser-sync-client.png?branch=master)](https://travis-ci.org/shakyShane/browser-sync-client)
Client-side script for BrowserSync
## Contributors
```
68 Shane Osbourne
1 Hugo Dias
1 Sergey Slipchenko
```
## License
Copyright (c) 2014 Shane Osbourne
Licensed under the MIT license.

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -1,89 +0,0 @@
var gulp = require("gulp");
var karma = require('gulp-karma');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var contribs = require('gulp-contribs');
var browserify = require('gulp-browserify');
var through2 = require('through2');
var rename = require('gulp-rename');
var testFiles = [
'test/todo.js'
];
gulp.task('test', function() {
// Be sure to return the stream
return gulp.src(testFiles)
.pipe(karma({
configFile: 'test/karma.conf.ci.js',
action: 'run'
}));
});
gulp.task('test:watch', function() {
gulp.src(testFiles)
.pipe(karma({
configFile: 'test/karma.conf.js',
action: 'watch'
}));
});
gulp.task('lint-test', function () {
gulp.src(['test/client-new/*.js', 'test/middleware/*.js'])
.pipe(jshint('test/.jshintrc'))
.pipe(jshint.reporter("default"))
.pipe(jshint.reporter("fail"))
});
gulp.task('lint-lib', function () {
return gulp.src(['lib/*', '!lib/browser-sync-client.js', '!lib/events.js'])
.pipe(jshint('lib/.jshintrc'))
.pipe(jshint.reporter("default"))
.pipe(jshint.reporter("fail"))
});
gulp.task('contribs', function () {
gulp.src('README.md')
.pipe(contribs())
.pipe(gulp.dest("./"))
});
/**
* Strip debug statements
* @returns {*}
*/
var stripDebug = function () {
return through2.obj(function (file, enc, cb) {
var string = file.contents.toString();
var regex = /\/\*\*debug:start\*\*\/[\s\S]*\/\*\*debug:end\*\*\//g;
var stripped = string.replace(regex, "");
file.contents = new Buffer(stripped);
this.push(file);
cb();
});
};
// Basic usage
gulp.task('build-dist', function() {
// Single entry point to browserify
gulp.src('lib/index.js')
.pipe(browserify())
.pipe(gulp.dest('./dist'))
.pipe(stripDebug())
.pipe(uglify())
.pipe(rename("index.min.js"))
.pipe(gulp.dest('./dist'));
});
gulp.task('build-dev', function() {
// Single entry point to browserify
gulp.src('lib/index.js')
.pipe(browserify())
.pipe(gulp.dest('./dist'))
});
gulp.task("dev", ['build-dist'], function () {
gulp.watch(["lib/*.js", "test/client-new/**/*.js"], ['build-dist']);
});
gulp.task('default', ["lint-lib", "lint-test", "build-dist", "test"]);

View file

@ -1,30 +0,0 @@
"use strict";
var fs = require("fs");
var path = require("path");
var script = path.resolve(__dirname + "/dist/index.min.js");
function init(options, connector, type) {
var result;
if (options && options.minify) {
result = fs.readFileSync(script);
} else {
script = path.resolve(__dirname + "/dist/index.js");
result = fs.readFileSync(script);
}
if (type && type === "file") {
return connector + result;
}
return function (req, res) {
res.setHeader("Content-Type", "text/javascript");
res.end(connector + result);
};
}
module.exports.middleware = init;
module.exports.plugin = init;

View file

@ -1,19 +0,0 @@
{
"curly": true,
"eqeqeq": true,
"immed": true,
"latedef": "nofunc",
"newcap": true,
"noarg": true,
"sub": true,
"undef": false,
"unused": false,
"quotmark": "double",
"boss": true,
"eqnull": true,
"node": true,
"globals": {
"window" : false,
"document" : false
}
}

View file

@ -1,102 +0,0 @@
"use strict";
var socket = require("./socket");
var emitter = require("./emitter");
var notify = require("./notify");
var utils = require("./browser.utils");
/**
* @constructor
*/
var BrowserSync = function (options) {
this.options = options;
this.socket = socket;
this.emitter = emitter;
this.utils = utils.utils;
var _this = this;
/**
* Options set
*/
socket.on("options:set", function (data) {
emitter.emit("notify", "Setting options...");
_this.options = data.options;
});
};
/**
* Helper to check if syncing is allowed
* @param data
* @param optPath
* @returns {boolean}
*/
BrowserSync.prototype.canSync = function (data, optPath) {
data = data || {};
var canSync = true;
if (optPath) {
canSync = this.getOption(optPath);
}
return canSync && data.url === window.location.pathname;
};
/**
* Helper to check if syncing is allowed
* @returns {boolean}
*/
BrowserSync.prototype.getOption = function (path) {
if (path && path.match(/\./)) {
return getByPath(this.options, path);
} else {
var opt = this.options[path];
if (isUndefined(opt)) {
return false;
} else {
return opt;
}
}
};
/**
* @type {Function}
*/
module.exports = BrowserSync;
/**
* @param {String} val
* @returns {boolean}
*/
function isUndefined(val) {
return "undefined" === typeof val;
}
/**
* @param obj
* @param path
*/
function getByPath(obj, path) {
for(var i = 0, tempPath = path.split("."), len = tempPath.length; i < len; i++){
if(!obj || typeof obj !== "object") {
return false;
}
obj = obj[tempPath[i]];
}
if(typeof obj === "undefined") {
return false;
}
return obj;
}

View file

@ -1,132 +0,0 @@
"use strict";
/**
* @returns {window}
*/
exports.getWindow = function () {
return window;
};
/**
*
* @returns {HTMLDocument}
*/
exports.getDocument = function () {
return document;
};
/**
* @type {{getScrollPosition: getScrollPosition, getScrollSpace: getScrollSpace}}
*/
exports.utils = {
/**
* Cross-browser scroll position
* @returns {{x: number, y: number}}
*/
getBrowserScrollPosition: function () {
var $window = exports.getWindow();
var $document = exports.getDocument();
var scrollX;
var scrollY;
var dElement = $document.documentElement;
var dBody = $document.body;
if ($window.pageYOffset !== undefined) {
scrollX = $window.pageXOffset;
scrollY = $window.pageYOffset;
} else {
scrollX = dElement.scrollLeft || dBody.scrollLeft || 0;
scrollY = dElement.scrollTop || dBody.scrollTop || 0;
}
return {
x: scrollX,
y: scrollY
};
},
/**
* @returns {{x: number, y: number}}
*/
getScrollSpace: function () {
var $document = exports.getDocument();
var dElement = $document.documentElement;
var dBody = $document.body;
return {
x: dBody.scrollHeight - dElement.clientWidth,
y: dBody.scrollHeight - dElement.clientHeight
};
},
/**
* Saves scroll position into cookies
*/
saveScrollPosition: function () {
var pos = exports.utils.getBrowserScrollPosition();
pos = [pos.x, pos.y];
document.cookie = "bs_scroll_pos=" + pos.join(",");
},
/**
* Restores scroll position from cookies
*/
restoreScrollPosition: function () {
var pos = document.cookie.replace(/(?:(?:^|.*;\s*)bs_scroll_pos\s*\=\s*([^;]*).*$)|^.*$/, "$1").split(",");
window.scrollTo(pos[0], pos[1]);
},
/**
* @param tagName
* @param elem
* @returns {*|number}
*/
getElementIndex: function (tagName, elem) {
var allElems = document.getElementsByTagName(tagName);
return Array.prototype.indexOf.call(allElems, elem);
},
/**
* Force Change event on radio & checkboxes (IE)
*/
forceChange: function (elem) {
elem.blur();
elem.focus();
},
/**
* @param elem
* @returns {{tagName: (elem.tagName|*), index: *}}
*/
getElementData: function (elem) {
var tagName = elem.tagName;
var index = exports.utils.getElementIndex(tagName, elem);
return {
tagName: tagName,
index: index
};
},
/**
* @param {string} tagName
* @param {number} index
*/
getSingleElement: function (tagName, index) {
var elems = document.getElementsByTagName(tagName);
return elems[index];
},
/**
*
*/
getBody: function () {
return document.getElementsByTagName("body")[0];
},
/**
*
*/
reloadBrowser: function () {
exports.getWindow().location.reload(true);
},
getWindow: exports.getWindow,
getDocument: exports.getDocument,
/**
* Are we dealing with old IE?
* @returns {boolean}
*/
isOldIe: function () {
return typeof window.attachEvent !== "undefined";
}
};

View file

@ -1,20 +0,0 @@
if (!("indexOf" in Array.prototype)) {
Array.prototype.indexOf= function(find, i) {
if (i === undefined) {
i = 0;
}
if (i < 0) {
i += this.length;
}
if (i < 0) {
i= 0;
}
for (var n = this.length; i < n; i += 1) {
if (i in this && this[i]===find) {
return i;
}
}
return -1;
};
}

View file

@ -1,218 +0,0 @@
"use strict";
var events = require("./events");
var utils = require("./browser.utils").utils;
var options = {
tagNames: {
"css": "link",
"jpg": "img",
"jpeg": "img",
"png": "img",
"svg": "img",
"gif": "img",
"js": "script"
},
attrs: {
"link": "href",
"img": "src",
"script": "src"
}
};
var hiddenElem;
var OPT_PATH = "codeSync";
var current = function () {
return window.location.pathname;
};
/**
* @param {BrowserSync} bs
*/
exports.init = function (bs) {
exports.saveScroll(utils.getWindow(), utils.getDocument());
bs.socket.on("file:reload", exports.reload(bs));
bs.socket.on("browser:reload", function () {
if (bs.canSync({url: current()}, OPT_PATH)) {
exports.reloadBrowser(true);
}
});
};
/**
* Use a cookie-drop to save scroll position of
* @param $window
* @param $document
*/
exports.saveScroll = function ($window, $document) {
if (!utils.isOldIe()) {
return;
}
if ($document.readyState === "complete") {
utils.restoreScrollPosition();
} else {
events.manager.addEvent($document, "readystatechange", function() {
if ($document.readyState === "complete") {
utils.restoreScrollPosition();
}
});
}
events.manager.addEvent(window, "beforeunload", utils.saveScrollPosition);
};
/**
* @param elem
* @param attr
* @param options
* @returns {{elem: HTMLElement, timeStamp: number}}
*/
exports.swapFile = function (elem, attr, options) {
var currentValue = elem[attr];
var timeStamp = new Date().getTime();
var suffix = "?rel=" + timeStamp;
var justUrl = /^[^\?]+(?=\?)/.exec(currentValue);
if (justUrl) {
currentValue = justUrl[0];
}
if (options) {
if (!options.timestamps) {
suffix = "";
}
}
elem[attr] = currentValue + suffix;
var body = document.body;
setTimeout(function () {
if (!hiddenElem) {
hiddenElem = document.createElement("DIV");
body.appendChild(hiddenElem);
} else {
hiddenElem.style.display = "none";
hiddenElem.style.display = "block";
}
}, 200);
return {
elem: elem,
timeStamp: timeStamp
};
};
/**
* @param {BrowserSync} bs
* @returns {*}
*/
exports.reload = function (bs) {
/**
* @param data - from socket
*/
return function (data) {
if (!bs.canSync({url: current()}, OPT_PATH)) {
return;
}
var transformedElem;
var options = bs.options;
var emitter = bs.emitter;
if (data.url || !options.injectChanges) {
exports.reloadBrowser(true);
}
if (data.assetFileName && data.fileExtension) {
var domData = exports.getElems(data.fileExtension);
var elems = exports.getMatches(domData.elems, data.assetFileName, domData.attr);
if (elems.length && options.notify) {
emitter.emit("notify", {message: "Injected: " + data.assetFileName});
}
for (var i = 0, n = elems.length; i < n; i += 1) {
transformedElem = exports.swapFile(elems[i], domData.attr, options);
}
}
return transformedElem;
};
};
/**
* @param fileExtension
* @returns {*}
*/
exports.getTagName = function (fileExtension) {
return options.tagNames[fileExtension];
};
/**
* @param tagName
* @returns {*}
*/
exports.getAttr = function (tagName) {
return options.attrs[tagName];
};
/**
* @param elems
* @param url
* @param attr
* @returns {Array}
*/
exports.getMatches = function (elems, url, attr) {
var matches = [];
for (var i = 0, len = elems.length; i < len; i += 1) {
if (elems[i][attr].indexOf(url) !== -1) {
matches.push(elems[i]);
}
}
return matches;
};
/**
* @param fileExtension
* @returns {{elems: NodeList, attr: *}}
*/
exports.getElems = function(fileExtension) {
var tagName = exports.getTagName(fileExtension);
var attr = exports.getAttr(tagName);
return {
elems: document.getElementsByTagName(tagName),
attr: attr
};
};
/**
* @returns {window}
*/
exports.getWindow = function () {
return window;
};
/**
* @param confirm
*/
exports.reloadBrowser = function (confirm) {
var $window = exports.getWindow();
if (confirm) {
$window.location.reload(true);
}
};

View file

@ -1,33 +0,0 @@
"use strict";
exports.events = {};
/**
* @param name
* @param data
*/
exports.emit = function (name, data) {
var event = exports.events[name];
var listeners;
if (event && event.listeners) {
listeners = event.listeners;
for (var i = 0, n = listeners.length; i < n; i += 1) {
listeners[i](data);
}
}
};
/**
* @param name
* @param func
*/
exports.on = function (name, func) {
var events = exports.events;
if (!events[name]) {
events[name] = {
listeners: [func]
};
} else {
events[name].listeners.push(func);
}
};

View file

@ -1,279 +0,0 @@
exports._ElementCache = function () {
var cache = {},
guidCounter = 1,
expando = "data" + (new Date).getTime();
this.getData = function (elem) {
var guid = elem[expando];
if (!guid) {
guid = elem[expando] = guidCounter++;
cache[guid] = {};
}
return cache[guid];
};
this.removeData = function (elem) {
var guid = elem[expando];
if (!guid) return;
delete cache[guid];
try {
delete elem[expando];
}
catch (e) {
if (elem.removeAttribute) {
elem.removeAttribute(expando);
}
}
};
};
/**
* Fix an event
* @param event
* @returns {*}
*/
exports._fixEvent = function (event) {
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
if (!event || !event.stopPropagation) {
var old = event || window.event;
// Clone the old object so that we can modify the values
event = {};
for (var prop in old) {
event[prop] = old[prop];
}
// The event occurred on this element
if (!event.target) {
event.target = event.srcElement || document;
}
// Handle which other element the event is related to
event.relatedTarget = event.fromElement === event.target ?
event.toElement :
event.fromElement;
// Stop the default browser action
event.preventDefault = function () {
event.returnValue = false;
event.isDefaultPrevented = returnTrue;
};
event.isDefaultPrevented = returnFalse;
// Stop the event from bubbling
event.stopPropagation = function () {
event.cancelBubble = true;
event.isPropagationStopped = returnTrue;
};
event.isPropagationStopped = returnFalse;
// Stop the event from bubbling and executing other handlers
event.stopImmediatePropagation = function () {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
};
event.isImmediatePropagationStopped = returnFalse;
// Handle mouse position
if (event.clientX != null) {
var doc = document.documentElement, body = document.body;
event.pageX = event.clientX +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0);
}
// Handle key presses
event.which = event.charCode || event.keyCode;
// Fix button for mouse clicks:
// 0 == left; 1 == middle; 2 == right
if (event.button != null) {
event.button = (event.button & 1 ? 0 :
(event.button & 4 ? 1 :
(event.button & 2 ? 2 : 0)));
}
}
return event;
};
/**
* @constructor
*/
exports._EventManager = function (cache) {
var nextGuid = 1;
this.addEvent = function (elem, type, fn) {
var data = cache.getData(elem);
if (!data.handlers) data.handlers = {};
if (!data.handlers[type])
data.handlers[type] = [];
if (!fn.guid) fn.guid = nextGuid++;
data.handlers[type].push(fn);
if (!data.dispatcher) {
data.disabled = false;
data.dispatcher = function (event) {
if (data.disabled) return;
event = exports._fixEvent(event);
var handlers = data.handlers[event.type];
if (handlers) {
for (var n = 0; n < handlers.length; n++) {
handlers[n].call(elem, event);
}
}
};
}
if (data.handlers[type].length == 1) {
if (document.addEventListener) {
elem.addEventListener(type, data.dispatcher, false);
}
else if (document.attachEvent) {
elem.attachEvent("on" + type, data.dispatcher);
}
}
};
function tidyUp(elem, type) {
function isEmpty(object) {
for (var prop in object) {
return false;
}
return true;
}
var data = cache.getData(elem);
if (data.handlers[type].length === 0) {
delete data.handlers[type];
if (document.removeEventListener) {
elem.removeEventListener(type, data.dispatcher, false);
}
else if (document.detachEvent) {
elem.detachEvent("on" + type, data.dispatcher);
}
}
if (isEmpty(data.handlers)) {
delete data.handlers;
delete data.dispatcher;
}
if (isEmpty(data)) {
cache.removeData(elem);
}
}
this.removeEvent = function (elem, type, fn) {
var data = cache.getData(elem);
if (!data.handlers) return;
var removeType = function (t) {
data.handlers[t] = [];
tidyUp(elem, t);
};
if (!type) {
for (var t in data.handlers) removeType(t);
return;
}
var handlers = data.handlers[type];
if (!handlers) return;
if (!fn) {
removeType(type);
return;
}
if (fn.guid) {
for (var n = 0; n < handlers.length; n++) {
if (handlers[n].guid === fn.guid) {
handlers.splice(n--, 1);
}
}
}
tidyUp(elem, type);
};
this.proxy = function (context, fn) {
if (!fn.guid) {
fn.guid = nextGuid++;
}
var ret = function () {
return fn.apply(context, arguments);
};
ret.guid = fn.guid;
return ret;
};
};
/**
* Trigger a click on an element
* @param elem
*/
exports.triggerClick = function (elem) {
var evObj;
if (document.createEvent) {
window.setTimeout(function () {
evObj = document.createEvent("MouseEvents");
evObj.initEvent("click", true, true);
elem.dispatchEvent(evObj);
}, 0);
} else {
window.setTimeout(function () {
if (document.createEventObject) {
evObj = document.createEventObject();
evObj.cancelBubble = true;
elem.fireEvent("on" + "click", evObj);
}
}, 0);
}
};
var cache = new exports._ElementCache();
var eventManager = new exports._EventManager(cache);
eventManager.triggerClick = exports.triggerClick;
exports.manager = eventManager;

View file

@ -1,65 +0,0 @@
"use strict";
/**
* This is the plugin for syncing clicks between browsers
* @type {string}
*/
var EVENT_NAME = "click";
var OPT_PATH = "ghostMode.clicks";
exports.canEmitEvents = true;
/**
* @param {BrowserSync} bs
* @param eventManager
*/
exports.init = function (bs, eventManager) {
eventManager.addEvent(document.body, EVENT_NAME, exports.browserEvent(bs));
bs.socket.on(EVENT_NAME, exports.socketEvent(bs, eventManager));
};
/**
* Uses event delegation to determine the clicked element
* @param {BrowserSync} bs
* @returns {Function}
*/
exports.browserEvent = function (bs) {
return function (event) {
if (exports.canEmitEvents) {
var elem = event.target || event.srcElement;
if (elem.type === "checkbox" || elem.type === "radio") {
bs.utils.forceChange(elem);
return;
}
bs.socket.emit(EVENT_NAME, bs.utils.getElementData(elem));
} else {
exports.canEmitEvents = true;
}
};
};
/**
* @param {BrowserSync} bs
* @param {manager} eventManager
* @returns {Function}
*/
exports.socketEvent = function (bs, eventManager) {
return function (data) {
if (bs.canSync(data, OPT_PATH)) {
var elem = bs.utils.getSingleElement(data.tagName, data.index);
if (elem) {
exports.canEmitEvents = false;
eventManager.triggerClick(elem);
}
}
};
};

View file

@ -1,67 +0,0 @@
"use strict";
/**
* This is the plugin for syncing clicks between browsers
* @type {string}
*/
var EVENT_NAME = "input:text";
var OPT_PATH = "ghostMode.forms.inputs";
exports.canEmitEvents = true;
/**
* @param {BrowserSync} bs
* @param eventManager
*/
exports.init = function (bs, eventManager) {
eventManager.addEvent(document.body, "keyup", exports.browserEvent(bs));
bs.socket.on(EVENT_NAME, exports.socketEvent(bs, eventManager));
};
/**
* @param {BrowserSync} bs
* @returns {Function}
*/
exports.browserEvent = function (bs) {
return function (event) {
var elem = event.target || event.srcElement;
var data;
if (exports.canEmitEvents) {
if (elem.tagName === "INPUT" || elem.tagName === "TEXTAREA") {
data = bs.utils.getElementData(elem);
data.value = elem.value;
bs.socket.emit(EVENT_NAME, data);
}
} else {
exports.canEmitEvents = true;
}
};
};
/**
* @param {BrowserSync} bs
* @returns {Function}
*/
exports.socketEvent = function (bs) {
return function (data) {
if (bs.canSync(data, OPT_PATH)) {
var elem = bs.utils.getSingleElement(data.tagName, data.index);
if (elem) {
elem.value = data.value;
return elem;
}
}
return false;
};
};

View file

@ -1,35 +0,0 @@
"use strict";
exports.plugins = {
"inputs": require("./ghostmode.forms.input"),
"toggles": require("./ghostmode.forms.toggles"),
"submit": require("./ghostmode.forms.submit")
};
/**
* Load plugins for enabled options
* @param bs
*/
exports.init = function (bs, eventManager) {
var checkOpt = true;
var options = bs.options.ghostMode.forms;
if (options === true) {
checkOpt = false;
}
function init(name) {
exports.plugins[name].init(bs, eventManager);
}
for (var name in exports.plugins) {
if (!checkOpt) {
init(name);
} else {
if (options[name]) {
init(name);
}
}
}
};

View file

@ -1,60 +0,0 @@
"use strict";
/**
* This is the plugin for syncing clicks between browsers
* @type {string}
*/
var EVENT_NAME = "form:submit";
var OPT_PATH = "ghostMode.forms.submit";
exports.canEmitEvents = true;
/**
* @param {BrowserSync} bs
* @param eventManager
*/
exports.init = function (bs, eventManager) {
var browserEvent = exports.browserEvent(bs);
eventManager.addEvent(document.body, "submit", browserEvent);
eventManager.addEvent(document.body, "reset", browserEvent);
bs.socket.on(EVENT_NAME, exports.socketEvent(bs, eventManager));
};
/**
* @param {BrowserSync} bs
* @returns {Function}
*/
exports.browserEvent = function (bs) {
return function (event) {
if (exports.canEmitEvents) {
var elem = event.target || event.srcElement;
var data = bs.utils.getElementData(elem);
data.type = event.type;
bs.socket.emit(EVENT_NAME, data);
} else {
exports.canEmitEvents = true;
}
};
};
/**
* @param {BrowserSync} bs
* @returns {Function}
*/
exports.socketEvent = function (bs) {
return function (data) {
if (bs.canSync(data, OPT_PATH)) {
var elem = bs.utils.getSingleElement(data.tagName, data.index);
exports.canEmitEvents = false;
if (elem && data.type === "submit") {
elem.submit();
}
if (elem && data.type === "reset") {
elem.reset();
}
return false;
}
return false;
};
};

View file

@ -1,96 +0,0 @@
"use strict";
/**
* This is the plugin for syncing clicks between browsers
* @type {string}
*/
var EVENT_NAME = "input:toggles";
var OPT_PATH = "ghostMode.forms.toggles";
exports.canEmitEvents = true;
/**
* @param {BrowserSync} bs
* @param eventManager
*/
exports.init = function (bs, eventManager) {
var browserEvent = exports.browserEvent(bs);
exports.addEvents(eventManager, browserEvent);
bs.socket.on(EVENT_NAME, exports.socketEvent(bs, eventManager));
};
/**
* @param eventManager
* @param event
*/
exports.addEvents = function (eventManager, event) {
var elems = document.getElementsByTagName("select");
var inputs = document.getElementsByTagName("input");
addEvents(elems);
addEvents(inputs);
function addEvents(domElems) {
for (var i = 0, n = domElems.length; i < n; i += 1) {
eventManager.addEvent(domElems[i], "change", event);
}
}
};
/**
* @param {BrowserSync} bs
* @returns {Function}
*/
exports.browserEvent = function (bs) {
return function (event) {
if (exports.canEmitEvents) {
var elem = event.target || event.srcElement;
var data;
if (elem.type === "radio" || elem.type === "checkbox" || elem.tagName === "SELECT") {
data = bs.utils.getElementData(elem);
data.type = elem.type;
data.value = elem.value;
data.checked = elem.checked;
bs.socket.emit(EVENT_NAME, data);
}
} else {
exports.canEmitEvents = true;
}
};
};
/**
* @param {BrowserSync} bs
* @returns {Function}
*/
exports.socketEvent = function (bs) {
return function (data) {
if (bs.canSync(data, OPT_PATH)) {
exports.canEmitEvents = false;
var elem = bs.utils.getSingleElement(data.tagName, data.index);
if (elem) {
if (data.type === "radio") {
elem.checked = true;
}
if (data.type === "checkbox") {
elem.checked = data.checked;
}
if (data.tagName === "SELECT") {
elem.value = data.value;
}
return elem;
}
return false;
}
return false;
};
};

View file

@ -1,20 +0,0 @@
"use strict";
var eventManager = require("./events").manager;
exports.plugins = {
"scroll": require("./ghostmode.scroll"),
"clicks": require("./ghostmode.clicks"),
"forms": require("./ghostmode.forms"),
"location": require("./ghostmode.location")
};
/**
* Load plugins for enabled options
* @param bs
*/
exports.init = function (bs) {
for (var name in exports.plugins) {
exports.plugins[name].init(bs, eventManager);
}
};

View file

@ -1,45 +0,0 @@
"use strict";
/**
* This is the plugin for syncing location
* @type {string}
*/
var EVENT_NAME = "browser:location";
var OPT_PATH = "ghostMode.location";
exports.canEmitEvents = true;
/**
* @param {BrowserSync} bs
*/
exports.init = function (bs) {
bs.socket.on(EVENT_NAME, exports.socketEvent());
};
/**
* Respond to socket event
*/
exports.socketEvent = function (bs) {
return function (data) {
if (data.override || bs.canSync(data, OPT_PATH)) {
if (data.path) {
exports.setPath(data.path);
} else {
exports.setUrl(data.url);
}
}
};
};
/**
* @param url
*/
exports.setUrl = function (url) {
window.location = url;
};
/**
* @param path
*/
exports.setPath = function (path) {
window.location.pathname = path;
};

View file

@ -1,101 +0,0 @@
"use strict";
/**
* This is the plugin for syncing scroll between devices
* @type {string}
*/
var EVENT_NAME = "scroll";
var OPT_PATH = "ghostMode.scroll";
var utils;
exports.canEmitEvents = true;
/**
* @param {BrowserSync} bs
* @param eventManager
*/
exports.init = function (bs, eventManager) {
utils = bs.utils;
eventManager.addEvent(window, EVENT_NAME, exports.browserEvent(bs));
bs.socket.on(EVENT_NAME, exports.socketEvent(bs));
};
/**
* @param {BrowserSync} bs
*/
exports.socketEvent = function (bs) {
return function (data) {
var scrollSpace = utils.getScrollSpace();
exports.canEmitEvents = false;
if (!bs.canSync(data, OPT_PATH)) {
return false;
}
if (bs.options && bs.options.scrollProportionally) {
return window.scrollTo(0, scrollSpace.y * data.position.proportional); // % of y axis of scroll to px
} else {
return window.scrollTo(0, data.position.raw);
}
};
};
/**
* @param bs
*/
exports.browserEvent = function (bs) {
return function () {
var canSync = exports.canEmitEvents;
if (canSync) {
bs.socket.emit(EVENT_NAME, {
position: exports.getScrollPosition()
});
}
exports.canEmitEvents = true;
};
};
/**
* @returns {{raw: number, proportional: number}}
*/
exports.getScrollPosition = function () {
var pos = utils.getBrowserScrollPosition();
return {
raw: pos, // Get px of y axis of scroll
proportional: exports.getScrollTopPercentage(pos) // Get % of y axis of scroll
};
};
/**
* @param {{x: number, y: number}} scrollSpace
* @param scrollPosition
* @returns {{x: number, y: number}}
*/
exports.getScrollPercentage = function (scrollSpace, scrollPosition) {
var x = scrollPosition.x / scrollSpace.x;
var y = scrollPosition.y / scrollSpace.y;
return {
x: x || 0,
y: y
};
};
/**
* Get just the percentage of Y axis of scroll
* @returns {number}
*/
exports.getScrollTopPercentage = function (pos) {
var scrollSpace = utils.getScrollSpace();
var percentage = exports.getScrollPercentage(scrollSpace, pos);
return percentage.y;
};

View file

@ -1,70 +0,0 @@
"use strict";
var socket = require("./socket");
var shims = require("./client-shims");
var notify = require("./notify");
var codeSync = require("./code-sync");
var BrowserSync = require("./browser-sync");
var ghostMode = require("./ghostmode");
var emitter = require("./emitter");
var events = require("./events");
var utils = require("./browser.utils").utils;
var shouldReload = false;
/**
* @param options
*/
exports.init = function (options) {
if (shouldReload) {
utils.reloadBrowser();
}
var BS = window.___browserSync___ || {};
if (!BS.client) {
BS.client = true;
var browserSync = new BrowserSync(options);
// Always init on page load
ghostMode.init(browserSync);
codeSync.init(browserSync);
if (options.notify) {
notify.init(browserSync);
notify.flash("Connected to BrowserSync");
}
}
};
/**
* Handle individual socket connections
*/
socket.on("connection", exports.init);
socket.on("disconnect", function () {
notify.flash("Disconnected From BrowserSync");
shouldReload = true;
});
/**debug:start**/
if (window.__karma__) {
window.__bs_scroll__ = require("./ghostmode.scroll");
window.__bs_clicks__ = require("./ghostmode.clicks");
window.__bs_location__ = require("./ghostmode.location");
window.__bs_inputs__ = require("./ghostmode.forms.input");
window.__bs_toggles__ = require("./ghostmode.forms.toggles");
window.__bs_submit__ = require("./ghostmode.forms.submit");
window.__bs_forms__ = require("./ghostmode.forms");
window.__bs_utils__ = require("./browser.utils");
window.__bs_emitter__ = emitter;
window.__bs = BrowserSync;
window.__bs_notify__ = notify;
window.__bs_code_sync__ = codeSync;
window.__bs_ghost_mode__ = ghostMode;
window.__bs_socket__ = socket;
window.__bs_index__ = exports;
}
/**debug:end**/

View file

@ -1,108 +0,0 @@
"use strict";
var scroll = require("./ghostmode.scroll");
var styles = [
"display: none",
"padding: 15px",
"font-family: sans-serif",
"position: fixed",
"font-size: 0.9em",
"z-index: 9999",
"right: 0px",
"top: 0px",
"border-bottom-left-radius: 5px",
"background-color: #1B2032",
"margin: 0",
"color: white",
"text-align: center"
];
var browserSync;
var elem;
var options;
var timeoutInt;
/**
* @param {BrowserSync} bs
* @returns {*}
*/
exports.init = function (bs) {
browserSync = bs;
options = bs.options;
var cssStyles = styles;
if (options.notify.styles) {
cssStyles = options.notify.styles;
}
elem = document.createElement("DIV");
elem.id = "__bs_notify__";
elem.style.cssText = cssStyles.join(";");
document.getElementsByTagName("body")[0].appendChild(elem);
var flashFn = exports.watchEvent();
browserSync.emitter.on("notify", flashFn);
browserSync.socket.on("browser:notify", flashFn);
return elem;
};
/**
* @returns {Function}
*/
exports.watchEvent = function () {
return function (data) {
if (typeof data === "string") {
return exports.flash(data);
}
exports.flash(data.message, data.timeout);
};
};
/**
*
*/
exports.getElem = function () {
return elem;
};
/**
* @returns {number|*}
*/
exports.getScrollTop = function () {
return browserSync.utils.getBrowserScrollPosition().y;
};
/**
* @param message
* @param [timeout]
* @returns {*}
*/
exports.flash = function (message, timeout) {
var elem = exports.getElem();
// return if notify was never initialised
if (!elem) {
return false;
}
elem.innerHTML = message;
elem.style.display = "block";
if (timeoutInt) {
clearTimeout(timeoutInt);
timeoutInt = undefined;
}
timeoutInt = window.setTimeout(function () {
elem.style.display = "none";
}, timeout || 2000);
return elem;
};

View file

@ -1,40 +0,0 @@
"use strict";
/**
* @type {{emit: emit, on: on}}
*/
var BS = window.___browserSync___ || {};
exports.socket = BS.socket || {
emit: function(){},
on: function(){}
};
/**
* @returns {string}
*/
exports.getPath = function () {
return window.location.pathname;
};
/**
* Alias for socket.emit
* @param name
* @param data
*/
exports.emit = function (name, data) {
var socket = exports.socket;
if (socket && socket.emit) {
// send relative path of where the event is sent
data.url = exports.getPath();
socket.emit(name, data);
}
};
/**
* Alias for socket.on
* @param name
* @param func
*/
exports.on = function (name, func) {
exports.socket.on(name, func);
};

View file

@ -1,75 +0,0 @@
{
"name": "browser-sync-client",
"description": "Client-side scripts for BrowserSync",
"version": "0.5.1",
"homepage": "https://github.com/shakyshane/browser-sync-client",
"author": {
"name": "Shane Osbourne",
"email": "shane.osbourne8@gmail.com"
},
"repository": {
"type": "git",
"url": "git://github.com/shakyshane/browser-sync-client.git"
},
"bugs": {
"url": "https://github.com/shakyshane/browser-sync-client/issues"
},
"licenses": [
{
"type": "MIT",
"url": "https://github.com/shakyshane/browser-sync-client/blob/master/LICENSE-MIT"
}
],
"main": "index.js",
"engines": {
"node": ">= 0.8.0"
},
"scripts": {
"test": "gulp && mocha test/middleware"
},
"devDependencies": {
"gulp-karma": "0.0.4",
"gulp-jshint": "~1.4.0",
"chai": "~1.9.0",
"sinon": "~1.8.2",
"karma-mocha": "~0.1.1",
"karma-sinon": "~1.0.0",
"gulp-contribs": "0.0.2",
"karma-firefox-launcher": "^0.1.3",
"karma-html2js-preprocessor": "^0.1.0",
"gulp-browserify": "^0.5.0",
"gulp-uglify": "^0.2.1",
"gulp": "^3.6.0",
"karma-coverage": "^0.2.1",
"karma-chrome-launcher": "^0.1.3",
"express": "^4.0.0",
"gulp-rename": "^1.2.0",
"mocha": "^1.18.2",
"through2": "^0.4.1",
"supertest": "^0.10.0"
},
"keywords": [],
"dependencies": {},
"gitHead": "da3e9b6d8c964abff8d583d5c8d0a51d24dfb08e",
"_id": "browser-sync-client@0.5.1",
"_shasum": "83d7022f1ceefb43d6b81a28bef9a5f7aab71a4e",
"_from": "browser-sync-client@^0.5.1",
"_npmVersion": "2.0.0",
"_npmUser": {
"name": "shakyshane",
"email": "shakyshane@gmail.com"
},
"maintainers": [
{
"name": "shakyshane",
"email": "shane.osbourne8@gmail.com"
}
],
"dist": {
"shasum": "83d7022f1ceefb43d6b81a28bef9a5f7aab71a4e",
"tarball": "http://registry.npmjs.org/browser-sync-client/-/browser-sync-client-0.5.1.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/browser-sync-client/-/browser-sync-client-0.5.1.tgz",
"readme": "ERROR: No README data found!"
}

View file

@ -1,239 +0,0 @@
# Commander.js
[![Build Status](https://api.travis-ci.org/tj/commander.js.svg)](http://travis-ci.org/tj/commander.js)
[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/tj/commander).
## Installation
$ npm install commander
## Option parsing
Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.0.1')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);
console.log('you ordered a pizza with:');
if (program.peppers) console.log(' - peppers');
if (program.pineapple) console.log(' - pineapple');
if (program.bbq) console.log(' - bbq');
console.log(' - %s cheese', program.cheese);
```
Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.
## Variadic arguments
The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to
append `...` to the argument name. Here is an example:
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.0.1')
.command('rmdir <dir> [otherDirs...]')
.action(function (dir, otherDirs) {
console.log('rmdir %s', dir);
if (otherDirs) {
otherDirs.forEach(function (oDir) {
console.log('rmdir %s', oDir);
});
}
});
program.parse(process.argv);
```
An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed
to your action as demonstrated above.
## Automated --help
The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
```
$ ./examples/pizza --help
Usage: pizza [options]
Options:
-V, --version output the version number
-p, --peppers Add peppers
-P, --pineapple Add pineapple
-b, --bbq Add bbq sauce
-c, --cheese <type> Add the specified type of cheese [marble]
-h, --help output usage information
```
## Coercion
```js
function range(val) {
return val.split('..').map(Number);
}
function list(val) {
return val.split(',');
}
function collect(val, memo) {
memo.push(val);
return memo;
}
function increaseVerbosity(v, total) {
return total + 1;
}
program
.version('0.0.1')
.usage('[options] <file ...>')
.option('-i, --integer <n>', 'An integer argument', parseInt)
.option('-f, --float <n>', 'A float argument', parseFloat)
.option('-r, --range <a>..<b>', 'A range', range)
.option('-l, --list <items>', 'A list', list)
.option('-o, --optional [value]', 'An optional value')
.option('-c, --collect [value]', 'A repeatable value', collect, [])
.option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
.parse(process.argv);
console.log(' int: %j', program.integer);
console.log(' float: %j', program.float);
console.log(' optional: %j', program.optional);
program.range = program.range || [];
console.log(' range: %j..%j', program.range[0], program.range[1]);
console.log(' list: %j', program.list);
console.log(' collect: %j', program.collect);
console.log(' verbosity: %j', program.verbose);
console.log(' args: %j', program.args);
```
## Custom help
You can display arbitrary `-h, --help` information
by listening for "--help". Commander will automatically
exit once you are done so that the remainder of your program
does not execute causing undesired behaviours, for example
in the following executable "stuff" will not output when
`--help` is used.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('../');
program
.version('0.0.1')
.option('-f, --foo', 'enable some foo')
.option('-b, --bar', 'enable some bar')
.option('-B, --baz', 'enable some baz');
// must be before .parse() since
// node's emit() is immediate
program.on('--help', function(){
console.log(' Examples:');
console.log('');
console.log(' $ custom-help --help');
console.log(' $ custom-help -h');
console.log('');
});
program.parse(process.argv);
console.log('stuff');
```
yielding the following help output:
```
Usage: custom-help [options]
Options:
-h, --help output usage information
-V, --version output the version number
-f, --foo enable some foo
-b, --bar enable some bar
-B, --baz enable some baz
Examples:
$ custom-help --help
$ custom-help -h
```
## .outputHelp()
Output help information without exiting.
## .help()
Output help information and exit immediately.
## Links
- [API documentation](http://tj.github.com/commander.js/)
- [ascii tables](https://github.com/LearnBoost/cli-table)
- [progress bars](https://github.com/tj/node-progress)
- [more progress bars](https://github.com/substack/node-multimeter)
- [examples](https://github.com/tj/commander.js/tree/master/examples)
## License
(The MIT License)
Copyright (c) 2011 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,981 +0,0 @@
/**
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter;
var spawn = require('child_process').spawn;
var path = require('path');
var dirname = path.dirname;
var basename = path.basename;
/**
* Expose the root command.
*/
exports = module.exports = new Command();
/**
* Expose `Command`.
*/
exports.Command = Command;
/**
* Expose `Option`.
*/
exports.Option = Option;
/**
* Initialize a new `Option` with the given `flags` and `description`.
*
* @param {String} flags
* @param {String} description
* @api public
*/
function Option(flags, description) {
this.flags = flags;
this.required = ~flags.indexOf('<');
this.optional = ~flags.indexOf('[');
this.bool = !~flags.indexOf('-no-');
flags = flags.split(/[ ,|]+/);
if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();
this.long = flags.shift();
this.description = description || '';
}
/**
* Return option name.
*
* @return {String}
* @api private
*/
Option.prototype.name = function() {
return this.long
.replace('--', '')
.replace('no-', '');
};
/**
* Check if `arg` matches the short or long flag.
*
* @param {String} arg
* @return {Boolean}
* @api private
*/
Option.prototype.is = function(arg) {
return arg == this.short || arg == this.long;
};
/**
* Initialize a new `Command`.
*
* @param {String} name
* @api public
*/
function Command(name) {
this.commands = [];
this.options = [];
this._execs = [];
this._args = [];
this._name = name;
}
/**
* Inherit from `EventEmitter.prototype`.
*/
Command.prototype.__proto__ = EventEmitter.prototype;
/**
* Add command `name`.
*
* The `.action()` callback is invoked when the
* command `name` is specified via __ARGV__,
* and the remaining arguments are applied to the
* function for access.
*
* When the `name` is "*" an un-matched command
* will be passed as the first arg, followed by
* the rest of __ARGV__ remaining.
*
* Examples:
*
* program
* .version('0.0.1')
* .option('-C, --chdir <path>', 'change the working directory')
* .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
* .option('-T, --no-tests', 'ignore test hook')
*
* program
* .command('setup')
* .description('run remote setup commands')
* .action(function() {
* console.log('setup');
* });
*
* program
* .command('exec <cmd>')
* .description('run the given remote command')
* .action(function(cmd) {
* console.log('exec "%s"', cmd);
* });
*
* program
* .command('teardown <dir> [otherDirs...]')
* .description('run teardown commands')
* .action(function(dir, otherDirs) {
* console.log('dir "%s"', dir);
* if (otherDirs) {
* otherDirs.forEach(function (oDir) {
* console.log('dir "%s"', oDir);
* });
* }
* });
*
* program
* .command('*')
* .description('deploy the given env')
* .action(function(env) {
* console.log('deploying "%s"', env);
* });
*
* program.parse(process.argv);
*
* @param {String} name
* @param {String} [desc]
* @return {Command} the new command
* @api public
*/
Command.prototype.command = function(name, desc) {
var args = name.split(/ +/);
var cmd = new Command(args.shift());
if (desc) cmd.description(desc);
if (desc) this.executables = true;
if (desc) this._execs[cmd._name] = true;
this.commands.push(cmd);
cmd.parseExpectedArgs(args);
cmd.parent = this;
if (desc) return this;
return cmd;
};
/**
* Add an implicit `help [cmd]` subcommand
* which invokes `--help` for the given command.
*
* @api private
*/
Command.prototype.addImplicitHelpCommand = function() {
this.command('help [cmd]', 'display help for [cmd]');
};
/**
* Parse expected `args`.
*
* For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
*
* @param {Array} args
* @return {Command} for chaining
* @api public
*/
Command.prototype.parseExpectedArgs = function(args) {
if (!args.length) return;
var self = this;
args.forEach(function(arg) {
var argDetails = {
required: false,
name: '',
variadic: false
};
switch (arg[0]) {
case '<':
argDetails.required = true;
argDetails.name = arg.slice(1, -1);
break;
case '[':
argDetails.name = arg.slice(1, -1);
break;
}
if (argDetails.name.indexOf('...') === argDetails.name.length - 3) {
argDetails.variadic = true;
argDetails.name = argDetails.name.slice(0, -3);
}
if (argDetails.name) {
self._args.push(argDetails);
}
});
return this;
};
/**
* Register callback `fn` for the command.
*
* Examples:
*
* program
* .command('help')
* .description('display verbose help')
* .action(function() {
* // output help here
* });
*
* @param {Function} fn
* @return {Command} for chaining
* @api public
*/
Command.prototype.action = function(fn) {
var self = this;
var listener = function(args, unknown) {
// Parse any so-far unknown options
args = args || [];
unknown = unknown || [];
var parsed = self.parseOptions(unknown);
// Output help if necessary
outputHelpIfNecessary(self, parsed.unknown);
// If there are still any unknown options, then we simply
// die, unless someone asked for help, in which case we give it
// to them, and then we die.
if (parsed.unknown.length > 0) {
self.unknownOption(parsed.unknown[0]);
}
// Leftover arguments need to be pushed back. Fixes issue #56
if (parsed.args.length) args = parsed.args.concat(args);
self._args.forEach(function(arg, i) {
if (arg.required && null == args[i]) {
self.missingArgument(arg.name);
} else if (arg.variadic) {
if (i !== self._args.length - 1) {
self.variadicArgNotLast(arg.name);
}
args[i] = args.slice(i);
}
});
// Always append ourselves to the end of the arguments,
// to make sure we match the number of arguments the user
// expects
if (self._args.length) {
args[self._args.length] = self;
} else {
args.push(self);
}
fn.apply(self, args);
};
this.parent.on(this._name, listener);
if (this._alias) this.parent.on(this._alias, listener);
return this;
};
/**
* Define option with `flags`, `description` and optional
* coercion `fn`.
*
* The `flags` string should contain both the short and long flags,
* separated by comma, a pipe or space. The following are all valid
* all will output this way when `--help` is used.
*
* "-p, --pepper"
* "-p|--pepper"
* "-p --pepper"
*
* Examples:
*
* // simple boolean defaulting to false
* program.option('-p, --pepper', 'add pepper');
*
* --pepper
* program.pepper
* // => Boolean
*
* // simple boolean defaulting to true
* program.option('-C, --no-cheese', 'remove cheese');
*
* program.cheese
* // => true
*
* --no-cheese
* program.cheese
* // => false
*
* // required argument
* program.option('-C, --chdir <path>', 'change the working directory');
*
* --chdir /tmp
* program.chdir
* // => "/tmp"
*
* // optional argument
* program.option('-c, --cheese [type]', 'add cheese [marble]');
*
* @param {String} flags
* @param {String} description
* @param {Function|Mixed} fn or default
* @param {Mixed} defaultValue
* @return {Command} for chaining
* @api public
*/
Command.prototype.option = function(flags, description, fn, defaultValue) {
var self = this
, option = new Option(flags, description)
, oname = option.name()
, name = camelcase(oname);
// default as 3rd arg
if (typeof fn != 'function') {
defaultValue = fn;
fn = null;
}
// preassign default value only for --no-*, [optional], or <required>
if (false == option.bool || option.optional || option.required) {
// when --no-* we make sure default is true
if (false == option.bool) defaultValue = true;
// preassign only if we have a default
if (undefined !== defaultValue) self[name] = defaultValue;
}
// register the option
this.options.push(option);
// when it's passed assign the value
// and conditionally invoke the callback
this.on(oname, function(val) {
// coercion
if (null !== val && fn) val = fn(val, undefined === self[name]
? defaultValue
: self[name]);
// unassigned or bool
if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) {
// if no value, bool true, and we have a default, then use it!
if (null == val) {
self[name] = option.bool
? defaultValue || true
: false;
} else {
self[name] = val;
}
} else if (null !== val) {
// reassign
self[name] = val;
}
});
return this;
};
/**
* Parse `argv`, settings options and invoking commands when defined.
*
* @param {Array} argv
* @return {Command} for chaining
* @api public
*/
Command.prototype.parse = function(argv) {
// implicit help
if (this.executables) this.addImplicitHelpCommand();
// store raw args
this.rawArgs = argv;
// guess name
this._name = this._name || basename(argv[1], '.js');
// process argv
var parsed = this.parseOptions(this.normalize(argv.slice(2)));
var args = this.args = parsed.args;
var result = this.parseArgs(this.args, parsed.unknown);
// executable sub-commands
var name = result.args[0];
if (this._execs[name] && typeof this._execs[name] != "function") {
return this.executeSubCommand(argv, args, parsed.unknown);
}
return result;
};
/**
* Execute a sub-command executable.
*
* @param {Array} argv
* @param {Array} args
* @param {Array} unknown
* @api private
*/
Command.prototype.executeSubCommand = function(argv, args, unknown) {
args = args.concat(unknown);
if (!args.length) this.help();
if ('help' == args[0] && 1 == args.length) this.help();
// <cmd> --help
if ('help' == args[0]) {
args[0] = args[1];
args[1] = '--help';
}
// executable
var dir = dirname(argv[1]);
var bin = basename(argv[1], '.js') + '-' + args[0];
// check for ./<bin> first
var local = path.join(dir, bin);
// run it
args = args.slice(1);
args.unshift(local);
var proc = spawn('node', args, { stdio: 'inherit', customFds: [0, 1, 2] });
proc.on('error', function(err) {
if (err.code == "ENOENT") {
console.error('\n %s(1) does not exist, try --help\n', bin);
} else if (err.code == "EACCES") {
console.error('\n %s(1) not executable. try chmod or run with root\n', bin);
}
});
this.runningCommand = proc;
};
/**
* Normalize `args`, splitting joined short flags. For example
* the arg "-abc" is equivalent to "-a -b -c".
* This also normalizes equal sign and splits "--abc=def" into "--abc def".
*
* @param {Array} args
* @return {Array}
* @api private
*/
Command.prototype.normalize = function(args) {
var ret = []
, arg
, lastOpt
, index;
for (var i = 0, len = args.length; i < len; ++i) {
arg = args[i];
if (i > 0) {
lastOpt = this.optionFor(args[i-1]);
}
if (arg === '--') {
// Honor option terminator
ret = ret.concat(args.slice(i));
break;
} else if (lastOpt && lastOpt.required) {
ret.push(arg);
} else if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) {
arg.slice(1).split('').forEach(function(c) {
ret.push('-' + c);
});
} else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) {
ret.push(arg.slice(0, index), arg.slice(index + 1));
} else {
ret.push(arg);
}
}
return ret;
};
/**
* Parse command `args`.
*
* When listener(s) are available those
* callbacks are invoked, otherwise the "*"
* event is emitted and those actions are invoked.
*
* @param {Array} args
* @return {Command} for chaining
* @api private
*/
Command.prototype.parseArgs = function(args, unknown) {
var name;
if (args.length) {
name = args[0];
if (this.listeners(name).length) {
this.emit(args.shift(), args, unknown);
} else {
this.emit('*', args);
}
} else {
outputHelpIfNecessary(this, unknown);
// If there were no args and we have unknown options,
// then they are extraneous and we need to error.
if (unknown.length > 0) {
this.unknownOption(unknown[0]);
}
}
return this;
};
/**
* Return an option matching `arg` if any.
*
* @param {String} arg
* @return {Option}
* @api private
*/
Command.prototype.optionFor = function(arg) {
for (var i = 0, len = this.options.length; i < len; ++i) {
if (this.options[i].is(arg)) {
return this.options[i];
}
}
};
/**
* Parse options from `argv` returning `argv`
* void of these options.
*
* @param {Array} argv
* @return {Array}
* @api public
*/
Command.prototype.parseOptions = function(argv) {
var args = []
, len = argv.length
, literal
, option
, arg;
var unknownOptions = [];
// parse options
for (var i = 0; i < len; ++i) {
arg = argv[i];
// literal args after --
if ('--' == arg) {
literal = true;
continue;
}
if (literal) {
args.push(arg);
continue;
}
// find matching Option
option = this.optionFor(arg);
// option is defined
if (option) {
// requires arg
if (option.required) {
arg = argv[++i];
if (null == arg) return this.optionMissingArgument(option);
this.emit(option.name(), arg);
// optional arg
} else if (option.optional) {
arg = argv[i+1];
if (null == arg || ('-' == arg[0] && '-' != arg)) {
arg = null;
} else {
++i;
}
this.emit(option.name(), arg);
// bool
} else {
this.emit(option.name());
}
continue;
}
// looks like an option
if (arg.length > 1 && '-' == arg[0]) {
unknownOptions.push(arg);
// If the next argument looks like it might be
// an argument for this option, we pass it on.
// If it isn't, then it'll simply be ignored
if (argv[i+1] && '-' != argv[i+1][0]) {
unknownOptions.push(argv[++i]);
}
continue;
}
// arg
args.push(arg);
}
return { args: args, unknown: unknownOptions };
};
/**
* Return an object containing options as key-value pairs
*
* @return {Object}
* @api public
*/
Command.prototype.opts = function() {
var result = {}
, len = this.options.length;
for (var i = 0 ; i < len; i++) {
var key = this.options[i].name();
result[key] = key === 'version' ? this._version : this[key];
}
return result;
};
/**
* Argument `name` is missing.
*
* @param {String} name
* @api private
*/
Command.prototype.missingArgument = function(name) {
console.error();
console.error(" error: missing required argument `%s'", name);
console.error();
process.exit(1);
};
/**
* `Option` is missing an argument, but received `flag` or nothing.
*
* @param {String} option
* @param {String} flag
* @api private
*/
Command.prototype.optionMissingArgument = function(option, flag) {
console.error();
if (flag) {
console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag);
} else {
console.error(" error: option `%s' argument missing", option.flags);
}
console.error();
process.exit(1);
};
/**
* Unknown option `flag`.
*
* @param {String} flag
* @api private
*/
Command.prototype.unknownOption = function(flag) {
console.error();
console.error(" error: unknown option `%s'", flag);
console.error();
process.exit(1);
};
/**
* Variadic argument with `name` is not the last argument as required.
*
* @param {String} name
* @api private
*/
Command.prototype.variadicArgNotLast = function(name) {
console.error();
console.error(" error: variadic arguments must be last `%s'", name);
console.error();
process.exit(1);
};
/**
* Set the program version to `str`.
*
* This method auto-registers the "-V, --version" flag
* which will print the version number when passed.
*
* @param {String} str
* @param {String} flags
* @return {Command} for chaining
* @api public
*/
Command.prototype.version = function(str, flags) {
if (0 == arguments.length) return this._version;
this._version = str;
flags = flags || '-V, --version';
this.option(flags, 'output the version number');
this.on('version', function() {
process.stdout.write(str + '\n');
process.exit(0);
});
return this;
};
/**
* Set the description to `str`.
*
* @param {String} str
* @return {String|Command}
* @api public
*/
Command.prototype.description = function(str) {
if (0 == arguments.length) return this._description;
this._description = str;
return this;
};
/**
* Set an alias for the command
*
* @param {String} alias
* @return {String|Command}
* @api public
*/
Command.prototype.alias = function(alias) {
if (0 == arguments.length) return this._alias;
this._alias = alias;
return this;
};
/**
* Set / get the command usage `str`.
*
* @param {String} str
* @return {String|Command}
* @api public
*/
Command.prototype.usage = function(str) {
var args = this._args.map(function(arg) {
return humanReadableArgName(arg);
});
var usage = '[options]'
+ (this.commands.length ? ' [command]' : '')
+ (this._args.length ? ' ' + args.join(' ') : '');
if (0 == arguments.length) return this._usage || usage;
this._usage = str;
return this;
};
/**
* Get the name of the command
*
* @param {String} name
* @return {String|Command}
* @api public
*/
Command.prototype.name = function(name) {
return this._name;
};
/**
* Return the largest option length.
*
* @return {Number}
* @api private
*/
Command.prototype.largestOptionLength = function() {
return this.options.reduce(function(max, option) {
return Math.max(max, option.flags.length);
}, 0);
};
/**
* Return help for options.
*
* @return {String}
* @api private
*/
Command.prototype.optionHelp = function() {
var width = this.largestOptionLength();
// Prepend the help information
return [pad('-h, --help', width) + ' ' + 'output usage information']
.concat(this.options.map(function(option) {
return pad(option.flags, width) + ' ' + option.description;
}))
.join('\n');
};
/**
* Return command help documentation.
*
* @return {String}
* @api private
*/
Command.prototype.commandHelp = function() {
if (!this.commands.length) return '';
var commands = this.commands.map(function(cmd) {
var args = cmd._args.map(function(arg) {
return humanReadableArgName(arg);
}).join(' ');
return [
cmd._name
+ (cmd._alias
? '|' + cmd._alias
: '')
+ (cmd.options.length
? ' [options]'
: '')
+ ' ' + args
, cmd.description()
];
});
var width = commands.reduce(function(max, command) {
return Math.max(max, command[0].length);
}, 0);
return [
''
, ' Commands:'
, ''
, commands.map(function(cmd) {
return pad(cmd[0], width) + ' ' + cmd[1];
}).join('\n').replace(/^/gm, ' ')
, ''
].join('\n');
};
/**
* Return program help documentation.
*
* @return {String}
* @api private
*/
Command.prototype.helpInformation = function() {
return [
''
, ' Usage: ' + this._name
+ (this._alias
? '|' + this._alias
: '')
+ ' ' + this.usage()
, '' + this.commandHelp()
, ' Options:'
, ''
, '' + this.optionHelp().replace(/^/gm, ' ')
, ''
, ''
].join('\n');
};
/**
* Output help information for this command
*
* @api public
*/
Command.prototype.outputHelp = function() {
process.stdout.write(this.helpInformation());
this.emit('--help');
};
/**
* Output help information and exit.
*
* @api public
*/
Command.prototype.help = function() {
this.outputHelp();
process.exit();
};
/**
* Camel-case the given `flag`
*
* @param {String} flag
* @return {String}
* @api private
*/
function camelcase(flag) {
return flag.split('-').reduce(function(str, word) {
return str + word[0].toUpperCase() + word.slice(1);
});
}
/**
* Pad `str` to `width`.
*
* @param {String} str
* @param {Number} width
* @return {String}
* @api private
*/
function pad(str, width) {
var len = Math.max(0, width - str.length);
return str + Array(len + 1).join(' ');
}
/**
* Output help information if necessary
*
* @param {Command} command to output help for
* @param {Array} array of options to search for -h or --help
* @api private
*/
function outputHelpIfNecessary(cmd, options) {
options = options || [];
for (var i = 0; i < options.length; i++) {
if (options[i] == '--help' || options[i] == '-h') {
cmd.outputHelp();
process.exit(0);
}
}
}
/**
* Takes an argument an returns its human readable equivalent for help usage.
*
* @param {Object} arg
* @return {String}
* @api private
*/
function humanReadableArgName(arg) {
var nameOutput = arg.name + (arg.variadic === true ? '...' : '');
return arg.required
? '<' + nameOutput + '>'
: '[' + nameOutput + ']'
}

View file

@ -1,70 +0,0 @@
{
"name": "commander",
"version": "2.5.0",
"description": "the complete solution for node.js command-line programs",
"keywords": [
"command",
"option",
"parser",
"prompt"
],
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/tj/commander.js.git"
},
"devDependencies": {
"should": ">= 0.0.1"
},
"scripts": {
"test": "make test"
},
"main": "index",
"engines": {
"node": ">= 0.6.x"
},
"files": [
"index.js"
],
"bugs": {
"url": "https://github.com/tj/commander.js/issues"
},
"homepage": "https://github.com/tj/commander.js",
"_id": "commander@2.5.0",
"_shasum": "d777b6a4d847d423e5d475da864294ac1ff5aa9d",
"_from": "commander@^2.3.0",
"_npmVersion": "1.4.9",
"_npmUser": {
"name": "zhiyelee",
"email": "zhiyelee@gmail.com"
},
"maintainers": [
{
"name": "tjholowaychuk",
"email": "tj@vision-media.ca"
},
{
"name": "somekittens",
"email": "rkoutnik@gmail.com"
},
{
"name": "zhiyelee",
"email": "zhiyelee@gmail.com"
},
{
"name": "thethomaseffect",
"email": "thethomaseffect@gmail.com"
}
],
"dist": {
"shasum": "d777b6a4d847d423e5d475da864294ac1ff5aa9d",
"tarball": "http://registry.npmjs.org/commander/-/commander-2.5.0.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/commander/-/commander-2.5.0.tgz",
"readme": "ERROR: No README data found!"
}

View file

@ -1,4 +0,0 @@
coverage/
docs/
test/
.travis.yml

File diff suppressed because it is too large Load diff

View file

@ -1,24 +0,0 @@
(The MIT License)
Copyright (c) 2010 Sencha Inc.
Copyright (c) 2011 LearnBoost
Copyright (c) 2011-2014 TJ Holowaychuk
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,194 +0,0 @@
# Connect
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
[![Gittip][gittip-image]][gittip-url]
Connect is an extensible HTTP server framework for [node](http://nodejs.org) using "plugins" known as _middleware_.
```js
var connect = require('connect')
var http = require('http')
var app = connect()
// gzip/deflate outgoing responses
var compression = require('compression')
app.use(compression())
// store session state in browser cookie
var cookieSession = require('cookie-session')
app.use(cookieSession({
keys: ['secret1', 'secret2']
}))
// parse urlencoded request bodies into req.body
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded())
// respond to all requests
app.use(function(req, res){
res.end('Hello from Connect!\n');
})
//create node.js http server and listen on port
http.createServer(app).listen(3000)
```
## Getting Started
Connect is a simple framework to glue together various "middleware" to handle requests.
### Install Connect
```sh
$ npm install connect
```
### Create an app
The main component is a Connect "app". This will store all the middleware
added and is, itself, a function.
```js
var app = connect();
```
### Use middleware
The core of Connect is "using" middleware. Middleware are added as a "stack"
where incoming requests will execute each middleware one-by-one until a middleware
does not call `next()` within it.
```js
app.use(function middleware1(req, res, next) {
// middleware 1
next();
});
app.use(function middleware2(req, res, next) {
// middleware 2
next();
});
```
### Mount middleware
The `.use()` method also takes an optional path string that is matched against
the beginning of the incoming request URL. This allows for basic routing.
```js
app.use('/foo', function fooMiddleware(req, res, next) {
// req.url starts with "/foo"
next();
});
app.use('/bar', function barMiddleware(req, res, next) {
// req.url starts with "/bar"
next();
});
```
### Error middleware
There are special cases of "error-handling" middleware. There are middleware
where the function takes exactly 4 arguments. Errors that occur in the middleware
added before the error middleware will invoke this middleware when errors occur.
```js
app.use(function onerror(err, req, res, next) {
// an error occurred!
});
```
### Create a server from the app
The last step is to actually use the Connect app in a server. The `.listen()` method
is a convenience to start a HTTP server.
```js
var server = app.listen(port);
```
The app itself is really just a function with three arguments, so it can also be handed
to `.createServer()` in Node.js.
```js
var server = http.createServer(app);
```
## Middleware
These middleware and libraries are officially supported by the Connect/Express team:
- [body-parser](https://github.com/expressjs/body-parser) - previous `bodyParser`, `json`, and `urlencoded`. You may also be interested in:
- [body](https://github.com/raynos/body)
- [co-body](https://github.com/visionmedia/co-body)
- [raw-body](https://github.com/stream-utils/raw-body)
- [compression](https://github.com/expressjs/compression) - previously `compress`
- [connect-timeout](https://github.com/expressjs/timeout) - previously `timeout`
- [cookie-parser](https://github.com/expressjs/cookie-parser) - previously `cookieParser`
- [cookie-session](https://github.com/expressjs/cookie-session) - previously `cookieSession`
- [csurf](https://github.com/expressjs/csurf) - previously `csrf`
- [errorhandler](https://github.com/expressjs/errorhandler) - previously `error-handler`
- [express-session](https://github.com/expressjs/session) - previously `session`
- [method-override](https://github.com/expressjs/method-override) - previously `method-override`
- [morgan](https://github.com/expressjs/morgan) - previously `logger`
- [response-time](https://github.com/expressjs/response-time) - previously `response-time`
- [serve-favicon](https://github.com/expressjs/serve-favicon) - previously `favicon`
- [serve-index](https://github.com/expressjs/serve-index) - previously `directory`
- [serve-static](https://github.com/expressjs/serve-static) - previously `static`
- [vhost](https://github.com/expressjs/vhost) - previously `vhost`
Most of these are exact ports of their Connect 2.x equivalents. The primary exception is `cookie-session`.
Some middleware previously included with Connect are no longer supported by the Connect/Express team, are replaced by an alternative module, or should be superseded by a better module. Use one of these alternatives instead:
- `cookieParser`
- [cookies](https://github.com/jed/cookies) and [keygrip](https://github.com/jed/keygrip)
- `limit`
- [raw-body](https://github.com/stream-utils/raw-body)
- `multipart`
- [connect-multiparty](https://github.com/superjoe30/connect-multiparty)
- [connect-busboy](https://github.com/mscdex/connect-busboy)
- `query`
- [qs](https://github.com/visionmedia/node-querystring)
- `staticCache`
- [st](https://github.com/isaacs/st)
- [connect-static](https://github.com/andrewrk/connect-static)
Checkout [http-framework](https://github.com/Raynos/http-framework/wiki/Modules) for many other compatible middleware!
## Running Tests
```bash
npm install
npm test
```
## Contributors
https://github.com/senchalabs/connect/graphs/contributors
## Node Compatibility
- Connect `< 1.x` - node `0.2`
- Connect `1.x` - node `0.4`
- Connect `< 2.8` - node `0.6`
- Connect `>= 2.8 < 3` - node `0.8`
- Connect `>= 3` - node `0.10`
## License
[MIT](LICENSE)
[npm-image]: https://img.shields.io/npm/v/connect.svg?style=flat
[npm-url]: https://npmjs.org/package/connect
[travis-image]: https://img.shields.io/travis/senchalabs/connect.svg?style=flat
[travis-url]: https://travis-ci.org/senchalabs/connect
[coveralls-image]: https://img.shields.io/coveralls/senchalabs/connect.svg?style=flat
[coveralls-url]: https://coveralls.io/r/senchalabs/connect
[downloads-image]: https://img.shields.io/npm/dm/connect.svg?style=flat
[downloads-url]: https://npmjs.org/package/connect
[gittip-image]: https://img.shields.io/gittip/dougwilson.svg?style=flat
[gittip-url]: https://www.gittip.com/dougwilson/

View file

@ -1,2 +0,0 @@
module.exports = require('./lib/connect');

View file

@ -1,34 +0,0 @@
/*!
* Connect
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter;
var merge = require('utils-merge');
var proto = require('./proto');
// expose createServer() as the module
module.exports = createServer;
/**
* Create a new connect server.
*
* @return {Function}
* @api public
*/
function createServer() {
function app(req, res, next){ app.handle(req, res, next); }
merge(app, proto);
merge(app, EventEmitter.prototype);
app.route = '/';
app.stack = [];
return app;
}

View file

@ -1,231 +0,0 @@
/*!
* Connect - HTTPServer
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var finalhandler = require('finalhandler');
var http = require('http');
var debug = require('debug')('connect:dispatcher');
var parseUrl = require('parseurl');
// prototype
var app = module.exports = {};
// environment
var env = process.env.NODE_ENV || 'development';
/* istanbul ignore next */
var defer = typeof setImmediate === 'function'
? setImmediate
: function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) }
/**
* Utilize the given middleware `handle` to the given `route`,
* defaulting to _/_. This "route" is the mount-point for the
* middleware, when given a value other than _/_ the middleware
* is only effective when that segment is present in the request's
* pathname.
*
* For example if we were to mount a function at _/admin_, it would
* be invoked on _/admin_, and _/admin/settings_, however it would
* not be invoked for _/_, or _/posts_.
*
* @param {String|Function|Server} route, callback or server
* @param {Function|Server} callback or server
* @return {Server} for chaining
* @api public
*/
app.use = function(route, fn){
// default route to '/'
if ('string' != typeof route) {
fn = route;
route = '/';
}
// wrap sub-apps
if ('function' == typeof fn.handle) {
var server = fn;
server.route = route;
fn = function(req, res, next){
server.handle(req, res, next);
};
}
// wrap vanilla http.Servers
if (fn instanceof http.Server) {
fn = fn.listeners('request')[0];
}
// strip trailing slash
if ('/' == route[route.length - 1]) {
route = route.slice(0, -1);
}
// add the middleware
debug('use %s %s', route || '/', fn.name || 'anonymous');
this.stack.push({ route: route, handle: fn });
return this;
};
/**
* Handle server requests, punting them down
* the middleware stack.
*
* @api private
*/
app.handle = function(req, res, out) {
var stack = this.stack
, searchIndex = req.url.indexOf('?')
, pathlength = searchIndex !== -1 ? searchIndex : req.url.length
, fqdn = req.url[0] !== '/' && 1 + req.url.substr(0, pathlength).indexOf('://')
, protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : ''
, removed = ''
, slashAdded = false
, index = 0;
// final function handler
var done = out || finalhandler(req, res, {
env: env,
onerror: logerror
});
// store the original URL
req.originalUrl = req.originalUrl || req.url;
function next(err) {
if (slashAdded) {
req.url = req.url.substr(1);
slashAdded = false;
}
if (removed.length !== 0) {
req.url = protohost + removed + req.url.substr(protohost.length);
removed = '';
}
// next callback
var layer = stack[index++];
// all done
if (!layer) {
defer(done, err);
return;
}
// route data
var path = parseUrl(req).pathname || '/';
var route = layer.route;
// skip this layer if the route doesn't match
if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) {
return next(err);
}
// skip if route match does not border "/", ".", or end
var c = path[route.length];
if (c !== undefined && '/' !== c && '.' !== c) {
return next(err);
}
// trim off the part of the url that matches the route
if (route.length !== 0 && route !== '/') {
removed = route;
req.url = protohost + req.url.substr(protohost.length + removed.length);
// ensure leading slash
if (!fqdn && req.url[0] !== '/') {
req.url = '/' + req.url;
slashAdded = true;
}
}
// call the layer handle
call(layer.handle, route, err, req, res, next);
}
next();
};
/**
* Listen for connections.
*
* This method takes the same arguments
* as node's `http.Server#listen()`.
*
* HTTP and HTTPS:
*
* If you run your application both as HTTP
* and HTTPS you may wrap them individually,
* since your Connect "server" is really just
* a JavaScript `Function`.
*
* var connect = require('connect')
* , http = require('http')
* , https = require('https');
*
* var app = connect();
*
* http.createServer(app).listen(80);
* https.createServer(options, app).listen(443);
*
* @return {http.Server}
* @api public
*/
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
/**
* Invoke a route handle.
*
* @api private
*/
function call(handle, route, err, req, res, next) {
var arity = handle.length;
var hasError = Boolean(err);
debug('%s %s : %s', handle.name || '<anonymous>', route, req.originalUrl);
try {
if (hasError && arity === 4) {
// error-handling middleware
handle(err, req, res, next);
return;
} else if (!hasError && arity < 4) {
// request-handling middleware
handle(req, res, next);
return;
}
} catch (e) {
// reset the error
err = e;
}
// continue
next(err);
}
/**
* Log error using console.error.
*
* @param {Error} err
* @api public
*/
function logerror(err){
if (env !== 'test') console.error(err.stack || err.toString());
}

View file

@ -1,3 +0,0 @@
{
"laxbreak": true
}

View file

@ -1,6 +0,0 @@
support
test
examples
example
*.sock
dist

View file

@ -1,157 +0,0 @@
2.1.0 / 2014-10-15
==================
* node: implement `DEBUG_FD` env variable support
* package: update "browserify" to v6.1.0
* package: add "license" field to package.json (#135, @panuhorsmalahti)
2.0.0 / 2014-09-01
==================
* package: update "browserify" to v5.11.0
* node: use stderr rather than stdout for logging (#29, @stephenmathieson)
1.0.4 / 2014-07-15
==================
* dist: recompile
* example: remove `console.info()` log usage
* example: add "Content-Type" UTF-8 header to browser example
* browser: place %c marker after the space character
* browser: reset the "content" color via `color: inherit`
* browser: add colors support for Firefox >= v31
* debug: prefer an instance `log()` function over the global one (#119)
* Readme: update documentation about styled console logs for FF v31 (#116, @wryk)
1.0.3 / 2014-07-09
==================
* Add support for multiple wildcards in namespaces (#122, @seegno)
* browser: fix lint
1.0.2 / 2014-06-10
==================
* browser: update color palette (#113, @gscottolson)
* common: make console logging function configurable (#108, @timoxley)
* node: fix %o colors on old node <= 0.8.x
* Makefile: find node path using shell/which (#109, @timoxley)
1.0.1 / 2014-06-06
==================
* browser: use `removeItem()` to clear localStorage
* browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777)
* package: add "contributors" section
* node: fix comment typo
* README: list authors
1.0.0 / 2014-06-04
==================
* make ms diff be global, not be scope
* debug: ignore empty strings in enable()
* node: make DEBUG_COLORS able to disable coloring
* *: export the `colors` array
* npmignore: don't publish the `dist` dir
* Makefile: refactor to use browserify
* package: add "browserify" as a dev dependency
* Readme: add Web Inspector Colors section
* node: reset terminal color for the debug content
* node: map "%o" to `util.inspect()`
* browser: map "%j" to `JSON.stringify()`
* debug: add custom "formatters"
* debug: use "ms" module for humanizing the diff
* Readme: add "bash" syntax highlighting
* browser: add Firebug color support
* browser: add colors for WebKit browsers
* node: apply log to `console`
* rewrite: abstract common logic for Node & browsers
* add .jshintrc file
0.8.1 / 2014-04-14
==================
* package: re-add the "component" section
0.8.0 / 2014-03-30
==================
* add `enable()` method for nodejs. Closes #27
* change from stderr to stdout
* remove unnecessary index.js file
0.7.4 / 2013-11-13
==================
* remove "browserify" key from package.json (fixes something in browserify)
0.7.3 / 2013-10-30
==================
* fix: catch localStorage security error when cookies are blocked (Chrome)
* add debug(err) support. Closes #46
* add .browser prop to package.json. Closes #42
0.7.2 / 2013-02-06
==================
* fix package.json
* fix: Mobile Safari (private mode) is broken with debug
* fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript
0.7.1 / 2013-02-05
==================
* add repository URL to package.json
* add DEBUG_COLORED to force colored output
* add browserify support
* fix component. Closes #24
0.7.0 / 2012-05-04
==================
* Added .component to package.json
* Added debug.component.js build
0.6.0 / 2012-03-16
==================
* Added support for "-" prefix in DEBUG [Vinay Pulim]
* Added `.enabled` flag to the node version [TooTallNate]
0.5.0 / 2012-02-02
==================
* Added: humanize diffs. Closes #8
* Added `debug.disable()` to the CS variant
* Removed padding. Closes #10
* Fixed: persist client-side variant again. Closes #9
0.4.0 / 2012-02-01
==================
* Added browser variant support for older browsers [TooTallNate]
* Added `debug.enable('project:*')` to browser variant [TooTallNate]
* Added padding to diff (moved it to the right)
0.3.0 / 2012-01-26
==================
* Added millisecond diff when isatty, otherwise UTC string
0.2.0 / 2012-01-22
==================
* Added wildcard support
0.1.0 / 2011-12-02
==================
* Added: remove colors unless stderr isatty [TooTallNate]
0.0.1 / 2010-01-03
==================
* Initial release

View file

@ -1,33 +0,0 @@
# get Makefile directory name: http://stackoverflow.com/a/5982798/376773
THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd)
# BIN directory
BIN := $(THIS_DIR)/node_modules/.bin
# applications
NODE ?= $(shell which node)
NPM ?= $(NODE) $(shell which npm)
BROWSERIFY ?= $(NODE) $(BIN)/browserify
all: dist/debug.js
install: node_modules
clean:
@rm -rf node_modules dist
dist:
@mkdir -p $@
dist/debug.js: node_modules browser.js debug.js dist
@$(BROWSERIFY) \
--standalone debug \
. > $@
node_modules: package.json
@NODE_ENV= $(NPM) install
@touch node_modules
.PHONY: all install clean

View file

@ -1,156 +0,0 @@
# debug
tiny node.js debugging utility modelled after node core's debugging technique.
## Installation
```bash
$ npm install debug
```
## Usage
With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility.
Example _app.js_:
```js
var debug = require('debug')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %s', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
```
Example _worker.js_:
```js
var debug = require('debug')('worker');
setInterval(function(){
debug('doing some work');
}, 1000);
```
The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:
![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png)
![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png)
## Millisecond diff
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png)
When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:
![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png)
## Conventions
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser".
## Wildcards
The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:".
## Browser support
Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`.
```js
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
b('doing some work');
}, 1200);
```
#### Web Inspector Colors
Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
option. These are WebKit web inspectors, Firefox ([since version
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
and the Firebug plugin for Firefox (any version).
Colored output looks something like:
![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png)
### stderr vs stdout
You can set an alternative logging method per-namespace by overriding the `log` method on a per-namespace or globally:
Example _stderr.js_:
```js
var debug = require('../');
var log = debug('app:log');
// by default console.log is used
log('goes to stdout!');
var error = debug('app:error');
// set this namespace to log via console.error
error.log = console.error.bind(console); // don't forget to bind to console!
error('goes to stderr');
log('still goes to stdout!');
// set all output to go via console.warn
// overrides all per-namespace log settings
debug.log = console.warn.bind(console);
log('now goes to stderr via console.warn');
error('still goes to stderr, but via console.warn now');
```
## Authors
- TJ Holowaychuk
- Nathan Rajlich
## License
(The MIT License)
Copyright (c) 2014 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,147 +0,0 @@
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
return ('WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
return JSON.stringify(v);
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// This hackery is required for IE8,
// where the `console.log` function doesn't have 'apply'
return 'object' == typeof console
&& 'function' == typeof console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
localStorage.removeItem('debug');
} else {
localStorage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = localStorage.debug;
} catch(e) {}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());

View file

@ -1,19 +0,0 @@
{
"name": "debug",
"repo": "visionmedia/debug",
"description": "small debugging utility",
"version": "2.1.0",
"keywords": [
"debug",
"log",
"debugger"
],
"main": "browser.js",
"scripts": [
"browser.js",
"debug.js"
],
"dependencies": {
"guille/ms.js": "0.6.1"
}
}

View file

@ -1,197 +0,0 @@
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = Array.prototype.slice.call(arguments);
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
if ('function' === typeof exports.formatArgs) {
args = exports.formatArgs.apply(self, args);
}
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}

View file

@ -1,209 +0,0 @@
/**
* Module dependencies.
*/
var tty = require('tty');
var util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
/**
* The file descriptor to write the `debug()` calls to.
* Set the `DEBUG_FD` env variable to override with another value. i.e.:
*
* $ DEBUG_FD=3 node script.js 3>debug.log
*/
var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
var stream = 1 === fd ? process.stdout :
2 === fd ? process.stderr :
createWritableStdioStream(fd);
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
var debugColors = (process.env.DEBUG_COLORS || '').trim().toLowerCase();
if (0 === debugColors.length) {
return tty.isatty(fd);
} else {
return '0' !== debugColors
&& 'no' !== debugColors
&& 'false' !== debugColors
&& 'disabled' !== debugColors;
}
}
/**
* Map %o to `util.inspect()`, since Node doesn't do that out of the box.
*/
var inspect = (4 === util.inspect.length ?
// node <= 0.8.x
function (v, colors) {
return util.inspect(v, void 0, void 0, colors);
} :
// node > 0.8.x
function (v, colors) {
return util.inspect(v, { colors: colors });
}
);
exports.formatters.o = function(v) {
return inspect(v, this.useColors)
.replace(/\s*\n\s*/g, ' ');
};
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
var name = this.namespace;
if (useColors) {
var c = this.color;
args[0] = ' \u001b[9' + c + 'm' + name + ' '
+ '\u001b[0m'
+ args[0] + '\u001b[3' + c + 'm'
+ ' +' + exports.humanize(this.diff) + '\u001b[0m';
} else {
args[0] = new Date().toUTCString()
+ ' ' + name + ' ' + args[0];
}
return args;
}
/**
* Invokes `console.error()` with the specified arguments.
*/
function log() {
return stream.write(util.format.apply(this, arguments) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (null == namespaces) {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
} else {
process.env.DEBUG = namespaces;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Copied from `node/src/node.js`.
*
* XXX: It's lame that node doesn't expose this API out-of-the-box. It also
* relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
*/
function createWritableStdioStream (fd) {
var stream;
var tty_wrap = process.binding('tty_wrap');
// Note stream._type is used for test-module-load-list.js
switch (tty_wrap.guessHandleType(fd)) {
case 'TTY':
stream = new tty.WriteStream(fd);
stream._type = 'tty';
// Hack to have stream not keep the event loop alive.
// See https://github.com/joyent/node/issues/1726
if (stream._handle && stream._handle.unref) {
stream._handle.unref();
}
break;
case 'FILE':
var fs = require('fs');
stream = new fs.SyncWriteStream(fd, { autoClose: false });
stream._type = 'fs';
break;
case 'PIPE':
case 'TCP':
var net = require('net');
stream = new net.Socket({
fd: fd,
readable: false,
writable: true
});
// FIXME Should probably have an option in net.Socket to create a
// stream from an existing fd which is writable only. But for now
// we'll just add this hack and set the `readable` member to false.
// Test: ./node test/fixtures/echo.js < /etc/passwd
stream.readable = false;
stream.read = null;
stream._type = 'pipe';
// FIXME Hack to have stream not keep the event loop alive.
// See https://github.com/joyent/node/issues/1726
if (stream._handle && stream._handle.unref) {
stream._handle.unref();
}
break;
default:
// Probably an error on in uv_guess_handle()
throw new Error('Implement me. Unknown stream file type!');
}
// For supporting legacy API we put the FD here.
stream.fd = fd;
stream._isStdio = true;
return stream;
}
/**
* Enable namespaces listed in `process.env.DEBUG` initially.
*/
exports.enable(load());

Some files were not shown because too many files have changed in this diff Show more