typst-nix/lib/typst-compile.nix

236 lines
7.3 KiB
Nix

{
lib,
hasSystem,
pkgs,
...
}:
let
compileTypst =
{
pkgs,
# package to take the typst binary from. can be a function from `pkgs` to your
# package
typstPackage ? pkgs.typst,
# possible values: pdf or html. other outputs (png, svg, bundle) are not supported,
# for now
format ? "pdf",
# root of the typst project
rootDir,
# main typst file
entrypoint ? "${rootDir}/main.typ",
# lockfile, representing the dependencies
lockfile ? "${rootDir}/typst.lock",
# exposed in Typst as `sys.inputs`. must be an attrset of `toStrings`-able values
inputs ? { },
# exposed in Typst as `sys.inputs`. must be an attrset of paths
inputFiles ? { },
# paths to fonts
fontPaths ? [ ],
# if set, Typst's own embedded fonts will be ignored
ignoreEmbeddedFonts ? false,
# UNIX timestamp exposed by datetime functions
creationTimestamp ? 0,
# pretty-format the output
pretty ? false,
pages ? null,
# see typst c --help
noPdfTags ? false,
# see typst c --help
ppi ? 144,
features ? [ ],
# an attrset of direct package overrides.
# type: `{ [String] :: [{ name: String, version: String, package: toString }] }`
# example: `@repo/name:1.0.0` would be expressed as
# `.repo = [ {name = "name"; version = "1.0.0"; package = ...; } ]`
# the reason for this format is that package name and version are often derived from
# the package content itself, so to allow expressing a package as a normal attrset,
# it need to contain its own name and version.
overridePackages ? { },
...
}:
let
typstPackage' = if builtins.isFunction typstPackage then typstPackage pkgs else typstPackage;
inputArgs = lib.flatten (
lib.mapAttrsToList (key: value: [
"--input"
"${key}=${builtins.toString value}"
]) inputs
);
inputFileArgs = lib.mapAttrsToList (
key: path:
" --input " + lib.escapeShellArg key + "=\"$(cat " + lib.escapeShellArg (toString path) + ")\""
) inputFiles;
features' = features ++ (lib.optional (format == "html") "html");
args = [
"typst"
"compile"
"--format"
format
"--root"
"${rootDir}"
"--ignore-system-fonts"
"--package-cache-path"
".cache/typst"
"--creation-timestamp"
(builtins.toString creationTimestamp)
"--ppi"
(builtins.toString ppi)
]
++ inputArgs
++ (lib.optional (
builtins.length fontPaths > 0
) "--font-path=${(lib.concatStringsSep ":" fontPaths)}")
++ (if ignoreEmbeddedFonts then [ "--ignore-embedded-fonts" ] else [ ])
++ (if pretty then [ "--pretty" ] else [ ])
++ (
if (pages != null) then
[
"--pages"
pages
]
else
[ ]
)
++ (if noPdfTags then [ "--no-pdf-tags" ] else [ ])
++ (
if (builtins.length features) > 0 then
[
"--features"
(lib.concatStringsSep "," features')
]
else
[ ]
)
++ [ entrypoint ];
ext = if format == "bundle" then "" else ".${format}";
lockfile' =
if builtins.pathExists lockfile then
builtins.fromJSON (builtins.readFile lockfile)
else
builtins.warn
"lockfile not found. If you have any dependencies, then you should describe them in `overridePackages`, or Typst won't find them!"
{ packages = [ ]; };
parseSpec =
spec:
let
parts = builtins.match "@([^/]+)/([^:]+):(.+)" spec;
in
assert lib.assertMsg (parts != null) "${spec} is not a valid package spec";
{
namespace = builtins.elemAt parts 0;
name = builtins.elemAt parts 1;
version = builtins.elemAt parts 2;
};
previewPackage =
{
name,
version,
hash,
}:
builtins.fetchTarball {
url = "https://packages.typst.org/preview/${name}-${version}.tar.gz";
sha256 = hash;
};
lockedPackages = lib.foldl' (
res: entry:
let
inherit (parseSpec entry.spec) namespace name version;
storeDir = previewPackage {
inherit name version;
hash = entry.hash;
};
in
assert lib.assertMsg (
namespace == "preview"
) "only @preview deps in the lock are supported at the moment";
lib.recursiveUpdate res { ${namespace}.${name}.${version} = storeDir; }
) { } lockfile'.packages;
overridePackages' = builtins.mapAttrs (
_: packages:
lib.foldl' (
acc:
{
name,
version,
package,
}:
lib.recursiveUpdate acc { ${name}.${version} = package; }
) { } packages
) overridePackages;
# NOTE: overridePackages used here! is overrides _everything_!
packages = lib.recursiveUpdate lockedPackages overridePackages';
linkDep =
{
namespace,
name,
version,
package,
}:
let
namespace' = lib.escapeShellArg namespace;
name' = lib.escapeShellArg name;
version' = lib.escapeShellArg version;
package' = lib.escapeShellArg "${package}";
in
assert lib.assertMsg (builtins.isString namespace) "`namespace` should be a string";
assert lib.assertMsg (builtins.isString name) "`name` should be a string";
assert lib.assertMsg (
builtins.isString version && builtins.match "^[0-9]+\.[0-9]+\.[0-9]+$" version != null
) "`version` should be a string and comply to the three-component version format";
# still use the escaped versions, to be safe. assertions above are for debug help
''
mkdir -p .cache/typst/${namespace'}/${name'}
ln -s ${package'} .cache/typst/${namespace'}/${name'}/${version'}
'';
linkDeps = lib.concatStringsSep "\n" (
lib.flatten (
lib.mapAttrsToList (
namespace: packages:
lib.mapAttrsToList (
name: packageVersions:
lib.mapAttrsToList (
version: package:
linkDep {
inherit
namespace
name
version
package
;
}
) packageVersions
) packages
) packages
)
);
in
assert lib.assertMsg (builtins.isAttrs inputs) "`inputs` must be an attrset";
assert lib.assertMsg (builtins.isAttrs inputFiles) "`inputFiles` must be an attrset";
pkgs.stdenv.mkDerivation {
name = "out${ext}";
src = rootDir;
buildInputs = with pkgs; [
coreutils
typstPackage'
];
buildPhase = ''
#!/bin/bash
set -euo pipefail
TMP="$(mktemp -d)"
cd "$TMP"
export HOME="$TMP"
${linkDeps}
${lib.escapeShellArgs args}${lib.concatStringsSep " " inputFileArgs} - >$out
'';
};
compileTypstSys = args: compileTypst ({ inherit pkgs; } // args);
in
{
config.lib.compileTypst = if hasSystem then compileTypstSys else compileTypst;
}