"""Tools to apply the hooks to a running `pywb` app."""
from pywb.apps.rewriterapp import RewriterApp
from pywb.rewrite.url_rewriter import UrlRewriter


def apply_post_app_hooks(rewriter_app, hooks):
    # Add most hook points
    _PatchedRewriterApp.patch(rewriter_app, hooks)


def apply_pre_app_hooks(hooks):
    """Apply hooks before the app has been instantiated."""

    # Patch out URLs to ignore
    _patch_url_rewriter(hooks)


def _patch_url_rewriter(hooks):
    # Modify the list of prefixes that prevent a URL from being rewritten
    prefixes = list(UrlRewriter.NO_REWRITE_URI_PREFIX)
    prefixes.extend(hooks.ignore_prefixes)
    UrlRewriter.NO_REWRITE_URI_PREFIX = tuple(prefixes)


class _PatchedRewriterApp(RewriterApp):
    hooks = None

    @classmethod
    def patch(cls, rewriter, hooks):
        # Change the class of the rewriter to be this class, forcibly casting
        # it to be an instance of this class
        rewriter.__class__ = cls
        rewriter.hooks = hooks

        # Update the Jinja environment to have the vars we want
        rewriter.jinja_env.jinja_env.globals.update(hooks.template_vars)

        # Set the Content-Security-Policy header
        rewriter.csp_header = hooks.csp_header

    def get_upstream_url(self, wb_url, kwargs, params):
        params["url"] = self.hooks.get_upstream_url(doc_url=params["url"])

        return super().get_upstream_url(wb_url, kwargs, params)

@@ -95,16 +95,126 @@
 iterApp%0A
+from pywb.rewrite.default_rewriter import DefaultRewriter%0Afrom pywb.rewrite.html_rewriter import HTMLRewriter%0A
 from pyw
@@ -308,35 +308,8 @@
 s):%0A
-    # Add most hook points%0A
     
@@ -458,64 +458,66 @@
     
-# P
+_p
 atch
- out URLs to ignore
+_url_rewriter(hooks)
 %0A    _
-p
+P
 atch
-_url_rewriter(hooks
+edHTMLRewriter.patch(
 )%0A%0A%0A
@@ -778,16 +778,738 @@
 ixes)%0A%0A%0A
+class _PatchedHTMLRewriter(HTMLRewriter):%0A    @classmethod%0A    def patch(cls):%0A        DefaultRewriter.DEFAULT_REWRITERS%5B%22html%22%5D = _PatchedHTMLRewriter%0A%0A    def _rewrite_link_href(self, attr_value, tag_attrs, rw_mod):%0A        # Prevent %60pywb%60 from attempting to insert Javascript style rewriting%0A        # stuff into %22%3Clink rel='manifest'%3E%22 items. This fixes a bug with%0A        # www.theguardian.com which declares it's manifest as %60text/javascript%60%0A        rel = self.get_attr(tag_attrs, %22rel%22)%0A%0A        if rel == %22manifest%22:%0A            # 'id_' type hint appears to disable any rewriting%0A            return self._rewrite_url(attr_value, %22id_%22)%0A%0A        return super()._rewrite_link_href(attr_value, tag_attrs, rw_mod)%0A%0A%0A
 class _P

Stop `pywb` from adding Javascript injects to JSON manifests