master 65618d88f606 cached
80 files
9.5 MB
2.5M tokens
115 symbols
1 requests
Copy disabled (too large) Download .txt
Showing preview only (10,306K chars total). Download the full file to get everything.
Repository: Jarred-Sumner/styleurl-extension
Branch: master
Commit: 65618d88f606
Files: 80
Total size: 9.5 MB

Directory structure:
gitextract_gnxt91oa/

├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── appveyor.yml
├── babel.config.dev.js
├── chrome/
│   ├── app/
│   │   └── components/
│   │       ├── Button.css
│   │       ├── Button.js
│   │       ├── CodeDiff.css
│   │       ├── CodeDiff.js
│   │       ├── Dropdown.css
│   │       ├── Dropdown.js
│   │       ├── FeedbackForm.css
│   │       ├── FeedbackForm.js
│   │       ├── HeaderBar.css
│   │       ├── HeaderBar.js
│   │       ├── Icon.css
│   │       ├── Icon.js
│   │       ├── StylesheetCodePreview.css
│   │       ├── StylesheetCodePreview.js
│   │       ├── Switcher.css
│   │       ├── Switcher.js
│   │       └── WhiteTextLogo.js
│   ├── extension/
│   │   ├── background/
│   │   │   ├── badge.js
│   │   │   ├── contextMenus.js
│   │   │   ├── inject.js
│   │   │   └── view_styleurl/
│   │   │       └── ViewStyleURL.js
│   │   ├── background.js
│   │   ├── create_styleurl/
│   │   │   ├── CreateStyleURL.js
│   │   │   ├── Gist.css
│   │   │   ├── Gist.js
│   │   │   ├── fonts.css
│   │   │   └── messages.js
│   │   ├── create_styleurl.css
│   │   ├── create_styleurl.js
│   │   ├── css_manager_content_script.js
│   │   ├── devtools.js
│   │   ├── github_gist_content_script.js
│   │   ├── inject_create_styleurl.js
│   │   ├── inject_view_styleurl.js
│   │   ├── inline_style_observer/
│   │   │   ├── inline_style_observer.js
│   │   │   └── inline_style_observer_manager.js
│   │   ├── inline_style_observer.js
│   │   ├── lib/
│   │   │   ├── StyleURLTab.js
│   │   │   ├── api.js
│   │   │   ├── browserAction.js
│   │   │   ├── gists.js
│   │   │   ├── injectScriptNames.js
│   │   │   ├── injectShadowDom.js
│   │   │   ├── makeEverythingImportant.js
│   │   │   ├── port.js
│   │   │   ├── stylefile.js
│   │   │   └── toFile.js
│   │   ├── postcss.config.js
│   │   ├── stylesheet_manager_content_script.js
│   │   ├── version_info.js
│   │   └── view_styleurl/
│   │       └── ViewStyleURL.js
│   ├── manifest.dev.json
│   ├── manifest.prod.json
│   └── views/
│       ├── background.pug
│       ├── create_styleurl.pug
│       ├── devtools.pug
│       ├── inject.pug
│       └── window.pug
├── package.json
├── scripts/
│   ├── .eslintrc
│   ├── build.js
│   ├── compress.js
│   ├── dev.js
│   ├── tasks.js
│   └── update-readme.js
├── stats.json
├── webpack/
│   ├── .eslintrc
│   ├── customPublicPath.js
│   ├── dev.config.js
│   ├── prod.config.js
│   ├── replace/
│   │   ├── JsonpMainTemplate.runtime.js
│   │   └── process-update.js
│   └── test.config.js
└── yarn-error.log

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
key.pem
node_modules
dev
dist
build
build.zip
credentials.json
releases

================================================
FILE: CHANGELOG.md
================================================
## 1.1.15

Fix bug in feedback box in ViewStyleURL bar

## 1.1.14

The bottom bar is now hidden when in print mode. Thanks whomever wrote in and flagged this issue.

## 1.1.13

StyleURL now supports creating secret gists, so that they don't appear in search or anywhere public. This is now the behavior by default.

## 1.1.12

Fixed issue where navigating around in Reddit sometimes caused a giant diff to appear of changes on the page. This happened because:

Reddit uses `<style>` which are empty in the DOM, but with rules populated via `insertRule` - https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule

It just so happens that these style tags are not editable from within devtools anyway.

As part of this, realized that if style tags are added/removed dynamically to the website while devtools is open, StyleURL will think the user changed it instead of the site.

TODO, these two fixes:

1.  Add a MutationObserver for tracking when style tags are added or removed from the DOM, and add the contents of the style tag to TAB_ORIGINAL_STYLES
2.  When history state updates, reset devtools.js. Currently, it only does this when you navigate.

## 1.1.11

- On some websites, the code diff text was centered. It should be left aligned. So, I made it left-aligned.

## 1.1.10

- Automatically hide the bottom bar when there are no more CSS changes
- Include whether in-app feedback is from the view styleurl or the create styleurl bar

## 1.1.9

- Fixed flash of unstyled content when the bar at the bottom loads
- Added in-app feedback widget to help us improve the product, inspired by the one in the Stripe Dashboard.

## 1.1.8

Bump version of `stylesheet-differ`. This fixes some bugs people were experiencing when viewing the diff.

## 1.1.7

- Hide Intercom **only** when the StyleURL bar is visible in the page because it covers up StyleURL and, for now, it's easier to forcefully hide it than to move it to be above the bar. TODO: observe for the `#intercom-container` selector instead of inserting a style tag when bar appears
- Add a spacer div to handle a good amount of cases where the bottom of screen is covered up by StyleURL. This won't fix every case, particularly websites like Facebook where the bottom of the screen is something else that's floaty

## 1.1.6

- Add "Share StyleURL" link to GitHub Gist
- Show error message when devtools isn't open and the user clicks "Share" or "Create Gist"

## 1.1.5

Ignore error causd by tab to not exist when resetting browserAction. This caused other things to break, and is a safe error to silence (famous last words)

## 1.1.4

Fix bug caused in 1.1.3 where the redirect URL was the share URL

## 1.1.3

Fix "Share changes" button on HTTP-only sites

## 1.1.2

Remove console.\*(^[error|log]) in production

## 1.1.1

Remove query string from exported filenames because that's usually just a way to deal with caching and not how filenames are in the filesystem.

## 1.1.0

Improve performance of memoizer slightly

## 1.0.9

Fix issue where stylesheets after page changes on the same tab were being diffed. For example, you'd open Hacker News, edit some styles, click on a link to a page, then it would show all the Hacker News styles being `unset`.

Now, it clears all the cached styles on `chrome.webNavigation.onCommitted`.

Additionally:

- Made the <CodeDiff /> box 400px wide instead of 320px.
- Made the filenames use "\_" instead of "!" as the replacement character when a character is invalid. For example, before `news.css!asodKPODSAKDPOK.css` and after `news.css_COKASODK.css`

## 1.0.8

Update stylesheet-differ to the latest version, fixing a bad bug.

## 1.0.7

Performance improvements and bug fixes

## 1.0.6

Bump version.

## 1.0.5

Bump version.

## 1.0.4

Bump version.

## 1.0.3

Bump version.

## 1.0.2

Initial Release.


================================================
FILE: LICENSE
================================================
 GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <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 Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

================================================
FILE: README.md
================================================
# StyleURL Extension

[StyleURL](https://www.styleurl.app) is the easiest way for developers & designers to collaborate on CSS changes. This is the source code for the Chrome extension.

### What's New (v1.1.15 - August 4, 2018)

Fix bug in feedback box in ViewStyleURL bar

---
    
## Export CSS from Chrome

Make style changes from Chrome Inspector, and StyleURL will show you the diff of your CSS changes in the page.

Before StyleURL, to get your CSS tweaks out of Chrome DevTools, you had to select each element, remember what you changed, and copy it to a file. Now, StyleURL will automatically detect all of your changes and show you the diff.

## Save to Gist

StyleURL integrates with GitHub Gists so that you can save and share your CSS changes easily. As of August 3rd, StyleURL creates secret gists only.

## Preview live changes from a link

Add `?__styleurl=gist_${gistID}` to the URL on a webpage, and it'll automatically load the CSS from the Gist onto that page (so long as there's a matching Stylefile).

## Stylefile - an open standard for user style metadata

StyleURL is not the primary storage place for the userstyles. They're currently stored on GitHub as a Gist (more providers could easily be added later). This reduces the dependence of any centralized party for StyleURL to work, giving people better control of their data.

Example Stylefile:

```yaml
---
version: 1.0 # Optional
domains: # Required
- news.ycombinator.com
url_patterns: # Required
- news.ycombinator.com/*
timestamp: '2018-07-27T04:21:42Z' # Optional
id: 6GJP # Optional, not currently used
redirect_url: https://news.ycombinator.com/ # Required
shared_via: StyleURL – import and export CSS changes from Chrome Inspector to a Gist
  you can share (like this one!) # Optional
```

StyleURL generates and uses a Stylefile to:

- Detect which pages a StyleURL should be applied to (`url_patterns`)
- Detect which domains a StyleURL correspond to (`domains`)
- When activated from a different page, which absolute URL to redirect to (`redirect_url`)

Under the hood, the way this works is:

- Given a StyleURL, the extension fetches the corresponding Gist, reads the Stylefile, and if the URL matches the current URL, downloads the stylesheets within the Gist and applies them to the current page.

### Development

You'll want to point it to production and make sure chrome://flags/#allow-insecure-localhost is enabled (TODO more words)


================================================
FILE: appveyor.yml
================================================
environment:
  matrix:
    - nodejs_version: '6'
    - nodejs_version: '7'

cache:
  - "%LOCALAPPDATA%/Yarn"
  - node_modules

install:
  - ps: Install-Product node $env:nodejs_version
  - yarn install

test_script:
  - node --version
  - yarn --version
  - yarn run lint
  - yarn test
  - yarn run build

build: off


================================================
FILE: babel.config.dev.js
================================================
module.exports = {
  presets: ["@babel/preset-env"],
  plugins: ["@babel/plugin-transform-runtime"]
};


================================================
FILE: chrome/app/components/Button.css
================================================
.Button {
    display: flex;
    align-items: center;
    border-radius: 4px;
    margin: 8px 0;
    cursor: pointer;
    width: auto;
}

a.Button {
    text-decoration: underline;
}

.Button-text {
    font-weight: 600;
    font-size: 14px;
    line-height: 18px;
    user-select: none;
}

.Button--size-default {
    padding: 6px 14px;
}

a.Button--color-blue,
.Button--color-blue {
    color: white;
    background-color: #5A95FF;
}

.Button--color-blue .Button-text {
    color: white;
}

.Button--color-black,
a.Button--color-black {
    color: white;
    background-color: #13161B;
}

.Button--color-white {
    border: 1px solid #333;
}

.Button--color-black .Button-text {
    color: white;
}

.Button--color-black:hover {
    filter: invert(5%);
}

.Button--color-default {
    color: white;
    background-color: transparent;
}

.Button-icon,
.Button-icon svg {
    height: 20px;
    width: 20px;
}

.Button-icon {
    margin-right: 4px;
}


================================================
FILE: chrome/app/components/Button.js
================================================
import classNames from "classnames";
import React from "react";
import "./Button.css";

export const BUTTON_COLORS = {
  blue: "blue",
  black: "black",
  default: "default",
  white: "white"
};

export const BUTTON_SIZES = {
  default: "default"
};

export class Button extends React.Component {
  static defaultProps = {
    size: BUTTON_SIZES.default,
    color: BUTTON_COLORS.default
  };

  render() {
    const { children, color, size, icon, onClick, href, download } = this.props;

    const ComponentName = href ? "a" : "div";

    const child = (
      <React.Fragment>
        {!!icon && <div className="Button-icon">{icon}</div>}
        {!!children && <div className="Button-text">{children}</div>}
      </React.Fragment>
    );

    return React.createElement(
      ComponentName,
      {
        onClick,
        href,
        target: href ? "_blank" : undefined,
        className: classNames("Button", {
          "Button--color-blue": BUTTON_COLORS[color] === BUTTON_COLORS.blue,
          "Button--color-black": BUTTON_COLORS[color] === BUTTON_COLORS.black,
          "Button--color-white": BUTTON_COLORS[color] === BUTTON_COLORS.white,
          "Button--color-default":
            BUTTON_COLORS[color] === BUTTON_COLORS.default,
          "Button--size-default": BUTTON_COLORS[size] === BUTTON_SIZES.default
        }),
        download
      },
      child
    );
  }
}


================================================
FILE: chrome/app/components/CodeDiff.css
================================================
.CodeDiff {
    width: 400px;
    max-width: 100%;
    overflow-x: hidden;
    overflow-y: auto;
    max-height: 240px;
    text-align: left;
}

.CodeDiff pre {
    margin: 0;
    padding: 14px 14px !important;
}

.CodeDiff pre code:nth-child(1) {
    padding-right: 14px !important;
}

.react-syntax-highlighter-line-number {
    user-select: none;
}

.CodeDiff > pre {
    background: #21262F !important;
}


================================================
FILE: chrome/app/components/CodeDiff.js
================================================
import React from "react";
import "./CodeDiff.css";
import SyntaxHighlighter from "react-syntax-highlighter";
import { monokai } from "react-syntax-highlighter/styles/hljs";
import filenameify from "filenamify";

const normalizeFilename = _filename => {
  const queryStringIndex = _filename.indexOf("?");
  const filename =
    queryStringIndex > -1 ? _filename.substr(0, queryStringIndex) : _filename;

  if (!filename.endsWith(".css")) {
    return filenameify(filename + ".css", {
      replacement: "_"
    });
  } else {
    return filenameify(filename, {
      replacement: "_"
    });
  }
};

export const concatStylesheets = (stylesheets, includeURL = false) => {
  const code = stylesheets
    .map(
      stylesheet =>
        `/* ${normalizeFilename(stylesheet[0])} */\n\n${stylesheet[1]}`
    )
    .join("\n\n");

  if (includeURL) {
    return (
      `/* Page: ${
        window.location.href
      } */\n/* Exported via StyleURL (https://www.styleurl.app) */\n` + code
    );
  } else {
    return code;
  }
};

export default class CodeDiff extends React.PureComponent {
  state = {
    code: "",
    stylesheets: []
  };

  static getDerivedStateFromProps(props, state) {
    if (props.stylesheets !== state.stylesheets) {
      return {
        code: concatStylesheets(props.stylesheets),
        stylesheets: props.stylesheets.slice()
      };
    } else {
      return {};
    }
  }

  render() {
    return (
      <div className="CodeDiff">
        <SyntaxHighlighter
          showLineNumbers
          customStyle={{
            background: "#21262F"
          }}
          language="css"
          style={monokai}
        >
          {this.state.code}
        </SyntaxHighlighter>
      </div>
    );
  }
}


================================================
FILE: chrome/app/components/Dropdown.css
================================================
.Dropdown {
  position: relative;
}

.Dropdown-content {
  padding: 14px 18px;
  align-items: center;
  cursor: pointer;
  white-space: nowrap;
  display: flex;
  color: white;
}

.Dropdown-content:hover,
.Dropdown--open .Dropdown-content,
.Dropdown-child {
  background-color: #21262f;
}

.Dropdown-title {
  font-weight: 600;
  font-size: 14px;
  line-height: 22px;
  user-select: none;
}

.Dropdown-icon {
  margin-right: 8px;
  margin-top: 3px;
}

.Dropdown-child {
  position: absolute;
  bottom: 51px;
  right: 0;
  box-shadow: 1px -1px 1px #ccc;
}


================================================
FILE: chrome/app/components/Dropdown.js
================================================
import React from "react";
import "./Dropdown.css";
import classNames from "classnames";
import onClickOutside from "react-onclickoutside";

class _DropdownChild extends React.Component {
  handleClickOutside = evt => this.props.hide(evt);
  handleClick = evt => evt.stopPropagation();

  render() {
    const { children, ...otherProps } = this.props;

    return (
      <div onClick={this.handleClick} className="Dropdown-child">
        {children}
      </div>
    );
  }
}

const DropdownChild = onClickOutside(_DropdownChild, {
  excludeScrollbar: true
});

class Dropdown extends React.Component {
  state = {
    isOpen: false
  };

  handleToggleOpen = evt => {
    if (this.props.onClick) {
      this.props.onClick();
    } else if (this.props.children) {
      const isOpen = !this.state.isOpen;
      this.setState({ isOpen });
      if (this.props.onToggle) {
        this.props.onToggle(isOpen);
      }
    }
  };
  // Do slight delay here as hack to account for previous button click
  handleClickOutside = evt => {
    if (this.state.isOpen) {
      this.setState({ isOpen: false });
    }
  };

  setDropdownRef = dropdownRef => (this.dropdownRef = dropdownRef);

  render() {
    const { icon, title, children } = this.props;
    const { isOpen } = this.state;

    return (
      <div
        ref={this.setDropdownRef}
        className={classNames("Dropdown", "ignore-react-onclickoutside", {
          "Dropdown--open": !!this.state.isOpen,
          "Dropdown--closed": !this.state.isOpen
        })}
      >
        <div onClick={this.handleToggleOpen} className="Dropdown-content">
          {icon && <div className="Dropdown-icon">{icon}</div>}
          {title && <div className="Dropdown-title">{title}</div>}
        </div>

        {isOpen ? (
          <DropdownChild hide={this.handleClickOutside}>
            {children}
          </DropdownChild>
        ) : null}
      </div>
    );
  }
}

export default Dropdown;


================================================
FILE: chrome/app/components/FeedbackForm.css
================================================
.FeedbackFormContainer {
    display: block;
    position: relative;
    white-space: nowrap;
    margin-left: 14px;
}

.FeedbackForm-placeholder,
.FeedbackForm-input {
    opacity: 1;
    border-radius: 4px;
}

.FeedbackForm--collapsed .FeedbackForm-input,
.FeedbackForm--expanded .FeedbackForm-placeholder {
    opacity: 0;
    transition: 0.2s opacity linear;
    pointer-events: none;
}

.FeedbackForm--expanded .FeedbackForm-input,
.FeedbackForm--collapsed .FeedbackForm-placeholder {
    opacity: 1;
    pointer-events: auto;
    transition: 0.2s opacity linear;
}

.FeedbackForm-input {
    position: absolute;
    bottom: 0px;
    left: 0;
    padding: 14px;
    background-color: white;
    border: 1px solid #e9ebf5;
    box-shadow: 0 0 20px 0 rgba(161, 166, 187, 0.35);
    width: 300px;
    flex-direction: column;
}

.FeedbackForm-copy {
    margin-top: 7px;
    color: #3B55E6;
    margin-bottom: 7px;
}

.FeedbackInput {
    margin: -7px -14px;
    padding: 7px 14px;
    font-family: "Open Sans", sans-serif;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    font-size: 14px;
    color: #333;
    line-height: 18px;
    appearance: none;
    border: 0;
    resize: none;
    outline: none;
    box-shadow: none;
    width: 100%;
}

.FeedbackForm-placeholder {
    background-color: #fcfcfc;
    align-items: center;
    padding: 7px 14px;
    justify-content: center;
    border: 1px solid #e9ebf5;
    display: flex;
}

.FeedbackForm-placeholder .Icon {
    display: flex;
    margin-top: auto;
    margin-bottom: auto;
}

.FeedbackForm-inputButtons {
    display: flex;
    justify-content: space-between;
}

.Icon {
    margin-right: 8px;
}

.FeedbackForm-inputButtons .Button {
    margin: 0;
    color: black;
}

.FeedbackForm-input {
    margin: 0;
}

@media (max-width: 1000px) {
    .FeedbackForm-placeholder > .FeedbackForm-title {
        display: none;
    }

    .FeedbackForm-placeholder {
        background: transparent;
        padding: 0;
        border: 0;
    }
}


================================================
FILE: chrome/app/components/FeedbackForm.js
================================================
import React from "react";
import { Icon } from "./Icon";
import onClickOutside from "react-onclickoutside";
import classNames from "classnames";
import { Button } from "./Button";
import "./FeedbackForm.css";

class FeedbackForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isExpanded: false,
      message: "",
      isSaving: false,
      hasSaved: false
    };
  }

  handleClickOutside = () => {
    if (this.state.isExpanded) {
      this.setState({ isExpanded: false });
    }
  };

  setExpanded = isExpanded => {
    this.setState({ isExpanded });
    if (isExpanded && this.inputRef) {
      this.inputRef.focus();
    }
  };
  handleCancel = () => this.setState({ isExpanded: false });
  handleSubmit = evt => {
    evt.preventDefault();
    this.props.onSendFeedback(this.state.message);
    this.setState({ message: "", isExpanded: false });
    alert("Thanks! Your feedback has been sent.");
  };

  disablePropagation = evt => {
    evt.stopPropagation();

    evt.nativeEvent.stopImmediatePropagation();
  };

  handleKeyDown = evt => {
    this.disablePropagation(evt);

    if (evt.keyCode === 27) {
      this.handleCancel();
    }
  };

  handleMessageChange = evt => this.setState({ message: evt.target.value });

  render() {
    const { isExpanded, message } = this.state;

    return (
      <div
        className="FeedbackFormContainer"
        onClick={() => this.setExpanded(true)}
      >
        <div
          className={classNames("FeedbackForm", {
            "FeedbackForm--expanded": isExpanded,
            "FeedbackForm--collapsed": !isExpanded
          })}
        >
          <div className="FeedbackForm-placeholder">
            <div className="Icon">
              <Icon
                width="14"
                height="14"
                name="feedback"
                size="16px"
                color="#B9BED1"
              />
            </div>

            <div className="FeedbackForm-title">
              Have feedback or questions?
            </div>
          </div>

          <form
            className="FeedbackForm-input"
            onClick={this.disablePropagation}
            onSubmit={this.handleSubmit}
          >
            <textarea
              required
              name="feedback"
              className="FeedbackInput"
              value={message}
              rows="3"
              ref={inputRef => (this.inputRef = inputRef)}
              placeholder="Have feedback or questions?"
              onKeyDown={this.handleKeyDown}
              onChange={this.handleMessageChange}
            />

            <div className="FeedbackForm-copy">
              Your feedback is sent directly to the founders.
            </div>

            <div className="FeedbackForm-inputButtons">
              <Button onClick={this.handleCancel} color="white">
                Cancel
              </Button>
              <Button onClick={this.handleSubmit} color="black">
                Send feedback
              </Button>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

export default onClickOutside(FeedbackForm);


================================================
FILE: chrome/app/components/HeaderBar.css
================================================
.HeaderBar {
  background-color: #13161b;
  padding: 0 28px;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: auto;
  align-items: center;
  width: auto;
  opacity: 1;
}

.HeaderSide {
  display: flex;
  align-items: center;
}

.HeaderBar--hidden {
  opacity: 0;
  pointer-events: none;
}

@media (max-width: 780px) {
  .HeaderBar--logo {
    display: none;
  }
}

.HeaderSide--right {
  justify-content: flex-end;
}

.HeaderSide--center {
  justify-content: center;
}

.HeaderBar-hideButton {
  margin-right: 14px;
  color: gray;
  cursor: pointer;
  margin-top: auto;
  margin-bottom: auto;
}

.HeaderBar-hideButton:hover {
  color: white;
}


================================================
FILE: chrome/app/components/HeaderBar.js
================================================
import React from "react";
import "./HeaderBar.css";
import WhiteTextLogo from "./WhiteTextLogo";
import classNames from "classnames";
import { Icon } from "./Icon";
import FeedbackForm from "./FeedbackForm";

export class HeaderBar extends React.Component {
  static defaultProps = {
    hidden: false
  };

  render() {
    const {
      hidden,
      onHide,
      center,
      className,
      children,
      onSendFeedback
    } = this.props;
    return (
      <header
        className={classNames("HeaderBar", className, {
          "HeaderBar--hidden": hidden
        })}
      >
        <div className="HeaderSide HeaderSide--left">
          <div onClick={onHide} className="HeaderBar-hideButton">
            <Icon height="20" name="close" />
          </div>
          <WhiteTextLogo className="HeaderBar--logo" />
          <FeedbackForm onSendFeedback={onSendFeedback} />
        </div>

        <div className="HeaderSide HeaderSide--center">{center}</div>

        <div className="HeaderSide HeaderSide--right">{children}</div>
      </header>
    );
  }
}

export default HeaderBar;


================================================
FILE: chrome/app/components/Icon.css
================================================
.IconFill {
    fill: currentColor;
}

.IconStroke {
    stroke: currentColor;
}


================================================
FILE: chrome/app/components/Icon.js
================================================
import React from "react";
import "./Icon.css";

const FeedbackIcon = ({ width, height, ...otherProps }) => (
  <svg width={width} height={height} {...otherProps} viewBox="0 0 22 22">
    <path
      d="M0 1v19.753a1 1 0 0 0 1.67.743l3.301-2.974H21a1 1 0 0 0 1-1V1a1 1 0 0 0-1-1H1a1 1 0 0 0-1 1zm5.891 3.14h4.19a.92.92 0 1 1 0 1.84H5.89a.92.92 0 1 1 0-1.84zm-.92 9.592a.92.92 0 0 1 .92-.92h8.14a.92.92 0 1 1 0 1.84h-8.14a.92.92 0 0 1-.92-.92zm11.138-3.416H5.891a.92.92 0 0 1 0-1.84H16.11a.92.92 0 1 1 0 1.84z"
      fillRule="nonzero"
      className="IconFill"
    />
  </svg>
);

const ExportIcon = ({ width, height, ...otherProps }) => (
  <svg width={width} height={height} viewBox="0 0 37 36">
    <g className="IconFill" fillRule="evenodd">
      <path d="M25.542 13.014v4h6.96v14.899H4.003v-14.9h6.96v-4H.003v22.9h36.499v-22.9z" />
      <path d="M16.252 7.834v19.41h4V7.568l2.694 2.694 2.828-2.828-7.388-7.39L10.73 7.7l2.828 2.828z" />
    </g>
  </svg>
);

const CodeIcon = ({ width, height, ...otherProps }) => (
  <svg {...otherProps} width={width} height={height} viewBox=" 0 0 32 20">
    <path
      d="M18.427.001c-.503.02-.933.359-1.059.833l-4.95 17.754c-.109.385.001.797.29 1.08.288.284.71.397 1.108.295.397-.1.708-.4.816-.785l4.95-17.755c.104-.345.03-.718-.2-1A1.157 1.157 0 0 0 18.428 0zM10.17 1.862a1.16 1.16 0 0 0-.595.243L.437 9.133c-.276.21-.437.532-.437.873 0 .34.161.662.437.872l9.138 7.028c.32.25.754.314 1.137.168.382-.146.655-.48.715-.875a1.1 1.1 0 0 0-.424-1.038l-8.008-6.15 8.008-6.16a1.09 1.09 0 0 0 .372-1.306 1.147 1.147 0 0 0-1.205-.683zm11.399 0a1.134 1.134 0 0 0-.982.806c-.126.439.037.907.41 1.183l8.008 6.16-8.008 6.15a1.1 1.1 0 0 0-.424 1.038c.06.395.333.729.715.875.383.146.816.082 1.137-.168l9.138-7.028c.276-.21.437-.532.437-.872 0-.34-.161-.663-.437-.873l-9.138-7.028c-.24-.19-.549-.278-.856-.243z"
      className="IconFill"
      fillRule="nonzero"
    />
  </svg>
);

const ForkIcon = ({ width, height, ...otherProps }) => (
  <svg {...otherProps} width={width} height={height} viewBox="0 0 20 26">
    <g className="IconFill IconStroke" fillRule="nonzero">
      <path d="M3.832 6.84h1.032v9.307H3.832z" />
      <path d="M4.335 7.347c-1.694 0-3.097-1.387-3.097-3.12a3.09 3.09 0 0 1 3.097-3.094c1.694 0 3.097 1.387 3.097 3.12a3.09 3.09 0 0 1-3.097 3.094zm0-5.174a2.075 2.075 0 0 0-2.064 2.08c0 1.147.926 2.08 2.064 2.08A2.075 2.075 0 0 0 6.4 4.253c0-1.146-.926-2.08-2.065-2.08zM15.665 7.347c-1.694 0-3.097-1.387-3.097-3.12a3.09 3.09 0 0 1 3.097-3.094c1.694 0 3.097 1.387 3.097 3.12a3.09 3.09 0 0 1-3.097 3.094zm0-5.174a2.075 2.075 0 0 0-2.065 2.08c0 1.147.926 2.08 2.065 2.08a2.075 2.075 0 0 0 2.064-2.08c0-1.146-.926-2.08-2.064-2.08zM4.335 24.973c-1.694 0-3.097-1.386-3.097-3.12a3.096 3.096 0 0 1 3.097-3.12 3.096 3.096 0 0 1 3.097 3.12c0 1.734-1.403 3.12-3.097 3.12zm0-5.2a2.075 2.075 0 0 0-2.064 2.08c0 1.147.926 2.08 2.064 2.08a2.075 2.075 0 0 0 2.065-2.08c0-1.146-.926-2.08-2.065-2.08z" />
      <path d="M4.838 19.24H3.806v-3.093c0-2.587 2.065-4.667 4.632-4.667h3.097c1.986 0 3.6-1.627 3.6-3.627V6.84h1.033v1.013c0 2.587-2.065 4.667-4.633 4.667h-3.07c-1.986 0-3.6 1.627-3.6 3.627l-.027 3.093z" />
    </g>
  </svg>
);

const ShareIcon = ({ width, height, ...otherProps }) => (
  <svg {...otherProps} viewBox="0 0 24 21" width={width} height={height}>
    <path
      d="M23.61 7.399L15.36.274c-.722-.623-1.86-.117-1.86.852v3.752C5.97 4.964 0 6.473 0 13.61c0 2.88 1.855 5.733 3.906 7.225.64.465 1.552-.119 1.316-.873-2.125-6.798 1.008-8.602 8.278-8.707v4.121c0 .97 1.14 1.474 1.86.851l8.25-7.125a1.125 1.125 0 0 0 0-1.702z"
      className="IconFill"
      fillRule="nonzero"
    />
  </svg>
);

const CloseIcon = ({ width, height, ...otherProps }) => (
  <svg {...otherProps} width={width} height={height} viewBox="0 0 100 100">
    <path
      className="IconFill"
      d="M72.9 11.5L50 34.4 27.1 11.5c-2.9-2.9-7.7-2.9-10.6 0l-4.2 4.2c-2.9 2.9-2.9 7.7 0 10.6l22.9 22.9-23 23c-2.9 2.9-2.9 7.7 0 10.6l4.2 4.2c2.9 2.9 7.7 2.9 10.6 0l23-22.9L72.9 87c2.9 2.9 7.7 2.9 10.6 0l4.2-4.2c2.9-2.9 2.9-7.7 0-10.6L64.8 49.3l22.9-22.9c2.9-2.9 2.9-7.7 0-10.6l-4.2-4.2c-2.9-3-7.6-3-10.6-.1z"
    />
  </svg>
);

const ICON_BY_NAME = {
  fork: ForkIcon,
  close: CloseIcon,
  code: CodeIcon,
  share: ShareIcon,
  export: ExportIcon,
  feedback: FeedbackIcon
};

export const Icon = ({ width, height, color, name, ...otherProps }) => {
  const IconComponent = ICON_BY_NAME[name];

  return (
    <IconComponent
      style={color ? { color } : undefined}
      {...otherProps}
      width={width}
      height={height}
    />
  );
};

export default Icon;


================================================
FILE: chrome/app/components/StylesheetCodePreview.css
================================================
.StylesheetCodePreview {
    border-top-left-radius: 2px;
    border-top-right-radius: 2px;
    overflow: hidden;
}

.StylesheetCodePreview-Actions {
    text-align: center;
    display: flex;
    justify-content: center;
}

.StylesheetCodePreview-Actions a.Button {
    width: 100%;
    justify-content: center;
    margin: 0;
    padding-top: 10px;
    padding-bottom: 10px;
    color: white !important;
}


================================================
FILE: chrome/app/components/StylesheetCodePreview.js
================================================
import React from "react";
import { Button, BUTTON_COLORS } from "./Button";
import "./StylesheetCodePreview.css";
import { getFilename } from "../../extension/create_styleurl/CreateStyleURL";
import CodeDiff, { concatStylesheets } from "./CodeDiff";

const buildViewURL = gistId => {
  return `https://gist.github.com/${gistId}`;
};

const buildDlUrl = stylesheets => {
  const blob = new Blob([concatStylesheets(stylesheets, true)], {
    type: "text/plain;charset=UTF-8"
  });
  return window.URL.createObjectURL(blob);
};

export class StylesheetCodePreview extends React.PureComponent {
  render() {
    const { gistId, stylesheets } = this.props;
    return (
      <div className="StylesheetCodePreview ignore-react-onclickoutside">
        <CodeDiff stylesheets={stylesheets} />
        <div className="StylesheetCodePreview-Actions">
          <Button color={BUTTON_COLORS.black} href={buildViewURL(gistId)}>
            Open gist
          </Button>
          <Button
            color={BUTTON_COLORS.black}
            href={buildDlUrl(stylesheets)}
            download={getFilename()}
          >
            Download
          </Button>
        </div>
      </div>
    );
  }
}

export default StylesheetCodePreview;


================================================
FILE: chrome/app/components/Switcher.css
================================================
.Switcher,
.SwitcherSide,
.SwitcherSide-label {
  display: flex;
  align-items: center;
}

.Switcher,
.SwitcherSide {
  border-radius: 100px;
}

.Switcher {
  justify-content: space-between;
  align-self: center;
  background-color: white;
  cursor: pointer;
}

@media (max-width: 650px) {
  .Switcher {
    display: none;
  }
}

.SwitcherSide {
  width: 152px;
  padding: 8px 0;
  text-align: center;
  justify-content: center;
  color: #050505;
}

.Switcher--on .SwitcherSide--on,
.Switcher--off .SwitcherSide--off {
  background-color: #5a95ff;
  color: white;
}

.SwitcherSide-label {
  color: inherit;
  font-size: 14px;
  font-weight: 600px;
  line-height: 19px;
  user-select: none;
}


================================================
FILE: chrome/app/components/Switcher.js
================================================
import React from "react";
import classNames from "classnames";
import "./Switcher.css";

export class Switcher extends React.PureComponent {
  handleToggle = () => this.props.onChange(!this.props.on);

  render() {
    const { onLabel, offLabel, on } = this.props;
    return (
      <div
        onClick={this.handleToggle}
        className={classNames("Switcher", {
          "Switcher--on": !!on,
          "Switcher--off": !on
        })}
      >
        <div className="SwitcherSide SwitcherSide--on">
          <div className="SwitcherSide-label">{onLabel}</div>
        </div>

        <div className="SwitcherSide SwitcherSide--off">
          <div className="SwitcherSide-label">{offLabel}</div>
        </div>
      </div>
    );
  }
}

export default Switcher;


================================================
FILE: chrome/app/components/WhiteTextLogo.js
================================================
import React from "react";

const getSrcForSize = multipler => {
  if (!multipler || multipler < 2) {
    return chrome.extension.getURL("img/white-text-logo.png");
  } else {
    return chrome.extension.getURL(`img/white-text-logo@${multipler}x.png`);
  }
};

const getSrcSet = () =>
  [1, 2, 3].map(size => `${getSrcForSize(size)} ${size}x`).join(", \n");

export default ({ src, srcSet, ...otherProps }) => (
  <a
    href={`${__FRONTEND_HOST__}/?utm_source="ext_logo_button"`}
    target="_blank"
  >
    <img
      {...otherProps}
      src={getSrcForSize()}
      srcSet={getSrcSet()}
      height={22.4}
      width={60.8}
      style={{
        userSelect: "none",
        MozUserSelect: "none",
        WebkitUserSelect: "none"
      }}
    />
  </a>
);


================================================
FILE: chrome/extension/background/badge.js
================================================
chrome.storage.local.get('todos', (obj) => {
  let todos = obj.todos;
  if (todos) {
    todos = JSON.parse(todos);
    const len = todos.filter(todo => !todo.marked).length;
    if (len > 0) {
      chrome.browserAction.setBadgeText({ text: len.toString() });
    }
  } else {
    // Initial
    chrome.browserAction.setBadgeText({ text: '1' });
  }
});


================================================
FILE: chrome/extension/background/contextMenus.js
================================================
let windowId = 0;
const CONTEXT_MENU_ID = 'example_context_menu';

function closeIfExist() {
  if (windowId > 0) {
    chrome.windows.remove(windowId);
    windowId = chrome.windows.WINDOW_ID_NONE;
  }
}

function popWindow(type) {
  closeIfExist();
  const options = {
    type: 'popup',
    left: 100,
    top: 100,
    width: 800,
    height: 475,
  };
  if (type === 'open') {
    options.url = 'window.html';
    chrome.windows.create(options, (win) => {
      windowId = win.id;
    });
  }
}

chrome.contextMenus.create({
  id: CONTEXT_MENU_ID,
  title: 'React Chrome Extension Example',
  contexts: ['all'],
  documentUrlPatterns: [
    'https://github.com/*'
  ]
});

chrome.contextMenus.onClicked.addListener((event) => {
  if (event.menuItemId === CONTEXT_MENU_ID) {
    popWindow('open');
  }
});


================================================
FILE: chrome/extension/background/inject.js
================================================
import injectScriptNames from "../lib/injectScriptNames";

const log = (...messages) =>
  console.log.apply(console, ["[inject]", ...messages]);

function isInjected(tabId, name) {
  return new Promise((resolve, reject) => {
    const scriptName = injectScriptNames[name];
    chrome.tabs.executeScript(
      tabId,
      {
        code: `!!document.querySelector("#${scriptName}")`,
        runAt: "document_start"
      },
      results => resolve(results[0])
    );
  });
}

export async function loadScript(name, tabId, cb, runAt = "document_end") {
  if (runAt !== "document_start") {
    const didInject = await isInjected(tabId, name);
    if (didInject) {
      log("SKIP injecting script", name, "into", tabId);
      cb && cb(false);
      return;
    }
  }

  log("Injecting script", name, "into", tabId);

  chrome.tabs.executeScript(
    tabId,
    { file: `/${name}.bundle.js`, runAt, allFrames: false },
    () => cb && cb(true)
  );
}

export const injectCreateStyleURLBar = (tabId, cb) => {
  loadScript("inject_create_styleurl", tabId, cb);
};

export const injectViewStyleURLBar = (tabId, cb) => {
  loadScript("inject_view_styleurl", tabId, cb);
};

export const injectCSSManager = (tabId, cb) => {
  loadScript("css_manager_content_script", tabId, cb, "document_start");
};

export const injectInlineStyleObserver = (tabId, cb) => {
  loadScript("inline_style_observer", tabId, cb, "document_start");
};


================================================
FILE: chrome/extension/background/view_styleurl/ViewStyleURL.js
================================================


================================================
FILE: chrome/extension/background.js
================================================
import Messenger from "chrome-ext-messenger";
import _ from "lodash";
import memoizee from "memoizee";
import Raven from "raven-js";
import _diffSheet from "stylesheet-differ";
import {
  injectCreateStyleURLBar,
  injectCSSManager,
  injectViewStyleURLBar
} from "./background/inject";
import {
  SCREENSHOT_CONTENT_TYPE,
  uploadScreenshot,
  uploadStylesheets,
  sendFeedback
} from "./lib/api";
import {
  BROWSER_ACTION_STATES,
  DEFAULT_ICON_PATH,
  getBrowserActionState,
  setBrowserActionToDefault,
  setBrowserActionToStyleApplied
} from "./lib/browserAction";
import { getGistIDFromURL, SPECIAL_QUERY_PARAMS } from "./lib/gists";
import injectScriptNames from "./lib/injectScriptNames";
import { MESSAGE_TYPES, PORT_TYPES } from "./lib/port";
import {
  startMonitoringTabID,
  stopMonitoringTabID as _stopMonitoringTabID,
  styleURLsForTabId
} from "./lib/StyleURLTab";
import { toFile } from "./lib/toFile";

const diffSheet = memoizee(_diffSheet, {
  maxAge: 300000, // 5 minutes,
  primitive: true
});

Raven.config(
  "https://26483721d124446bb37ebe913d3b8347@sentry.io/1246693"
).install();

Raven.setExtraContext({
  version: chrome.runtime.getManifest().version,
  environment: process.env.NODE_ENV
});

Raven.context(function() {
  let DEVTOOLS_OPEN_TABS = {};
  let devtoolConnection;
  let gistConnection;
  let stylesheetManagerConnection;
  let inlineStyleObserverConnection;
  let inlineHeaderConnection;
  const messenger = new Messenger();

  messenger.initBackgroundHub({
    connectedHandler: function(extensionPart, connectionName, tabId) {
      if (extensionPart === "devtool") {
        DEVTOOLS_OPEN_TABS[tabId] = true;
      }
    },
    disconnectedHandler: function(extensionPart, connectionName, tabId) {
      if (
        extensionPart === "devtool" &&
        getBrowserActionState() === BROWSER_ACTION_STATES.upload_style
      ) {
        setBrowserActionToDefault({ tabId });
      }

      if (extensionPart === "devtool") {
        DEVTOOLS_OPEN_TABS[tabId] = false;
      }

      if (
        extensionPart === "devtool" &&
        tabId &&
        !styleURLsForTabId(tabId).length
      ) {
        inlineStyleObserverConnection.sendMessage(
          `content_script:${PORT_TYPES.inline_style_observer}:${tabId}`,
          {
            kind: MESSAGE_TYPES.stop_observing_inline_styles
          }
        );
      }
    }
  });

  const log = (...messages) =>
    console.log.apply(console, ["[Background]", ...messages]);

  const TAB_IDS_TO_APPLY_STYLES = {};
  const TAB_IDS_STYLESHEET_DIFFS = {};
  const TAB_ORIGINAL_STYLES = {};
  const LAST_RECEIVED_TAB_ORIGINAL_STYLES = {};

  const stopMonitoringTabID = tabId => {
    _stopMonitoringTabID(tabId);

    delete TAB_IDS_STYLESHEET_DIFFS[tabId];
    delete TAB_ORIGINAL_STYLES[tabId];
    delete TAB_ORIGINAL_STYLES[tabId];
    delete LAST_RECEIVED_TAB_ORIGINAL_STYLES[tabId];
  };

  const getTab = tabId =>
    new Promise((resolve, reject) => {
      chrome.tabs.get(tabId, resolve);
    });

  const getTabId = sender => parseInt(_.last(sender.split("::")), 10);

  const handleGistContentScriptMessages = async (
    request,
    from,
    sender,
    sendResponse
  ) => {
    const { kind = null } = request;

    const kinds = MESSAGE_TYPES;

    if (!kind) {
      return;
    }

    if (!_.values(kinds).includes(kind)) {
      console.error(
        "[background] request kind must be one of",
        _.values(kinds)
      );
      return;
    }

    if (kind === kinds.get_gist_content) {
      if (!request.url) {
        console.error("[background] invalid get_gist_content: missing url");
        sendResponse({ success: false });
        return;
      }

      return window
        .fetch(request.url, {
          redirect: "follow",
          credentials: "include"
        })
        .then(response => response.text())
        .then(value => {
          return sendResponse({
            url: request.url,
            response: true,
            value
          });
        });
    }
  };

  const shouldAssumeChangesAreReal = tabId => {
    return (
      LAST_RECEIVED_TAB_ORIGINAL_STYLES[tabId] &&
      new Date().getTime() - LAST_RECEIVED_TAB_ORIGINAL_STYLES[tabId] > 5000
    );
  };

  const toggleStylebar = (tabId, show) => {
    const script = (idName, opacity) => {
      document.getElementById(idName).style.opacity = opacity;
    };

    return new Promise(resolve => {
      chrome.tabs.executeScript(
        tabId,
        {
          code: `(${script.toString()})("${
            injectScriptNames.inject_create_styleurl
          }", ${show ? 1 : 0})`,
          runAt: "document_start"
        },
        () => {
          setTimeout(() => {
            resolve();
          }, 50);
        }
      );
    });
  };

  const sendStyleURLsToTab = ({ tabId }) => {
    styleURLsForTabId(tabId).forEach(styleurl => {
      stylesheetManagerConnection.sendMessage(
        `content_script:${PORT_TYPES.stylesheet_manager}:${tabId}`,
        { kind: MESSAGE_TYPES.get_styleurl, value: styleurl.toJSON() }
      );
    });
  };

  const autodetectStyleURL = async ({ url, tabId }) => {
    const gistId = getGistIDFromURL(url);

    if (!gistId) {
      return;
    }

    await startMonitoringTabID({ tabId, gistId });
    sendStyleURLsToTab({ tabId });

    injectCSSManager(tabId);
  };

  const handleInlineStyleObserverMessages = async (
    request,
    from,
    sender,
    sendResponse
  ) => {
    const { kind = null } = request;
    const kinds = MESSAGE_TYPES;

    if (!kind) {
      return;
    }

    if (!_.values(kinds).includes(kind)) {
      console.error(
        "[background] request kind must be one of",
        _.values(kinds)
      );
      return;
    }

    const tabId = getTabId(from);
    const tab = await getTab(tabId);

    if (
      kind === MESSAGE_TYPES.style_diff_changed &&
      !styleURLsForTabId(tabId).length
    ) {
      injectCreateStyleURLBar(tabId, success => {
        if (!success) {
          return;
        }

        inlineHeaderConnection.sendMessage(
          `content_script:${PORT_TYPES.inline_header}:${tabId}`,
          {
            kind: MESSAGE_TYPES.open_style_editor
          }
        );
      });
    }
    log(request.value);
  };

  const handleInlineHeaderMessages = async (
    request,
    from,
    sender,
    sendResponse
  ) => {
    const { kind = null } = request;
    const kinds = MESSAGE_TYPES;

    if (!kind) {
      return;
    }

    if (!_.values(kinds).includes(kind)) {
      console.error(
        "[background] request kind must be one of",
        _.values(kinds)
      );
      return;
    }

    const tabId = getTabId(from);
    const tab = await getTab(tabId);

    if (kind === kinds.log) {
    } else if (kind === kinds.send_feedback) {
      sendFeedback({
        message: request.value.message,
        from: request.value.from
      });
    } else if (kind === kinds.get_current_styles_diff) {
      if (
        !DEVTOOLS_OPEN_TABS[tabId] &&
        request.value &&
        request.value.devtools_required
      ) {
        inlineHeaderConnection.sendMessage(
          `content_script:${PORT_TYPES.inline_header}:${tabId}`,
          {
            kind: MESSAGE_TYPES.open_devtools_plz
          }
        );
      }

      getCurrentStylesheetsDiff(tabId).then(response => sendResponse(response));
    } else if (kind === kinds.send_success_notification) {
      chrome.notifications.create({
        type: "basic",
        iconUrl: chrome.extension.getURL(DEFAULT_ICON_PATH["128"]),
        title: !request.value.didCopy
          ? `Created styleurl`
          : "Copied your styleurl to clipboard",
        message:
          "Your CSS changes have been exported to a styleurl successfully. Now you can share it!"
      });
    } else if (kind === kinds.get_styleurl) {
      const styleURL = _.first(styleURLsForTabId(tabId));
      sendResponse({ value: styleURL, kind });
    } else if (kind === kinds.update_styleurl_state) {
      const styleURL = _.first(styleURLsForTabId(tabId));
      const { isBarEnabled, isStyleEnabled } = request.value;

      if (isBarEnabled !== styleURL.isBarEnabled) {
        styleURL.isBarEnabled = isBarEnabled;
      }

      if (isStyleEnabled !== styleURL.isStyleEnabled) {
        styleURL.isStyleEnabled = isStyleEnabled;
      }

      inlineHeaderConnection.sendMessage(
        `content_script:${PORT_TYPES.inline_header}:${tabId}`,
        { value: styleURL, kind: kinds.update_styleurl_state }
      );

      if (!from.includes(PORT_TYPES.stylesheet_manager)) {
        sendStyleURLsToTab({ tabId });
      }
    } else if (kind === kinds.shared_styleurl) {
      chrome.notifications.create({
        type: "basic",
        iconUrl: chrome.extension.getURL(DEFAULT_ICON_PATH["128"]),
        title: "Copied styleurl to clipboard",
        message: "Share the styleurl by pasting it to a friend or colleague"
      });
    } else if (kind === kinds.upload_stylesheets) {
      toggleStylebar(tabId, false).then(() => {
        chrome.tabs.captureVisibleTab(null, { format: "png" }, async function(
          photo
        ) {
          uploadStylesheets({
            stylesheets: request.value.stylesheets,
            url: tab.url,
            visibility: request.value.visibility
          }).then(stylesheetResponse => {
            sendResponse(stylesheetResponse);
            if (stylesheetResponse.success) {
              chrome.tabs.update(tabId, { selected: true });

              window.setTimeout(async () => {
                // Capturing the photo fails sometimes shrug
                if (photo) {
                  uploadScreenshot({
                    photo: await toFile(photo, SCREENSHOT_CONTENT_TYPE),
                    key: stylesheetResponse.data.id,
                    domain: stylesheetResponse.data.domain
                  });
                }

                toggleStylebar(tabId, true);
              }, 50);
            } else {
              alert("Something didnt work quite right. Please try again!");
            }
          });
        });
      });
    }
  };

  const handleDevtoolMessages = async (request, from, sender, sendResponse) => {
    const { kind = null } = request;
    const kinds = MESSAGE_TYPES;

    if (!kind) {
      return;
    }

    if (!_.values(kinds).includes(kind)) {
      console.error(
        "[background] request kind must be one of",
        _.values(kinds)
      );
      return;
    }

    const tabId = getTabId(from);
    const tab = await getTab(tabId);

    if (kind === kinds.log) {
      console.log.apply(console, request.value);
    } else if (kind === kinds.send_content_stylesheets) {
      log("Received content stylesheets", request.value);
      if (!TAB_ORIGINAL_STYLES[tabId]) {
        TAB_ORIGINAL_STYLES[tabId] = request.value;
        LAST_RECEIVED_TAB_ORIGINAL_STYLES[tabId] = new Date().getTime();
      } else {
        const contentStyles = request.value;
        const existingSheets = TAB_ORIGINAL_STYLES[tabId];
        contentStyles.forEach(style => {
          const index = _.findIndex(
            existingSheets,
            sheet => sheet.url === style.url
          );
          if (index === -1) {
            TAB_ORIGINAL_STYLES[tabId].push(style);
            LAST_RECEIVED_TAB_ORIGINAL_STYLES[tabId] = new Date().getTime();
          }
        });
      }
    } else if (kind === kinds.open_style_editor) {
      injectCreateStyleURLBar(tabId);
    } else if (
      kind === kinds.style_diff_changed &&
      shouldAssumeChangesAreReal(tabId) &&
      !styleURLsForTabId(tabId)
    ) {
      injectCreateStyleURLBar(tabId);
    }
  };

  const getInlineStylesDiff = tabId => {
    return inlineStyleObserverConnection
      .sendMessage(
        `content_script:${PORT_TYPES.inline_style_observer}:${tabId}`,
        {
          kind: MESSAGE_TYPES.get_inline_style_diff
        }
      )
      .then(response => {
        log("Received inline styles!");

        const { old_stylesheet, new_stylesheet } = response.value;

        if (!new_stylesheet || !new_stylesheet.content) {
          return null;
        }

        const content = old_stylesheet
          ? diffSheet(old_stylesheet.content, new_stylesheet.content)
          : new_stylesheet.content;

        return {
          url: new_stylesheet.url,
          content
        };
      });
  };

  const getCurrentStylesheetsDiff = tabId => {
    console.time("Diff All Sheets");
    return devtoolConnection
      .sendMessage(`devtool:${PORT_TYPES.devtool_widget}:${tabId}`, {
        kind: MESSAGE_TYPES.get_current_styles_diff
      })
      .then(
        async response => {
          log("Received styles!");
          let modifiedSheets = response.value.stylesheets.slice();
          const currentStyles = response.value.general_stylesheets;
          const oldStyles = TAB_ORIGINAL_STYLES[tabId];
          if (oldStyles) {
            oldStyles
              .filter(
                style =>
                  style.url &&
                  style.url.indexOf("inject_create_styleurl.css") === -1 // this comes up ugh
              )
              .forEach(oldStyle => {
                const newStyle = currentStyles.find(
                  style => style.url === oldStyle.url
                );

                console.time("Diff Sheet [No Memoize]");
                const diffedStyle = diffSheet(
                  oldStyle ? oldStyle.content || "" : "",
                  newStyle ? newStyle.content || "" : ""
                );
                console.timeEnd("Diff Sheet [No Memoize]");

                if (diffedStyle && diffedStyle.trim().length > 0) {
                  modifiedSheets.push({
                    url: oldStyle.url,
                    content: diffedStyle
                  });
                }
              });
          }

          TAB_IDS_STYLESHEET_DIFFS[tabId] = modifiedSheets;

          try {
            const fauxInlineStylesheet = await getInlineStylesDiff(tabId);

            if (fauxInlineStylesheet) {
              modifiedSheets.push(fauxInlineStylesheet);
            }
          } catch (exception) {
            console.error(exception);
          }

          console.timeEnd("Diff All Sheets");

          return {
            stylesheets: modifiedSheets
          };
        },
        err => {
          console.error(err);
          alert("Something went wrong. Please try again");
        }
      );
  };

  chrome.browserAction.onClicked.addListener(tab => {
    console.log("Clicked Browser Action", getBrowserActionState());
    if (getBrowserActionState() === BROWSER_ACTION_STATES.default) {
      injectCreateStyleURLBar(tab.id);
    } else if (getBrowserActionState() === BROWSER_ACTION_STATES.upload_style) {
      injectCreateStyleURLBar(tab.id);
    } else if (
      getBrowserActionState() === BROWSER_ACTION_STATES.style_applied
    ) {
      injectViewStyleURLBar(tab.id);
    }
  });

  chrome.webNavigation.onBeforeNavigate.addListener(
    ({ tabId, url }) => {
      autodetectStyleURL({ tabId, url });
    },
    {
      url: Object.values(SPECIAL_QUERY_PARAMS).map(queryContains => ({
        queryContains
      }))
    }
  );

  const autoInsertCSS = async tab => {
    await autodetectStyleURL(tab);
    const styleURLs = styleURLsForTabId(tab.tabId);

    // Handle case where we haven't loaded the styleurl gist yet
    const pendingStyleURLs = styleURLs.filter(({ loaded = false }) => !loaded);
    if (pendingStyleURLs) {
      await Promise.all(
        pendingStyleURLs.map(styleurl => styleurl.load(styleurl.gistId))
      );
    }

    const appliedStyles = styleURLs.filter(styleURLTab =>
      styleURLTab.applyToTab(tab, stylesheetManagerConnection)
    );

    const styleCount = appliedStyles.length;
    if (styleCount > 0) {
      setBrowserActionToStyleApplied({ tabId: tab.tabId, styleCount });
    } else {
      // TODO: see if this is too aggro
      setBrowserActionToDefault({ tabId: tab.tabId });
    }
  };

  chrome.webNavigation.onCommitted.addListener(tab =>
    stopMonitoringTabID(tab.tabId)
  );
  chrome.webNavigation.onCommitted.addListener(autoInsertCSS);
  chrome.webNavigation.onHistoryStateUpdated.addListener(({ tabId, url }) =>
    autodetectStyleURL({ url, tabId })
  );

  chrome.webNavigation.onReferenceFragmentUpdated.addListener(({ tabId }) =>
    sendStyleURLsToTab({ tabId })
  );

  const injectBarHistoryListener = async ({ tabId, url }) => {
    if (!url) {
      return;
    }

    const styleURLs = styleURLsForTabId(tabId);

    // Handle case where we haven't loaded the styleurl gist yet
    const pendingStyleURLs = styleURLs.filter(({ loaded = false }) => !loaded);
    if (pendingStyleURLs) {
      await Promise.all(
        pendingStyleURLs.map(styleurl => styleurl.load(styleurl.gistId))
      );
    }

    if (
      styleURLs
        .filter(({ isBarEnabled }) => isBarEnabled)
        .find(styleURL => styleURL.canApplyStyle(url))
    ) {
      injectViewStyleURLBar(tabId);
    }
  };

  chrome.webNavigation.onDOMContentLoaded.addListener(injectBarHistoryListener);

  chrome.webNavigation.onHistoryStateUpdated.addListener(
    injectBarHistoryListener
  );
  chrome.webNavigation.onTabReplaced.addListener(injectBarHistoryListener);

  chrome.tabs.onRemoved.addListener(tabId => {
    if (TAB_IDS_TO_APPLY_STYLES[tabId]) {
      stopMonitoringTabID(tabId);
    }

    if (DEVTOOLS_OPEN_TABS[tabId]) {
      DEVTOOLS_OPEN_TABS[tabId] = false;
    }
  });

  devtoolConnection = messenger.initConnection(
    PORT_TYPES.devtool_widget,
    handleDevtoolMessages
  );

  gistConnection = messenger.initConnection(
    PORT_TYPES.github_gist,
    handleGistContentScriptMessages
  );

  inlineHeaderConnection = messenger.initConnection(
    PORT_TYPES.inline_header,
    handleInlineHeaderMessages
  );

  stylesheetManagerConnection = messenger.initConnection(
    PORT_TYPES.stylesheet_manager,
    handleInlineHeaderMessages
  );

  inlineStyleObserverConnection = messenger.initConnection(
    PORT_TYPES.inline_style_observer,
    handleInlineStyleObserverMessages
  );

  // If you just installed and have a styleURL page open, reload the tab so that the content script is loaded
  chrome.runtime.onInstalled.addListener(() => {
    chrome.tabs.query({ url: `${__FRONTEND_HOST__}/*` }, tabs => {
      tabs.forEach(tab => chrome.tabs.reload(tab.id));

      // See if there's any active non-homepage StyleURL tabs and set it to active
      // Basically we want to ignore / and all of the root routes
      // We _do_ want "/news.ycombinator.com/long_gist_id"
      const styleURLTab = tabs.find(
        tab =>
          `${__FRONTEND_HOST__}/`.split("/").length < tab.url.split("/").length
      );
      // Also set it to active
      if (styleURLTab) {
        chrome.tabs.update(styleURLTab.id, { active: true });
      }
    });
  });
});


================================================
FILE: chrome/extension/create_styleurl/CreateStyleURL.js
================================================
import { HeaderBar } from "app/components/HeaderBar";
import Messenger from "chrome-ext-messenger";
import classNames from "classnames";
import filenameify from "filenamify";
import _ from "lodash";
import React from "react";
import CodeDiff, { concatStylesheets } from "../../app/components/CodeDiff";
import Dropdown from "../../app/components/Dropdown";
import { Icon } from "../../app/components/Icon";
import injectScriptNames from "../lib/injectScriptNames";
import { MESSAGE_TYPES, PORT_TYPES } from "../lib/port";
import { INITIAL_WIDTH } from "./messages";

const messenger = new Messenger();

export const getFilename = () => {
  // The plus here is just here so the VSCode syntax highlighter doesnt get messed up
  // Weird VSCode bug :shrug:
  return filenameify(`${location.pathname.substr(1)}.diff` + ".css", {
    replacement: "_"
  });
};

const buildEditURL = gistId => {
  return `${__API_HOST__}/api/gists/edit/${gistId}`;
};

function copyToClipboard(text) {
  const input = document.createElement("textarea");
  input.style.position = "fixed";
  input.style.opacity = 0;
  input.value = text;
  document.body.appendChild(input);
  input.select();
  document.execCommand("Copy");
  document.body.removeChild(input);
}

class CreateStyleURL extends React.PureComponent {
  state = {
    stylesheets: [],
    downloadURL: null
  };

  static getDerivedStateFromProps(props, state) {
    if (props.stylesheets !== state.stylesheets) {
      if (props.stylesheets) {
        const blob = new Blob([concatStylesheets(props.stylesheets, true)], {
          type: "text/plain;charset=UTF-8"
        });

        return {
          stylesheets: props.stylesheets,
          downloadURL: window.URL.createObjectURL(blob)
        };
      } else {
        if (state.downloadURL) {
          URL.revokeObjectURL(state.downloadURL);
        }

        return { stylesheets: [], downloadURL: null };
      }
    } else {
      return {};
    }
  }

  render() {
    const {
      onToggleDiff,
      onExport,
      onShareChanges,
      stylesheets,
      shareURL,
      setShareLinkRef,
      onSendFeedback,
      hidden,
      onHide
    } = this.props;

    return (
      <HeaderBar
        hidden={hidden}
        onHide={onHide}
        onSendFeedback={onSendFeedback}
        center={
          <input
            value={shareURL}
            readOnly
            ref={setShareLinkRef}
            className={classNames("ShareLink", {
              "ShareLink--shown": shareURL
            })}
          />
        }
      >
        <Dropdown
          onToggle={onToggleDiff}
          icon={<Icon width={"32"} height="15" name="code" />}
          title="View changes"
        >
          <div className="ViewChanges">
            <CodeDiff stylesheets={stylesheets} />
            <div className="ViewChanges-actions">
              <a
                href={this.state.downloadURL}
                download={getFilename()}
                className="ViewChanges-action"
              >
                <div className="ViewChanges-action-text">Download</div>
              </a>
              <div className="ViewChanges-separator" />
              <div onClick={onExport} className="ViewChanges-action">
                <div className="ViewChanges-action-text">Create Gist</div>
              </div>
            </div>
          </div>
        </Dropdown>
        <Dropdown
          onClick={onShareChanges}
          icon={<Icon width={"24"} height="15" name="share" />}
          title="Share changes"
        />
      </HeaderBar>
    );
  }
}

class CreateStyleURLContainer extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      width: INITIAL_WIDTH,
      shareURL: "",
      hidden: false,
      stylesheets: []
    };

    this._connection = messenger.initConnection(
      PORT_TYPES.inline_header,
      this.handleMessage
    );
  }

  handleMessage = async (request, from, sender, sendResponse) => {
    const kinds = MESSAGE_TYPES;
    const { kind = null } = request;
    if (kind === kinds.style_diff_changed) {
      this.syncStylesheets();
    } else if (kind === kinds.open_devtools_plz) {
      alert(
        "Please open Chrome Devtools and try again -- ⋮ -> More Tools -> Developer Tools"
      );
    }
  };

  componentWillUnmount() {
    if (this._connection) {
      this._connection.disconnect();
    }
  }

  syncStylesheets = () => {
    this._sendMessage({
      kind: MESSAGE_TYPES.get_current_styles_diff
    }).then(({ stylesheets }) => {
      this.setState({
        stylesheets: stylesheets.map(({ content, url }) => [
          _.last(url.split("/")),
          content
        ])
      });
      this.setVisible(!_.isEmpty(stylesheets));
    });
  };

  setShareLinkRef = shareLinkRef => (this.shareLinkRef = shareLinkRef);

  handleToggleDiff = isOpen => {
    if (isOpen) {
      this.syncStylesheets();
    }
  };

  _sendMessage = message => {
    return this._connection.sendMessage(
      `background:${PORT_TYPES.inline_header}`,
      message
    );
  };

  handleExport = async () => {
    const { stylesheets } = await this._sendMessage({
      kind: MESSAGE_TYPES.get_current_styles_diff,
      value: {
        devtools_required: true
      }
    });

    if (!stylesheets || !stylesheets.length) {
      alert("Please make some CSS changes and try again");
      return;
    }

    this._sendMessage({
      kind: MESSAGE_TYPES.upload_stylesheets,
      value: {
        stylesheets,
        visibility: "private"
      }
    }).then(response => {
      if (response && response.data && response.data.url) {
        window.open(response.data.url, "_blank");
      }
    });
  };

  handleSendFeedback = message => {
    return this._sendMessage({
      kind: MESSAGE_TYPES.send_feedback,
      value: {
        message,
        from: "create"
      }
    });
  };

  handleShareChanges = () => {
    return this._sendMessage({
      kind: MESSAGE_TYPES.get_current_styles_diff,
      value: {
        devtools_required: true
      }
    }).then(({ stylesheets }) => {
      if (!stylesheets || !stylesheets.length) {
        alert("Please make some CSS changes and try again");
        return;
      }

      this._sendMessage({
        kind: MESSAGE_TYPES.upload_stylesheets,
        value: {
          stylesheets,
          visibility: "public"
        }
      })
        .then(response => {
          if (response && response.success) {
            const shareURL = response.data.share_url;

            this.setState({ shareURL });
            window.open(response.data.url, "_blank");
            return shareURL;
          }

          return null;
        })
        .then(shareURL => {
          if (!shareURL) {
            return;
          }

          copyToClipboard(shareURL);

          this._sendMessage({
            kind: MESSAGE_TYPES.send_success_notification,
            value: {
              didCopy: true
            }
          });
        });
    });
  };

  setVisible = isVisible => {
    const hidden = !isVisible;
    if (hidden === this.state.hidden) {
      return;
    }

    this.setState({ hidden });

    const shadowRoot = document.querySelector(
      `#${injectScriptNames.inject_create_styleurl}`
    );

    if (hidden) {
      shadowRoot.style.opacity = 0;
      shadowRoot.style.pointerEvents = "none";
    } else {
      shadowRoot.style.opacity = 1;
      shadowRoot.style.pointerEvents = "auto";
    }
  };

  handleHideBar = () => this.setVisible(false);

  render() {
    return (
      <CreateStyleURL
        hidden={this.state.hidden}
        onExport={this.handleExport}
        onShareChanges={this.handleShareChanges}
        onHide={this.handleHideBar}
        stylesheets={this.state.stylesheets}
        onToggleDiff={this.handleToggleDiff}
        onSendFeedback={this.handleSendFeedback}
        setShareLinkRef={this.setShareLinkRef}
        shareURL={this.state.shareURL}
      />
    );
  }
}

export default CreateStyleURLContainer;


================================================
FILE: chrome/extension/create_styleurl/Gist.css
================================================
#gist_root,
#gist_root body {
    margin: 0;
    padding: 0;
}

#gist_root {
    width: auto;
}

#gist_root .gist {
    display: block !important;
    position: relative !important;
}

#gist_root .gist-file {
    border: none !important;
    display: flex;
    flex-direction: column-reverse;
    margin-bottom: 0;
}

.gist-data,
.file-box,
.file,
.blob-wrapper,
.js-file-line-container {
    width: auto;
}

#gist_root .gist-data {
    background-color: #272822 !important;
    padding: 15px 5px !important;
    border: 0 !important;
    border-bottom: none !important;
    border-radius: 0px;
}

#gist_root .gist .highlight {
    background-color: #272822 !important;
}

#gist_root .gist .gist-meta {
    border-radius: 0;
    background-color: rgb(65, 65, 67);
}

#gist_root .gist .gist-meta,
#gist_root .gist .gist-meta a {
    color: white;
}

#gist_root .blob-num {
    border: solid #464741 !important;
    border-width: 0 1px 0 0 !important;
}

/* MONOKAI THEME SYNTAX HIGHLIGHTING - NOT COMPLETE */
#gist_root .blob-code-inner, #gist_root .pl-c1 {
    color: rgb(78, 198, 234) !important;
}

#gist_root .js-line-number {
    color: #8f908a !important;
}

#gist_root .pl-ent {
    color: #fc1f70 !important;
}

#gist_root .pl-e {
    color: #a4e402 !important;
}

#gist_root .pl-c {
    color: #75715d !important;
}

#gist_root .pl-s, .pl-pds {
    color: #e6dc6d !important;
}


================================================
FILE: chrome/extension/create_styleurl/Gist.js
================================================
import React from "react";
import "./gist.css";

const gistURL = ({ file, id }) => {
  const fileArg = file ? `?file=${file}` : "";

  return `https://gist.github.com/${id}.js${fileArg}`;
};

export class Gist extends React.Component {
  state = {
    url: null
  };

  static getDerivedStateFromProps(props, state) {
    const { id, file } = props;

    const url = gistURL({ id, file });

    if (url !== state.url) {
      return { url };
    } else {
      return {};
    }
  }

  componentDidUpdate(_prevProps, prevState) {
    if (this.state.url !== prevState.url) {
      this._updateIframeContent();
    }
  }

  componentDidMount() {
    this._updateIframeContent();
  }

  _updateIframeContent = () => {
    const { id, file, height } = this.props;

    const iframe = this.iframeNode;

    let doc = iframe.document;
    if (iframe.contentDocument) doc = iframe.contentDocument;
    else if (iframe.contentWindow) doc = iframe.contentWindow.document;

    const gistLink = this.state.url;
    const gistScript = `<script type="text/javascript" src="${gistLink}"></script>`;
    const stylesheetHref = document.querySelector("#root_stylesheet").href;
    const styles = `<link rel="stylesheet" href="${stylesheetHref}" />`;
    const elementId = file ? `gist-${id}-${file}` : `gist-${id}`;

    const resizeScript = `onload="parent.document.getElementById('${elementId}').style.height=document.body.scrollHeight + 'px'"`;
    const iframeHtml = `<html id="gist_root"><head><base target="_blank">${styles}</head><body ${resizeScript}>${gistScript}</body></html>`;

    doc.open();
    doc.writeln(iframeHtml);
    doc.close();
  };

  render() {
    const { id, file, height, width } = this.props;

    return (
      <iframe
        ref={n => {
          this.iframeNode = n;
        }}
        width="600"
        height={400}
        frameBorder={0}
        id={file ? `gist-${id}-${file}` : `gist-${id}`}
      />
    );
  }
}

export default Gist;


================================================
FILE: chrome/extension/create_styleurl/fonts.css
================================================
/* cyrillic-ext */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 400;
    src: local("Open Sans Regular"), local("OpenSans-Regular"), url(./fonts/OpenSans-Regular.ttf) format("truetype");
    unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}

/* cyrillic */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 400;
    src: local("Open Sans Regular"), local("OpenSans-Regular"), url(./fonts/OpenSans-Regular.ttf) format("truetype");
    unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}

/* greek-ext */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 400;
    src: local("Open Sans Regular"), local("OpenSans-Regular"), url(./fonts/OpenSans-Regular.ttf) format("truetype");
    unicode-range: U+1F00-1FFF;
}

/* greek */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 400;
    src: local("Open Sans Regular"), local("OpenSans-Regular"), url(./fonts/OpenSans-Regular.ttf) format("truetype");
    unicode-range: U+0370-03FF;
}

/* vietnamese */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 400;
    src: local("Open Sans Regular"), local("OpenSans-Regular"), url(./fonts/OpenSans-Regular.ttf) format("truetype");
    unicode-range: U+0102-0103, U+0110-0111, U+1EA0-1EF9, U+20AB;
}

/* latin-ext */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 400;
    src: local("Open Sans Regular"), local("OpenSans-Regular"), url(./fonts/OpenSans-Regular.ttf) format("truetype");
    unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}

/* latin */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 400;
    src: local("Open Sans Regular"), local("OpenSans-Regular"), url(./fonts/OpenSans-Regular.ttf) format("truetype");
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

/* cyrillic-ext */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 600;
    src: local("Open Sans SemiBold"), local("OpenSans-SemiBold"), url(./fonts/OpenSans-SemiBold.ttf) format("truetype");
    unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}

/* cyrillic */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 600;
    src: local("Open Sans SemiBold"), local("OpenSans-SemiBold"), url(./fonts/OpenSans-SemiBold.ttf) format("truetype");
    unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}

/* greek-ext */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 600;
    src: local("Open Sans SemiBold"), local("OpenSans-SemiBold"), url(./fonts/OpenSans-SemiBold.ttf) format("truetype");
    unicode-range: U+1F00-1FFF;
}

/* greek */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 600;
    src: local("Open Sans SemiBold"), local("OpenSans-SemiBold"), url(./fonts/OpenSans-SemiBold.ttf) format("truetype");
    unicode-range: U+0370-03FF;
}

/* vietnamese */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 600;
    src: local("Open Sans SemiBold"), local("OpenSans-SemiBold"), url(./fonts/OpenSans-SemiBold.ttf) format("truetype");
    unicode-range: U+0102-0103, U+0110-0111, U+1EA0-1EF9, U+20AB;
}

/* latin-ext */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 600;
    src: local("Open Sans SemiBold"), local("OpenSans-SemiBold"), url(./fonts/OpenSans-SemiBold.ttf) format("truetype");
    unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}

/* latin */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 600;
    src: local("Open Sans SemiBold"), local("OpenSans-SemiBold"), url(./fonts/OpenSans-SemiBold.ttf) format("truetype");
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

/* cyrillic-ext */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 700;
    src: local("Open Sans Bold"), local("OpenSans-Bold"), url(./fonts/OpenSans-Bold.ttf) format("truetype");
    unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}

/* cyrillic */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 700;
    src: local("Open Sans Bold"), local("OpenSans-Bold"), url(./fonts/OpenSans-Bold.ttf) format("truetype");
    unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}

/* greek-ext */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 700;
    src: local("Open Sans Bold"), local("OpenSans-Bold"), url(./fonts/OpenSans-Bold.ttf) format("truetype");
    unicode-range: U+1F00-1FFF;
}

/* greek */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 700;
    src: local("Open Sans Bold"), local("OpenSans-Bold"), url(./fonts/OpenSans-Bold.ttf) format("truetype");
    unicode-range: U+0370-03FF;
}

/* vietnamese */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 700;
    src: local("Open Sans Bold"), local("OpenSans-Bold"), url(./fonts/OpenSans-Bold.ttf) format("truetype");
    unicode-range: U+0102-0103, U+0110-0111, U+1EA0-1EF9, U+20AB;
}

/* latin-ext */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 700;
    src: local("Open Sans Bold"), local("OpenSans-Bold"), url(./fonts/OpenSans-Bold.ttf) format("truetype");
    unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}

/* latin */
@font-face {
    font-family: 'Open Sans';
    font-style: normal;
    font-weight: 700;
    src: local("Open Sans Bold"), local("OpenSans-Bold"), url(./fonts/OpenSans-Bold.ttf) format("truetype");
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}


================================================
FILE: chrome/extension/create_styleurl/messages.js
================================================
export const INITIAL_HEIGHT = 76;


================================================
FILE: chrome/extension/create_styleurl.css
================================================
/* @import "reset-css"; */
@import "./create_styleurl/fonts.css";

.StyleURLShadowDOMRoot,
textarea,
div,
input {
    font-family: "Open Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}

.StyleURLShadowDOMRoot {
    margin: 0;
    padding: 0;
    font-size: 10pt;
    height: 100%;
    width: 100%;
}

h1,
h2,
h3 {
    margin: 0;
    padding: 0;
    font-weight: 600;
}

.ShareTextInput {
    padding: 14px;
    color: white;
    font-size: 12px;
    border-top-left-radius: 2px;
    border-top-right-radius: 2px;
    overflow: hidden;
}

.ViewChanges-actions {
    display: flex;
    border-top: 1px solid #13161b;
}

.ViewChanges-separator {
    height: 31px;
    width: 1px;
    display: block;
    flex-shrink: 0;
    flex-grow: 0;
    content: "";
}

.ViewChanges-action {
    display: flex;
    align-items: center;
    flex: 0.5;
    color: white;
    justify-content: center;
    padding: 6px 8px;
    font-weight: 600;
    text-decoration: none;
    cursor: pointer;
    font-size: 14px;
}

.ViewChanges-action-icon {
    margin-top: auto;
    margin-bottom: auto;
    margin-right: 8px;
}

.ViewChanges-action:hover,
.ViewChanges-separator {
    background-color: #13161b;
}

.ShareLink {
    font-size: 14px;
    color: #fff;
    background-color: rgb(65, 70, 81);
    appearance: none;
    -webkit-appearance: none;
    -moz-appearance: none;
    border: 0;
    outline: 0;
    padding: 6px 8px;
    width: 300px;
    display: none;
    text-align: center;
}

.ShareLink--shown {
    display: inline-block;
}

@media print {
    .StyleURLShadowDOMRoot {
        display: none;
    }
}


================================================
FILE: chrome/extension/create_styleurl.js
================================================
import React from "react";
import ReactDOM from "react-dom";
import CreateStyleURL from "./create_styleurl/CreateStyleURL";
import "./create_styleurl.css";


================================================
FILE: chrome/extension/css_manager_content_script.js
================================================
// This code has largely been adapted from https://github.com/openstyles/stylus/blob/master/content/apply.js
// ...thanks
import Messenger from "chrome-ext-messenger";
import { PORT_TYPES, MESSAGE_TYPES } from "./lib/port";
import { makeAllRulesImportant } from "./lib/makeEverythingImportant";
import { shouldApplyStyleToURL } from "./lib/stylefile";

(() => {
  if (typeof window.applyOnMessage === "function") {
    // some weird bug in new Chrome: the content script gets injected multiple times
    return;
  }
  console.log("[CSSManager] INJECT START");
  const messenger = new Messenger();
  const connection = messenger.initConnection(
    PORT_TYPES.stylesheet_manager,
    applyOnMessage
  );
  const ID_PREFIX = "__styleurl-";

  const CHROME = chrome.app
    ? parseInt(navigator.userAgent.match(/Chrom\w+\/(?:\d+\.){2}(\d+)|$/)[1])
    : NaN;
  var ROOT = document.documentElement;
  var isOwnPage = location.protocol.endsWith("-extension:");
  var disableAll = false;
  var exposeIframes = false;
  var styleElements = new Map();
  var disabledElements = new Map();
  var retiredStyleTimers = new Map();
  var docRewriteObserver;
  var docRootObserver;

  requestStyles();

  window.applyOnMessage = applyOnMessage;

  if (!isOwnPage) {
    window.dispatchEvent(new CustomEvent(chrome.runtime.id));
    window.addEventListener(chrome.runtime.id, orphanCheck, true);
  }

  function requestStyles(options, callback = applyStyles) {
    var matchUrl = location.href;
    if (!matchUrl.match(/^(http|file|chrome|ftp)/)) {
      // dynamic about: and javascript: iframes don't have an URL yet
      // so we'll try the parent frame which is guaranteed to have a real URL
      try {
        if (window !== parent) {
          matchUrl = parent.location.href;
        }
      } catch (e) {}
    }

    console.log("[CSSManager] REQUEST STYLE");

    connection
      .sendMessage(`background:${PORT_TYPES.stylesheet_manager}`, {
        kind: MESSAGE_TYPES.get_styleurl
      })
      .then(message => {
        applyOnMessage(message.value);
      });
  }

  const convertFromStyleURL = value => {
    const { stylesheets = [], isStyleEnabled = true, stylefile = {} } = value;

    const styles = stylesheets.map(stylesheet => ({
      code: stylesheet[1],
      id: stylesheet[0],
      enabled: isStyleEnabled,
      important: stylesheet[0].includes(".inline.css")
    }));

    const _stylesMap = {};

    styles.forEach(style => (_stylesMap[style.id] = [style]));
    _stylesMap.length = styles.length;

    return {
      prefs: {
        disableAll:
          shouldApplyStyleToURL(stylefile, window.location.href) &&
          !isStyleEnabled
      },
      styles: _stylesMap
    };
  };

  function applyOnMessage(message, from, sender, sendResponse) {
    const request = convertFromStyleURL(
      typeof message.value !== "undefined" ? message.value : message
    );
    let kind = "styleApply";

    console.log("[CSSManager] RECEIVE STYLE");

    switch (kind) {
      case "styleDeleted":
        removeStyle(request.styles[1]);
        break;

      case "styleUpdated":
        if (request.style.enabled) {
          removeStyle({ id: request.style.id, retire: true });
          requestStyles({ id: request.style.id });
        } else {
          removeStyle(request.style);
        }
        break;

      case "styleAdded":
        if (request.style.enabled) {
          requestStyles({ id: request.style.id });
        }
        break;

      case "styleApply":
        applyStyles(request.styles);
        break;

      case "styleReplaceAll":
        replaceAll(request.styles);
        break;

      case "prefChanged":
        if ("disableAll" in request.prefs) {
          doDisableAll(request.prefs.disableAll);
        }
        if ("exposeIframes" in request.prefs) {
          doExposeIframes(request.prefs.exposeIframes);
        }
        break;

      case "ping":
        sendResponse(true);
        break;
    }

    if (disableAll !== request.prefs.disableAll) {
      doDisableAll(request.prefs.disableAll);
    }
  }

  function doDisableAll(disable = disableAll) {
    if (!disable === !disableAll) {
      return;
    }
    disableAll = disable;
    Array.prototype.forEach.call(document.styleSheets, stylesheet => {
      if (
        stylesheet.ownerNode.matches(`style.styleurl[id^="${ID_PREFIX}"]`) &&
        stylesheet.disabled !== disable
      ) {
        stylesheet.disabled = disable;
      }
    });
  }

  function doExposeIframes(state = exposeIframes) {
    if (
      state === exposeIframes ||
      (state === true && typeof exposeIframes === "string") ||
      window === parent
    ) {
      return;
    }
    exposeIframes = state;
    const attr = document.documentElement.getAttribute("styleurl-iframe");
    if (state && state !== attr) {
      document.documentElement.setAttribute("styleurl-iframe", state);
    } else if (!state && attr !== undefined) {
      document.documentElement.removeAttribute("styleurl-iframe");
    }
  }

  function applyStyleState({ id, enabled }) {
    const inCache = disabledElements.get(id) || styleElements.get(id);
    const inDoc = document.getElementById(ID_PREFIX + id);
    if (enabled) {
      if (inDoc) {
        return;
      } else if (inCache) {
        addStyleElement(inCache);
        disabledElements.delete(id);
      } else {
        requestStyles({ id });
      }
    } else {
      if (inDoc) {
        disabledElements.set(id, inDoc);
        docRootObserver.evade(() => inDoc.remove());
      }
    }
  }

  function removeStyle({ id, retire = false }) {
    const el = document.getElementById(ID_PREFIX + id);
    if (el) {
      if (retire) {
        // to avoid page flicker when the style is updated
        // instead of removing it immediately we rename its ID and queue it
        // to be deleted in applyStyles after a new version is fetched and applied
        const deadID = id + "-ghost";
        el.id = ID_PREFIX + deadID;
        // in case something went wrong and new style was never applied
        retiredStyleTimers.set(
          deadID,
          setTimeout(removeStyle, 1000, { id: deadID })
        );
      } else {
        docRootObserver.evade(() => el.remove());
      }
    }
    styleElements.delete(ID_PREFIX + id);
    disabledElements.delete(id);
    retiredStyleTimers.delete(id);
  }

  function applyStyles(styles) {
    if (!styles) {
      // Chrome is starting up
      requestStyles();
      return;
    }

    if (!document.documentElement) {
      new MutationObserver((mutations, observer) => {
        if (document.documentElement) {
          observer.disconnect();
          applyStyles(styles);
        }
      }).observe(document, { childList: true });
      return;
    }

    if ("disableAll" in styles) {
      doDisableAll(styles.disableAll);
    }
    if ("exposeIframes" in styles) {
      doExposeIframes(styles.exposeIframes);
    }

    const gotNewStyles = styles.length || styles.needTransitionPatch;
    if (gotNewStyles) {
      if (docRootObserver) {
        docRootObserver.stop();
      } else {
        initDocRootObserver();
      }
    }

    if (styles.needTransitionPatch) {
      applyTransitionPatch();
    }

    if (gotNewStyles) {
      for (const id in styles) {
        const sections = styles[id];
        if (!Array.isArray(sections)) continue;
        applySections(
          id,
          sections.map(({ code }) => code).join("\n"),
          sections.find(({ important = false }) => !!important)
        );
      }
      docRootObserver.start({ sort: true });
    }

    if (!isOwnPage && !docRewriteObserver && styleElements.size) {
      initDocRewriteObserver();
    }

    if (retiredStyleTimers.size) {
      setTimeout(() => {
        for (const [id, timer] of retiredStyleTimers.entries()) {
          removeStyle({ id });
          clearTimeout(timer);
        }
      });
    }
  }

  function applySections(styleId, code, important) {
    const id = ID_PREFIX + styleId;
    let el = styleElements.get(id) || document.getElementById(id);
    if (el && el.textContent !== code) {
      if (CHROME < 3321) {
        // workaround for Chrome devtools bug fixed in v65
        el.remove();
        el = null;
      } else {
        el.textContent = code;
      }
    }
    if (!el) {
      if (document.documentElement instanceof SVGSVGElement) {
        // SVG document style
        el = document.createElementNS("http://www.w3.org/2000/svg", "style");
      } else if (document instanceof XMLDocument) {
        // XML document style
        el = document.createElementNS("http://www.w3.org/1999/xhtml", "style");
      } else {
        // HTML document style; also works on HTML-embedded SVG
        el = document.createElement("style");
      }
      Object.assign(el, {
        id,
        type: "text/css",
        textContent: code
      });
      // SVG className is not a string, but an instance of SVGAnimatedString
      el.classList.add("styleurl");

      if (important) {
        el.classList.add("styleurl--important");
      }

      addStyleElement(el, important);
    }
    styleElements.set(id, el);
    disabledElements.delete(Number(styleId));
    return el;
  }

  function addStyleElement(newElement, important) {
    if (!ROOT) {
      return;
    }
    let next;
    const newStyleId = getStyleId(newElement);
    for (const el of styleElements.values()) {
      if (
        el.parentNode &&
        !el.id.endsWith("-ghost") &&
        getStyleId(el) > newStyleId
      ) {
        next = el.parentNode === ROOT ? el : null;
        break;
      }
    }
    if (next === newElement.nextElementSibling) {
      return;
    }
    docRootObserver.evade(() => {
      ROOT.insertBefore(newElement, next || null);
      if (disableAll) {
        newElement.disabled = true;
      }
    });
  }

  function replaceAll(newStyles) {
    if (
      "disableAll" in newStyles &&
      disableAll === newStyles.disableAll &&
      styleElements.size === countStylesInHash(newStyles) &&
      [...styleElements.values()].every(
        el =>
          el.disabled === disableAll &&
          el.parentNode === ROOT &&
          el.textContent ===
            (newStyles[getStyleId(el)] || []).map(({ code }) => code).join("\n")
      )
    ) {
      return;
    }
    const oldStyles = Array.prototype.slice.call(
      document.querySelectorAll(`style.styleurl[id^="${ID_PREFIX}"]`)
    );
    oldStyles.forEach(el => (el.id += "-ghost"));
    styleElements.clear();
    disabledElements.clear();
    [...retiredStyleTimers.values()].forEach(clearTimeout);
    retiredStyleTimers.clear();
    applyStyles(newStyles);
    docRootObserver.evade(() => oldStyles.forEach(el => el.remove()));
  }

  function applyTransitionPatch() {
    // CSS transition bug workaround: since we insert styles asynchronously,
    // the browsers, especially Firefox, may apply all transitions on page load
    const className = chrome.runtime.id + "-transition-bug-fix";
    const docId = document.documentElement.id
      ? "#" + document.documentElement.id
      : "";
    document.documentElement.classList.add(className);
    applySections(
      0,
      `
        ${docId}.${className}:root * {
          transition: none !important;
        }
      `
    );
    setTimeout(() => {
      removeStyle({ id: 0 });
      document.documentElement.classList.remove(className);
    });
  }

  function getStyleId(el) {
    return parseInt(el.id.substr(ID_PREFIX.length));
  }

  function countStylesInHash(styleHash) {
    let num = 0;
    for (const k in styleHash) {
      num += !isNaN(parseInt(k)) ? 1 : 0;
    }
    return num;
  }

  function orphanCheck() {
    if (chrome.i18n && chrome.i18n.getUILanguage()) {
      return true;
    }
    // In Chrome content script is orphaned on an extension update/reload
    // so we need to detach event listeners
    [docRewriteObserver, docRootObserver].forEach(ob => ob && ob.disconnect());
    window.removeEventListener(chrome.runtime.id, orphanCheck, true);
    try {
      chrome.runtime.onMessage.removeListener(applyOnMessage);
    } catch (e) {}
  }

  function initDocRewriteObserver() {
    // detect documentElement being rewritten from inside the script
    docRewriteObserver = new MutationObserver(mutations => {
      for (let m = mutations.length; --m >= 0; ) {
        const added = mutations[m].addedNodes;
        for (let n = added.length; --n >= 0; ) {
          if (added[n].localName === "html") {
            reinjectStyles();
            return;
          }
        }
      }
    });
    docRewriteObserver.observe(document, { childList: true });
    // detect dynamic iframes rewritten after creation by the embedder i.e. externally
    setTimeout(() => {
      if (document.documentElement !== ROOT) {
        reinjectStyles();
      }
    });
    // re-add styles if we detect documentElement being recreated
    function reinjectStyles() {
      if (!styleElements) {
        orphanCheck();
        return;
      }
      ROOT = document.documentElement;
      docRootObserver.stop();
      const imported = [];
      for (const [id, el] of styleElements.entries()) {
        const copy = document.importNode(el, true);
        el.textContent += " "; // invalidate CSSOM cache
        imported.push([id, copy]);
        addStyleElement(copy);
      }
      docRootObserver.start();
      styleElements = new Map(imported);
    }
  }

  function initDocRootObserver() {
    let lastRestorationTime = 0;
    let restorationCounter = 0;
    let observing = false;
    let sorting = false;
    let observer;
    // allow any types of elements between ours, except for the following:
    const ORDERED_TAGS = ["head", "body", "frameset", "style", "link"];

    init();
    return;

    function init() {
      observer = new MutationObserver(sortStyleElements);
      docRootObserver = { start, stop, evade, disconnect: stop };
      setTimeout(sortStyleElements);
    }
    function start({ sort = false } = {}) {
      if (sort && sortStyleMap()) {
        sortStyleElements();
      }
      if (!observing && ROOT && observer) {
        observer.observe(ROOT, { childList: true });
        observing = true;
      }
    }
    function stop() {
      if (observing) {
        observer.takeRecords();
        observer.disconnect();
        observing = false;
      }
    }
    function evade(fn) {
      const wasObserving = observing;
      if (observing) {
        stop();
      }
      fn();
      if (wasObserving) {
        start();
      }
    }
    function sortStyleMap() {
      const list = [];
      let prevStyleId = 0;
      let needsSorting = false;
      for (const entry of styleElements.entries()) {
        list.push(entry);
        const el = entry[1];
        const styleId = getStyleId(el);
        el.styleId = styleId;
        needsSorting |= styleId < prevStyleId;
        prevStyleId = styleId;
      }
      if (needsSorting) {
        styleElements = new Map(
          list.sort((a, b) => a[1].styleId - b[1].styleId)
        );
        return true;
      }
    }
    function sortStyleElements() {
      if (!observing) {
        return;
      }
      let prevExpected = document.documentElement.lastElementChild;
      while (prevExpected && isSkippable(prevExpected, true)) {
        prevExpected = prevExpected.previousElementSibling;
      }
      if (!prevExpected) {
        return;
      }
      for (let el of styleElements.values()) {
        if (!isMovable(el)) {
          continue;
        }
        while (true) {
          const next = prevExpected.nextElementSibling;
          if (next && isSkippable(next)) {
            prevExpected = next;
          } else if (
            next === el ||
            (next === el.previousElementSibling && next) ||
            moveAfter(el, next || prevExpected)
          ) {
            prevExpected = el;
            break;
          } else {
            return;
          }
        }
      }
      if (sorting) {
        sorting = false;
        if (observer) observer.takeRecords();
        if (!restorationLimitExceeded()) {
          start();
        } else {
          setTimeout(start, 1000);
        }
      }
    }
    function isMovable(el) {
      return !!(el.parentNode || !disabledElements.has(getStyleId(el)));
    }
    function isSkippable(el, skipOwnStyles) {
      return (
        !ORDERED_TAGS.includes(el.localName) ||
        (el.id.startsWith(ID_PREFIX) &&
          (skipOwnStyles || el.id.endsWith("-ghost")) &&
          el.localName === "style" &&
          el.className === "styleurl")
      );
    }
    function moveAfter(el, expected) {
      if (!sorting) {
        sorting = true;
        stop();
      }
      expected.insertAdjacentElement("afterend", el);
      if (el.disabled !== disableAll) {
        // moving an element resets its 'disabled' state
        el.disabled = disableAll;
      }

      if (el.className.includes("styleurl--important")) {
        makeAllRulesImportant(el);
      }
      return true;
    }
    function restorationLimitExceeded() {
      const t = performance.now();
      if (t - lastRestorationTime > 1000) {
        restorationCounter = 0;
      }
      lastRestorationTime = t;
      return ++restorationCounter > 5;
    }
  }
})();


================================================
FILE: chrome/extension/devtools.js
================================================
import Messenger from "chrome-ext-messenger";
import Hashes from "jshashes";
import _ from "lodash";
import { MESSAGE_TYPES, PORT_TYPES } from "./lib/port";
const messenger = new Messenger();
const SHA256 = new Hashes.SHA256();

let connection;

const log = (...messages) => {
  connection.sendMessage(`background:${PORT_TYPES.devtool_widget}`, {
    kind: MESSAGE_TYPES.log,
    value: ["[DEVTOOLS]", ...messages]
  });
};

const isResourceStyle = resource => resource && resource.type === "stylesheet";

const isInspectorStyle = resource => {
  const isStylesheet =
    resource.url.startsWith("inspector://") && isResourceStyle(resource);
  return isStylesheet;
};

const isGeneralStyle = resource => {
  const isStylesheet =
    resource.url.startsWith("inspector://") === false &&
    isResourceStyle(resource);
  return isStylesheet;
};

const getResources = () =>
  new Promise((resolve, reject) =>
    chrome.devtools.inspectedWindow.getResources(resources => {
      resolve(resources);
    })
  );

const getResourceUrl = resource => {
  let resourceUrl = resource.url;
  if (resourceUrl.startsWith("data:")) {
    resourceUrl = `datauri-${SHA256.hex(resourceUrl)}` + ".css";
  }
  return resourceUrl;
};

const getResourceContent = resource =>
  new Promise((resolve, reject) => {
    const resourceUrl = getResourceUrl(resource);
    log("GET", resourceUrl);
    resource.getContent(content => {
      resolve({
        url: resourceUrl,
        content
      });
    });
  });

// Warning --
// This gets called in browser context, do not use es modules here
const getStyleTagsInBrowser = () => {
  const __extractedStyles = document.styleSheets;
  const styles = {};
  Object.keys(__extractedStyles).map(ind => {
    const ss = __extractedStyles[ind];
    // ignore:
    // - non-style tags
    // - empty style tags (those are not editable from devtools)
    if (
      typeof ss.href === "string" ||
      !ss.ownerNode ||
      ss.ownerNode.innerHTML.length === 0 ||
      (ss.ownerNode.id && ss.ownerNode.id.includes("__styleurl"))
    ) {
      return null;
    }

    let id = ss.ownerNode.dataset.styleurl_id;
    if (!id) {
      id = ss.ownerNode.id ? ss.ownerNode.id : `styletag_${ind}`;

      if (!!document.querySelector(`[data-style_url="${id}"`)) {
        id = `styletag_${Math.random()
          .toString(36)
          .replace(/[^a-z]+/g, "")
          .substr(0, 5)}`;
      }

      ss.ownerNode.dataset.styleurl_id = id;
    }

    const content = Object.keys(ss.cssRules)
      .map(sind => ss.cssRules[sind].cssText)
      .join("\n");

    styles[id] = content;
  });
  return styles;
};

const getStyleTags = () =>
  new Promise(resolve => {
    chrome.tabs.executeScript(
      chrome.devtools.inspectedWindow.tabId,
      {
        code: `((${getStyleTagsInBrowser.toString()})())`
      },
      ds => {
        const styleTags = ds[0];

        resolve(
          _.keys(styleTags).map(key => {
            return { url: key, content: styleTags[key] };
          })
        );
      }
    );
  });

const getLoadedSheets = () => {
  return getResources()
    .then(resources => resources.filter(isGeneralStyle))
    .then(stylesheets => Promise.all(stylesheets.map(getResourceContent)))
    .catch(error => alert(error));
};

const getGeneralStyles = () =>
  new Promise((resolve, reject) => {
    Promise.all([getStyleTags(), getLoadedSheets()]).then(allStyles => {
      const filteredStyles = _
        .compact(_.flatten(allStyles))
        .map(({ content, url }) => ({ url, content: content }));
      return resolve(filteredStyles);
    });
  });

const getInspectorStyles = () => {
  return getResources()
    .then(resources => resources.filter(isInspectorStyle))
    .then(stylesheets => Promise.all(stylesheets.map(getResourceContent)))
    .catch(error => alert(error));
};

const createConnection = () => {
  return messenger.initConnection(
    PORT_TYPES.devtool_widget,
    handleReceivedMessage
  );
};

const handleReceivedMessage = (request, from, sender, sendResponse) => {
  if (request.kind === MESSAGE_TYPES.get_current_styles_diff) {
    Promise.all([getInspectorStyles(), getGeneralStyles()]).then(promises => {
      sendResponse({
        kind: MESSAGE_TYPES.get_current_styles_diff,
        response: true,
        value: {
          ...request.value,
          stylesheets: promises[0],
          general_stylesheets: promises[1]
        }
      });
    });
  }
};

const sendStyleDiffChangedEvent = el => {
  if (isResourceStyle(el)) {
    getInspectorStyles().then(stylesheets => {
      if (!connection) {
        return;
      }

      connection.sendMessage(`background:${PORT_TYPES.devtool_widget}`, {
        kind: MESSAGE_TYPES.style_diff_changed,
        value: {
          stylesheets
        }
      });
    });
  }
};

const sendContentStyles = () => {
  return new Promise(resolve => {
    getGeneralStyles().then(stylesheets => {
      if (!connection) {
        return;
      }

      connection.sendMessage(`background:${PORT_TYPES.devtool_widget}`, {
        kind: MESSAGE_TYPES.send_content_stylesheets,
        value: stylesheets
      });
      resolve();
    });
  });
};

const sendSelectedElementToContentScript = () => {
  chrome.devtools.inspectedWindow.eval(
    ` window.__styleurlSelectedElement = $0;
      window.__styleurlSetSelected && window.__styleurlSetSelected($0);`,
    {
      useContentScriptContext: true
    }
  );
};

const setupConnection = () => {
  connection = createConnection();

  sendContentStyles();
  sendStyleDiffChangedEvent();
  sendSelectedElementToContentScript();
};

chrome.devtools.network.onNavigated.addListener(function() {
  if (connection) {
    connection.disconnect();
  }

  if (_.isNumber(chrome.devtools.inspectedWindow.tabId)) {
    setupConnection();
  }
});

chrome.devtools.inspectedWindow.onResourceContentCommitted.addListener(
  sendStyleDiffChangedEvent
);

chrome.devtools.inspectedWindow.onResourceAdded.addListener(
  sendStyleDiffChangedEvent
);

const contentStyleListener = resource => {
  if (resource.url.startsWith("debugger://")) {
    return;
  }
  log("CONTENT COMMITTED", resource ? resource.url : null);
  sendContentStyles(resource).then(() => {
    connection.sendMessage(`background:${PORT_TYPES.devtool_widget}`, {
      kind: MESSAGE_TYPES.open_style_editor
    });

    connection.sendMessage(
      `content_script:${PORT_TYPES.inline_header}:${
        chrome.devtools.inspectedWindow.tabId
      }`,
      { kind: MESSAGE_TYPES.style_diff_changed }
    );

    connection.sendMessage(`background:${PORT_TYPES.devtool_widget}`, {
      kind: MESSAGE_TYPES.style_diff_changed
    });
  });
};

chrome.devtools.inspectedWindow.onResourceContentCommitted.addListener(
  _.debounce(contentStyleListener, 150)
);
setupConnection();

chrome.devtools.panels.elements.onSelectionChanged.addListener(() => {
  sendSelectedElementToContentScript();
});


================================================
FILE: chrome/extension/github_gist_content_script.js
================================================
// Privacy Notice
// StyleURL does *not* send all gists the user opens to StyleURL's server.
// Before requesting the contents of the gist, StyleURL looks for "Stylefile.yml" or "Stylefile" to assess whether or not it might be a StyleURL
// Only when it does find a matching filename, it requests the content of the stylesheets
// We want to protect user's privacy as much as possible, even if its a little more work for us.
import { MESSAGE_TYPES, PORT_TYPES } from "./lib/port";
import { SPECIAL_QUERY_PARAMS, STYLEFILE_NAMES } from "./lib/gists";
import { loadStylefileFromString } from "./lib/stylefile";
import Messenger from "chrome-ext-messenger";

const messenger = new Messenger();
const connection = messenger.initConnection(PORT_TYPES.github_gist);

const getGistID = () => window.location.pathname.split("/")[2];

const buildShareURL = (stylefile, gistID) => {
  return `${__FRONTEND_HOST__}/${stylefile.domains[0]}/${gistID}`;
};

const buildStyleURL = styleFile => {
  const originalURL = styleFile.redirect_url;

  const queryString = originalURL.includes("?")
    ? originalURL.split("?")[1]
    : "";
  const searchParams = new URLSearchParams(queryString);

  searchParams.append(SPECIAL_QUERY_PARAMS.gist_id, `gist_${getGistID()}`);

  return `${originalURL}?${searchParams.toString()}`;
};

const log = (...messages) =>
  console.log.apply(console, ["[StyleURL]", ...messages]);

const renderStyleURLBar = (styleFile, gistID) => {
  log("Detected Stylefile", styleFile);

  const div = document.createElement("div");
  div.innerHTML = `<div style="background-color: #0366d6; padding-top: 14px; padding-bottom: 14px;"><div class="container-lg px-3 clearfix"><div id="styleurl_bar_root" style="display: flex; justify-content: space-between; align-items: center; color white;">
  <div style="font-size: 18px; white-space: nowrap; color: white;">Apply this StyleURL on <strong>${
    styleFile.domains[0]
  }</strong>?</div>

  <div style="display: flex; align-items: center;">
  <a href="${buildShareURL(
    styleFile,
    gistID
  )}" class="btn-link" style="color: white; margin-right: 14px; font-weight: bold; text-decoration: underline;">Share StyleURL</a>
  <a href="${buildStyleURL(styleFile)}" class="btn">Apply StyleURL</a>

  </div>
</div></div></div>`;
  document.body.prepend(div);
};

// Hard to know 100% of the time whether or not we're on the gist page
const isGistPage = pathname => {
  const parts = pathname.split("/");
  const isCorrectLength = parts.length === 3; // ["", "User-Name", "hash"]

  if (!isCorrectLength) {
    return false;
  }

  const gistId = parts[2];

  return gistId.length > 5;
};

const isRawDownloadLink = pathname => {
  return pathname.includes("/raw/");
};

const getGistFilenames = () => {
  return window
    .fetch(window.location.pathname + ".json")
    .then(resp => resp.json(), () => false)
    .then(
      gist => {
        if (!gist || !gist.files) {
          return [];
        }

        return gist.files || [];
      },
      () => []
    );
};

const getFileURL = filename => {
  const files = Array.from(document.querySelectorAll(".file-box"));

  const fileBox = files.find(fileBox =>
    Array.from(fileBox.querySelectorAll(".file-info .gist-blob-name")).find(
      element => element.innerText === filename
    )
  );

  if (!fileBox) {
    return null;
  }

  const rawFileLink = Array.from(
    fileBox.querySelectorAll(".file-actions a.btn")
  ).find(element => isRawDownloadLink(element.href));

  if (!rawFileLink) {
    return null;
  }

  return rawFileLink.href;
};

const getGistFileContents = filename => {
  return connection
    .sendMessage(`background:${PORT_TYPES.github_gist}`, {
      kind: MESSAGE_TYPES.get_gist_content,
      url: getFileURL(filename)
    })
    .then(({ value }) => {
      return value;
    });
};

if (isGistPage(location.pathname)) {
  getGistFilenames().then(fileNames => {
    if (!fileNames) {
      return null;
    }

    const filename = fileNames.find(name => STYLEFILE_NAMES.indexOf(name) > -1);
    if (!filename) {
      return;
    }

    getGistFileContents(filename)
      .then(yaml => {
        return loadStylefileFromString(yaml);
      })
      .then(styleFile => {
        if (!styleFile) {
          return;
        }

        renderStyleURLBar(styleFile, getGistID());
      });
  });
}


================================================
FILE: chrome/extension/inject_create_styleurl.js
================================================
import { injectShadowDOM } from "./lib/injectShadowDom";
import CreateStyleURL from "./create_styleurl/CreateStyleURL";
import "./create_styleurl.css";
import injectScriptNames from "./lib/injectScriptNames";

injectShadowDOM({
  id: injectScriptNames.inject_create_styleurl,
  Component: CreateStyleURL,
  include: chrome.extension.getURL("/inject_create_styleurl.css")
});


================================================
FILE: chrome/extension/inject_view_styleurl.js
================================================
import { injectShadowDOM } from "./lib/injectShadowDom";
import injectScriptNames from "./lib/injectScriptNames";
import ViewStyleURLContainer from "./view_styleurl/ViewStyleURL";

injectShadowDOM({
  id: injectScriptNames.inject_view_styleurl,
  Component: ViewStyleURLContainer,
  include: chrome.extension.getURL("/inject_view_styleurl.css")
});


================================================
FILE: chrome/extension/inline_style_observer/inline_style_observer.js
================================================
import { getSingleSelector } from "optimal-select";

export class InlineStyleObserver {
  constructor(onChange) {
    this.changeSet = {};
    this._observer = null;
    this.observing = false;

    this.onChange = onChange;
  }

  setSelectedElement = element => {
    const wasObserving = this.observing;
    if (wasObserving) {
      this.stop();
    }

    this.selectedElement = element;

    this.start();
  };

  start = () => {
    if (!this._observer) {
      this._observer = new MutationObserver(this.handleMutation);
    }

    if (this.observing || !this.selectedElement) {
      return;
    }

    this._observer.observe(this.selectedElement, {
      attributes: true,
      attributeOldValue: true,
      attributeFilter: ["style"]
    });

    this.observing = true;
  };

  stop = () => {
    if (!this.observing || !this._observer) {
      return;
    }

    this._observer.disconnect();
    this.observing = false;
  };

  handleMutation = mutations => {
    mutations.forEach(mutation => {
      if (mutation.attributeName !== "style") {
        return;
      }

      if (!mutation.target) {
        return;
      }

      const selector = getSingleSelector(mutation.target);

      if (!this.changeSet[selector]) {
        this.changeSet[selector] = {
          selector,
          before: mutation.oldValue,
          after: mutation.target.style.cssText
        };
      }

      this.changeSet[selector].after = mutation.target.style.cssText;
    });

    this.onChange(this.changeSet);
  };
}


================================================
FILE: chrome/extension/inline_style_observer/inline_style_observer_manager.js
================================================
import Messenger from "chrome-ext-messenger";
import { PORT_TYPES, MESSAGE_TYPES } from "../lib/port";
import { InlineStyleObserver } from "./inline_style_observer";

const buildRuleFromSelectorAndCssText = (selector, text) => {
  return `${selector} { ${text} }`;
};

export class InlineStyleObserverManager {
  constructor() {
    this._messenger = new Messenger();
    this._connection = this._messenger.initConnection(
      PORT_TYPES.inline_style_observer,
      this.handleMessage
    );
    this.oldStylesheet = null;
    this.newStylesheet = null;
    this._observer = new InlineStyleObserver(this.handleChange);

    if (window.__styleurlSelectedElement) {
      this._observer.setSelectedElement(window.__styleurlSelectedElement);
    }

    window.__styleurlSetSelected = this._observer.setSelectedElement;
  }

  _sendMessage = message => {
    return this._connection.sendMessage(
      `background:${PORT_TYPES.inline_style_observer}`,
      message
    );
  };

  handleMessage = async (request, from, sender, sendResponse) => {
    const { kind } = request;

    if (kind === MESSAGE_TYPES.start_observing_inline_styles) {
      this._observer.start();
    } else if (kind === MESSAGE_TYPES.stop_observing_inline_styles) {
      this._observer.stop();
    } else if (kind === MESSAGE_TYPES.get_inline_style_diff) {
      sendResponse({
        kind: MESSAGE_TYPES.get_inline_style_diff,
        value: {
          old_stylesheet: this.oldStylesheet,
          new_stylesheet: this.newStylesheet
        }
      });
    }
  };

  handleChange = changes => {
    // So....theres no CSS file here -- because the styles are inline!
    // But, we're going to be exporting as a stylesheet, so we're just going to make it look like we're sending over a stylesheet

    const oldStylesheet = {
      url: "inline_style_edits.inline.css"
    };

    const newStylesheet = {
      url: "inline_style_edits.inline.css"
    };

    const oldRules = [];
    const newRules = [];

    // Ignore the ones we don't have a selector for...sorry.
    Object.values(changes)
      .filter(({ selector }) => !!selector)
      .forEach(change => {
        if (change.before) {
          oldRules.push(
            buildRuleFromSelectorAndCssText(change.selector, change.before)
          );
        } else {
          oldRules.push(buildRuleFromSelectorAndCssText(change.selector, ""));
        }

        if (change.after) {
          newRules.push(
            buildRuleFromSelectorAndCssText(change.selector, change.after)
          );
        } else {
          newRules.push(buildRuleFromSelectorAndCssText(change.selector, ""));
        }
      });

    oldStylesheet.content = oldRules.join("\n");
    newStylesheet.content = newRules.join("\n");

    this.oldStylesheet = oldStylesheet;
    this.newStylesheet = newStylesheet;

    if (newStylesheet.content) {
      this._sendMessage({
        kind: MESSAGE_TYPES.style_diff_changed
      });
    }
  };
}


================================================
FILE: chrome/extension/inline_style_observer.js
================================================
import { InlineStyleObserverManager } from "./inline_style_observer/inline_style_observer_manager";

const startManager = () => {
  window.__InlineStyleObserverManager = new InlineStyleObserverManager();
};

if (!window.__InlineStyleObserverManager) {
  startManager();
}


================================================
FILE: chrome/extension/lib/StyleURLTab.js
================================================
import {
  getGistById,
  loadStylefileFromGist,
  getStylesheetsFromGist
} from "./gists";
import { shouldApplyStyleToURL } from "./stylefile";
import { injectCSSManager } from "../background/inject";
import { MESSAGE_TYPES, PORT_TYPES } from "./port";

const TAB_IDS_TO_STYLEURL = {};

const applyStylesheetToTabId = (stylesheet, tabId) => {
  const content = stylesheet[1];
  chrome.tabs.insertCSS(
    tabId,
    {
      cssOrigin: "user",
      code: content,
      allFrames: true,
      runAt: "document_end"
    },
    (...args) => {
      console.log("Inserted Stylesheet into tab", tabId, {
        stylesheet: content
      });
    }
  );
};

export class StyleURL {
  constructor({ gistId }) {
    this.gistId = gistId;

    this.isBarEnabled = true;
    this.isStyleEnabled = true;
    this._appliedToURLs = {};
  }

  toJSON = () => {
    return {
      gistId: this.gistId,
      gist: this.gist,
      isBarEnabled: this.isBarEnabled,
      isStyleEnabled: this.isStyleEnabled,
      stylefile: this.stylefile,
      stylesheets: this.stylesheets,
      appliedToURLS: this._appliedToURLs
    };
  };

  setAppliedToURL = (url, didApply) => {
    this._appliedToURLs[url] = !!didApply;

    return !!didApply;
  };

  load = async gistId => {
    const gist = await getGistById(gistId);
    this.gist = gist;
    this.stylefile = loadStylefileFromGist(gist);
    this.stylesheets = getStylesheetsFromGist(gist);
    this.loaded = true;
  };

  applyToTab = (tab, connection) => {
    if (!this.canApplyStyle(tab.url)) {
      return this.setAppliedToURL(tab.url, false);
    }

    injectCSSManager(tab.tabId);
    if (connection) {
      connection.sendMessage(
        `content_script:${PORT_TYPES.stylesheet_manager}:${tab.tabId}`,
        {
          kind: MESSAGE_TYPES.get_styleurl,
          value: this.toJSON()
        }
      );
    }

    return this.setAppliedToURL(tab.url, true);
  };

  canApplyStyle = url => {
    return !!this.stylefile && shouldApplyStyleToURL(this.stylefile, url);
  };
}

export const styleURLsForTabId = tabId => {
  return TAB_IDS_TO_STYLEURL[tabId] || [];
};

export const startMonitoringTabID = async ({ tabId, gistId }) => {
  if (!TAB_IDS_TO_STYLEURL[tabId]) {
    TAB_IDS_TO_STYLEURL[tabId] = [];
  }

  const existingStyleURLTab = TAB_IDS_TO_STYLEURL[tabId].find(
    tab => tab.gistId === gistId
  );
  if (existingStyleURLTab) {
    return existingStyleURLTab;
  } else {
    const styleUrlTab = new StyleURL({ gistId });
    TAB_IDS_TO_STYLEURL[tabId].push(styleUrlTab);
    await styleUrlTab.load(gistId);

    return styleUrlTab;
  }
};

export const stopMonitoringTabID = tabId => {
  if (TAB_IDS_TO_STYLEURL[tabId] && TAB_IDS_TO_STYLEURL[tabId].length === 0) {
    delete TAB_IDS_TO_STYLEURL[tabId];
  }
};


================================================
FILE: chrome/extension/lib/api.js
================================================
import S3Upload from "react-s3-uploader/s3upload";

const uploaders = {};
export const SCREENSHOT_CONTENT_TYPE = "image/png";

export const buildURL = path => {
  return __API_HOST__ + path;
};

const apiFetch = (path, options = {}) => {
  const headers = new Headers(options.headers || {});
  headers.append(
    "User-Agent",
    `StyleURL v${chrome.app.getDetails().version} (${process.env.NODE_ENV})`
  );
  headers.append("Content-Type", "application/json");
  headers.append("X-StyleURL-Version", chrome.app.getDetails().version);

  return window
    .fetch(buildURL(path), {
      ...options,
      credentials: "include",
      redirect: "follow",
      headers
    })
    .then(response => response.json())
    .catch(error => {
      console.error(error);
      return {
        success: false
      };
    });
};

export const getGistById = id => apiFetch(`/api/gists/${id}`);

export const uploadStylesheets = async ({
  stylesheets,
  url,
  visibility = "public"
}) => {
  return apiFetch("/api/stylesheet_groups", {
    method: "POST",
    body: JSON.stringify({
      url,
      stylesheets,
      visibility
    })
  });
};

export const sendFeedback = async ({ message, from }) => {
  return apiFetch("/api/feedback", {
    method: "POST",
    body: JSON.stringify({
      message,
      version: chrome.runtime.getManifest().version,
      from
    })
  });
};

export const processScreenshot = ({
  key: stylesheet_key,
  domain: stylesheet_domain
}) => ({ publicUrl: url }) => {
  return apiFetch("/api/photos/process", {
    method: "POST",
    body: JSON.stringify({
      url,
      stylesheet_key,
      stylesheet_domain,
      content_type: SCREENSHOT_CONTENT_TYPE
    })
  }).then(() => {
    delete uploaders[stylesheet_key];
  });
};

export const uploadScreenshot = ({ key, domain, photo }) => {
  uploaders[key] = new S3Upload({
    files: [photo],
    signingUrl: "/api/photos/presign",
    onFinishS3Put: processScreenshot({ key, domain }),
    onError: error => {
      console.error(error);
      delete uploaders[key];
    },
    server: __API_HOST__,
    uploadRequestHeaders: {}
  });
};


================================================
FILE: chrome/extension/lib/browserAction.js
================================================
const PLUS_IMAGE_PATH = {
  "16": "img/plus_16x16.png",
  "19": "img/plus_19x19.png",
  "38": "img/plus_38x38.png",
  "48": "img/plus_48x48.png",
  "128": "img/plus_128x128.png"
};

export const DEFAULT_ICON_PATH = {
  "16": "img/default_16x16.png",
  "19": "img/default_19x19.png",
  "38": "img/default_38x38.png",
  "48": "img/default_48x48.png",
  "128": "img/default_128x128.png"
};

export const BROWSER_ACTION_STATES = {
  default: "default",
  style_applied: "style_applied",
  upload_style: "upload_style"
};

let BROWSER_ACTION_STATE = BROWSER_ACTION_STATES.default;

export const setBrowserActionToDefault = ({ tabId }) => {
  try {
    chrome.browserAction.setIcon({
      tabId,
      path: DEFAULT_ICON_PATH
    });
    chrome.browserAction.setTitle({
      tabId,
      title: "StyleURL"
    });

    BROWSER_ACTION_STATE = BROWSER_ACTION_STATES.default;
  } catch (exception) {
    console.error(exception);
  }
};

export const setBrowserActionToStyleApplied = ({ styleCount, tabId }) => {
  try {
    chrome.browserAction.setIcon({
      tabId,
      path: DEFAULT_ICON_PATH
    });

    chrome.browserAction.setBadgeText({
      text: `${styleCount}`,
      tabId: tabId
    });

    BROWSER_ACTION_STATE = BROWSER_ACTION_STATES.style_applied;
  } catch (exception) {
    console.error(exception);
  }
};

export const getBrowserActionState = () => BROWSER_ACTION_STATE;


================================================
FILE: chrome/extension/lib/gists.js
================================================
import _ from "lodash";
import { loadStylefileFromString } from "./stylefile";

export const STYLEFILE_NAMES = ["Stylefile.yml", "Stylefile"];
export const SPECIAL_QUERY_PARAMS = {
  gist_id: "__styleurl"
};

export { getGistById } from "./api";

export const getGistIDFromURL = url => {
  const queryString = _.last(url.split("?"));

  if (!queryString) {
    return null;
  }

  const params = new URLSearchParams(queryString);
  const param = params.get(SPECIAL_QUERY_PARAMS.gist_id);

  if (!param) {
    return null;
  }

  return _.last(param.split("gist_"));
};

export const getStylesheetsFromGist = gist => {
  return _
    .keys(gist.files || [])
    .filter(fileName => {
      const file = gist.files[fileName];

      return file.type === "text/css";
    })
    .map(filename => [filename, gist.files[filename].content]);
};

export const loadStylefileFromGist = gist => {
  const filename = _.keys(gist.files || []).find(fileName => {
    return STYLEFILE_NAMES.includes(fileName);
  });

  if (!filename) {
    return null;
  }

  return loadStylefileFromString(gist.files[filename].content);
};


================================================
FILE: chrome/extension/lib/injectScriptNames.js
================================================
export default {
  inject_create_styleurl: "__styleurl_create_styleurl_shadowdom",
  inject_view_styleurl: "__styleurl_view_styleurl_shadowdom"
};


================================================
FILE: chrome/extension/lib/injectShadowDom.js
================================================
import React from "react";
import ReactDOM from "react-dom";
import ShadowDOM from "react-shadow";

const Z_INDEX = 2147483647;

export const injectShadowDOM = ({
  id,
  Component,
  include,
  position = "bottom"
}) => {
  if (!!document.querySelector(id)) {
    return;
  }

  // Sorry Intercom!
  if (document.querySelector("#intercom-container")) {
    document.querySelector("#intercom-container").style.display = "none";
  }

  const disableIntercomForcefully = document.createElement("style");
  disableIntercomForcefully.id =
    "__styleurl-disable-intercom-while-styleurl-bar-in-page-sorry-intercom";
  disableIntercomForcefully.innerHTML =
    "#intercom-container { display: none !important; opacity: 0 !important; pointer-events: none !important; }";
  document.body.appendChild(disableIntercomForcefully);

  const hideFOUC = document.createElement("style");

  hideFOUC.id = "__styleurl--handle-loading-fouc";

  hideFOUC.innerHTML = `
#${id} > div {
  display: none;
}

#${id} > div.resolved {
  display: block;
}
  `;
  document.body.appendChild(hideFOUC);

  const shadowContainer = document.createElement("div");
  shadowContainer.id = id;
  shadowContainer.style.width = "100%";
  shadowContainer.style.position = "fixed";
  shadowContainer.style.left = 0;
  shadowContainer.style.right = 0;
  shadowContainer.style.display = "block";
  shadowContainer.style.zIndex = Z_INDEX; // https://stackoverflow.com/questions/491052/minimum-and-maximum-value-of-z-index
  shadowContainer.style.boxSizing = "border-box";

  if (position === "bottom") {
    shadowContainer.style.bottom = 0;
  } else if (position === "top") {
    shadowContainer.style.top = 0;
  }

  document.body.appendChild(shadowContainer);

  ReactDOM.render(
    <ShadowDOM include={[include]}>
      <div className="ignore-react-onclickoutside">
        <div className="StyleURLShadowDOMRoot">
          <Component />
        </div>
      </div>
    </ShadowDOM>,
    shadowContainer
  );

  const spacerDiv = document.createElement("div");
  spacerDiv.style.width = "1px";
  spacerDiv.style.height = "50px";
  spacerDiv.style.content = "''";
  spacerDiv.style.display = "block";

  spacerDiv.id = "__styleurl-spacer";

  document.body.appendChild(spacerDiv);
};


================================================
FILE: chrome/extension/lib/makeEverythingImportant.js
================================================
const getStylesheet = element => {
  for (let i = 0; i < document.styleSheets.length; i++) {
    const stylesheet = document.styleSheets[i];

    if (stylesheet.ownerNode === element) {
      return stylesheet;
    }
  }

  return null;
};

export const makeAllRulesImportant = styleElement => {
  if (!styleElement) {
    return;
  }

  const stylesheet = getStylesheet(styleElement);

  for (let i = 0; i < stylesheet.rules.length; i++) {
    const rule = stylesheet.rules[i];

    if (!rule.style) {
      continue;
    }

    for (let k = 0; k < rule.style.length; k++) {
      const declarationName = rule.style[k];
      const value = rule.style.getPropertyValue(declarationName);

      // A lot of shorthand properties mark everything as initial, e.g. "background"
      // We don't wanna actually set those to !important
      if (value !== "initial") {
        rule.style.setProperty(declarationName, value, "important");
      }
    }
  }
};


================================================
FILE: chrome/extension/lib/port.js
================================================
import _ from "lodash";
const DEV_CHROME_PORT_PREFIX = "STYLEURL_DEV_PORT/";
const PROD_CHROME_PORT_PREFIX = "STYLEURL_PORT/";

const CHROME_PORT_PREFIX =
  process.env.NODE_ENV === "PRODUCTION"
    ? PROD_CHROME_PORT_PREFIX
    : DEV_CHROME_PORT_PREFIX;

export const tabIdFromPortName = _portName => {
  return parseInt(_.last(_portName.split("tab/")), 10);
};

export const PORT_TYPES = {
  github_gist: "github_gist",
  inline_header: "inline_header",
  devtool_widget: "devtool_widget",
  stylesheet_manager: "stylesheet_manager",
  inline_style_observer: "inline_style_observer"
};

export const MESSAGE_TYPES = {
  get_styles_diff: "get_styles_diff",
  get_gist_content: "get_gist_content",
  apply_stylesheets: "apply_stylesheets",
  style_diff_changed: "style_diff_changed",
  send_content_stylesheets: "send_stylesheets",
  log: "log",
  create_style_url: "create_style_url",
  send_success_notification: "send_success_notification",
  toggle_styleurl_css: "toggle_styleurl_css",
  get_styleurl: "get_styleurl",
  update_styleurl_state: "update_styleurl_state",
  shared_styleurl: "shared_styleurl",
  get_current_styles_diff: "get_current_styles_diff",
  upload_stylesheets: "upload_stylesheets",
  start_observing_inline_styles: "start_observing_inline_styles",
  stop_observing_inline_styles: "start_observing_inline_styles",
  geT_inline_style_diff: "get_all_inline_styles",
  open_style_editor: "open_style_editor",
  open_devtools_plz: "open_devtools_plz",
  send_feedback: "send_feedback"
};

export const STYLESHEET_TYPE = {
  inspector: "inspector",
  remote: "remote",
  style_tag: "style_tag"
};


================================================
FILE: chrome/extension/lib/stylefile.js
================================================
import URLPattern from "url-pattern";
import YAML from "js-yaml";
import _ from "lodash";

export const loadStylefileFromString = string => {
  return YAML.safeLoad(string);
};

export const shouldApplyStyleToURL = (stylefile, url) => {
  const matchableURL = _.last(url.split("://"));
  const patterns = stylefile.url_patterns.map(
    pattern => new URLPattern(pattern)
  );

  return !!patterns.find(pattern => pattern.match(matchableURL));
};


================================================
FILE: chrome/extension/lib/toFile.js
================================================
const toBlob = base64String => {
  return window.fetch(base64String).then(res => res.blob());
};

export const toFile = async (base64String, type) => {
  const blob = await toBlob(base64String);

  Object.defineProperty(blob, "name", {
    get: function() {
      return "photo.png";
    }
  });

  Object.defineProperty(blob, "type", {
    get: function() {
      return type;
    }
  });

  return blob;
};


================================================
FILE: chrome/extension/postcss.config.js
================================================
module.exports = {
  plugins: {
    "postcss-import": {},
    "postcss-cssnext": {}
  }
};


================================================
FILE: chrome/extension/stylesheet_manager_content_script.js
================================================
// This file is loosely based on https://github.com/openstyles/stylus/blob/master/content/apply.js
// Though, heavily refactored to use a more OO approach than imperative
import Messenger from "chrome-ext-messenger";
import { PORT_TYPES } from "./lib/port";

const messenger = new Messenger();

const ID_PREFIX = "__styleurl";
const ROOT = document.documentElement;

class DocumentRootObserver {
  ORDERED_TAGS = ["head", "body", "frameset", "style", "link"];

  constructor({rootEl}) {
    this.lastRestorationTime = 0;
    this.restoractionCounter = 0;
    this.observing = false;
    this.sorting = false;
    this.rootEl = rootEl;

    this.observer = new MutationObserver(this.sortStyleElements);
    setTimeout(this.sortStyleElements);
  }

  start = ({ sort = false } = {}) => {
    if (sort && this.sortStyleMap()) {
      this.sortStyleElements();
    }

    if (!this.observing && this.rootEl && this.observer) {
      this.observer.observe(this.rootEl, { childList: true });
      this.observing = true;
    }
  }

  function stop() {
    if (observing) {
      observer.takeRecords();
      observer.disconnect();
      observing = false;
    }
  }
  function evade(fn) {
    const wasObserving = observing;
    if (observing) {
      stop();
    }
    fn();
    if (wasObserving) {
      start();
    }
  }
  function sortStyleMap() {
    const list = [];
    let prevStyleId = 0;
    let needsSorting = false;
    for (const entry of styleElements.entries()) {
      list.push(entry);
      const el = entry[1];
      const styleId = getStyleId(el);
      el.styleId = styleId;
      needsSorting |= styleId < prevStyleId;
      prevStyleId = styleId;
    }
    if (needsSorting) {
      styleElements = new Map(
        list.sort((a, b) => a[1].styleId - b[1].styleId)
      );
      return true;
    }
  }
  function sortStyleElements() {
    if (!observing) {
      return;
    }
    let prevExpected = document.documentElement.lastElementChild;
    while (prevExpected && isSkippable(prevExpected, true)) {
      prevExpected = prevExpected.previousElementSibling;
    }
    if (!prevExpected) {
      return;
    }
    for (const el of styleElements.values()) {
      if (!isMovable(el)) {
        continue;
      }
      while (true) {
        const next = prevExpected.nextElementSibling;
        if (next && isSkippable(next)) {
          prevExpected = next;
        } else if (
          next === el ||
          (next === el.previousElementSibling && next) ||
          moveAfter(el, next || prevExpected)
        ) {
          prevExpected = el;
          break;
        } else {
          return;
        }
      }
    }
    if (sorting) {
      sorting = false;
      if (observer) observer.takeRecords();
      if (!restorationLimitExceeded()) {
        start();
      } else {
        setTimeout(start, 1000);
      }
    }
  }
  function isMovable(el) {
    return el.parentNode || !disabledElements.has(getStyleId(el));
  }
  function isSkippable(el, skipOwnStyles) {
    return (
      !ORDERED_TAGS.includes(el.localName) ||
      (el.id.startsWith(ID_PREFIX) &&
        (skipOwnStyles || el.id.endsWith("-ghost")) &&
        el.localName === "style" &&
        el.className === "stylus")
    );
  }
  function moveAfter(el, expected) {
    if (!sorting) {
      sorting = true;
      stop();
    }
    expected.insertAdjacentElement("afterend", el);
    if (el.disabled !== disableAll) {
      // moving an element resets its 'disabled' state
      el.disabled = disableAll;
    }
    return true;
  }
  function restorationLimitExceeded() {
    const t = performance.now();
    if (t - lastRestorationTime > 1000) {
      restorationCounter = 0;
    }
    lastRestorationTime = t;
    return ++restorationCounter > 5;
  }
}

class StylesheetManager {
  constructor() {
    this.disableAllStyles = false;
    this.exposeIframes = false;
    this.docRewriteObserver = null;
    this.docRootObserver = null;
    this.styleElements = new Map();
    this.disabledElements = new Map();
    this.retiredStyleTimers = new Map();

    this.connection = messenger.initConnection(
      PORT_TYPES.stylesheet_manager,
      this.handleMessage
    );
  }

  handleMessage = () => {};

  get matchURL() {
    const matchURL = location.href;
    if (matchURL.match(/^(http|file|chrome|ftp)/)) {
      // dynamic about: and javascript: iframes don't have an URL yet
      // so we'll try the parent frame which is guaranteed to have a real URL
      try {
        if (window !== parent) {
          return parent.location.href;
        }
      } catch (e) {}
    }

    return matchURL;
  }

  get styleTagQuery() {
    return `style.styleurl[id^="${ID_PREFIX}"]`;
  }

  getStyles = () => {};

  setDisableAllStyles = shouldDisableAll => {
    if (!this.disableAllStyles === !shouldDisableAll) {
      return;
    }

    this.disableAllStyles = shouldDisableAll;

    Array.prototype.forEach.call(document.styleSheets, stylesheet => {
      if (
        stylesheet.ownerNode.matches(this.styleTagQuery) &&
        stylesheet.disabled !== shouldDisableAll
      ) {
        stylesheet.disabled = shouldDisableAll;
      }
    });
  };

  removeStyle = ({ id, expire = false }) => {
    const el = document.getElementById(ID_PREFIX + id);
    if (el && retire) {
      // to avoid page flicker when the style is updated
      // instead of removing it immediately we rename its ID and queue it
      // to be deleted in applyStyles after a new version is fetched and applied
      const expiredID = id + "-expired";
      el.id = ID_PREFIX + deadID;
      // in case something went wrong and new style was never applied
      retiredStyleTimers.set(
        expiredID,
        window.setTimeout(() => this.removeStyle({ id: expiredID }), 1000)
      );
    } else if (el) {
      docRootObserver.evade(() => el.remove());
    }

    this.styleElements.delete(ID_PREFIX + id);
    this.disabledElements.delete(id);
    this.retiredStyleTimers.delete(id);
  };

  updateStylesheets = styles => {
    if (!document.documentElement) {
      new MutationObserver((mutations, observer) => {
        if (document.documentElement) {
          observer.disconnect();
          applyStyles(styles);
        }
      }).observe(document, { childList: true });
      return;
    }

    if ("disableAll" in styles) {
      doDisableAll(styles.disableAll);
    }

    const gotNewStyles = styles.length;
    if (gotNewStyles) {
      if (docRootObserver) {
        docRootObserver.stop();
      } else {
        initDocRootObserver();
      }
    }

    if (styles.needTransitionPatch) {
      applyTransitionPatch();
    }

    if (gotNewStyles) {
      for (const id in styles) {
        const sections = styles[id];
        if (!Array.isArray(sections)) continue;
        applySections(id, sections.map(({ code }) => code).join("\n"));
      }
      docRootObserver.start({ sort: true });
    }

    if (!isOwnPage && !docRewriteObserver && styleElements.size) {
      initDocRewriteObserver();
    }

    if (retiredStyleTimers.size) {
      setTimeout(() => {
        for (const [id, timer] of retiredStyleTimers.entries()) {
          removeStyle({ id });
          clearTimeout(timer);
        }
      });
    }
  };
}


================================================
FILE: chrome/extension/version_info.js
================================================
const writeVersionToDOM = () => {
  const metadata = {
    id: chrome.runtime.id,
    environment: process.env.NODE_ENV,
    version: chrome.runtime.getManifest().version
  };

  const scriptTag = document.createElement("script");
  scriptTag.id = `__styleurl-extension`;
  scriptTag.type = "application/json";

  scriptTag.innerHTML = JSON.stringify(metadata);

  document.documentElement.appendChild(scriptTag);
  console.log("Wrie Version");
};

if (document.body) {
  writeVersionToDOM();
} else {
  window.addEventListener("DOMContentLoaded", writeVersionToDOM);
}


================================================
FILE: chrome/extension/view_styleurl/ViewStyleURL.js
================================================
import React from "react";
import Messenger from "chrome-ext-messenger";
import "../create_styleurl.css";
import { HeaderBar } from "app/components/HeaderBar";
import { PORT_TYPES, MESSAGE_TYPES } from "../lib/port";
import { Switcher } from "../../app/components/Switcher";
import Dropdown from "../../app/components/Dropdown";
import { Icon } from "../../app/components/Icon";
import { StylesheetCodePreview } from "../../app/components/StylesheetCodePreview";
import { CopyToClipboard } from "react-copy-to-clipboard";
import injectScriptNames from "../lib/injectScriptNames";
const messenger = new Messenger();

const buildShareURL = ({ domain, id }) => {
  return `${__FRONTEND_HOST__}/${domain}/${id}`;
};

const buildForkURL = ({ gistId }) => {
  return `${__API_HOST__}/api/fork?gist_id=${encodeURIComponent(gistId)}`;
};

class ViewStyleURL extends React.PureComponent {
  handleOpenFork = () => {
    const { gistId } = this.props;

    window.open(buildForkURL({ gistId }), "_blank");
  };

  render() {
    const {
      toggleApplyStyle,
      toggleIsBarEnabled,
      isStyleEnabled,
      isBarEnabled,
      gistId,
      hidden,
      onHide,
      stylesheets,
      onSendFeedback,
      onClickShare,
      shareURL
    } = this.props;

    return (
      <HeaderBar
        className="HeaderBar--ViewStyleURL"
        hidden={!isBarEnabled || hidden}
        onHide={onHide}
        onSendFeedback={onSendFeedback}
        center={
          <Switcher
            onLabel="New changes"
            offLabel="Original"
            on={isStyleEnabled}
            onChange={toggleApplyStyle}
          />
        }
      >
        <Dropdown
          icon={<Icon width={"32"} height="15" name="code" />}
          title="Code"
        >
          <StylesheetCodePreview gistId={gistId} stylesheets={stylesheets} />
        </Dropdown>
        <CopyToClipboard text={shareURL} onCopy={onClickShare}>
          <Dropdown
            icon={<Icon width={"24"} height="15" name="share" />}
            title="Share"
          />
        </CopyToClipboard>
      </HeaderBar>
    );
  }
}

class ViewStyleURLContainer extends React.Component {
  constructor(props) {
    super(props);

    this._connection = messenger.initConnection(
      PORT_TYPES.inline_header,
      this.handleMessage
    );

    this.state = {
      styleurl: null,
      isBarEnabled: false,
      hidden: false,
      isStyleEnabled: false
    };
  }

  handleHide = () => {
    this.setState({ hidden: true });
    const shadowRoot = document.querySelector(
      `#${injectScriptNames.inject_view_styleurl}`
    );
    shadowRoot.style.display = "none";
  };

  componentDidMount() {
    this._sendMessage(MESSAGE_TYPES.get_styleurl).then(({ value }) =>
      this.updateStyleURL(value)
    );
  }

  updateStyleURL = styleurl =>
    this.setState({
      styleurl,
      isBarEnabled: styleurl.isBarEnabled,
      isStyleEnabled: styleurl.isStyleEnabled
    });

  _sendMessage = (kind, message) => {
    return this._connection.sendMessage(
      `background:${PORT_TYPES.inline_header}`,
      {
        kind,
        value: message
      }
    );
  };

  handleClickShare = () => {
    this._sendMessage(MESSAGE_TYPES.shared_styleurl);
  };

  toggleBarEnabled = () => {
    this._sendMessage(MESSAGE_TYPES.update_styleurl_state, {
      ...this.state.styleurl,
      isBarEnabled: !this.state.isBarEnabled
    });
  };
  handleSendFeedback = message => {
    return this._sendMessage(MESSAGE_TYPES.send_feedback, {
      message,
      from: "view"
    });
  };

  toggleApplyStyle = () => {
    this._sendMessage(MESSAGE_TYPES.update_styleurl_state, {
      ...this.state.styleurl,
      isStyleEnabled: !this.state.isStyleEnabled
    });
  };

  handleMessage = (request, from, sender, sendResponse) => {
    const { kind, value } = request;

    if (
      kind === MESSAGE_TYPES.get_styleurl ||
      kind === MESSAGE_TYPES.update_styleurl_state
    ) {
      this.updateStyleURL(value);
    }
  };

  componentWillUnmount() {
    if (this._connection) {
      this._connection.disconnect();
    }
  }

  render() {
    const { isStyleEnabled, isBarEnabled, hidden } = this.state;
    console.log(this.state.styleurl);

    return (
      <ViewStyleURL
        isStyleEnabled={isStyleEnabled}
        isBarEnabled={isBarEnabled}
        stylesheets={this.state.styleurl ? this.state.styleurl.stylesheets : []}
        gistId={this.state.styleurl ? this.state.styleurl.gistId : null}
        toggleApplyStyle={this.toggleApplyStyle}
        onClickShare={this.handleClickShare}
        onSendFeedback={this.handleSendFeedback}
        hidden={hidden}
        onHide={this.handleHide}
        shareURL={
          this.state.styleurl &&
          buildShareURL({
            domain: this.state.styleurl.stylefile.domains[0],
            id: this.state.styleurl.gistId
          })
        }
      />
    );
  }
}

export default ViewStyleURLContainer;


================================================
FILE: chrome/manifest.dev.json
================================================
{
  "version": "1.0.0",
  "name": "StyleURL (Development)",
  "manifest_version": 2,
  "description":
    "Publish CSS changes you made in Chrome Inspector to other people",
  "browser_action": {},
  "devtools_page": "devtools.html",
  "icons": {
    "16": "img/default_16x16.png",
    "48": "img/default_48x48.png",
    "128": "img/default_128x128.png"
  },
  "web_accessible_resources": [
    "create_styleurl.html",
    "inject.html",
    "*.js",
    "*.css",
    "img/*.png"
  ],
  "background": {
    "page": "background.html"
  },
  "content_scripts": [
    {
      "matches": ["https://gist.github.com/*/*"],
      "js": ["github_gist_content_script.bundle.js"],
      "run_at": "document_end"
    },
    {
      "matches": [
        "http://localhost:3000/*",
        "http://localhost:3001/*",
        "http://localhost:3002/*",
        "https://api.styleurl.app/*",
        "https://styleurl.app/*",
        "https://www.styleurl.app/*",
        "https://styleurl.app/*"
      ],
      "js": ["version_info.bundle.js"],
      "run_at": "document_start"
    },
    {
      "matches": ["<all_urls>"],
      "js": ["inline_style_observer.bundle.js"],
      "run_at": "document_start"
    }
  ],
  "permissions": [
    "tabs",
    "<all_urls>",
    "webNavigation",
    "storage",
    "clipboardWrite",
    "notifications"
  ],
  "content_security_policy":
    "default-src 'self'; script-src 'self' https://gist.github.com http://localhost:3000 https://localhost:3000 'unsafe-eval'; connect-src https://sentry.io https://gist.github.com https://gist.githubusercontent.com http://localhost:3000 https://s3-us-west-2.amazonaws.com https://api.github.com data: https://styleurlapp.s3-us-west-2.amazonaws.com https://styleurlapp.s3.us-west-2.amazonaws.com http://localhost:3001 http://localhost:3002 https://localhost:3000; style-src * 'unsafe-inline' 'self' blob:; img-src 'self' data:; font-src 'self' data: http://localhost:3000;"
}


================================================
FILE: chrome/manifest.prod.json
================================================
{
  "version": "1.1.15",
  "name": "StyleURL",
  "manifest_version": 2,
  "description": "StyleURL lets you export and share CSS tweaks instantly.",
  "browser_action": {},
  "devtools_page": "devtools.html",
  "icons": {
    "16": "img/default_16x16.png",
    "48": "img/default_48x48.png",
    "128": "img/default_128x128.png"
  },
  "background": {
    "page": "background.html"
  },
  "web_accessible_resources": [
    "create_styleurl.html",
    "inject.html",
    "*.js",
    "*.css",
    "img/*.png"
  ],
  "content_scripts": [
    {
      "matches": ["https://gist.github.com/*/*"],
      "js": ["github_gist_content_script.bundle.js"],
      "run_at": "document_end"
    },
    {
      "matches": [
        "https://api.styleurl.app/*",
        "https://styleurl.app/*",
        "https://www.styleurl.app/*"
      ],
      "js": ["version_info.bundle.js"],
      "run_at": "document_start"
    },
    {
      "matches": ["<all_urls>"],
      "js": ["inline_style_observer.bundle.js"],
      "run_at": "document_start"
    }
  ],
  "permissions": [
    "tabs",
    "<all_urls>",
    "webNavigation",
    "storage",
    "clipboardWrite",
    "notifications"
  ],
  "content_security_policy":
    "default-src 'self'; script-src 'self' https://gist.github.com 'unsafe-eval'; connect-src https://sentry.io https://gist.github.com https://gist.githubusercontent.com https://s3-us-west-2.amazonaws.com https://api.github.com data: https://styleurlapp.s3-us-west-2.amazonaws.com https://styleurlapp.s3.us-west-2.amazonaws.com https://api.styleurl.app https://www.styleurl.app https://styleurl.app; style-src * 'unsafe-inline' 'self' blob:; img-src 'self' data:; font-src 'self' data:;"
}


================================================
FILE: chrome/views/background.pug
================================================
doctype html

html
  head
    script(src=env == 'prod' ? '/background.bundle.js' : 'https://localhost:3000/background.bundle.js')


================================================
FILE: chrome/views/create_styleurl.pug
================================================
doctype html

html
  head
    meta(charset='UTF-8')
    title "Create StyleURL"
    link(id="root_stylesheet" rel="stylesheet" href='/create_styleurl.css')

  body
    #root
    script(src='/create_styleurl.bundle.js')


================================================
FILE: chrome/views/devtools.pug
================================================
doctype html

html
  head
    script(src=env == 'prod' ? '/devtools.bundle.js' : 'http://localhost:3000/devtools.bundle.js')


================================================
FILE: chrome/views/inject.pug
================================================
doctype html

html
  head
    meta(charset='UTF-8')
    title Redux TodoMVC Example (Inject)
    style.
      html, body {
        background-color: rgba(0,0,0,0)
      }
  body
    #root
    script(src=env == 'prod' ? '/todoapp.bundle.js' : 'https://localhost:3000/todoapp.bundle.js')


================================================
FILE: chrome/views/window.pug
================================================
doctype html

html
  head
    meta(charset='UTF-8')
    title Redux TodoMVC Example (Window)
  body
    #root
    if env !== 'prod'
      script(src='chrome-extension://lmhkpmbekcpmknklioeibfkpmmfibljd/redux-devtools-extension.js')
    script(src=env == 'prod' ? '/todoapp.bundle.js' : 'http://localhost:3000/todoapp.bundle.js')


================================================
FILE: package.json
================================================
{
  "name": "styleurl-extension",
  "version": "1.1.15",
  "description": "StyleURL Chrome extension",
  "private": true,
  "scripts": {
    "dev": "node scripts/dev",
    "build": "node scripts/build",
    "compress": "node scripts/compress",
    "update-readme": "node scripts/update-readme",
    "compress-keygen": "crx keygen",
    "clean": "rimraf build/ dev/ *.zip *.crx",
    "lint": "eslint app chrome test scripts webpack/*.js",
    "test-e2e": "cross-env NODE_ENV=test mocha -r ./test/setup-app test/e2e",
    "test": "cross-env NODE_ENV=test mocha -r ./test/setup-app test/app",
    "release": "yarn && yarn build && yarn compress --release && yarn update-readme"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/jarred-sumner/styleurl-extension"
  },
  "keywords": [
    "chrome",
    "extension",
    "react",
    "redux",
    "hot reload",
    "webpack",
    "boilerplate"
  ],
  "author": "Jarred Sumner <jarred@jarredsumner.com>",
  "license": "AGPL",
  "devDependencies": {
    "@babel/plugin-proposal-class-properties": "^7.0.0-beta.53",
    "babel-loader": "^8.0.0-beta",
    "babel-plugin-lodash": "^3.3.4",
    "babel-plugin-module-resolver": "^3.1.1",
    "babel-plugin-transform-remove-console": "^6.9.4",
    "chai": "^3.2.0",
    "chrome-webstore-upload": "^0.2.2",
    "chromedriver": "^2.33.2",
    "cross-env": "^3.1.3",
    "crx": "^3.0.3",
    "css-loader": "^0.25.0",
    "css-modules-require-hook": "^4.0.5",
    "css-to-string-loader": "^0.1.3",
    "eslint": "^3.9.1",
    "eslint-config-airbnb": "^12.0.0",
    "eslint-plugin-import": "^1.16.0",
    "eslint-plugin-jsx-a11y": "^2.2.3",
    "eslint-plugin-react": "^6.5.0",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^1.1.11",
    "gh-release": "^3.2.1",
    "jsdom": "^9.2.1",
    "memfs": "^2.9.4",
    "mini-css-extract-plugin": "^0.4.1",
    "minimist": "^1.2.0",
    "mocha": "^3.1.2",
    "postcss-loader": "^2.1.5",
    "pug-cli": "^1.0.0-alpha6",
    "raw-loader": "^0.5.1",
    "rimraf": "^2.4.3",
    "selenium-webdriver": "^2.47.0",
    "shelljs": "^0.7.0",
    "sinon": "^1.17.1",
    "style-loader": "^0.13.1",
    "uglifyjs-webpack-plugin": "^1.2.7",
    "url-loader": "^1.0.1",
    "webpack": "^4.15.0",
    "webpack-bundle-analyzer": "^2.13.1",
    "webpack-cli": "^3.0.8",
    "webpack-hot-middleware": "^2.10.0",
    "webpack-httpolyglot-server": "^0.3.0",
    "write-assets-webpack-plugin": "^1.0.4"
  },
  "dependencies": {
    "@babel/core": "^7.0.0-beta.52",
    "@babel/plugin-transform-runtime": "^7.0.0-beta.52",
    "@babel/preset-env": "^7.0.0-beta.52",
    "@babel/preset-react": "^7.0.0-beta.52",
    "@babel/runtime": "^7.0.0-beta.52",
    "autoprefixer": "^7.2.5",
    "bluebird": "^3.5.1",
    "chrome-ext-messenger": "^2.0.12",
    "classnames": "^2.2.6",
    "core-js": "^2.5.7",
    "cssobj-converter": "^2.3.3",
    "data-uri-to-blob": "^0.0.4",
    "diff-match-patch": "^1.0.1",
    "filenamify": "^2.1.0",
    "js-yaml": "^3.12.0",
    "jshashes": "^1.0.7",
    "lodash": "^4.17.10",
    "memoizee": "^0.4.12",
    "optimal-select": "^4.0.1",
    "postcss-cssnext": "^3.1.0",
    "postcss-import": "^11.1.0",
    "raven-js": "^3.26.3",
    "react": "^16.4.1",
    "react-copy-to-clipboard": "^5.0.1",
    "react-dock": "^0.2.4",
    "react-dom": "^16.4.1",
    "react-onclickoutside": "^6.7.1",
    "react-s3-uploader": "^4.8.0",
    "react-shadow": "^16.3.0",
    "react-syntax-highlighter": "^8.0.1",
    "redux": "^3.2.1",
    "redux-thunk": "^2.0.1",
    "reset-css": "^4.0.1",
    "sticky-js": "^1.2.0",
    "stylesheet-differ": "^0.0.21",
    "url-parse": "^1.4.1",
    "url-pattern": "^1.0.3"
  }
}


================================================
FILE: scripts/.eslintrc
================================================
{
  "env": {
    "shelljs": true
  },
  "rules": {
    "no-console": 0,
    "import/no-extraneous-dependencies": ["error", { "devDependencies": true }]
  }
}


================================================
FILE: scripts/build.js
================================================
const tasks = require('./tasks');

tasks.replaceWebpack();
console.log('[Copy assets]');
console.log('-'.repeat(80));
tasks.copyAssets('build');

console.log('[Webpack Build]');
console.log('-'.repeat(80));
exec('webpack --config webpack/prod.config.js --progress --profile --colors');


================================================
FILE: scripts/compress.js
================================================
const fs = require("fs");
const ChromeExtension = require("crx");
const path = require("path");

const RELEASES_PATH = path.join(__dirname, "../releases");
const BUILD_PATH = path.join(__dirname, "../build");
const manifest = require(path.join(BUILD_PATH, "manifest.json"));
const name = manifest.name;
const version = manifest.version;
const argv = require("minimist")(process.argv.slice(2));

const keyPath = argv.key || "key.pem";
const existsKey = fs.existsSync(keyPath);
const crx = new ChromeExtension({
  appId: argv["app-id"],
  codebase: argv.codebase,
  privateKey: existsKey ? fs.readFileSync(keyPath) : null
});

const ghRelease = require("gh-release");

const baseName = `${name}-${version}`;
const crxFilename = path.join(RELEASES_PATH, `${baseName}.crx`);
const zipFileName = path.join(RELEASES_PATH, `${baseName}.zip`);

crx
  .load(BUILD_PATH)
  .then(() => crx.loadContents())
  .then(async archiveBuffer => {
    return new Promise((resolve, reject) => {
      fs.writeFile(zipFileName, archiveBuffer, () => {
        console.log(`Wrote ${zipFileName}`);

        const CREDENTIALS_PATH = path.join(__dirname, "../credentials.json");
        if (!!argv["release"]) {
          if (!fs.existsSync(CREDENTIALS_PATH)) {
            console.error(
              "Expected credentials.json at ",
              CREDENTIALS_PATH,
              "to look like",
              {
                clientId: "CLIENT_ID",
                clientSecret: "CLIENT_SECRET",
                access_token: "ACCESS_TOKEN",
                expires_in: 3600,
                refreshToken: "REFRESH_TOKEN",
                scope: "https://www.googleapis.com/auth/chromewebstore",
                token_type: "Bearer"
              }
            );
            process.exit();
            return;
          }

          console.log("Uploading to Chrome Store...");
          const webStore = require("chrome-webstore-upload")({
            ...require(CREDENTIALS_PATH),
            extensionId: "emplcligcppnlalfjknjbanolhlnkmgp"
          });

          webStore
            .fetchToken()
            .then(token => {
              return webStore
                .uploadExisting(fs.createReadStream(zipFileName), token)
                .then(res => {
                  console.log(res);
                  console.log("Uploaded to Chrome Store...Publishing");
                  return webStore.publish("default", token);
                })
                .then(res => {
                  console.log(res);
                  console.log(
                    `Published ${version} to Chrome Store successfully`
                  );
                });
            })
            .catch(err => console.error(err));
        }
      });

      return resolve(
        crx.pack(archiveBuffer).then(crxBuffer => {
          return new Promise((resolve, reject) => {
            fs.writeFile(crxFilename, crxBuffer, () => {
              console.log(`Wrote ${crxFilename}`);
              resolve();
            });
          });
        })
      );
    });
  })
  .then(() => {
    if (!argv["release"]) {
      return;
    }

    const options = {
      tag_name: `v${version}`,
      version: version,
      target_commitish: "master",
      name: `v${version}`,
      draft: false,
      prerelease: false,
      repo: "styleurl-extension",
      owner: "Jarred-Sumner",
      endpoint: "https://api.github.com",
      auth: require(`/Users/${
        process.env.USER
      }/Library/Application Support/gh-release/config.json`),
      assets: [`./releases/${baseName}.crx`, `./releases/${baseName}.zip`]
    };

    return new Promise((resolve, reject) => {
      ghRelease(options, function(err, result) {
        if (err) {
          reject(err);
          return;
        }

        resolve(result); // create release response: https://developer.github.com/v3/repos/releases/#response-4
      });
    });
  })
  .catch(err => {
    console.error(err);
  });


================================================
FILE: scripts/dev.js
================================================
const tasks = require('./tasks');
const createWebpackServer = require('webpack-httpolyglot-server');
const devConfig = require('../webpack/dev.config');

tasks.replaceWebpack();
console.log('[Copy assets]');
console.log('-'.repeat(80));
tasks.copyAssets('dev');

console.log('[Webpack Dev]');
console.log('-'.repeat(80));
console.log('If you\'re developing Inject page,');
console.log('please allow `https://localhost:3000` connections in Google Chrome,');
console.log('and load unpacked extensions with `./dev` folder. (see https://developer.chrome.com/extensions/getstarted#unpacked)\n');
createWebpackServer(devConfig, {
  host: 'localhost',
  port: 3000
});


================================================
FILE: scripts/tasks.js
================================================
require('shelljs/global');

exports.replaceWebpack = () => {
  const replaceTasks = [{
    from: 'webpack/replace/JsonpMainTemplate.runtime.js',
    to: 'node_modules/webpack/lib/JsonpMainTemplate.runtime.js'
  }, {
    from: 'webpack/replace/process-update.js',
    to: 'node_modules/webpack-hot-middleware/process-update.js'
  }];

  replaceTasks.forEach(task => cp(task.from, task.to));
};

exports.copyAssets = (type) => {
  const env = type === 'build' ? 'prod' : type;
  rm('-rf', type);
  mkdir(type);
  cp(`chrome/manifest.${env}.json`, `${type}/manifest.json`);
  cp('-R', 'chrome/assets/*', type);
  exec(`pug -O "{ env: '${env}' }" -o ${type} chrome/views/`);
};


================================================
FILE: scripts/update-readme.js
================================================
const fs = require("fs");
var path = require("path");
var changelogParser = require("changelog-parser");

const root = path.resolve(__dirname, "..");

var pkg = require(path.resolve(root, "package.json"));
var logPath = path.resolve(root, "CHANGELOG.md");
const README_PATH = path.resolve(root, "README.md");
const _ = require("lodash");

const README = fs.readFileSync(README_PATH, "utf-8");

const WHATS_NEW_STRING = "### What's New";

function formatDate(date) {
  var monthNames = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
  ];

  var day = date.getDate();
  var monthIndex = date.getMonth();
  var year = date.getFullYear();

  return monthNames[monthIndex] + " " + day + ", " + year;
}

changelogParser(logPath, function(err, result) {
  if (err) throw err;

  // check for 'unreleased' section in CHANGELOG: allow sections which do not include a body (eg. 'Added', 'Changed', etc.)

  var unreleased = result.versions
    .filter(function(release) {
      return release.title && release.title.toLowerCase
        ? release.title.toLowerCase().indexOf("unreleased") !== -1
        : false;
    })
    .filter(function(release) {
      return !!release.body;
    });

  if (unreleased.length > 0) {
    throw new Error("Unreleased changes detected in CHANGELOG.md, aborting");
  }

  var log = result.versions.filter(function(release) {
    return release.version !== null;
  })[0];

  if (!log) {
    throw new Error("Changelog missing");
  }

  const whatsNewIndex = README.indexOf(WHATS_NEW_STRING);
  const hasWhatsNewSection = whatsNewIndex > -1;
  console.log(README);
  if (!hasWhatsNewSection) {
    throw new Error(`README is missing ${WHATS_NEW_STRING}`);
  }

  const whatsNewEnd = README.substr(whatsNewIndex).indexOf("---");

  const whatsNewSection = `${WHATS_NEW_STRING} (v${log.version} - ${formatDate(
    new Date()
  )})

${log.body}

---
  `;
  const newReadMe =
    README.substr(0, whatsNewIndex) +
    whatsNewSection +
    README.substr(whatsNewIndex + whatsNewEnd + "\n---".length);
  fs.writeFileSync(README_PATH, newReadMe);
});


================================================
FILE: stats.json
================================================
{
  "errors": [],
  "warnings": [
    "./node_modules/css/node_modules/source-map/lib/source-map/source-map-generator.js 8:45-52\nCritical dependency: require function is used in a way in which dependencies cannot be statically extracted\n    at CommonJsRequireContextDependency.getWarnings (/Users/jarred/Code/styleurl/node_modules/webpack/lib/dependencies/ContextDependency.js:40:18)\n    at Compilation.reportDependencyErrorsAndWarnings (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:1311:24)\n    at Compilation.finish (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:1125:9)\n    at hooks.make.callAsync.err (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compiler.js:545:17)\n    at _done (eval at create (/Users/jarred/Code/styleurl/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:9:1)\n    at _err2 (eval at create (/Users/jarred/Code/styleurl/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:44:22)\n    at _addModuleChain (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:1053:12)\n    at processModuleDependencies.err (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:979:9)\n    at process._tickCallback (internal/process/next_tick.js:61:11)\n @ ./node_modules/css/node_modules/source-map/lib/source-map.js\n @ ./node_modules/css/lib/stringify/source-map-support.js\n @ ./node_modules/css/lib/stringify/index.js\n @ ./node_modules/css/index.js\n @ ./node_modules/native-css/src/native-css.js\n @ ./node_modules/native-css/index.js\n @ ./node_modules/stylesheet-differ/lib/index.js\n @ ./chrome/extension/background.js\n @ multi ./webpack/customPublicPath ./chrome/extension/background",
    "./node_modules/css/node_modules/source-map/lib/source-map/source-map-consumer.js 8:45-52\nCritical dependency: require function is used in a way in which dependencies cannot be statically extracted\n    at CommonJsRequireContextDependency.getWarnings (/Users/jarred/Code/styleurl/node_modules/webpack/lib/dependencies/ContextDependency.js:40:18)\n    at Compilation.reportDependencyErrorsAndWarnings (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:1311:24)\n    at Compilation.finish (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:1125:9)\n    at hooks.make.callAsync.err (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compiler.js:545:17)\n    at _done (eval at create (/Users/jarred/Code/styleurl/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:9:1)\n    at _err2 (eval at create (/Users/jarred/Code/styleurl/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:44:22)\n    at _addModuleChain (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:1053:12)\n    at processModuleDependencies.err (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:979:9)\n    at process._tickCallback (internal/process/next_tick.js:61:11)\n @ ./node_modules/css/node_modules/source-map/lib/source-map.js\n @ ./node_modules/css/lib/stringify/source-map-support.js\n @ ./node_modules/css/lib/stringify/index.js\n @ ./node_modules/css/index.js\n @ ./node_modules/native-css/src/native-css.js\n @ ./node_modules/native-css/index.js\n @ ./node_modules/stylesheet-differ/lib/index.js\n @ ./chrome/extension/background.js\n @ multi ./webpack/customPublicPath ./chrome/extension/background",
    "./node_modules/css/node_modules/source-map/lib/source-map/source-node.js 8:45-52\nCritical dependency: require function is used in a way in which dependencies cannot be statically extracted\n    at CommonJsRequireContextDependency.getWarnings (/Users/jarred/Code/styleurl/node_modules/webpack/lib/dependencies/ContextDependency.js:40:18)\n    at Compilation.reportDependencyErrorsAndWarnings (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:1311:24)\n    at Compilation.finish (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:1125:9)\n    at hooks.make.callAsync.err (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compiler.js:545:17)\n    at _done (eval at create (/Users/jarred/Code/styleurl/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:9:1)\n    at _err2 (eval at create (/Users/jarred/Code/styleurl/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:44:22)\n    at _addModuleChain (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:1053:12)\n    at processModuleDependencies.err (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:979:9)\n    at process._tickCallback (internal/process/next_tick.js:61:11)\n @ ./node_modules/css/node_modules/source-map/lib/source-map.js\n @ ./node_modules/css/lib/stringify/source-map-support.js\n @ ./node_modules/css/lib/stringify/index.js\n @ ./node_modules/css/index.js\n @ ./node_modules/native-css/src/native-css.js\n @ ./node_modules/native-css/index.js\n @ ./node_modules/stylesheet-differ/lib/index.js\n @ ./chrome/extension/background.js\n @ multi ./webpack/customPublicPath ./chrome/extension/background",
    "./node_modules/encoding/lib/iconv-loader.js 9:12-34\nCritical dependency: the request of a dependency is an expression\n    at CommonJsRequireContextDependency.getWarnings (/Users/jarred/Code/styleurl/node_modules/webpack/lib/dependencies/ContextDependency.js:40:18)\n    at Compilation.reportDependencyErrorsAndWarnings (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:1311:24)\n    at Compilation.finish (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:1125:9)\n    at hooks.make.callAsync.err (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compiler.js:545:17)\n    at _done (eval at create (/Users/jarred/Code/styleurl/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:9:1)\n    at _err2 (eval at create (/Users/jarred/Code/styleurl/node_modules/tapable/lib/HookCodeFactory.js:24:12), <anonymous>:44:22)\n    at _addModuleChain (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:1053:12)\n    at processModuleDependencies.err (/Users/jarred/Code/styleurl/node_modules/webpack/lib/Compilation.js:979:9)\n    at process._tickCallback (internal/process/next_tick.js:61:11)\n @ ./node_modules/encoding/lib/encoding.js\n @ ./node_modules/fetch/lib/fetch.js\n @ ./node_modules/native-css/src/native-css.js\n @ ./node_modules/native-css/index.js\n @ ./node_modules/stylesheet-differ/lib/index.js\n @ ./chrome/extension/background.js\n @ multi ./webpack/customPublicPath ./chrome/extension/background",
    "configuration\nThe 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.\nYou can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/",
    "asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).\nThis can impact web performance.\nAssets: \n  background.bundle.js (2.15 MiB)\n  github_gist_content_script.bundle.js (512 KiB)",
    "entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.\nEntrypoints:\n  background (2.15 MiB)\n      background.bundle.js\n  github_gist_content_script (512 KiB)\n      github_gist_content_script.bundle.js\n",
    "webpack performance recommendations: \nYou can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.\nFor more info visit https://webpack.js.org/guides/code-splitting/"
  ],
  "version": "4.15.1",
  "hash": "10b89731af90bbbe7739",
  "time": 2055,
  "builtAt": 1531872087771,
  "publicPath": "",
  "outputPath": "/Users/jarred/Code/styleurl/build",
  "assetsByChunkName": {
    "popup": [
      "popup.css",
      "popup.bundle.js"
    ],
    "inject": "inject.bundle.js",
    "background": "background.bundle.js",
    "devtools": "devtools.bundle.js",
    "github_gist_content_script": "github_gist_content_script.bundle.js"
  },
  "assets": [
    {
      "name": "d7d5d4588a9f50c99264bc12e4892a7c.ttf",
      "size": 217276,
      "chunks": [],
      "chunkNames": [],
      "emitted": true
    },
    {
      "name": "e1c83f9474e0cc1d84a13c6d1ddf3ca5.ttf",
      "size": 221164,
      "chunks": [],
      "chunkNames": [],
      "emitted": true
    },
    {
      "name": "f5331cb6372b6c0d8baf2dd7e200498c.ttf",
      "size": 224452,
      "chunks": [],
      "chunkNames": [],
      "emitted": true
    },
    {
      "name": "popup.css",
      "size": 9982,
      "chunks"
Download .txt
gitextract_gnxt91oa/

├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── appveyor.yml
├── babel.config.dev.js
├── chrome/
│   ├── app/
│   │   └── components/
│   │       ├── Button.css
│   │       ├── Button.js
│   │       ├── CodeDiff.css
│   │       ├── CodeDiff.js
│   │       ├── Dropdown.css
│   │       ├── Dropdown.js
│   │       ├── FeedbackForm.css
│   │       ├── FeedbackForm.js
│   │       ├── HeaderBar.css
│   │       ├── HeaderBar.js
│   │       ├── Icon.css
│   │       ├── Icon.js
│   │       ├── StylesheetCodePreview.css
│   │       ├── StylesheetCodePreview.js
│   │       ├── Switcher.css
│   │       ├── Switcher.js
│   │       └── WhiteTextLogo.js
│   ├── extension/
│   │   ├── background/
│   │   │   ├── badge.js
│   │   │   ├── contextMenus.js
│   │   │   ├── inject.js
│   │   │   └── view_styleurl/
│   │   │       └── ViewStyleURL.js
│   │   ├── background.js
│   │   ├── create_styleurl/
│   │   │   ├── CreateStyleURL.js
│   │   │   ├── Gist.css
│   │   │   ├── Gist.js
│   │   │   ├── fonts.css
│   │   │   └── messages.js
│   │   ├── create_styleurl.css
│   │   ├── create_styleurl.js
│   │   ├── css_manager_content_script.js
│   │   ├── devtools.js
│   │   ├── github_gist_content_script.js
│   │   ├── inject_create_styleurl.js
│   │   ├── inject_view_styleurl.js
│   │   ├── inline_style_observer/
│   │   │   ├── inline_style_observer.js
│   │   │   └── inline_style_observer_manager.js
│   │   ├── inline_style_observer.js
│   │   ├── lib/
│   │   │   ├── StyleURLTab.js
│   │   │   ├── api.js
│   │   │   ├── browserAction.js
│   │   │   ├── gists.js
│   │   │   ├── injectScriptNames.js
│   │   │   ├── injectShadowDom.js
│   │   │   ├── makeEverythingImportant.js
│   │   │   ├── port.js
│   │   │   ├── stylefile.js
│   │   │   └── toFile.js
│   │   ├── postcss.config.js
│   │   ├── stylesheet_manager_content_script.js
│   │   ├── version_info.js
│   │   └── view_styleurl/
│   │       └── ViewStyleURL.js
│   ├── manifest.dev.json
│   ├── manifest.prod.json
│   └── views/
│       ├── background.pug
│       ├── create_styleurl.pug
│       ├── devtools.pug
│       ├── inject.pug
│       └── window.pug
├── package.json
├── scripts/
│   ├── .eslintrc
│   ├── build.js
│   ├── compress.js
│   ├── dev.js
│   ├── tasks.js
│   └── update-readme.js
├── stats.json
├── webpack/
│   ├── .eslintrc
│   ├── customPublicPath.js
│   ├── dev.config.js
│   ├── prod.config.js
│   ├── replace/
│   │   ├── JsonpMainTemplate.runtime.js
│   │   └── process-update.js
│   └── test.config.js
└── yarn-error.log
Download .txt
SYMBOL INDEX (115 symbols across 29 files)

FILE: chrome/app/components/Button.js
  constant BUTTON_COLORS (line 5) | const BUTTON_COLORS = {
  constant BUTTON_SIZES (line 12) | const BUTTON_SIZES = {
  class Button (line 16) | class Button extends React.Component {
    method render (line 22) | render() {

FILE: chrome/app/components/CodeDiff.js
  class CodeDiff (line 42) | class CodeDiff extends React.PureComponent {
    method getDerivedStateFromProps (line 48) | static getDerivedStateFromProps(props, state) {
    method render (line 59) | render() {

FILE: chrome/app/components/Dropdown.js
  class _DropdownChild (line 6) | class _DropdownChild extends React.Component {
    method render (line 10) | render() {
  class Dropdown (line 25) | class Dropdown extends React.Component {
    method render (line 50) | render() {

FILE: chrome/app/components/FeedbackForm.js
  class FeedbackForm (line 8) | class FeedbackForm extends React.Component {
    method constructor (line 9) | constructor(props) {
    method render (line 56) | render() {

FILE: chrome/app/components/HeaderBar.js
  class HeaderBar (line 8) | class HeaderBar extends React.Component {
    method render (line 13) | render() {

FILE: chrome/app/components/Icon.js
  constant ICON_BY_NAME (line 62) | const ICON_BY_NAME = {

FILE: chrome/app/components/StylesheetCodePreview.js
  class StylesheetCodePreview (line 18) | class StylesheetCodePreview extends React.PureComponent {
    method render (line 19) | render() {

FILE: chrome/app/components/Switcher.js
  class Switcher (line 5) | class Switcher extends React.PureComponent {
    method render (line 8) | render() {

FILE: chrome/extension/background/contextMenus.js
  constant CONTEXT_MENU_ID (line 2) | const CONTEXT_MENU_ID = 'example_context_menu';
  function closeIfExist (line 4) | function closeIfExist() {
  function popWindow (line 11) | function popWindow(type) {

FILE: chrome/extension/background/inject.js
  function isInjected (line 6) | function isInjected(tabId, name) {
  function loadScript (line 20) | async function loadScript(name, tabId, cb, runAt = "document_end") {

FILE: chrome/extension/create_styleurl/CreateStyleURL.js
  function copyToClipboard (line 28) | function copyToClipboard(text) {
  class CreateStyleURL (line 39) | class CreateStyleURL extends React.PureComponent {
    method getDerivedStateFromProps (line 45) | static getDerivedStateFromProps(props, state) {
    method render (line 68) | render() {
  class CreateStyleURLContainer (line 129) | class CreateStyleURLContainer extends React.Component {
    method constructor (line 130) | constructor(props) {
    method componentWillUnmount (line 158) | componentWillUnmount() {
    method render (line 299) | render() {

FILE: chrome/extension/create_styleurl/Gist.js
  class Gist (line 10) | class Gist extends React.Component {
    method getDerivedStateFromProps (line 15) | static getDerivedStateFromProps(props, state) {
    method componentDidUpdate (line 27) | componentDidUpdate(_prevProps, prevState) {
    method componentDidMount (line 33) | componentDidMount() {
    method render (line 60) | render() {

FILE: chrome/extension/create_styleurl/messages.js
  constant INITIAL_HEIGHT (line 1) | const INITIAL_HEIGHT = 76;

FILE: chrome/extension/css_manager_content_script.js
  function requestStyles (line 43) | function requestStyles(options, callback = applyStyles) {
  function applyOnMessage (line 91) | function applyOnMessage(message, from, sender, sendResponse) {
  function doDisableAll (line 146) | function doDisableAll(disable = disableAll) {
  function doExposeIframes (line 161) | function doExposeIframes(state = exposeIframes) {
  function applyStyleState (line 178) | function applyStyleState({ id, enabled }) {
  function removeStyle (line 198) | function removeStyle({ id, retire = false }) {
  function applyStyles (line 221) | function applyStyles(styles) {
  function applySections (line 285) | function applySections(styleId, code, important) {
  function addStyleElement (line 327) | function addStyleElement(newElement, important) {
  function replaceAll (line 354) | function replaceAll(newStyles) {
  function applyTransitionPatch (line 381) | function applyTransitionPatch() {
  function getStyleId (line 403) | function getStyleId(el) {
  function countStylesInHash (line 407) | function countStylesInHash(styleHash) {
  function orphanCheck (line 415) | function orphanCheck() {
  function initDocRewriteObserver (line 428) | function initDocRewriteObserver() {
  function initDocRootObserver (line 468) | function initDocRootObserver() {

FILE: chrome/extension/devtools.js
  constant SHA256 (line 6) | const SHA256 = new Hashes.SHA256();

FILE: chrome/extension/inline_style_observer/inline_style_observer.js
  class InlineStyleObserver (line 3) | class InlineStyleObserver {
    method constructor (line 4) | constructor(onChange) {

FILE: chrome/extension/inline_style_observer/inline_style_observer_manager.js
  class InlineStyleObserverManager (line 9) | class InlineStyleObserverManager {
    method constructor (line 10) | constructor() {

FILE: chrome/extension/lib/StyleURLTab.js
  constant TAB_IDS_TO_STYLEURL (line 10) | const TAB_IDS_TO_STYLEURL = {};
  class StyleURL (line 30) | class StyleURL {
    method constructor (line 31) | constructor({ gistId }) {

FILE: chrome/extension/lib/api.js
  constant SCREENSHOT_CONTENT_TYPE (line 4) | const SCREENSHOT_CONTENT_TYPE = "image/png";

FILE: chrome/extension/lib/browserAction.js
  constant PLUS_IMAGE_PATH (line 1) | const PLUS_IMAGE_PATH = {
  constant DEFAULT_ICON_PATH (line 9) | const DEFAULT_ICON_PATH = {
  constant BROWSER_ACTION_STATES (line 17) | const BROWSER_ACTION_STATES = {
  constant BROWSER_ACTION_STATE (line 23) | let BROWSER_ACTION_STATE = BROWSER_ACTION_STATES.default;

FILE: chrome/extension/lib/gists.js
  constant STYLEFILE_NAMES (line 4) | const STYLEFILE_NAMES = ["Stylefile.yml", "Stylefile"];
  constant SPECIAL_QUERY_PARAMS (line 5) | const SPECIAL_QUERY_PARAMS = {

FILE: chrome/extension/lib/injectShadowDom.js
  constant Z_INDEX (line 5) | const Z_INDEX = 2147483647;

FILE: chrome/extension/lib/port.js
  constant DEV_CHROME_PORT_PREFIX (line 2) | const DEV_CHROME_PORT_PREFIX = "STYLEURL_DEV_PORT/";
  constant PROD_CHROME_PORT_PREFIX (line 3) | const PROD_CHROME_PORT_PREFIX = "STYLEURL_PORT/";
  constant CHROME_PORT_PREFIX (line 5) | const CHROME_PORT_PREFIX =
  constant PORT_TYPES (line 14) | const PORT_TYPES = {
  constant MESSAGE_TYPES (line 22) | const MESSAGE_TYPES = {
  constant STYLESHEET_TYPE (line 45) | const STYLESHEET_TYPE = {

FILE: chrome/extension/stylesheet_manager_content_script.js
  constant ID_PREFIX (line 8) | const ID_PREFIX = "__styleurl";
  constant ROOT (line 9) | const ROOT = document.documentElement;
  class DocumentRootObserver (line 11) | class DocumentRootObserver {
    method constructor (line 14) | constructor({rootEl}) {
    method function (line 36) | function stop() {
    method function (line 43) | function evade(fn) {
    method sortStyleMap (line 53) | sortStyleMap() {
    method sortStyleElements (line 72) | sortStyleElements() {
    method function (line 113) | function isMovable(el) {
    method isSkippable (line 116) | isSkippable(el, skipOwnStyles) {
    method function (line 125) | function moveAfter(el, expected) {
    method restorationLimitExceeded (line 137) | restorationLimitExceeded() {
  class StylesheetManager (line 147) | class StylesheetManager {
    method constructor (line 148) | constructor() {
    method matchURL (line 165) | get matchURL() {
    method styleTagQuery (line 180) | get styleTagQuery() {

FILE: chrome/extension/view_styleurl/ViewStyleURL.js
  class ViewStyleURL (line 22) | class ViewStyleURL extends React.PureComponent {
    method render (line 29) | render() {
  class ViewStyleURLContainer (line 76) | class ViewStyleURLContainer extends React.Component {
    method constructor (line 77) | constructor(props) {
    method componentDidMount (line 101) | componentDidMount() {
    method componentWillUnmount (line 159) | componentWillUnmount() {
    method render (line 165) | render() {

FILE: scripts/compress.js
  constant RELEASES_PATH (line 5) | const RELEASES_PATH = path.join(__dirname, "../releases");
  constant BUILD_PATH (line 6) | const BUILD_PATH = path.join(__dirname, "../build");

FILE: scripts/update-readme.js
  constant README_PATH (line 9) | const README_PATH = path.resolve(root, "README.md");
  constant README (line 12) | const README = fs.readFileSync(README_PATH, "utf-8");
  constant WHATS_NEW_STRING (line 14) | const WHATS_NEW_STRING = "### What's New";
  function formatDate (line 16) | function formatDate(date) {

FILE: webpack/replace/JsonpMainTemplate.runtime.js
  function webpackHotUpdateCallback (line 7) | function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disa...
  function evalCode (line 13) | function evalCode(code, context) {
  function hotDownloadManifest (line 28) | function hotDownloadManifest(timeout) { // eslint-disable-line no-unused...

FILE: webpack/replace/process-update.js
  function upToDate (line 19) | function upToDate(hash) {
  function check (line 31) | function check() {
  function logUpdates (line 74) | function logUpdates(updatedModules, renewedModules) {
  function handleError (line 119) | function handleError(err) {
  function performReload (line 133) | function performReload() {
Copy disabled (too large) Download .json
Condensed preview — 80 files, each showing path, character count, and a content snippet. Download the .json file for the full structured content (10,930K chars).
[
  {
    "path": ".gitignore",
    "chars": 71,
    "preview": "key.pem\nnode_modules\ndev\ndist\nbuild\nbuild.zip\ncredentials.json\nreleases"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 3830,
    "preview": "## 1.1.15\n\nFix bug in feedback box in ViewStyleURL bar\n\n## 1.1.14\n\nThe bottom bar is now hidden when in print mode. Than"
  },
  {
    "path": "LICENSE",
    "chars": 34503,
    "preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software"
  },
  {
    "path": "README.md",
    "chars": 2431,
    "preview": "# StyleURL Extension\n\n[StyleURL](https://www.styleurl.app) is the easiest way for developers & designers to collaborate "
  },
  {
    "path": "appveyor.yml",
    "chars": 317,
    "preview": "environment:\n  matrix:\n    - nodejs_version: '6'\n    - nodejs_version: '7'\n\ncache:\n  - \"%LOCALAPPDATA%/Yarn\"\n  - node_mo"
  },
  {
    "path": "babel.config.dev.js",
    "chars": 103,
    "preview": "module.exports = {\n  presets: [\"@babel/preset-env\"],\n  plugins: [\"@babel/plugin-transform-runtime\"]\n};\n"
  },
  {
    "path": "chrome/app/components/Button.css",
    "chars": 950,
    "preview": ".Button {\n    display: flex;\n    align-items: center;\n    border-radius: 4px;\n    margin: 8px 0;\n    cursor: pointer;\n  "
  },
  {
    "path": "chrome/app/components/Button.js",
    "chars": 1394,
    "preview": "import classNames from \"classnames\";\nimport React from \"react\";\nimport \"./Button.css\";\n\nexport const BUTTON_COLORS = {\n "
  },
  {
    "path": "chrome/app/components/CodeDiff.css",
    "chars": 409,
    "preview": ".CodeDiff {\n    width: 400px;\n    max-width: 100%;\n    overflow-x: hidden;\n    overflow-y: auto;\n    max-height: 240px;\n"
  },
  {
    "path": "chrome/app/components/CodeDiff.js",
    "chars": 1733,
    "preview": "import React from \"react\";\nimport \"./CodeDiff.css\";\nimport SyntaxHighlighter from \"react-syntax-highlighter\";\nimport { m"
  },
  {
    "path": "chrome/app/components/Dropdown.css",
    "chars": 555,
    "preview": ".Dropdown {\n  position: relative;\n}\n\n.Dropdown-content {\n  padding: 14px 18px;\n  align-items: center;\n  cursor: pointer;"
  },
  {
    "path": "chrome/app/components/Dropdown.js",
    "chars": 1951,
    "preview": "import React from \"react\";\nimport \"./Dropdown.css\";\nimport classNames from \"classnames\";\nimport onClickOutside from \"rea"
  },
  {
    "path": "chrome/app/components/FeedbackForm.css",
    "chars": 2020,
    "preview": ".FeedbackFormContainer {\n    display: block;\n    position: relative;\n    white-space: nowrap;\n    margin-left: 14px;\n}\n\n"
  },
  {
    "path": "chrome/app/components/FeedbackForm.js",
    "chars": 3167,
    "preview": "import React from \"react\";\nimport { Icon } from \"./Icon\";\nimport onClickOutside from \"react-onclickoutside\";\nimport clas"
  },
  {
    "path": "chrome/app/components/HeaderBar.css",
    "chars": 672,
    "preview": ".HeaderBar {\n  background-color: #13161b;\n  padding: 0 28px;\n  display: grid;\n  grid-template-columns: 1fr 1fr 1fr;\n  gr"
  },
  {
    "path": "chrome/app/components/HeaderBar.js",
    "chars": 1103,
    "preview": "import React from \"react\";\nimport \"./HeaderBar.css\";\nimport WhiteTextLogo from \"./WhiteTextLogo\";\nimport classNames from"
  },
  {
    "path": "chrome/app/components/Icon.css",
    "chars": 81,
    "preview": ".IconFill {\n    fill: currentColor;\n}\n\n.IconStroke {\n    stroke: currentColor;\n}\n"
  },
  {
    "path": "chrome/app/components/Icon.js",
    "chars": 4593,
    "preview": "import React from \"react\";\nimport \"./Icon.css\";\n\nconst FeedbackIcon = ({ width, height, ...otherProps }) => (\n  <svg wid"
  },
  {
    "path": "chrome/app/components/StylesheetCodePreview.css",
    "chars": 408,
    "preview": ".StylesheetCodePreview {\n    border-top-left-radius: 2px;\n    border-top-right-radius: 2px;\n    overflow: hidden;\n}\n\n.St"
  },
  {
    "path": "chrome/app/components/StylesheetCodePreview.js",
    "chars": 1231,
    "preview": "import React from \"react\";\nimport { Button, BUTTON_COLORS } from \"./Button\";\nimport \"./StylesheetCodePreview.css\";\nimpor"
  },
  {
    "path": "chrome/app/components/Switcher.css",
    "chars": 692,
    "preview": ".Switcher,\n.SwitcherSide,\n.SwitcherSide-label {\n  display: flex;\n  align-items: center;\n}\n\n.Switcher,\n.SwitcherSide {\n  "
  },
  {
    "path": "chrome/app/components/Switcher.js",
    "chars": 774,
    "preview": "import React from \"react\";\nimport classNames from \"classnames\";\nimport \"./Switcher.css\";\n\nexport class Switcher extends "
  },
  {
    "path": "chrome/app/components/WhiteTextLogo.js",
    "chars": 763,
    "preview": "import React from \"react\";\n\nconst getSrcForSize = multipler => {\n  if (!multipler || multipler < 2) {\n    return chrome."
  },
  {
    "path": "chrome/extension/background/badge.js",
    "chars": 355,
    "preview": "chrome.storage.local.get('todos', (obj) => {\n  let todos = obj.todos;\n  if (todos) {\n    todos = JSON.parse(todos);\n    "
  },
  {
    "path": "chrome/extension/background/contextMenus.js",
    "chars": 809,
    "preview": "let windowId = 0;\nconst CONTEXT_MENU_ID = 'example_context_menu';\n\nfunction closeIfExist() {\n  if (windowId > 0) {\n    c"
  },
  {
    "path": "chrome/extension/background/inject.js",
    "chars": 1426,
    "preview": "import injectScriptNames from \"../lib/injectScriptNames\";\n\nconst log = (...messages) =>\n  console.log.apply(console, [\"["
  },
  {
    "path": "chrome/extension/background/view_styleurl/ViewStyleURL.js",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "chrome/extension/background.js",
    "chars": 18891,
    "preview": "import Messenger from \"chrome-ext-messenger\";\nimport _ from \"lodash\";\nimport memoizee from \"memoizee\";\nimport Raven from"
  },
  {
    "path": "chrome/extension/create_styleurl/CreateStyleURL.js",
    "chars": 8006,
    "preview": "import { HeaderBar } from \"app/components/HeaderBar\";\nimport Messenger from \"chrome-ext-messenger\";\nimport classNames fr"
  },
  {
    "path": "chrome/extension/create_styleurl/Gist.css",
    "chars": 1386,
    "preview": "#gist_root,\n#gist_root body {\n    margin: 0;\n    padding: 0;\n}\n\n#gist_root {\n    width: auto;\n}\n\n#gist_root .gist {\n    "
  },
  {
    "path": "chrome/extension/create_styleurl/Gist.js",
    "chars": 1962,
    "preview": "import React from \"react\";\nimport \"./gist.css\";\n\nconst gistURL = ({ file, id }) => {\n  const fileArg = file ? `?file=${f"
  },
  {
    "path": "chrome/extension/create_styleurl/fonts.css",
    "chars": 6440,
    "preview": "/* cyrillic-ext */\n@font-face {\n    font-family: 'Open Sans';\n    font-style: normal;\n    font-weight: 400;\n    src: loc"
  },
  {
    "path": "chrome/extension/create_styleurl/messages.js",
    "chars": 34,
    "preview": "export const INITIAL_HEIGHT = 76;\n"
  },
  {
    "path": "chrome/extension/create_styleurl.css",
    "chars": 1700,
    "preview": "/* @import \"reset-css\"; */\n@import \"./create_styleurl/fonts.css\";\n\n.StyleURLShadowDOMRoot,\ntextarea,\ndiv,\ninput {\n    fo"
  },
  {
    "path": "chrome/extension/create_styleurl.js",
    "chars": 156,
    "preview": "import React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport CreateStyleURL from \"./create_styleurl/CreateStyleUR"
  },
  {
    "path": "chrome/extension/css_manager_content_script.js",
    "chars": 17281,
    "preview": "// This code has largely been adapted from https://github.com/openstyles/stylus/blob/master/content/apply.js\n// ...thank"
  },
  {
    "path": "chrome/extension/devtools.js",
    "chars": 6917,
    "preview": "import Messenger from \"chrome-ext-messenger\";\nimport Hashes from \"jshashes\";\nimport _ from \"lodash\";\nimport { MESSAGE_TY"
  },
  {
    "path": "chrome/extension/github_gist_content_script.js",
    "chars": 4334,
    "preview": "// Privacy Notice\n// StyleURL does *not* send all gists the user opens to StyleURL's server.\n// Before requesting the co"
  },
  {
    "path": "chrome/extension/inject_create_styleurl.js",
    "chars": 375,
    "preview": "import { injectShadowDOM } from \"./lib/injectShadowDom\";\nimport CreateStyleURL from \"./create_styleurl/CreateStyleURL\";\n"
  },
  {
    "path": "chrome/extension/inject_view_styleurl.js",
    "chars": 349,
    "preview": "import { injectShadowDOM } from \"./lib/injectShadowDom\";\nimport injectScriptNames from \"./lib/injectScriptNames\";\nimport"
  },
  {
    "path": "chrome/extension/inline_style_observer/inline_style_observer.js",
    "chars": 1519,
    "preview": "import { getSingleSelector } from \"optimal-select\";\n\nexport class InlineStyleObserver {\n  constructor(onChange) {\n    th"
  },
  {
    "path": "chrome/extension/inline_style_observer/inline_style_observer_manager.js",
    "chars": 2961,
    "preview": "import Messenger from \"chrome-ext-messenger\";\nimport { PORT_TYPES, MESSAGE_TYPES } from \"../lib/port\";\nimport { InlineSt"
  },
  {
    "path": "chrome/extension/inline_style_observer.js",
    "chars": 272,
    "preview": "import { InlineStyleObserverManager } from \"./inline_style_observer/inline_style_observer_manager\";\n\nconst startManager "
  },
  {
    "path": "chrome/extension/lib/StyleURLTab.js",
    "chars": 2776,
    "preview": "import {\n  getGistById,\n  loadStylefileFromGist,\n  getStylesheetsFromGist\n} from \"./gists\";\nimport { shouldApplyStyleToU"
  },
  {
    "path": "chrome/extension/lib/api.js",
    "chars": 2128,
    "preview": "import S3Upload from \"react-s3-uploader/s3upload\";\n\nconst uploaders = {};\nexport const SCREENSHOT_CONTENT_TYPE = \"image/"
  },
  {
    "path": "chrome/extension/lib/browserAction.js",
    "chars": 1389,
    "preview": "const PLUS_IMAGE_PATH = {\n  \"16\": \"img/plus_16x16.png\",\n  \"19\": \"img/plus_19x19.png\",\n  \"38\": \"img/plus_38x38.png\",\n  \"4"
  },
  {
    "path": "chrome/extension/lib/gists.js",
    "chars": 1111,
    "preview": "import _ from \"lodash\";\nimport { loadStylefileFromString } from \"./stylefile\";\n\nexport const STYLEFILE_NAMES = [\"Stylefi"
  },
  {
    "path": "chrome/extension/lib/injectScriptNames.js",
    "chars": 147,
    "preview": "export default {\n  inject_create_styleurl: \"__styleurl_create_styleurl_shadowdom\",\n  inject_view_styleurl: \"__styleurl_v"
  },
  {
    "path": "chrome/extension/lib/injectShadowDom.js",
    "chars": 2247,
    "preview": "import React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport ShadowDOM from \"react-shadow\";\n\nconst Z_INDEX = 2147"
  },
  {
    "path": "chrome/extension/lib/makeEverythingImportant.js",
    "chars": 953,
    "preview": "const getStylesheet = element => {\n  for (let i = 0; i < document.styleSheets.length; i++) {\n    const stylesheet = docu"
  },
  {
    "path": "chrome/extension/lib/port.js",
    "chars": 1617,
    "preview": "import _ from \"lodash\";\nconst DEV_CHROME_PORT_PREFIX = \"STYLEURL_DEV_PORT/\";\nconst PROD_CHROME_PORT_PREFIX = \"STYLEURL_P"
  },
  {
    "path": "chrome/extension/lib/stylefile.js",
    "chars": 447,
    "preview": "import URLPattern from \"url-pattern\";\nimport YAML from \"js-yaml\";\nimport _ from \"lodash\";\n\nexport const loadStylefileFro"
  },
  {
    "path": "chrome/extension/lib/toFile.js",
    "chars": 409,
    "preview": "const toBlob = base64String => {\n  return window.fetch(base64String).then(res => res.blob());\n};\n\nexport const toFile = "
  },
  {
    "path": "chrome/extension/postcss.config.js",
    "chars": 91,
    "preview": "module.exports = {\n  plugins: {\n    \"postcss-import\": {},\n    \"postcss-cssnext\": {}\n  }\n};\n"
  },
  {
    "path": "chrome/extension/stylesheet_manager_content_script.js",
    "chars": 7231,
    "preview": "// This file is loosely based on https://github.com/openstyles/stylus/blob/master/content/apply.js\n// Though, heavily re"
  },
  {
    "path": "chrome/extension/version_info.js",
    "chars": 570,
    "preview": "const writeVersionToDOM = () => {\n  const metadata = {\n    id: chrome.runtime.id,\n    environment: process.env.NODE_ENV,"
  },
  {
    "path": "chrome/extension/view_styleurl/ViewStyleURL.js",
    "chars": 4952,
    "preview": "import React from \"react\";\nimport Messenger from \"chrome-ext-messenger\";\nimport \"../create_styleurl.css\";\nimport { Heade"
  },
  {
    "path": "chrome/manifest.dev.json",
    "chars": 1939,
    "preview": "{\n  \"version\": \"1.0.0\",\n  \"name\": \"StyleURL (Development)\",\n  \"manifest_version\": 2,\n  \"description\":\n    \"Publish CSS c"
  },
  {
    "path": "chrome/manifest.prod.json",
    "chars": 1690,
    "preview": "{\n  \"version\": \"1.1.15\",\n  \"name\": \"StyleURL\",\n  \"manifest_version\": 2,\n  \"description\": \"StyleURL lets you export and s"
  },
  {
    "path": "chrome/views/background.pug",
    "chars": 130,
    "preview": "doctype html\n\nhtml\n  head\n    script(src=env == 'prod' ? '/background.bundle.js' : 'https://localhost:3000/background.bu"
  },
  {
    "path": "chrome/views/create_styleurl.pug",
    "chars": 219,
    "preview": "doctype html\n\nhtml\n  head\n    meta(charset='UTF-8')\n    title \"Create StyleURL\"\n    link(id=\"root_stylesheet\" rel=\"style"
  },
  {
    "path": "chrome/views/devtools.pug",
    "chars": 125,
    "preview": "doctype html\n\nhtml\n  head\n    script(src=env == 'prod' ? '/devtools.bundle.js' : 'http://localhost:3000/devtools.bundle."
  },
  {
    "path": "chrome/views/inject.pug",
    "chars": 286,
    "preview": "doctype html\n\nhtml\n  head\n    meta(charset='UTF-8')\n    title Redux TodoMVC Example (Inject)\n    style.\n      html, body"
  },
  {
    "path": "chrome/views/window.pug",
    "chars": 329,
    "preview": "doctype html\n\nhtml\n  head\n    meta(charset='UTF-8')\n    title Redux TodoMVC Example (Window)\n  body\n    #root\n    if env"
  },
  {
    "path": "package.json",
    "chars": 3674,
    "preview": "{\n  \"name\": \"styleurl-extension\",\n  \"version\": \"1.1.15\",\n  \"description\": \"StyleURL Chrome extension\",\n  \"private\": true"
  },
  {
    "path": "scripts/.eslintrc",
    "chars": 158,
    "preview": "{\n  \"env\": {\n    \"shelljs\": true\n  },\n  \"rules\": {\n    \"no-console\": 0,\n    \"import/no-extraneous-dependencies\": [\"error"
  },
  {
    "path": "scripts/build.js",
    "chars": 286,
    "preview": "const tasks = require('./tasks');\n\ntasks.replaceWebpack();\nconsole.log('[Copy assets]');\nconsole.log('-'.repeat(80));\nta"
  },
  {
    "path": "scripts/compress.js",
    "chars": 3954,
    "preview": "const fs = require(\"fs\");\nconst ChromeExtension = require(\"crx\");\nconst path = require(\"path\");\n\nconst RELEASES_PATH = p"
  },
  {
    "path": "scripts/dev.js",
    "chars": 662,
    "preview": "const tasks = require('./tasks');\nconst createWebpackServer = require('webpack-httpolyglot-server');\nconst devConfig = r"
  },
  {
    "path": "scripts/tasks.js",
    "chars": 674,
    "preview": "require('shelljs/global');\n\nexports.replaceWebpack = () => {\n  const replaceTasks = [{\n    from: 'webpack/replace/JsonpM"
  },
  {
    "path": "scripts/update-readme.js",
    "chars": 2191,
    "preview": "const fs = require(\"fs\");\nvar path = require(\"path\");\nvar changelogParser = require(\"changelog-parser\");\n\nconst root = p"
  },
  {
    "path": "stats.json",
    "chars": 9550609,
    "preview": "{\n  \"errors\": [],\n  \"warnings\": [\n    \"./node_modules/css/node_modules/source-map/lib/source-map/source-map-generator.js"
  },
  {
    "path": "webpack/.eslintrc",
    "chars": 101,
    "preview": "{\n  \"rules\": {\n    \"import/no-extraneous-dependencies\": [\"error\", { \"devDependencies\": true }]\n  }\n}\n"
  },
  {
    "path": "webpack/customPublicPath.js",
    "chars": 595,
    "preview": "/* global __webpack_public_path__ __HOST__ __PORT__ */\n/* eslint no-global-assign: 0 camelcase: 0 */\n\nif (process.env.NO"
  },
  {
    "path": "webpack/dev.config.js",
    "chars": 4464,
    "preview": "const path = require(\"path\");\nconst webpack = require(\"webpack\");\nconst WriteAssetsWebpackPlugin = require(\"write-assets"
  },
  {
    "path": "webpack/prod.config.js",
    "chars": 4336,
    "preview": "const path = require(\"path\");\nconst webpack = require(\"webpack\");\nconst autoprefixer = require(\"autoprefixer\");\nconst Mi"
  },
  {
    "path": "webpack/replace/JsonpMainTemplate.runtime.js",
    "chars": 2300,
    "preview": "/*\n\tMIT License http://www.opensource.org/licenses/mit-license.php\n\tAuthor Tobias Koppers @sokra\n*/\n/*globals hotAddUpda"
  },
  {
    "path": "webpack/replace/process-update.js",
    "chars": 4111,
    "preview": "/**\n * Based heavily on https://github.com/webpack/webpack/blob/\n *  c0afdf9c6abc1dd70707c594e473802a566f7b6e/hot/only-d"
  },
  {
    "path": "webpack/test.config.js",
    "chars": 295,
    "preview": "// for babel-plugin-webpack-loaders\nconst config = require(\"./prod.config\");\n\nmodule.exports = {\n  node: {\n    fs: \"mock"
  },
  {
    "path": "yarn-error.log",
    "chars": 264572,
    "preview": "Arguments: \n  /usr/local/Cellar/node/10.1.0/bin/node /usr/local/bin/yarn add -D @babel/react\n\nPATH: \n  /Applications/Ske"
  }
]

About this extraction

This page contains the full source code of the Jarred-Sumner/styleurl-extension GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 80 files (9.5 MB), approximately 2.5M tokens, and a symbol index with 115 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!