Source code for core.filters

""" Extra webasset filters. """
import os
import rcssmin  # type:ignore[import-untyped]

from webassets.filter import Filter, register_filter  # type:ignore
from webassets.filter.datauri import (  # type:ignore[import-untyped]
    CSSDataUri, CSSUrlRewriter)
from dukpy.webassets import BabelJSX  # type:ignore[import-untyped]
from dukpy import jsx_compile  # type:ignore[import-untyped]


from typing import Any, IO


[docs] class JsxFilter(BabelJSX): """ DukPy is a simple javascript interpreter for Python built on top of duktape engine without any external dependency. Note: let is not supported by the duktape engine, see https://github.com/amol-/dukpy/issues/47. """
[docs] name = 'jsx'
[docs] babel_options: dict[str, Any] = {'minified': True}
[docs] def input( self, _in: IO[str], out: IO[str], *, source_path: str | None = None, **kwargs: Any ) -> None: """:param kwargs: are actually babel options""" options = self.babel_options.copy() if source_path: options['filename'] = os.path.basename(source_path) if self.loader == 'systemjs': options['plugins'] = ['transform-es2015-modules-systemjs'] elif self.loader == 'umd': options['plugins'] = ['transform-es2015-modules-umd'] out.write(self.transformer(_in.read(), **options))
[docs] def setup(self) -> None: self.transformer = jsx_compile
register_filter(JsxFilter)
[docs] class DataUriFilter(CSSDataUri): """ Overrides the default datauri filter to work around this issue: https://github.com/miracle2k/webassets/issues/387 """
[docs] name = 'datauri'
[docs] def input(self, _in: IO[str], out: IO[str], **kw: Any) -> None: self.keywords = kw self.source_path = self.keywords['source_path'] self.output_path = self.keywords['output_path'] return super(CSSUrlRewriter, self).input(_in, out, **kw)
@property
[docs] def source_url(self) -> str: return self.ctx.resolver.resolve_source_to_url( self.ctx, self.keywords['source_path'], self.keywords['source'])
@property
[docs] def output_url(self) -> str: return self.ctx.resolver.resolve_output_to_url( self.ctx, self.keywords['output'])
register_filter(DataUriFilter)
[docs] class RCSSMinFilter(Filter): """ Adds the rcssmin filter (not yet included in webassets) """
[docs] name = 'custom-rcssmin'
[docs] def setup(self) -> None: self.rcssmin = rcssmin
[docs] def output(self, _in: IO[str], out: IO[str], **kw: Any) -> None: out.write(self.rcssmin.cssmin(_in.read()))
register_filter(RCSSMinFilter)