Compiler

Swift
public actor Compiler

A Sass compiler that uses Dart Sass as an embedded child process.

The Dart Sass compiler is bundled with this package for macOS and Ubuntu 64-bit Linux. For other platforms you need to supply this separately, see the readme.

Some debug logging is available via a swift-log Logger that produces goodpath protocol and compiler lifecycle tracing at Logger.Level.debug log level, approx 300 bytes per compile request, and protocol and lifecycle error reporting at Logger.Level.debug log level for conditions that are also reported through errors thrown from some API.

You must shut down the compiler using shutdownGracefully(...) before the last reference to the object is released otherwise the program will exit.

Custom importer resolution

Dart Sass uses a different algorithm to LibSass for processing imports. Each stylesheet is associated with the importer that loaded it – this may be an internal or hidden filesystem importer. Import resolution then goes:

  • Consult the stylesheet’s associated importer.
  • Consult every DartSass.ImportResolver given to the compiler, first the global list then the per-compilation list, in order within each list.

Topics

Initializers

init(eventLoopGroup: any EventLoopGroup, timeout: Int, messageStyle: CompilerMessageStyle, verboseDeprecations: Bool, deprecationControl: DeprecationControl, warningLevel: CompilerWarningLevel, importers: [ImportResolver], functions: SassFunctionMap)

Use the bundled Dart Sass compiler as the Sass compiler.

The bundled Dart Sass compiler is built on latest macOS (14) or Ubuntu (20.04). If you are running on another operating system then use init(eventLoopGroup:embeddedCompilerFileURL:embeddedCompilerFileArguments:timeout:messageStyle:verboseDeprecations:deprecationControl:warningLevel:importers:functions:) supplying the path of the correct Dart Sass compiler.

Initialization continues asynchronously after the initializer completes; failures are reported when the compiler is next used.

You must shut down the compiler with shutdownGracefully() before letting it go out of scope.

Declaration
Swift
public init(
    eventLoopGroup: any EventLoopGroup = MultiThreadedEventLoopGroup.singleton,
    timeout: Int = 60,
    messageStyle: CompilerMessageStyle = .plain,
    verboseDeprecations: Bool = false,
    deprecationControl: DeprecationControl = DeprecationControl(),
    warningLevel: CompilerWarningLevel = .all,
    importers: [ImportResolver] = [],
    functions: SassFunctionMap = [:]) throws
Parameters
eventLoopGroup

NIO EventLoopGroup to use. Default uses the NIO shared EventLoopGroup.

timeout

Maximum time in seconds allowed for the embedded compiler to compile a stylesheet. Detects hung compilers. Default is a minute; set -1 to disable timeouts.

messageStyle

Style for diagnostic message descriptions. Default is .plain.

verboseDeprecations

Control for deprecation warning messages. If false then the compiler will send only a few deprecation warnings of the same type. Default is false meaning repeated deprecation warnings are suppressed.

deprecationControl

Fine-grained control over how each deprecated feature is handled. Default is to issue a warning when any deprecated feature is used.

warningLevel

Control for warning messages from Sass files. Default is .all meaning all warnings mentioned in Sass files are produced.

importers

Rules for resolving @import that cannot be satisfied relative to the source file’s URL, used for all this compiler’s compilations.

functions

Sass functions available to all this compiler’s compilations.

Throws

LifecycleError if the program can’t be found.

init(eventLoopGroup: any EventLoopGroup, embeddedCompilerFileURL: URL, embeddedCompilerFileArguments: [String], timeout: Int, messageStyle: CompilerMessageStyle, verboseDeprecations: Bool, deprecationControl: DeprecationControl, warningLevel: CompilerWarningLevel, importers: [ImportResolver], functions: SassFunctionMap)

Use a program as the Sass embedded compiler.

Initialization continues asynchronously after the initializer returns; failures are reported when the compiler is next used.

You must shut down the compiler with shutdownGracefully() before letting it go out of scope.

Declaration
Swift
public init(
    eventLoopGroup: any EventLoopGroup = MultiThreadedEventLoopGroup.singleton,
    embeddedCompilerFileURL: URL,
    embeddedCompilerFileArguments: [String] = [],
    timeout: Int = 60,
    messageStyle: CompilerMessageStyle = .plain,
    verboseDeprecations: Bool = false,
    deprecationControl: DeprecationControl = DeprecationControl(),
    warningLevel: CompilerWarningLevel = .all,
    importers: [ImportResolver] = [],
    functions: SassFunctionMap = [:])
Parameters
eventLoopGroup

NIO EventLoopGroup to use. Default uses the NIO shared EventLoopGroup.

embeddedCompilerFileURL

Path of the sass program or something else that speaks the Sass embedded protocol. Check the readme for the supported protocol versions.

embeddedCompilerFileArguments

Any arguments to be passed to the embeddedCompilerFileURL program. Default none.

timeout

Maximum time in seconds allowed for the embedded compiler to compile a stylesheet. Detects hung compilers. Default is a minute; set -1 to disable timeouts.

messageStyle

Style for diagnostic message descriptions. Default is .plain.

verboseDeprecations

Control for deprecation warning messages. If false then the compiler will send only a few deprecation warnings of the same type. Default is false meaning repeated deprecation warnings are suppressed.

deprecationControl

Fine-grained control over how each deprecated feature is handled. Default is to issue a warning when any deprecated feature is used.

warningLevel

Control for warning messages from Sass files. Default is .all meaning all warnings mentioned in Sass files are produced.

importers

Rules for resolving @import that cannot be satisfied relative to the source file’s URL, used for all this compiler’s compilations.

functions

Sass functions available to all this compiler’s compilations.

Compilation

func compile(string: String, syntax: Syntax, url: URL?, importer: ImportResolver?, outputStyle: CssStyle, sourceMapStyle: SourceMapStyle, includeCharset: Bool, importers: [ImportResolver], functions: SassFunctionMap) async -> CompilerResults

Compile to CSS from an inline stylesheet.

Declaration
Swift
public func compile(
    string: String,
    syntax: Syntax = .scss,
    url: URL? = nil,
    importer: ImportResolver? = nil,
    outputStyle: CssStyle = .expanded,
    sourceMapStyle: SourceMapStyle = .separateSources,
    includeCharset: Bool = false,
    importers: [ImportResolver] = [],
    functions: SassFunctionMap = [:]
) async throws -> CompilerResults
Parameters
string

The stylesheet text to compile.

syntax

The syntax of string, default .scss.

url

The absolute URL to associate with string, from where it was loaded. Default nil meaning unknown.

importer

Rule to resolve @import etc. from string relative to url. Default nil meaning no filesystem importer is configured. Unlike some Sass implementations this means that imports of files from the current directory don’t work automatically: add a loadpath to importers.

outputStyle

How to format the produced CSS. Default .expanded.

sourceMapStyle

Kind of source map to create for the CSS. Default .separateSources.

includeCharset

If the output is non-ASCII, whether to include @charset.

importers

Rules for resolving @import etc. for this compilation, used in order after any set globally. Default none.

functions

Functions for this compilation, overriding any with the same name previously set globally. Default none.

Throws

CompilerError if there is a critical error with the input, for example a syntax error. Some other kind of error if something goes wrong with the compiler infrastructure itself.

Return Value

CompilerResults with CSS and optional source map.

func compile(fileURL: URL, outputStyle: CssStyle, sourceMapStyle: SourceMapStyle, includeCharset: Bool, importers: [ImportResolver], functions: SassFunctionMap) async -> CompilerResults

Compile to CSS from a stylesheet file.

Declaration
Swift
public func compile(
    fileURL: URL,
    outputStyle: CssStyle = .expanded,
    sourceMapStyle: SourceMapStyle = .separateSources,
    includeCharset: Bool = false,
    importers: [ImportResolver] = [],
    functions: SassFunctionMap = [:]
) async throws -> CompilerResults
Parameters
fileURL

The URL of the file to compile. The file extension determines the expected syntax of the contents, so it must be css/scss/sass.

outputStyle

How to format the produced CSS. Default .expanded.

sourceMapStyle

Kind of source map to create for the CSS. Default .separateSources.

includeCharset

If the output is non-ASCII, whether to include @charset.

importers

Rules for resolving @import etc. for this compilation, used in order after fileURL’s directory and any set globally.. Default none.

functions

Functions for this compilation, overriding any with the same name previously set globally. Default none.

Throws

CompilerError if there is a critical error with the input, for example a syntax error. Some other kind of error if something goes wrong with the compiler infrastructure itself.

Return Value

CompilerResults with CSS and optional source map.

Lifecycle

var compilerProcessIdentifier: Int32?

The process ID of the embedded Sass compiler.

Not normally needed; could be used to adjust resource usage or maybe send it a signal if stuck. The process ID is reported after waiting for any [re]initialization to complete; a value of nil means that the compiler is broken or shutdown.

Declaration
Swift
public var compilerProcessIdentifier: Int32? { get async }

var compilerName: String?

The name of the underlying Sass implementation. nil if unknown.

Declaration
Swift
public var compilerName: String? { get async }

var compilerVersion: String?

The version of the underlying Sass implementation. For Dart Sass and LibSass this is in semver format. nil if unknown (never got a version).

Declaration
Swift
public var compilerVersion: String? { get async }

var compilerPackageVersion: String?

The version of the package implementing the compiler side of the embedded Sass protocol. Probably in semver format. nil if unknown (never got a version).

Declaration
Swift
public var compilerPackageVersion: String? { get async }

func reinit() async

Restart the embedded Sass compiler.

Normally a single instance of the compiler’s process persists across all invocations to compile(...) on this Compiler instance. This method stops the current compiler process and starts a new one: the intended use is for compilers whose resource usage escalates over time and need calming down. You probably don’t need to call it.

Any outstanding compilations are failed.

Throws an error if the compiler cannot be restarted due to error or because shutdownGracefully() has already been called.

Declaration
Swift
public func reinit() async throws

func shutdownGracefully() async

Shut down the compiler.

You must call this before the last reference to the Compiler is released.

Cancels any outstanding work and shuts down internal threads. There’s no way back from this state: to do more compilation you will need a new instance.

Declaration
Swift
public func shutdownGracefully() async