|
| 1 | +#!/usr/bin/env DENO_DIR=/tmp deno run --version=v2.1.2 |
| 2 | +// Imports |
| 3 | +import { STATUS_CODE as Status, STATUS_TEXT as StatusText } from "@std/http" |
| 4 | +import { banner as _banner, js, meta } from "@www/tools.ts" |
| 5 | + |
| 6 | +/** API: Minify css */ |
| 7 | +export default async function (request: Request) { |
| 8 | + if (request.method !== "POST") { |
| 9 | + return new Response(StatusText[Status.MethodNotAllowed], { status: Status.MethodNotAllowed }) |
| 10 | + } |
| 11 | + if (new URL(`https://${request.headers.get("Host")}`).hostname !== new URL(`https://${Deno.env.get("ALLOWED_HOST") || "localhost"}`).hostname) { |
| 12 | + return new Response("Custom builds may not be linked directly", { status: Status.Forbidden }) |
| 13 | + } |
| 14 | + try { |
| 15 | + const options = await request.json() |
| 16 | + const bundled = await js("@mizu/render/client", { |
| 17 | + banner: _banner.replace(`${meta.name} — ${meta.version}\n`, `${meta.name} — ${meta.version} — Custom build (${new Date().toDateString()})\n`), |
| 18 | + minify: options.minify === true ? "terser" : false, |
| 19 | + format: ["iife", "esm"].includes(options.format) ? options.format : throws("format: must be 'iife' or 'esm'"), |
| 20 | + raw: { |
| 21 | + define: { |
| 22 | + "globalThis.MIZU_CUSTOM_DEFAULTS_CONTEXT": options.context ? options.context : "null", |
| 23 | + "globalThis.MIZU_CUSTOM_DEFAULTS_WARN": options.console?.includes("warn") ? "console.warn" : "false", |
| 24 | + "globalThis.MIZU_CUSTOM_DEFAULTS_DEBUG": options.console?.includes("debug") ? "console.debug" : "false", |
| 25 | + }, |
| 26 | + }, |
| 27 | + overrides: { |
| 28 | + imports: { |
| 29 | + "./defaults.ts": Array.isArray(options.directives) && options.directives.every((name) => typeof name === "string") |
| 30 | + ? `data:text/javascript;base64,${ |
| 31 | + btoa( |
| 32 | + ` |
| 33 | + import _mizu from "@mizu/mizu" |
| 34 | + ${options.directives.map((name: string, i: number) => `import _${i} from "@mizu/${name}"`).join("\n")} |
| 35 | + export default [${options.directives.map((_: string, i: number) => `_${i}`).join(", ")}].flat(Infinity) |
| 36 | + `.split("\n").map((line) => line.trim()).filter(Boolean).join("\n"), |
| 37 | + ) |
| 38 | + }` |
| 39 | + : throws("directives: must be an array of string"), |
| 40 | + }, |
| 41 | + }, |
| 42 | + }) |
| 43 | + return new Response(bundled, { headers: { "Content-Type": "application/javascript; charset=utf-8" } }) |
| 44 | + } catch (error) { |
| 45 | + if (error instanceof TypeError) { |
| 46 | + return new Response(error.message, { status: Status.BadRequest }) |
| 47 | + } |
| 48 | + return new Response(error.message, { status: Status.InternalServerError }) |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +/** Throws a `TypeError` with the provided message. */ |
| 53 | +function throws(message: string): never { |
| 54 | + throw new TypeError(message) |
| 55 | +} |
0 commit comments