Skills de design : hallmark (MIT) et impeccable (Apache 2.0)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
Claude committed 2026-11-27 15:34:11 +00:00
1 parent bc4148c8fe
commit 0cef90ceae
251 files changed
+41856

No files matched your search

@@ -0,0 +1 @@
0.1.31
@@ -0,0 +1,98 @@
{
"craft": {
"description": "Deprecated compatibility alias for an ordinary Impeccable new-work request. It adds no behavior; natural build and redesign requests use the same flow.",
"argumentHint": "[feature description]"
},
"init": {
"description": "Sets up a project for impeccable. Runs a multi-round discovery interview when context is missing and writes PRODUCT.md (strategic: users, brand, principles); pre-configures live mode; then recommends the best commands to run next. Every other command reads these files before doing work. Use once per project.",
"argumentHint": ""
},
"document": {
"description": "Generate a DESIGN.md file that captures the current visual design system. Auto-extracts colors, typography, spacing, radii, and component patterns from the codebase, then asks the user to confirm descriptive language for atmosphere and color character. Follows the Google Stitch DESIGN.md format so the file is tool-compatible. Use when you need a visual design spec an AI agent can follow to stay on-brand.",
"argumentHint": ""
},
"extract": {
"description": "Pull reusable patterns, components, and design tokens into the design system. Identifies repeated patterns and consolidates them. Use when you have drift across the codebase and want to bring things back to a consistent system.",
"argumentHint": "[target]"
},
"live": {
"description": "Interactive live variant mode. Select elements in the browser, pick a design action, and get AI-generated HTML+CSS variants hot-swapped via HMR. Requires a running dev server. Use when you want to visually experiment with design alternatives in real time.",
"argumentHint": ""
},
"generate": {
"description": "Agent-driven live variant generation. Boots live mode, finds the named element on the open page, scrolls the browser to it, and delivers N variants in the requested direction for the user to cycle and accept. Use for requests that name an element and a direction, like 'generate 3 bold variants of the pricing cards', skipping manual element picking.",
"argumentHint": "[count] [direction] variants of [element]"
},
"adapt": {
"description": "Adapt designs to work across different screen sizes, devices, contexts, or platforms. Implements breakpoints, fluid layouts, and touch targets. Use when the user mentions responsive design, mobile layouts, breakpoints, viewport adaptation, or cross-device compatibility.",
"argumentHint": "[target] [context (mobile, tablet, print...)]"
},
"animate": {
"description": "Review a feature and enhance it with purposeful animations, micro-interactions, and motion effects that improve usability and delight. Use when the user mentions adding animation, transitions, micro-interactions, motion design, hover effects, or making the UI feel more alive.",
"argumentHint": "[target]"
},
"audit": {
"description": "Run technical quality checks across accessibility, performance, theming, responsive design, and anti-patterns. Generates a scored report with P0-P3 severity ratings and actionable plan. Use when the user wants an accessibility check, performance audit, or technical quality review.",
"argumentHint": "[area (feature, page, component...)]"
},
"bolder": {
"description": "Amplify safe or boring designs to make them more visually interesting and stimulating. Increases impact while maintaining usability. Use when the user says the design looks bland, generic, too safe, lacks personality, or wants more visual impact and character.",
"argumentHint": "[target]"
},
"clarify": {
"description": "Improve unclear UX copy, error messages, microcopy, labels, and instructions to make interfaces easier to understand. Use when the user mentions confusing text, unclear labels, bad error messages, hard-to-follow instructions, or wanting better UX writing.",
"argumentHint": "[target]"
},
"colorize": {
"description": "Add strategic color to features that are too monochromatic or lack visual interest, making interfaces more engaging and expressive. Use when the user mentions the design looking gray, dull, lacking warmth, needing more color, or wanting a more vibrant or expressive palette.",
"argumentHint": "[target]"
},
"critique": {
"description": "Evaluate design from a UX perspective, assessing visual hierarchy, information architecture, emotional resonance, cognitive load, and overall quality with quantitative scoring, persona-based testing, automated anti-pattern detection, and actionable feedback. Use when the user asks to review, critique, evaluate, or give feedback on a design or component.",
"argumentHint": "[area (feature, page, component...)]"
},
"delight": {
"description": "Add moments of joy, personality, and unexpected touches that make interfaces memorable and enjoyable to use. Elevates functional to delightful. Use when the user asks to add polish, personality, animations, micro-interactions, delight, or make an interface feel fun or memorable.",
"argumentHint": "[target]"
},
"distill": {
"description": "Strip designs to their essence by removing unnecessary complexity. Great design is simple, powerful, and clean. Use when the user asks to simplify, declutter, reduce noise, remove elements, or make a UI cleaner and more focused.",
"argumentHint": "[target]"
},
"harden": {
"description": "Make interfaces production-ready: error handling, i18n, text overflow, edge case management, and resilience under real-world data. Use when the user asks to harden, make production-ready, handle edge cases, add error states, or fix overflow and i18n issues.",
"argumentHint": "[target]"
},
"onboard": {
"description": "Design onboarding flows, first-run experiences, and empty states that guide new users to value. Covers welcome screens, account setup, progressive disclosure, contextual tooltips, feature announcements, and activation moments. Use when the user mentions onboarding, first-time users, empty states, activation, getting started, new user flows, or the aha moment.",
"argumentHint": "[target]"
},
"layout": {
"description": "Improve layout, spacing, and visual rhythm. Fixes monotonous grids, inconsistent spacing, and weak visual hierarchy. Use when the user mentions layout feeling off, spacing issues, visual hierarchy, crowded UI, alignment problems, or wanting better composition.",
"argumentHint": "[target]"
},
"optimize": {
"description": "Diagnoses and fixes UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.",
"argumentHint": "[target]"
},
"overdrive": {
"description": "Pushes interfaces past conventional limits with technically ambitious implementations — shaders, spring physics, scroll-driven reveals, 60fps animations. Use when the user wants to wow, impress, go all-out, or make something that feels extraordinary.",
"argumentHint": "[target]"
},
"polish": {
"description": "Performs a final quality pass fixing alignment, spacing, consistency, and micro-detail issues before shipping. Use when the user mentions polish, finishing touches, pre-launch review, something looks off, or wants to go from good to great.",
"argumentHint": "[target]"
},
"quieter": {
"description": "Tones down visually aggressive or overstimulating designs, reducing intensity while preserving quality. Use when the user mentions too bold, too loud, overwhelming, aggressive, garish, or wants a calmer, more refined aesthetic.",
"argumentHint": "[target]"
},
"shape": {
"description": "Plan UX and UI before code. Runs a discovery interview (one round by default), uses visual probes when available, and produces a user-confirmed design brief for implementation.",
"argumentHint": "[feature to shape]"
},
"typeset": {
"description": "Improves typography by fixing font choices, hierarchy, sizing, weight, and readability so text feels intentional. Use when the user mentions fonts, type, readability, text hierarchy, sizing looks off, or wants more polished, intentional typography.",
"argumentHint": "[target]"
}
}
@@ -0,0 +1,121 @@
[
{
"family": "Betania Patmos GDL",
"weight": 400,
"category": "handwriting",
"variable": false,
"reason": "not loaded or no lettering"
},
{
"family": "Betania Patmos In GDL",
"weight": 400,
"category": "handwriting",
"variable": false,
"reason": "not loaded or no lettering"
},
{
"family": "Doto",
"weight": 300,
"category": "sans",
"variable": true,
"reason": "not loaded or no lettering"
},
{
"family": "Doto",
"weight": 700,
"category": "sans",
"variable": true,
"reason": "not loaded or no lettering"
},
{
"family": "Jacquard 12 Charted",
"weight": 400,
"category": "display",
"variable": false,
"reason": "not loaded or no lettering"
},
{
"family": "Jacquard 24 Charted",
"weight": 400,
"category": "display",
"variable": false,
"reason": "not loaded or no lettering"
},
{
"family": "Jacquarda Bastarda 9 Charted",
"weight": 400,
"category": "display",
"variable": false,
"reason": "not loaded or no lettering"
},
{
"family": "Jersey 10 Charted",
"weight": 400,
"category": "display",
"variable": false,
"reason": "not loaded or no lettering"
},
{
"family": "Jersey 15 Charted",
"weight": 400,
"category": "display",
"variable": false,
"reason": "not loaded or no lettering"
},
{
"family": "Jersey 20 Charted",
"weight": 400,
"category": "display",
"variable": false,
"reason": "not loaded or no lettering"
},
{
"family": "Jersey 25 Charted",
"weight": 400,
"category": "display",
"variable": false,
"reason": "not loaded or no lettering"
},
{
"family": "Micro 5 Charted",
"weight": 400,
"category": "display",
"variable": false,
"reason": "not loaded or no lettering"
},
{
"family": "Montserrat Underline",
"weight": 400,
"category": "sans",
"variable": true,
"reason": "not loaded or no lettering"
},
{
"family": "Montserrat Underline",
"weight": 700,
"category": "sans",
"variable": true,
"reason": "not loaded or no lettering"
},
{
"family": "Redacted",
"weight": 400,
"category": "display",
"variable": false,
"reason": "not loaded or no lettering"
},
{
"family": "Yarndings 12 Charted",
"weight": 400,
"category": "display",
"variable": false,
"reason": "not loaded or no lettering"
},
{
"family": "Yarndings 20 Charted",
"weight": 400,
"category": "display",
"variable": false,
"reason": "not loaded or no lettering"
}
]
@@ -0,0 +1 @@
{"schema":2,"text":"The quick brown fox jumps over the lazy dog 0123456789 HAMBURGEVONS","textCaps":"THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG 0123456789 HAMBURGEVONS","sizes":[48,14,"48c"],"features":["advance","advTall","advX","advCV","gap","xRatio","descRatio","stemW","contrast","serif","roundFrac","densTall","densX","runDensity","vprof0","vprof1","vprof2","vprof3","vprof4","vprof5","vprof6","vprof7","vprof8","vprof9","hrun25","hrun50","hrun75","hrun90","vrun25","vrun50","vrun75","vrun90","colq25","colq75","wq25","wq75"],"categories":["sans","serif","display","handwriting","mono"],"entries":[["ABeeZee",400,0,0,"0hy0hd0j408u04n0ke08w0410tz0rs0660cc0d41he00800802c04v03w04903y04a02c01h03v04305309h03i0460890h00ij0ra0fn0k9","0ir0ir0ir07g03y0kf09604r0tp0my06o0e50ff1h900700902i04t04104e04y03d02k00s04k04u0680cu04a0520ah0i10i80qw0gs0jq","0j10j1___0az057______0460uo0rs03n0cp___1ch00000002104d03g03w03m03904403304204705409y03k04a08e0i90kx0rs0ef0kr"],["ADLaM Display",400,2,0,"0i30id0ht08d03g0il08n0660xz0rw08r0gx0ik1h600600a02305704i04s04i03002q00j0600680800ez04z06l0fi0ni0hv0pv0ex0k3","0hs0is0hs07g02z0jh08f06j0x10kj04t0hu0jr1fq00400a02905504g04r05603802b00406a06p0a40fc05e07p0gn0mg0iy0pt0gt0js","0jb0jb___0an041___08n06o0xe0rh02p0h0___17u00100301m04f03p04303h03j04k02b06i06u08m0g705g07g0gh0qq0nt0rs0f00n2"],["AR One Sans",400,0,1,"0ig0ig0hv0880570k808n03q0u20ww0420bm0cw1gx00800802j04n03s04a03q04e02601v03o03w04k09c03b03q07c0fz0io0rq0g50j1","0hs0hs0hs07903y0kc07p04j0ti___03r0dy0fs1hd00300b01e05403w04e04s04402b01g04e04o05x0cj04304p0ah0hg0iw0rm0gs0ir","0i60ig___09l05s______03u0u30wy01b0bn___1bn00000002904b03b03y03i03404203b03o03y04h0ag03e03v07b0f90l10rs0f00mi"],["AR One Sans",700,0,1,"0jm0jm0jw06j04m0k808n05q0vl0uz08k0fz0hb1ef00700902404x03z04c04403x02f01k05n06007r0fq04y05v0el0ke0jn0rs0hv0lc","0jj0kj0jj06c03x0l509506a0vs0of09m0gs0i41as00600902804s03y04a04q03p02e01e06506m0a70gl05c06m0fv0l50jt0rq0ik0li","0k70k7___07r057______05v0ux0v203l0g6___18d00000001u04k03i04003i03a04h02n05q0680820gu0540640ej0pz0ns0rs0hb0nn"],["Abel",400,0,0,"0du0f00d905x04m0jr08302s0qq0rs0150az0c61vn00500802n04m03w04903u04802201w02q02t03b05n02p03606m0gz0j10rp0d90fk","0di0ff0di06g03v0jr07c03w0qp___0140ec0g01x300200a01k05103z04d04q03z02b01l03i03x04r09903q04h09q0hz0j80qz0di0ff","0fn0fn___048058______02u0rf0rs0000aw___1q300000002e04603h04203e03a03x03402s02v03b05l02o03706f0j00m80rs0f20fn"],["Abhaya Libre",400,1,0,"0j10kr0ig07f02w0i408303r1fn22t0d00aa0bb1ly00900e03d04f04804k04503h02d00l03i03u04a06501j02b05f0cf0hb0ph0g50lx","0is0k90ia0b402z0hq08a04u16u1fq0c00dc0f11le00700e03o04l04d04l05c02i02100604k04y05v08o02i03v07x0fs0h30ow0gt0mq","0lo0lo___09b04z___05c04a1rw25v0b80af___1d300000703503q03j03903x03l03b03503w04a04t06d01k02a0670cj0ni0rs0hk0ri"],["Abhaya Libre",700,1,0,"0jm0lx0jm07502b0ig0830551vv1hu0dl0c40de1kj00800e03404h04f04q04203i02d00k04r05605n07j01l02w0800h40hw0py0hb0mh","0it0ks0it0bb01z0i208905w1gg1470cc0ee0h91km00600d03e04m04j04s05802j02100605f05z06p09102f04k0a60i60h70oy0gt0ks","0p60p6___07i04z___05j05y2f71p70dw0cb___1br00000702r03t03p03d03y03s03e02v04z05y06f08001m02t08y0k40ol0rs0l30sp"],["Aboreto",400,2,0,"0gq0gq___0br07i___0570311370rs03f07x___1a700000202j03k03k03x03r03k03k03b03003103d03y01j02h0550ab0hl0rs0cp0mh","0ge0ge___0cs06r___07c048113___02q0bc___1cj00100301b04303k03u04d03l03t03603v04904m06402g03y07e0fo0ja0rs0bk0l7","0gq0gq___0br07i___0570311370rs03f07x___1a700000202j03k03k03x03r03k03k03b03003103d03y01j02h0550ab0hl0rs0cp0mh"],["Abril Fatface",400,2,0,"0ku0ku0ij0dm01r0hh09907432j0z10cz0f30g81qj00900b02g04q04v05104702t02m00k05q07407g08401c04x0e10lz0hl0q20hd0nq","0iq0jq0i90c802z0hg09607j1xp0tt0cq0hl0hw1lw00700b02q04q04u04z04t02g02m00706o07j07z09i02k06t0gj0nv0h60pt0fs0mo","0mi0mi___08q02w___09607x3p715m0990fa___1hf00100202103u03z04003g03u03y02o05707z08108v01b04f0en0rh0q10rs0j10qj"],["Abyssinica SIL",400,1,0,"0hk0jk0if07n02b0ij08n04316b1ss0930c30d11jf00900903504m04304n04903c02l00n03v04704w08m02903606x0ff0hu0pb0gp0k5","0hp0io0hp0lg01z0jc09104y11t1j507f0ej0g21if00800903904n04404l05702v02h00804p05306a0a303704d0930hm0hz0pp0fq0jo","0ks0ks___07u042______04h1811yk07v0by___1c500000002q04003d03u03803d04003b04b04j05809e02d03d07v0g20nr0rs0gr0pz"],["Aclonica",400,0,0,"0jo0g70j406l02w0ij08p05u1bm0rs0fd0f00fh1le00500a02e05604z05504h03l01j00305o05z06q09p03704s0c40ju0hj0n50gs0m0","0kd0gb0jd08u0210i408l06i1920z20hw0gm0hh1i200400b02t05e05704105g03h01000206806u07q0cp03q05h0de0jq0hj0mp0hb0mf","0ow0ow___091042___0a807u1kq0rt0c90ft___17i00300401v04603r04303h03m04602i07l07v08a0dv03t0640fa0rk0nx0rs0hd0qm"],["Acme",400,0,0,"0fn0hd0fn07t02b0ij07s04q0sh0v901n0fh0h41tf00500c02305e04j05404o03602600804j04y0650bj04905g0ba0ib0hd0nq0eh0hd","0fr0gq0er0dx02y0je08705f0sn0l302h0h60j51p500400b02805404f04w05603c02200605405l0860cv04z06k0dx0ji0i20nw0er0ip","0iq0iq___09j04e___02x05h0u10wp00h0ff___1fj00000001s04i03n03l04303n04302g05805o0720dw04m0670cz0p20my0rs0em0l2"],["Actor",400,0,0,"0fm0g70fm08t03h0ii08o03h0tr0rs0580bj0d01r900a00l02u05004g04o04q02x02500703a03j04808103003l07j0f90gs0n80eg0hx"Line truncated
@@ -0,0 +1,9 @@
# Engine binary digests for the pinned ENGINE_VERSION: <engine-version> <asset> <sha256>.
# The launchers, the npm shim, `impeccable install` and scripts/fetch-engine.mjs verify
# every engine download against this file. Written by
# `node scripts/check-engine-release.mjs --record` after each engine release.
0.1.31 impeccable-darwin-arm64 0d96cf802af6c52f3ed0925a409c7f4a1eda6a4c4b8274ff545b1d23e8dd6ae6
0.1.31 impeccable-darwin-x64 af28d77242fc345f11ade5075c304beef2e938a3df70905a95f9864708ee0a2a
0.1.31 impeccable-linux-x64 01c642862b0e505277bb8810b1a74aacc42b2b38eb24bc69bc0bcf324089be77
0.1.31 impeccable-linux-arm64 fd488471ae6df728e260bb54c26d0f7fa9235765777f8ee2ff28e9d3dba0dc6b
0.1.31 impeccable-windows-x64.exe f6606bbf6bd8993e2b0dab98261c27659a865e7dcbc775986d40e8808527ff47
+342
View File
@@ -0,0 +1,342 @@
#!/bin/sh
# Impeccable launcher. Runs the platform binary shipped next to this script:
# <this dir>/bin/<os>-<arch>/impeccable
# Order: $IMPECCABLE_BIN, the sibling binary, ~/.impeccable/bin/impeccable,
# the version-pinned cache, then `impeccable` on PATH. Never needs Node.
# The unversioned home binary and the PATH candidate are validated with the
# engine-probe handshake first: the retired 3.x npm CLI also installed a bin
# named `impeccable`, and exec'ing it would fail every verb with
# "Unknown command". The sibling binary must also report the version in
# VERSION: it is gitignored, so a skill upgrade that copies files over this
# directory leaves the old engine in place. A local build of the same version
# passes, which is why it is not hashed. IMPECCABLE_BIN is the operator's
# explicit choice and is exec'd without a probe. The version-pinned cache and
# the download are verified against engine-checksums.txt (next to this
# script), never against anything published beside the binary; a
# <binary>.verified stamp holding the manifest digest and the binary's size
# skips rehashing until either changes or the binary is newer than the stamp.
# No path hashes on every run: hooks run this launcher on every edit.
set -eu
# True when the candidate answers the engine handshake (prints
# "impeccable-engine <version>", exit 0). Quiet and fast (<100ms).
# IMPECCABLE_LAUNCHER_PROBE marks the child as a probe: a copy of this
# launcher reached recursively (e.g. symlinked onto PATH as `impeccable`)
# then skips its own probes and refuses to download, so probing stays cheap
# and can never loop.
probe_ok() {
probe_out=$(IMPECCABLE_LAUNCHER_PROBE=1 "$1" engine-probe 2>/dev/null) || return 1
case "$probe_out" in
impeccable-engine*) probe_version=${probe_out#impeccable-engine }; return 0 ;;
esac
return 1
}
probing=${IMPECCABLE_LAUNCHER_PROBE:-}
# Space, tab and CR, made once: hooks run this launcher on every edit and turn
# end, and every process it starts before the engine costs real time on a busy
# Windows machine (#1237), so the hot path below sticks to shell builtins.
ws=$(printf ' \t\r')
# Sets $digest_out to the digest engine-checksums.txt records for engine
# version $1 and asset $2 (lines are "<version> <asset> <sha256>"), empty when
# there is none.
# A CR is a separator too (CRLF checkouts), and a last line with no newline
# still counts.
manifest_digest() {
digest_out=""
[ -f "$manifest" ] || return 0
while IFS="$ws" read -r m_version m_asset m_sum _ || [ -n "$m_version" ]; do
case "$m_version" in ''|'#'*) continue ;; esac
if [ "$m_version" = "$1" ] && [ "$m_asset" = "$2" ]; then
digest_out=$m_sum
return 0
fi
done < "$manifest"
return 0
}
# Sets $expected (and, on Windows on ARM, which runs x64 binaries,
# $expected_x64) from engine-checksums.txt.
read_expected() {
manifest_digest "$version" "$asset"
expected=$digest_out
expected_x64=""
if [ "$os" = windows ] && [ "$arch" = arm64 ]; then
manifest_digest "$version" impeccable-windows-x64.exe
expected_x64=$digest_out
fi
}
# Sets $size to the byte count of the cached binary (BSD wc pads it).
cached_size() {
size=$(wc -c < "$cached") || size=""
size=${size##* }
}
# Sets $actual to the sha256 of $1, empty when no hash tool works.
hash_file() {
actual=""
if command -v shasum >/dev/null 2>&1; then
if digest=$(shasum -a 256 "$1" 2>/dev/null); then actual=${digest%% *}; fi
elif command -v sha256sum >/dev/null 2>&1; then
if digest=$(sha256sum "$1" 2>/dev/null); then actual=${digest%% *}; fi
fi
}
# This script's directory without dirname or a subshell: what dirname "$0"
# gives, made absolute by a cd there and back. A backslash separates too:
# Windows hook commands spell the launcher C:\...\scripts\impeccable (#1462).
case $0 in
*/*|*\\*) dir=${0%[/\\]*} ;;
*) dir=. ;;
esac
[ -n "$dir" ] || dir=/
caller_pwd=$PWD
CDPATH= cd -- "$dir" || { echo "impeccable: cannot enter the launcher directory $dir" >&2; exit 127; }
dir=$PWD
skill_dir=${dir%/*}
[ -n "$skill_dir" ] || skill_dir=/
cd -- "$caller_pwd" || { echo "impeccable: cannot return to $caller_pwd" >&2; exit 127; }
# VS Code syncs a plugin without the executable bit. Its hooks run this through
# sh, so restore the bit for the commands the skill runs directly (#1249).
[ -x "$0" ] || chmod +x "$0" 2>/dev/null || :
manifest="$dir/engine-checksums.txt"
# What the binary needs to know about its home: the skill directory (for
# reference/*.md and command-metadata.json) and how to name itself in the
# commands it prints. Exported BEFORE any exec below, including the
# IMPECCABLE_BIN override: an engine binary reached with no IMPECCABLE_SKILL_DIR
# cannot find reference/*.md (so native platform refs never inline) or read its
# own version (so UPDATE_AVAILABLE never fires). Setting it here covers every
# candidate the launcher can exec.
: "${IMPECCABLE_SKILL_DIR:=$skill_dir}"
: "${IMPECCABLE_SELF:=$0}"
export IMPECCABLE_SKILL_DIR IMPECCABLE_SELF
if [ -n "${IMPECCABLE_BIN:-}" ] && [ -x "${IMPECCABLE_BIN}" ]; then
exec "${IMPECCABLE_BIN}" "$@"
fi
# Windows names itself in the environment, which saves a process there; one
# uname covers the rest. PROCESSOR_ARCHITECTURE is what impeccable.cmd reads,
# so both launchers pick the same cached engine (AMD64 under x64 Git Bash on
# ARM64, as uname -m reported before).
if [ "${OS:-}" = Windows_NT ]; then
sys="Windows_NT ${PROCESSOR_ARCHITECTURE:-unknown}"
else
sys=$(uname -sm 2>/dev/null) || sys="unknown unknown"
fi
case "${sys%% *}" in
Darwin) os=darwin ;;
Linux) os=linux ;;
MINGW*|MSYS*|CYGWIN*|Windows_NT) os=windows ;;
*) os=unknown ;;
esac
case "${sys##* }" in
arm64|aarch64|ARM64) arch=arm64 ;;
x86_64|amd64|AMD64) arch=x64 ;;
*) arch=unknown ;;
esac
version=""
[ -f "$dir/VERSION" ] && { IFS="$ws" read -r version _ < "$dir/VERSION" || :; }
bin="$dir/bin/$os-$arch/impeccable"
[ "$os" = windows ] && bin="$bin.exe"
# Lost the executable bit in transit (zip extraction, some copiers).
if [ -f "$bin" ] && { [ -x "$bin" ] || chmod +x "$bin" 2>/dev/null; }; then
if [ -n "$probing" ] || [ -z "$version" ] || { probe_ok "$bin" && [ "$probe_version" = "$version" ]; }; then
exec "$bin" "$@"
fi
echo "impeccable: skipping $bin: it reports engine ${probe_version:-unknown} but this skill pins $version; delete it to stop this warning" >&2
fi
# On Windows (an MSYS/Git Bash shell) the cached names carry .exe so this
# launcher and impeccable.cmd share one cache.
exe=""
[ "$os" = windows ] && exe=".exe"
home_bin="${HOME:-/nonexistent}/.impeccable/bin/impeccable$exe"
if [ -z "$probing" ] && [ -x "$home_bin" ] && probe_ok "$home_bin"; then
exec "$home_bin" "$@"
fi
# Version-pinned user cache, filled by the download below or by `impeccable update`.
cache_root="${IMPECCABLE_HOME:-${HOME:-/nonexistent}/.impeccable}"
cached="$cache_root/bin/$version/impeccable$exe"
asset="impeccable-$os-$arch"
[ "$os" = windows ] && asset="$asset.exe"
if [ -n "$version" ] && [ -x "$cached" ]; then
read_expected
cached_size
stamp=""
stamp_size=""
{ IFS="$ws" read -r stamp stamp_size _ < "$cached.verified"; } 2>/dev/null || :
if [ -n "$stamp" ] && [ "$stamp_size" = "$size" ] && { [ "$stamp" = "$expected" ] || [ "$stamp" = "$expected_x64" ]; } && [ ! "$cached" -nt "$cached.verified" ]; then
exec "$cached" "$@"
fi
hash_file "$cached"
if [ -n "$actual" ] && { [ "$actual" = "$expected" ] || [ "$actual" = "$expected_x64" ]; }; then
{ echo "$actual $size" > "$cached.verified"; } 2>/dev/null || :
exec "$cached" "$@"
fi
echo "impeccable: cannot verify the cached engine $cached against $manifest; not using it" >&2
fi
if [ -z "$probing" ] && command -v impeccable >/dev/null 2>&1 && probe_ok impeccable; then
exec impeccable "$@"
fi
# Last resort: fetch this version's binary for the current platform from the
# public release channel into the user cache. Needs network; sandboxes without
# egress preinstall the binary on PATH instead.
setup_help() {
echo "Engine $version setup needs network access and write permission to $cache_root/bin/$version." >&2
echo "Run this launcher ($0) with engine-probe in a terminal that has those permissions, then retry the original command." >&2
echo "Alternatively, set IMPECCABLE_HOME to a writable cache location, or IMPECCABLE_BIN to a preinstalled engine binary." >&2
}
fetch_url() {
http_status=""
download_host=""
fetch_error=""
if command -v curl >/dev/null 2>&1; then
fetch_result=0
metadata=$(curl -fsSL --retry 2 -w '%{http_code} %{url_effective} %{errormsg}' -o "$tmp" "$1" 2>/dev/null) || fetch_result=$?
http_status=${metadata%% *}
effective_url=${metadata#* }
curl_msg=${effective_url#* }
effective_url=${effective_url%% *}
fetch_error="curl exit $fetch_result${curl_msg:+: $curl_msg}"
# Only the authority is needed, never the signed storage URL's query.
download_host=${effective_url#*://}
download_host=${download_host%%/*}
download_host=${download_host##*@}
case "$download_host" in
\[*) download_host=${download_host%%]*}] ;;
*) download_host=${download_host%%:*} ;;
esac
download_host=$(printf '%s' "$download_host" | tr '[:upper:]' '[:lower:]')
return "$fetch_result"
elif command -v wget >/dev/null 2>&1; then
fetch_result=0
wget_out=$(wget -O "$tmp" "$1" 2>&1) || fetch_result=$?
newline='
'
fetch_error="wget exit $fetch_result: ${wget_out##*$newline}"
return "$fetch_result"
else
return 1
fi
}
# SIGKILL or a crash skips the traps below and strands the staging file, so
# each download first removes parts in any version's cache that are an hour
# idle and whose owner PID is gone (the age covers a curl outliving its
# launcher). A cache it cannot write is reported later, never here.
sweep_stale_parts() {
find "$cache_root/bin" -mindepth 2 -maxdepth 2 -type f -name '.impeccable.part.*' -mmin +60 2>/dev/null |
while IFS= read -r part; do
owner=${part##*.part.}
case "$owner" in ''|*[!0-9]*) continue ;; esac
kill -0 "$owner" 2>/dev/null || rm -f "$part" 2>/dev/null || :
done
}
check_download() {
download_file=${1:-$tmp}
if [ ! -f "$download_file" ]; then
echo "impeccable: download completed but the file was removed before execution: $url; check your antivirus quarantine or logs. Refusing to continue; do not disable protection." >&2
exit 127
fi
if [ ! -s "$download_file" ]; then
rm -f "$download_file"
echo "impeccable: downloaded file is empty: $url; refusing the unverified download" >&2
exit 127
fi
}
if [ -n "$probing" ]; then
# Inside another launcher's probe: no download, fail fast and quiet.
exit 127
fi
if [ -n "$version" ] && [ "$os" != unknown ] && [ "$arch" != unknown ]; then
base="${IMPECCABLE_DOWNLOAD_BASE:-https://github.com/pbakaus/impeccable/releases/download}"
url="$base/engine-v$version/$asset"
read_expected
# Fail closed before any network traffic or cache write.
if [ -z "$expected" ] && [ -z "$expected_x64" ]; then
echo "impeccable: no checksum for engine $version ($asset) in $manifest; refusing the unverified download" >&2
exit 127
fi
sweep_stale_parts
tmp="$cache_root/bin/$version/.impeccable.part.$$"
# An interrupted download (Ctrl-C, a hook timeout) would otherwise leave the
# PID-named staging file behind for good. The handlers must exit explicitly.
cleanup() { rm -f "$tmp" 2>/dev/null || :; }
trap 'cleanup; exit 129' HUP
trap 'cleanup; exit 130' INT
trap 'cleanup; exit 143' TERM
if ! mkdir -p "$cache_root/bin/$version" 2>/dev/null; then
echo "impeccable: engine $version is not installed; cannot create cache directory: $cache_root/bin/$version" >&2
setup_help
exit 127
fi
# Check the actual staging file, not just directory existence: a cache from
# an earlier run can be readable but no longer writable inside a sandbox.
if ! (umask 077; : > "$tmp") 2>/dev/null; then
echo "impeccable: engine $version is not installed; cannot write to cache directory: $cache_root/bin/$version" >&2
setup_help
exit 127
fi
fetched=0
if [ -n "$expected" ] && fetch_url "$url"; then
fetched=1
elif [ -n "$expected_x64" ]; then
# Windows on ARM runs x64 binaries; fall back when no arm64 asset exists.
url="$base/engine-v$version/impeccable-windows-x64.exe"
expected=$expected_x64
fetch_url "$url" && fetched=1
fi
if [ "$fetched" = 1 ]; then
check_download
# No sha256 tool refuses the download too.
hash_file "$tmp"
check_download
if [ -z "$actual" ]; then
rm -f "$tmp"
echo "impeccable: cannot verify $url (no sha256 tool, or hashing failed); refusing the unverified download" >&2
exit 127
fi
if [ "$actual" != "$expected" ]; then
rm -f "$tmp"
echo "impeccable: checksum mismatch downloading $url" >&2
exit 127
fi
check_download
if ! chmod +x "$tmp" 2>/dev/null; then
check_download
rm -f "$tmp"
echo "impeccable: could not make the verified download executable: $url" >&2
exit 127
fi
check_download
if ! mv -f "$tmp" "$cached" 2>/dev/null; then
check_download
rm -f "$tmp"
echo "impeccable: could not cache the verified download: $url" >&2
exit 127
fi
check_download "$cached"
cached_size
{ echo "$actual $size" > "$cached.verified"; } 2>/dev/null || :
exec "$cached" "$@"
fi
rm -f "$tmp" 2>/dev/null
case "$http_status" in
5[0-9][0-9])
case "$download_host" in
github.com|*.github.com|githubusercontent.com|*.githubusercontent.com)
echo "impeccable: could not download engine $version: GitHub's downloads are failing right now (HTTP $http_status from $download_host). This is an outage on GitHub's side, not a problem with your setup or the CLI, so updating won't help. Check https://www.githubstatus.com and run the same command again once GitHub has recovered." >&2 ;;
*)
echo "impeccable: could not download engine $version: $download_host is failing right now (HTTP $http_status), a server error on $download_host's side. Try again later." >&2 ;;
esac
exit 127 ;;
esac
echo "impeccable: could not download engine $version from $url${fetch_error:+ ($fetch_error)}; check network access, the release URL, and curl or wget availability." >&2
setup_help
exit 127
fi
echo "impeccable: no engine binary for $os-$arch found (looked in $bin, $cached, PATH)." >&2
echo "Download impeccable-$os-$arch from https://github.com/pbakaus/impeccable/releases (tag engine-v$version) into $cache_root/bin/$version/impeccable$exe (then chmod +x), or set IMPECCABLE_BIN to a preinstalled engine binary. Docs: https://impeccable.style" >&2
exit 127
@@ -0,0 +1,363 @@
@echo off
setlocal
rem Impeccable launcher (Windows). Runs bin\windows-<arch>\impeccable.exe next
rem to this file, else a cached or freshly downloaded engine binary.
rem
rem Structure notes (this file is exercised by dry parsing and string-level
rem tests, not yet on a real Windows machine):
rem - No multi-line parenthesized blocks: cmd expands %var% at block parse
rem time, which made the old download path read back empty %url%/%cached%.
rem Linear goto flow keeps every expansion on its own line, and avoids
rem delayed expansion eating ! characters in user arguments.
rem - The unversioned user binary and the PATH candidate are validated with
rem the engine-probe handshake (see :probe) so the retired 3.x npm CLI,
rem whose bin is also named impeccable, is never exec'd. The sibling binary
rem must also report the version in VERSION: it is not tracked, so a skill
rem upgrade can leave an old engine in place. IMPECCABLE_BIN stays trusted.
rem - Downloads and the version-pinned cache are verified via certutil
rem against engine-checksums.txt next to this file, and fail closed; a
rem .verified stamp lets later runs skip hashing the cache while it holds
rem the manifest digest and the binary's size and is not older than the
rem binary. On ARM64 the arm64 asset is tried first and the x64 asset is the
rem fallback (Windows on ARM runs x64 binaries), each only when the manifest
rem has a line for it.
if not defined IMPECCABLE_SKILL_DIR set "IMPECCABLE_SKILL_DIR=%~dp0.."
if not defined IMPECCABLE_SELF set "IMPECCABLE_SELF=%~f0"
set "arch=x64"
if /I "%PROCESSOR_ARCHITECTURE%"=="ARM64" set "arch=arm64"
if not defined IMPECCABLE_BIN goto no_env_bin
if not exist "%IMPECCABLE_BIN%" goto no_env_bin
set "run=%IMPECCABLE_BIN%"
goto run
:no_env_bin
set "version="
if exist "%~dp0VERSION" set /p version=<"%~dp0VERSION"
set "bin=%~dp0bin\windows-%arch%\impeccable.exe"
if not exist "%bin%" goto no_sibling
if defined IMPECCABLE_LAUNCHER_PROBE goto sibling_ok
if not defined version goto sibling_ok
call :probe "%bin%"
if "%probe_version%"=="%version%" goto sibling_ok
if not defined probe_version set "probe_version=unknown"
echo impeccable: skipping "%bin%": it reports engine %probe_version% but this skill pins %version%; delete it to stop this warning 1>&2
goto no_sibling
:sibling_ok
set "run=%bin%"
goto run
:no_sibling
set "home_bin=%USERPROFILE%\.impeccable\bin\impeccable.exe"
if not exist "%home_bin%" goto no_home_bin
if defined IMPECCABLE_LAUNCHER_PROBE goto no_home_bin
call :probe "%home_bin%"
if not "%probe_ok%"=="1" goto no_home_bin
set "run=%home_bin%"
goto run
:no_home_bin
if not defined IMPECCABLE_HOME set "IMPECCABLE_HOME=%USERPROFILE%\.impeccable"
set "cached=%IMPECCABLE_HOME%\bin\%version%\impeccable.exe"
set "asset=impeccable-windows-%arch%.exe"
set "manifest=%~dp0engine-checksums.txt"
if not defined version goto no_cache
if not exist "%cached%" goto no_cache
call :read_expected
for %%f in ("%cached%") do set "size=%%~zf"
set "stamp="
if exist "%cached%.verified" for /f "usebackq tokens=1,2" %%s in ("%cached%.verified") do set "stamp=%%s"& set "stamp_size=%%t"
if not defined stamp goto cache_hash
if not "%stamp_size%"=="%size%" goto cache_hash
if /I "%stamp%"=="%expected%" goto cache_stamp_matches
if /I "%stamp%"=="%expected_x64%" goto cache_stamp_matches
goto cache_hash
:cache_stamp_matches
rem Newest first: the stamp must be listed before the binary it vouches for.
set "newest="
for /f "delims=" %%f in ('dir /b /a:-d /o:-d "%cached%*" 2^>nul') do if not defined newest set "newest=%%f"
if /I "%newest%"=="impeccable.exe.verified" goto cache_trusted
:cache_hash
call :sha256 "%cached%" "%TEMP%\impeccable-hash-%RANDOM%%RANDOM%.txt"
if not defined actual goto cache_unverified
if /I "%actual%"=="%expected%" goto cache_verified
if /I "%actual%"=="%expected_x64%" goto cache_verified
:cache_unverified
echo impeccable: cannot verify the cached engine "%cached%" against "%manifest%"; not using it 1>&2
goto no_cache
:cache_verified
(>"%cached%.verified" echo %actual% %size%) 2>nul
:cache_trusted
set "run=%cached%"
goto run
:no_cache
if defined IMPECCABLE_LAUNCHER_PROBE goto download
rem The first impeccable on PATH, resolved once so the probe and the run see
rem the same file. A batch shim (npm writes impeccable.cmd) must run under
rem call to return here (#1240), and call expands % in the arguments a second
rem time; a real binary runs directly so a target such as a%20b reaches it intact.
set "path_bin="
rem where also lists npm's extensionless POSIX shim, which cmd cannot run:
rem take the first match with a runnable extension.
rem Loop letters c and k are not path modifiers, so %%~xc reads as the
rem extension of c and never as a loop variable followed by text.
for /f "delims=" %%c in ('where impeccable 2^>nul') do if not defined path_bin for %%k in (.exe .com .cmd .bat) do if /I "%%~xc"=="%%k" set "path_bin=%%c"
if not defined path_bin goto download
call :probe "%path_bin%"
if not "%probe_ok%"=="1" goto download
for %%k in ("%path_bin%") do set "path_ext=%%~xk"
if /I "%path_ext%"==".cmd" goto path_shim
if /I "%path_ext%"==".bat" goto path_shim
"%path_bin%" %*
exit /b %errorlevel%
:path_shim
call "%path_bin%" %*
exit /b %errorlevel%
:download
rem Last resort: fetch this version's binary from the release channel into
rem the version-pinned user cache, verify it, then run it. Never inside
rem another launcher's probe: fail fast and quiet instead.
if defined IMPECCABLE_LAUNCHER_PROBE exit /b 127
if not defined version goto fail
call :read_expected
if not defined expected if not defined expected_x64 goto no_checksum
where curl.exe >nul 2>nul
if errorlevel 1 goto curl_missing
if not defined IMPECCABLE_DOWNLOAD_BASE set "IMPECCABLE_DOWNLOAD_BASE=https://github.com/pbakaus/impeccable/releases/download"
if exist "%IMPECCABLE_HOME%\bin\%version%\" goto cache_ready
mkdir "%IMPECCABLE_HOME%\bin\%version%" >nul 2>nul
if errorlevel 1 goto cache_directory_failed
:cache_ready
rem Remove staging directories killed runs left in any version's cache, once
rem two days idle (forfiles /d counts days; a live curl's open file stays).
forfiles /p "%IMPECCABLE_HOME%\bin" /s /m .impeccable.part.* /d -2 /c "cmd /c if @isdir==TRUE rd /s /q @path" >nul 2>nul
rem Stage the download in a directory only this run owns, as the sh launcher
rem does with .impeccable.part.$$: concurrent first runs (parallel hooks, two
rem agents) must never write, hash or move each other's files. mkdir fails
rem when the name exists, so it claims the name atomically. RANDOM alone is
rem not enough because cmd seeds it from the clock in whole seconds; the
rem timestamp and the retry on collision keep same-second runs apart. A cache
rem directory that refuses every mkdir is reported as unwritable.
set "attempt=0"
:claim_staging
set /a attempt+=1
if %attempt% GTR 20 goto cache_write_failed
set "stamp=%TIME: =0%"
set "stamp=%stamp::=%"
set "stamp=%stamp:.=%"
set "stamp=%stamp:,=%"
set "staging=%IMPECCABLE_HOME%\bin\%version%\.impeccable.part.%stamp%-%RANDOM%%RANDOM%"
mkdir "%staging%" >nul 2>nul
if errorlevel 1 goto claim_staging
set "part=%staging%\impeccable.exe"
rem Redirection failures do not reliably update ERRORLEVEL in cmd.exe;
rem branch on the command's failure directly.
(type nul >"%part%") 2>nul || goto staging_write_failed
set "url=%IMPECCABLE_DOWNLOAD_BASE%/engine-v%version%/%asset%"
if not defined expected goto fetch_x64
call :fetch_url
if not errorlevel 1 goto verify
:fetch_x64
if not defined expected_x64 goto download_failed
set "asset=impeccable-windows-x64.exe"
set "expected=%expected_x64%"
set "url=%IMPECCABLE_DOWNLOAD_BASE%/engine-v%version%/%asset%"
call :fetch_url
if errorlevel 1 goto download_failed
:verify
call :check_download
if errorlevel 1 exit /b 127
rem Mirrors the sh launcher and fails closed: a freshly downloaded binary
rem runs only after its hash matches the digest read from engine-checksums.txt.
rem An empty certutil result refuses the download instead of running an
rem unverified binary.
call :sha256 "%part%" "%staging%\hash.txt"
call :check_download
if errorlevel 1 exit /b 127
if not defined actual goto verify_refuse
if /I "%actual%"=="%expected%" goto place
call :discard_staging
echo impeccable: checksum mismatch downloading %url% 1>&2
exit /b 127
:verify_refuse
call :check_download
if errorlevel 1 exit /b 127
call :discard_staging
echo impeccable: cannot verify %url% (certutil could not hash it); refusing the unverified download 1>&2
exit /b 127
:fetch_url
set "http_status="
set "effective_url="
set "download_host="
set "curl_error="
curl.exe -fsSL --retry 2 -w "%%{http_code} %%{url_effective} %%{errormsg}" -o "%part%" "%url%" >"%staging%\http.txt" 2>nul
set "fetch_result=%errorlevel%"
for /f "usebackq tokens=1" %%a in ("%staging%\http.txt") do set "http_status=%%a"
for /f "usebackq tokens=2" %%a in ("%staging%\http.txt") do set "effective_url=%%a"
for /f "usebackq tokens=2,*" %%a in ("%staging%\http.txt") do set "curl_error=%%b"
rem Token 2 is the authority after scheme://. Drop userinfo and the port.
for /f "tokens=2 delims=/" %%h in ("%effective_url%") do set "download_host=%%h"
for /f "tokens=1,* delims=@" %%h in ("%download_host%") do if not "%%i"=="" set "download_host=%%i"
rem Bracketed IPv6 hosts contain colons that are not port separators.
if "%download_host:~0,1%"=="[" goto fetch_ipv6
for /f "tokens=1 delims=:" %%h in ("%download_host%") do set "download_host=%%h"
exit /b %fetch_result%
:fetch_ipv6
for /f "tokens=1 delims=]" %%h in ("%download_host%") do set "download_host=%%h]"
exit /b %fetch_result%
:read_expected
rem Sets expected (and, on ARM64, expected_x64: Windows on ARM runs x64
rem binaries) from engine-checksums.txt.
call :manifest_digest "%asset%" expected
set "expected_x64="
if "%arch%"=="arm64" call :manifest_digest impeccable-windows-x64.exe expected_x64
exit /b 0
:manifest_digest
rem Sets the variable named %2 to the digest the first engine-checksums.txt
rem line for this version and asset %1 records, empty when there is none.
set "%~2="
if not exist "%manifest%" exit /b 0
for /f "usebackq tokens=1-3" %%a in ("%manifest%") do if "%%a"=="%version%" if /I "%%b"=="%~1" if not defined %~2 set "%~2=%%c"
exit /b 0
:sha256
rem Sets actual to the sha256 of %~1, empty when certutil fails. %~2 is the
rem scratch file for its output. Check certutil's status before parsing: its
rem error text on stdout is not a digest.
set "actual="
certutil -hashfile "%~1" SHA256 >"%~2" 2>nul
if errorlevel 1 goto sha256_done
for /f "usebackq skip=1 delims=" %%h in ("%~2") do if not defined actual set "actual=%%h"
if not defined actual goto sha256_done
set "actual=%actual: =%"
:sha256_done
del "%~2" >nul 2>nul
exit /b 0
:check_download
set "download_file=%~1"
if not defined download_file set "download_file=%part%"
if not exist "%download_file%" goto download_missing
for %%f in ("%download_file%") do if %%~zf==0 goto download_empty
exit /b 0
:download_missing
call :discard_staging
echo impeccable: download completed but the file was removed before execution: %url%; check your antivirus quarantine or logs. Refusing to continue; do not disable protection. 1>&2
exit /b 127
:download_empty
del "%download_file%" >nul 2>nul
call :discard_staging
echo impeccable: downloaded file is empty: %url%; refusing the unverified download 1>&2
exit /b 127
:discard_staging
rem Removes this run's staging directory and whatever is left in it. Never
rem touches another run's staging directory or the cached binary.
if defined staging rd /s /q "%staging%" >nul 2>nul
exit /b 0
:place
call :check_download
if errorlevel 1 exit /b 127
move /y "%part%" "%cached%" >nul 2>nul
if errorlevel 1 goto place_failed
call :discard_staging
call :check_download "%cached%"
if errorlevel 1 exit /b 127
for %%f in ("%cached%") do set "size=%%~zf"
(>"%cached%.verified" echo %actual% %size%) 2>nul
set "run=%cached%"
goto run
:place_failed
call :check_download
if errorlevel 1 exit /b 127
call :discard_staging
echo impeccable: could not cache the verified download: %url% 1>&2
exit /b 127
:run
"%run%" %*
exit /b %errorlevel%
:probe
rem Sets probe_ok=1 when %1 answers the engine handshake: prints
rem "impeccable-engine <version>" and exits 0, and probe_version to that
rem version. The 3.x npm CLI answers any unknown verb with "Unknown command",
rem exit 1, so it never passes.
rem The candidate runs under call: an npm .cmd shim run without it takes
rem over this script and never returns (#1240).
set "probe_ok="
set "probe_version="
set "probe_tmp=%TEMP%\impeccable-probe-%RANDOM%%RANDOM%.txt"
set "IMPECCABLE_LAUNCHER_PROBE=1"
call "%~1" engine-probe >"%probe_tmp%" 2>nul
set "probe_err=%ERRORLEVEL%"
set "IMPECCABLE_LAUNCHER_PROBE="
if not "%probe_err%"=="0" goto probe_done
findstr /b /c:"impeccable-engine" "%probe_tmp%" >nul 2>nul
if errorlevel 1 goto probe_done
set "probe_ok=1"
for /f "usebackq tokens=2" %%v in ("%probe_tmp%") do if not defined probe_version set "probe_version=%%v"
:probe_done
del "%probe_tmp%" >nul 2>nul
exit /b 0
:no_checksum
echo impeccable: no checksum for engine %version% (%asset%) in "%manifest%"; refusing the unverified download 1>&2
exit /b 127
:cache_directory_failed
echo impeccable: engine %version% is not installed; cannot create cache directory: "%IMPECCABLE_HOME%\bin\%version%" 1>&2
goto setup_failed
:staging_write_failed
call :discard_staging
:cache_write_failed
echo impeccable: engine %version% is not installed; cannot write to cache directory: "%IMPECCABLE_HOME%\bin\%version%" 1>&2
goto setup_failed
:curl_missing
echo impeccable: cannot download engine %version%; curl.exe is unavailable. 1>&2
goto setup_failed
:download_failed
call :discard_staging
if not "%http_status:~0,1%"=="5" goto download_generic
if "%http_status:~2,1%"=="" goto download_generic
if /I "%download_host%"=="github.com" goto download_github
if /I "%download_host:~-11%"==".github.com" goto download_github
if /I "%download_host%"=="githubusercontent.com" goto download_github
if /I "%download_host:~-22%"==".githubusercontent.com" goto download_github
echo impeccable: could not download engine %version%: %download_host% is failing right now (HTTP %http_status%), a server error on %download_host%'s side. Try again later. 1>&2
exit /b 127
:download_github
echo impeccable: could not download engine %version%: GitHub's downloads are failing right now (HTTP %http_status% from %download_host%). This is an outage on GitHub's side, not a problem with your setup or the CLI, so updating won't help. Check https://www.githubstatus.com and run the same command again once GitHub has recovered. 1>&2
exit /b 127
:download_generic
rem Delayed expansion keeps cmd metacharacters in curl's message literal.
setlocal EnableDelayedExpansion
if defined curl_error set "curl_error=: !curl_error!"
echo impeccable: could not download engine %version% from !url! (curl exit %fetch_result%!curl_error!); check network access and the release URL. 1>&2
endlocal
:setup_failed
echo Engine %version% setup needs network access and write permission to "%IMPECCABLE_HOME%\bin\%version%". 1>&2
echo Run this launcher ("%~f0") with engine-probe in a terminal that has those permissions, then retry the original command. 1>&2
echo Alternatively, set IMPECCABLE_HOME to a writable cache location, or IMPECCABLE_BIN to a preinstalled engine binary. 1>&2
exit /b 127
:fail
echo impeccable: no engine binary found (looked in %bin%, %cached%, PATH). 1>&2
echo Download impeccable-windows-%arch%.exe from https://github.com/pbakaus/impeccable/releases (tag engine-v%version%) and save it as %cached%, or set IMPECCABLE_BIN to a preinstalled engine binary. Docs: https://impeccable.style 1>&2
exit /b 127
@@ -0,0 +1,320 @@
/**
* Browser-side DOM helpers for Impeccable live mode.
*
* Kept separate from live-browser.js so future browser script parts can share
* chrome mounting, lookup, focus, and picker helpers without depending on the
* full overlay UI bundle.
*/
(function (root) {
'use strict';
if (!root) return;
function createLiveBrowserDomHelpers({
prefix,
skipTags,
document: doc = root.document,
css = root.CSS,
crypto = root.crypto,
} = {}) {
if (!prefix) throw new Error('prefix required');
if (!doc) throw new Error('document required');
const tagsToSkip = skipTags || new Set();
function own(el) {
return el && (el.id?.startsWith(prefix) || el.closest?.('[id^="' + prefix + '"]'));
}
function pickable(el) {
if (!el || el.nodeType !== 1) return false;
if (tagsToSkip.has(String(el.tagName || '').toLowerCase())) return false;
if (own(el)) return false;
const r = el.getBoundingClientRect();
return r.width >= 20 && r.height >= 20;
}
function desc(el) {
if (!el) return '';
let s = el.tagName.toLowerCase();
if (el.id) s += '#' + el.id;
else if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
return s;
}
function rectIsUsableAnchor(rect) {
return !!rect && rect.width > 0.5 && rect.height > 0.5;
}
function makeFrozenAnchor(el) {
if (!el || !el.getBoundingClientRect) return null;
const r = el.getBoundingClientRect();
if (!rectIsUsableAnchor(r)) return null;
const rect = {
x: r.x, y: r.y,
top: r.top, left: r.left,
right: r.right, bottom: r.bottom,
width: r.width, height: r.height,
};
return {
__impeccableFrozenAnchor: true,
tagName: el.tagName || 'DIV',
id: el.id || '',
classList: el.classList ? [...el.classList] : [],
hasAttribute: () => false,
getBoundingClientRect: () => rect,
};
}
function hasFrameworkHmrOwnership(el) {
for (let node = el; node; node = node.parentElement) {
let keys = [];
try { keys = Object.getOwnPropertyNames(node); } catch {}
if (keys.some((key) => (
key.startsWith('__reactFiber$')
|| key.startsWith('__reactProps$')
|| key.startsWith('__reactContainer$')
|| key === '_reactRootContainer'
|| key === '__vueParentComponent'
|| key === '__vue_app__'
|| key === '__vnode'
|| key === '__svelte_meta'
))) {
return true;
}
}
return false;
}
function id8() {
// randomUUID is secure-context only (issue #1055); getRandomValues is not.
try {
if (typeof crypto?.randomUUID === 'function') return crypto.randomUUID().replace(/-/g, '').slice(0, 8);
} catch { /* fall through */ }
try {
if (typeof crypto?.getRandomValues === 'function') {
const bytes = crypto.getRandomValues(new Uint8Array(4));
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
}
} catch { /* fall through */ }
return (Math.random().toString(16).slice(2) + Date.now().toString(16)).slice(0, 8);
}
function cssId(id) {
if (css?.escape) return css.escape(id);
return String(id).replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g, '\\$1');
}
function liveUiRoot() {
const uiRoot = root.__IMPECCABLE_LIVE_UI_ROOT__;
if (uiRoot && typeof uiRoot.appendChild === 'function') return uiRoot;
return doc.body;
}
// A modal <dialog> (showModal) paints in the top layer and makes every
// node outside its subtree inert, so chrome on <body> can be neither seen
// nor clicked while one is open, and no z-index reaches it (issue #879).
// While a modal is open the chrome parks inside the topmost one, in one
// popover: inside the dialog it is not inert, and a popover shown after
// the dialog paints above it. One popover for all of it, because
// top-layer entries stack by show order, which would drop the z-index
// order between the roots. The detect overlay (browser-bundle/
// 40-overlay.js) mounts its outlines here too: it finds the host by this
// id and places its outlines again on the event of the same name, fired
// on every move.
const topLayerHost = doc.createElement('div');
topLayerHost.id = prefix + '-top-layer';
// Same box as the SvelteKit shadow host: 0x0, fixed, chrome overflows it.
// `all: initial` also clears the popover UA box.
for (const [name, value] of Object.entries({
all: 'initial', position: 'fixed', top: '0', left: '0', width: '0', height: '0', overflow: 'visible',
})) topLayerHost.style.setProperty(name, value, 'important');
const pageRoots = new WeakSet(); // chrome nodes mounted on the page itself
const openModals = []; // in the order they opened; last is topmost
// Modals that were open before watching began have no readable top-layer
// order, but the topmost one's backdrop covers the viewport, so a hit
// test lands in it. Raise that one to the top of the stack.
function raiseHitModal() {
const i = openModals.indexOf(doc.elementFromPoint(0, 0)?.closest('dialog:modal'));
if (i !== -1) openModals.push(...openModals.splice(i, 1));
}
function syncTopLayerHost(records = []) {
for (const { type, target, oldValue } of records) {
if (type !== 'attributes' || oldValue !== null || !target.matches('dialog:modal')) continue;
// Opened, or closed and reopened in one task (the observer sees only
// the end state): either way it is back on top of the top layer, so
// a host shown inside it earlier has to be shown again. A write to an
// `open` that was already set (oldValue not null) moved nothing.
const i = openModals.indexOf(target);
if (i !== -1) openModals.splice(i, 1);
openModals.push(target);
if (topLayerHost.parentNode === target) topLayerHost.remove();
}
// A closed dialog, or one removed from the document while open, stops
// matching :modal. Whichever is now on top may predate the watch.
const before = openModals.length;
for (let i = openModals.length - 1; i >= 0; i--) {
if (!openModals[i].matches('dialog:modal')) openModals.splice(i, 1);
}
if (openModals.length < before && openModals.length > 1) raiseHitModal();
const modal = openModals[openModals.length - 1] || null;
if (topLayerHost.parentNode === modal) return;
if (modal) {
modal.appendChild(topLayerHost);
for (const el of [...doc.body.children]) if (pageRoots.has(el)) topLayerHost.appendChild(el);
topLayerHost.showPopover();
} else {
doc.body.append(...topLayerHost.childNodes);
topLayerHost.remove();
}
doc.dispatchEvent(new Event(topLayerHost.id));
}
// Returns the function that stops watching and puts the chrome back.
function watchModalDialogs() {
if (typeof topLayerHost.showPopover !== 'function') return () => {};
topLayerHost.popover = 'manual';
// Parked in the page's dialog, chrome clicks would bubble into its own
// handlers, such as a click-outside-the-box close. Live listens in capture.
topLayerHost.addEventListener('click', (e) => e.stopPropagation());
openModals.push(...doc.querySelectorAll('dialog:modal'));
raiseHitModal();
const observer = new MutationObserver(syncTopLayerHost);
observer.observe(doc, { subtree: true, childList: true, attributes: true, attributeOldValue: true, attributeFilter: ['open'] });
syncTopLayerHost();
return () => {
observer.disconnect();
openModals.length = 0;
syncTopLayerHost();
};
}
// A copy of a page element without the chrome parked inside it, which a
// picked modal dialog contains.
function cloneWithoutChrome(el) {
const clone = el.cloneNode(true);
if (el.contains(topLayerHost)) clone.querySelector('#' + cssId(topLayerHost.id)).remove();
return clone;
}
// Mount a chrome node on the page itself: <body>, or the top-layer host
// while the chrome is parked in a modal.
function uiAppendToPage(el) {
pageRoots.add(el);
(topLayerHost.parentNode ? topLayerHost : doc.body).appendChild(el);
return el;
}
// Copy text through a selected textarea and execCommand, for origins where
// navigator.clipboard is missing or refused (plain HTTP, issue #1055).
// The textarea mounts like any page-level chrome, so while a modal
// <dialog> is open it sits in that dialog's top-layer host: on <body> it
// would be inert, and inert text cannot be selected or copied.
function copyTextViaSelection(text) {
let ta = null;
const previous = activeElementDeep();
try {
ta = doc.createElement('textarea');
ta.id = prefix + '-clipboard';
ta.value = text;
ta.setAttribute('readonly', '');
ta.setAttribute('aria-hidden', 'true');
ta.tabIndex = -1;
ta.style.cssText = 'position:fixed;top:0;left:0;width:1px;height:1px;opacity:0;pointer-events:none;';
uiAppendToPage(ta);
ta.select();
return doc.execCommand('copy');
} catch {
return false;
} finally {
ta?.remove();
if (previous && previous !== activeElementDeep() && typeof previous.focus === 'function') {
try { previous.focus({ preventScroll: true }); } catch { /* best effort */ }
}
}
}
function uiAppend(el) {
const uiRoot = liveUiRoot();
if (uiRoot === doc.body) return uiAppendToPage(el);
// An adapter shadow root: its host is the node that sits on the page.
if (uiRoot.host) pageRoots.add(uiRoot.host);
uiRoot.appendChild(el);
return el;
}
function uiAppendStyle(styleEl) {
const uiRoot = liveUiRoot();
if (uiRoot && uiRoot !== doc.body) uiRoot.appendChild(styleEl);
else doc.head.appendChild(styleEl);
return styleEl;
}
function uiGetById(id) {
const uiRoot = liveUiRoot();
if (uiRoot?.getElementById) {
const found = uiRoot.getElementById(id);
if (found) return found;
}
if (uiRoot?.querySelector) {
const found = uiRoot.querySelector('#' + cssId(id));
if (found) return found;
}
return doc.getElementById(id);
}
function activeElementDeep() {
let active = doc.activeElement;
while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
return active;
}
function defangOutsideHandlers(rootEl, { setPointerEvents = true } = {}) {
if (!rootEl) return;
if (setPointerEvents) {
rootEl.style.setProperty('pointer-events', 'auto', 'important');
}
const stop = (e) => e.stopPropagation();
rootEl.addEventListener('pointerdown', stop);
rootEl.addEventListener('mousedown', stop);
rootEl.addEventListener('focusin', stop);
}
// The half of the defang that cannot sit on the chrome: a focus trap (Radix /
// Reka FocusScope) also hears the page's own focusout as focus leaves its
// modal for our chrome, and pulls it back. Register on the document in
// capture, ahead of the trap. The page's own focusout handlers miss that
// one transition too; blur still fires.
function stopFocusOutIntoChrome(e) {
if (own(e.relatedTarget)) e.stopPropagation();
}
return {
own,
pickable,
desc,
rectIsUsableAnchor,
makeFrozenAnchor,
hasFrameworkHmrOwnership,
id8,
cssId,
liveUiRoot,
uiAppend,
uiAppendToPage,
copyTextViaSelection,
topLayerHost,
watchModalDialogs,
cloneWithoutChrome,
uiAppendStyle,
uiGetById,
activeElementDeep,
defangOutsideHandlers,
stopFocusOutIntoChrome,
};
}
root.__IMPECCABLE_LIVE_DOM__ = {
version: 1,
createLiveBrowserDomHelpers,
};
})(typeof window !== 'undefined' ? window : globalThis);
@@ -0,0 +1,246 @@
/**
* Browser-side resolution of project detector waivers for Impeccable live mode.
*
* The live server serializes `.impeccable/config.json` + `config.local.json`
* detector ignores (plus the served-root prefixes from the inject config's
* `files` globs) into `window.__IMPECCABLE_PROJECT_IGNORES__`. This part
* resolves that config against the current page's URL path when a detect scan
* starts, so the overlay suppresses the same findings the CLI and the edit
* hook do (issue #639).
*
* Mirrors filterDetectionFindings in cli/lib/impeccable-config.mjs:
* 1. `ignoreRules` suppress a rule project-wide.
* 2. `ignoreValues` entries with `value: "*"` suppress their rule in the
* files their globs name. The CLI never applies an unscoped wildcard
* (isIgnoredFindingValue returns false for it), so neither does this.
* 3. Remaining `ignoreValues` entries match on the finding's own value;
* those are forwarded as `disabledValues` for the detector bundle to
* apply where the findings are assembled.
* 4. `ignoreFiles` globs that name the page waive it wholesale: the
* resolver reports `skipScan: true` and the detector answers the scan
* with zero findings, mirroring shouldIgnoreDetectionFile in the CLI
* and the edit hook's own ignoreFiles gate.
*
* `pageFiles`, when the server could resolve it, lists the real project
* files the inject config serves. A URL that suffix-matches exactly one of
* them takes that file as its only project identity; an ambiguous or absent
* match falls back to the served-root common ancestor below.
*
* Known gap, unchanged from PR #645: framework apps inject into source files
* (src/routes/about/+page.svelte) while scans see route URLs (/about), so
* entries scoped to source or asset paths never match a page candidate and
* are dropped. That shows the finding, which is the conservative direction.
*
* Kept separate from live-browser.js so the glob and page-scope logic can be
* unit tested in Node (tests/live-browser-ignores.test.mjs) without the full
* overlay UI bundle.
*/
(function (root) {
'use strict';
if (!root) return;
// Keep in step with normalizeIgnoreRule / normalizeIgnoreValue in
// cli/lib/impeccable-config.mjs.
function normalizeIgnoreRule(rule) {
return String(rule || '').trim().toLowerCase();
}
function normalizeIgnoreValue(value) {
return String(value || '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ')
.toLowerCase();
}
// Glob -> RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
// Keep in step with globToRegex in cli/lib/impeccable-config.mjs.
function globToRegex(glob) {
let re = '^';
let i = 0;
while (i < glob.length) {
const c = glob[i];
if (c === '*') {
if (glob[i + 1] === '*') {
i += 2;
if (glob[i] === '/') {
re += '(?:.*/)?';
i += 1;
} else {
re += '.*';
}
} else {
re += '[^/]*';
i += 1;
}
} else if (c === '?') {
re += '[^/]';
i += 1;
} else if (c === '{') {
const end = glob.indexOf('}', i);
if (end === -1) { re += '\\{'; i += 1; continue; }
const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
re += `(?:${parts.join('|')})`;
i = end + 1;
} else if (/[.+^$()|[\]\\]/.test(c)) {
re += `\\${c}`;
i += 1;
} else {
re += c;
i += 1;
}
}
re += '$';
return new RegExp(re);
}
// The project-relative paths this page could be known as. Ignore globs are
// project-relative (prototype/foo.html) and the URL is site-relative
// (/foo.html), because a static server's root usually sits inside the
// project; `roots` carries that prefix. The server reads it from the inject
// config's own `files` globs, which already state where the served pages
// are. Do not derive it from the ignore globs: a single entry scoped to
// prototype/library/** would then lend prototype/library/ as a candidate
// prefix to every page, and that rule would suppress site-wide.
//
// Each prefixed path also contributes its slash suffixes, mirroring
// findingMatchesScopedIgnoreFile in cli/lib/impeccable-config.mjs (which
// matches globs against every path suffix of the finding's file).
//
// One live session is served by one server, so a single document root must
// sit at or above every configured page. The only prefix that can safely
// be asserted is therefore the deepest common ancestor of the glob roots.
// Treating each glob's own prefix as an identity goes wrong in both
// directions: disjoint roots (src/ and public/) invent simultaneous
// identities for one URL, so a waiver scoped to src/foo.html hides a
// finding on a page served from public/foo.html; nested roots (prototype/
// and prototype/library/, from globs at two depths in one tree) are not
// alternatives at all, and demanding a waiver match under both stops
// prototype/index.html from applying anywhere. When the globs share no
// common root, no prefix is asserted and only the URL path itself matches.
function pageCandidates(pathname, roots, pageFiles) {
let pagePath = String(pathname || '');
try {
pagePath = decodeURIComponent(pagePath);
} catch {
// Malformed percent-escape: match on the raw path rather than throwing.
}
pagePath = pagePath.replace(/^\/+/, '');
// A directory URL serves that directory's index, and the ignore globs
// name files. Without this, /news/ never matches prototype/news/index.html.
if (pagePath === '' || pagePath.endsWith('/')) pagePath += 'index.html';
const candidates = new Set();
const addSuffixes = (fullPath) => {
const parts = fullPath.split('/').filter(Boolean);
for (let i = 0; i < parts.length; i++) {
candidates.add(parts.slice(i).join('/'));
}
};
addSuffixes(pagePath);
// The served page list names the real files the inject config serves.
// A URL that suffix-matches exactly one of them has an unambiguous
// project identity; assert that identity and stop guessing from roots
// (PR #645 review: with src/ and public/ both served, /foo.html must not
// borrow src/foo.html's waivers while actually serving public/foo.html).
// Zero matches or several fall through to the common-ancestor fallback:
// ambiguity resolves toward showing the finding.
const knownPages = [];
for (const entry of Array.isArray(pageFiles) ? pageFiles : []) {
if (typeof entry !== 'string' || !entry) continue;
if (entry === pagePath || entry.endsWith('/' + pagePath)) knownPages.push(entry);
}
if (knownPages.length === 1) {
addSuffixes(knownPages[0]);
return [...candidates];
}
const prefixes = [];
for (const entry of Array.isArray(roots) ? roots : []) {
if (typeof entry !== 'string') continue;
prefixes.push(entry.split('/').filter(Boolean));
}
let common = prefixes.length > 0 ? prefixes[0] : [];
for (const segments of prefixes.slice(1)) {
let i = 0;
while (i < common.length && i < segments.length && common[i] === segments[i]) i += 1;
common = common.slice(0, i);
}
if (common.length > 0) addSuffixes(common.join('/') + '/' + pagePath);
return [...candidates];
}
function matchesScope(globs, candidates) {
return globs.some((glob) => {
let re;
try {
re = globToRegex(String(glob));
} catch {
// Malformed glob: skip it, as matchesAnyGlob does in the CLI.
return false;
}
return candidates.some((candidate) => re.test(candidate));
});
}
/**
* Resolve the serialized project ignores for one page.
*
* @param {object} options
* @param {object} options.ignores window.__IMPECCABLE_PROJECT_IGNORES__,
* in whatever state it arrived: absent, null, or hand-edited into the
* wrong shape. Every read tolerates that and degrades to no filtering.
* @param {string} options.pathname location.pathname of the scanned page.
* @returns {{ disabledRules: string[], disabledValues: Array<{rule: string, value: string}>, skipScan: boolean }}
*/
function resolveDetectIgnores({ ignores, pathname } = {}) {
const config = ignores && typeof ignores === 'object' ? ignores : {};
const asArray = (value) => (Array.isArray(value) ? value : []);
const candidates = pageCandidates(pathname, config.roots, config.pageFiles);
// detector.ignoreFiles waives whole files. When any glob names this
// page, the scan itself is skipped; rule and value lists are returned
// empty because nothing will run.
const ignoreFileGlobs = asArray(config.ignoreFiles)
.filter((glob) => typeof glob === 'string' && glob.trim());
if (ignoreFileGlobs.length > 0 && matchesScope(ignoreFileGlobs, candidates)) {
return { disabledRules: [], disabledValues: [], skipScan: true };
}
const disabledRules = new Set(
asArray(config.ignoreRules)
.filter((rule) => typeof rule === 'string')
.map(normalizeIgnoreRule)
.filter(Boolean),
);
const disabledValues = [];
for (const entry of asArray(config.ignoreValues)) {
if (!entry || typeof entry !== 'object') continue;
const rule = normalizeIgnoreRule(entry.rule);
const value = normalizeIgnoreValue(entry.value);
if (!rule || !value) continue;
const files = [
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
...asArray(entry.files).filter((glob) => typeof glob === 'string' && glob.trim()),
];
if (value === '*') {
// Wildcards suppress their rule only inside the files they name.
if (files.length > 0 && matchesScope(files, candidates)) disabledRules.add(rule);
continue;
}
if (files.length > 0 && !matchesScope(files, candidates)) continue;
disabledValues.push({ rule, value });
}
return { disabledRules: [...disabledRules], disabledValues, skipScan: false };
}
root.__IMPECCABLE_LIVE_IGNORES__ = {
version: 1,
resolveDetectIgnores,
};
})(typeof window !== 'undefined' ? window : globalThis);
@@ -0,0 +1,183 @@
/**
* Browser-side durable session helpers for Impeccable live mode.
*
* Kept separate from live-browser.js so recovery state can be tested without
* booting the full overlay UI. Served before live-browser.js and attached to
* window.__IMPECCABLE_LIVE_SESSION__.
*/
(function (root) {
'use strict';
// crypto.randomUUID() exists only in secure contexts (HTTPS, localhost), so a
// dev site on a LAN IP, a Tailscale address, or a custom hostname over plain
// HTTP has no randomUUID at all (issue #1055). getRandomValues() is available
// in every context; Math.random() covers runtimes with no crypto. Live ids
// only have to be unique per session, not unguessable.
function randomUUID(cryptoImpl) {
const c = cryptoImpl === undefined ? root.crypto : cryptoImpl;
try {
if (c && typeof c.randomUUID === 'function') return c.randomUUID();
} catch { /* fall through to getRandomValues */ }
const bytes = new Uint8Array(16);
let filled = false;
try {
if (c && typeof c.getRandomValues === 'function') {
c.getRandomValues(bytes);
filled = true;
}
} catch { /* fall through to Math.random */ }
if (!filled) {
for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
}
bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
bytes[8] = (bytes[8] & 0x3f) | 0x80; // RFC 4122 variant
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
return hex.slice(0, 8) + '-' + hex.slice(8, 12) + '-' + hex.slice(12, 16)
+ '-' + hex.slice(16, 20) + '-' + hex.slice(20);
}
function randomId8(cryptoImpl) {
return randomUUID(cryptoImpl).replace(/-/g, '').slice(0, 8);
}
function createLiveBrowserSessionState({ prefix, storage, idFactory }) {
if (!prefix) throw new Error('prefix required');
let store = storage;
if (!store) {
try { store = root.localStorage; } catch { store = null; /* storage denied */ }
}
const makeId = idFactory || function () { return randomId8(); };
const sessionKey = prefix + '-session';
const handledKey = sessionKey + '-handled';
const scrollKey = sessionKey + '-scroll';
let checkpointRevision = 0;
const owner = makeId();
function safeRead(key) {
try { return store.getItem(key); } catch { return null; }
}
function safeWrite(key, value) {
try { store.setItem(key, value); } catch { /* quota exceeded or private mode */ }
}
function safeRemove(key) {
try { store.removeItem(key); } catch { /* unavailable storage */ }
}
function loadSession() {
try {
const raw = safeRead(sessionKey);
if (!raw) return null;
const parsed = JSON.parse(raw);
if (Number.isInteger(parsed.checkpointRevision)) {
checkpointRevision = Math.max(checkpointRevision, parsed.checkpointRevision);
}
return parsed;
} catch { return null; }
}
function saveSession(session) {
if (!session || !session.id) return;
// Adopt a revision another tab stored so this write does not lower it.
// localStorage has no compare-and-set, so a save from another tab that
// lands between this read and the write below can still be overwritten.
loadSession();
const payload = {
...session,
checkpointRevision,
};
safeWrite(sessionKey, JSON.stringify(payload));
}
function clearSession() {
safeRemove(sessionKey);
}
function nextCheckpointRevision() {
const existing = loadSession();
checkpointRevision += 1;
if (existing?.id) saveSession(existing);
return checkpointRevision;
}
function seedCheckpointRevision(value) {
if (Number.isInteger(value)) checkpointRevision = Math.max(checkpointRevision, value);
return checkpointRevision;
}
function currentCheckpointRevision() {
return checkpointRevision;
}
function readHandledIds() {
const raw = safeRead(handledKey);
if (!raw) return [];
try {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) {
return parsed.filter(id => typeof id === 'string' && id);
}
if (typeof parsed === 'string' && parsed) return [parsed];
} catch { /* legacy values were stored as a plain session id */ }
return [raw];
}
function markHandled(id) {
if (!id) return;
const ids = readHandledIds().filter(existing => existing !== id);
ids.push(id);
safeWrite(handledKey, JSON.stringify(ids.slice(-8)));
}
function isHandled(id) {
return !!id && readHandledIds().includes(id);
}
function clearHandled(id) {
if (!id) {
safeRemove(handledKey);
return;
}
const remaining = readHandledIds().filter(existing => existing !== id);
if (remaining.length > 0) safeWrite(handledKey, JSON.stringify(remaining));
else safeRemove(handledKey);
}
function writeScrollY(y) {
safeWrite(scrollKey, String(y));
}
function readScrollY() {
const raw = safeRead(scrollKey);
if (raw == null) return null;
const n = parseFloat(raw);
return isFinite(n) ? n : null;
}
function clearScrollY() {
safeRemove(scrollKey);
}
return {
owner,
sessionKey,
handledKey,
scrollKey,
saveSession,
loadSession,
clearSession,
nextCheckpointRevision,
seedCheckpointRevision,
currentCheckpointRevision,
markHandled,
isHandled,
clearHandled,
writeScrollY,
readScrollY,
clearScrollY,
};
}
root.__IMPECCABLE_LIVE_SESSION__ = { createLiveBrowserSessionState, randomUUID, randomId8 };
})(typeof window !== 'undefined' ? window : globalThis);
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,14 @@
(function(y,v){typeof exports=="object"&&typeof module!="undefined"?v(exports):typeof define=="function"&&define.amd?define(["exports"],v):(y=typeof globalThis!="undefined"?globalThis:y||self,v(y.modernScreenshot={}))})(this,function(y){"use strict";var rr=Object.defineProperty,nr=Object.defineProperties;var or=Object.getOwnPropertyDescriptors;var Z=Object.getOwnPropertySymbols;var xe=Object.prototype.hasOwnProperty,Me=Object.prototype.propertyIsEnumerable;var Oe=Math.pow,Le=(y,v,N)=>v in y?rr(y,v,{enumerable:!0,configurable:!0,writable:!0,value:N}):y[v]=N,D=(y,v)=>{for(var N in v||(v={}))xe.call(v,N)&&Le(y,N,v[N]);if(Z)for(var N of Z(v))Me.call(v,N)&&Le(y,N,v[N]);return y},M=(y,v)=>nr(y,or(v));var je=(y,v)=>{var N={};for(var R in y)xe.call(y,R)&&v.indexOf(R)<0&&(N[R]=y[R]);if(y!=null&&Z)for(var R of Z(y))v.indexOf(R)<0&&Me.call(y,R)&&(N[R]=y[R]);return N};var C=(y,v,N)=>new Promise((R,O)=>{var X=P=>{try{q(N.next(P))}catch(W){O(W)}},j=P=>{try{q(N.throw(P))}catch(W){O(W)}},q=P=>P.done?R(P.value):Promise.resolve(P.value).then(X,j);q((N=N.apply(y,v)).next())});var Be;function v(e,t){return e[13]=1,e[14]=t>>8,e[15]=t&255,e[16]=t>>8,e[17]=t&255,e}const N=112,R=72,O=89,X=115;let j;function q(){const e=new Int32Array(256);for(let t=0;t<256;t++){let r=t;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r}return e}function P(e){let t=-1;j||(j=q());for(let r=0;r<e.length;r++)t=j[(t^e[r])&255]^t>>>8;return t^-1}function W(e){const t=e.length-1;for(let r=t;r>=4;r--)if(e[r-4]===9&&e[r-3]===N&&e[r-2]===R&&e[r-1]===O&&e[r]===X)return r-3;return 0}function ae(e,t,r=!1){const n=new Uint8Array(13);t*=39.3701,n[0]=N,n[1]=R,n[2]=O,n[3]=X,n[4]=t>>>24,n[5]=t>>>16,n[6]=t>>>8,n[7]=t&255,n[8]=n[4],n[9]=n[5],n[10]=n[6],n[11]=n[7],n[12]=1;const i=P(n),a=new Uint8Array(4);if(a[0]=i>>>24,a[1]=i>>>16,a[2]=i>>>8,a[3]=i&255,r){const s=W(e);return e.set(n,s),e.set(a,s+13),e}else{const s=new Uint8Array(4);s[0]=0,s[1]=0,s[2]=0,s[3]=9;const o=new Uint8Array(54);return o.set(e,0),o.set(s,33),o.set(n,37),o.set(a,50),o}}const qe="AAlwSFlz",We="AAAJcEhZ",He="AAAACXBI";function Ve(e){let t=e.indexOf(qe);return t===-1&&(t=e.indexOf(We)),t===-1&&(t=e.indexOf(He)),t}const se="[modern-screenshot]",U=typeof window!="undefined",ze=U&&"Worker"in window,ie=U&&"atob"in window,Xe=U&&"btoa"in window,ee=U?(Be=window.navigator)==null?void 0:Be.userAgent:"",le=ee.includes("Chrome"),G=ee.includes("AppleWebKit")&&!le,te=ee.includes("Firefox"),Ge=e=>e&&"__CONTEXT__"in e,Ye=e=>e.constructor.name==="CSSFontFaceRule",Je=e=>e.constructor.name==="CSSImportRule",Ke=e=>e.constructor.name==="CSSLayerBlockRule",I=e=>e.nodeType===1,H=e=>typeof e.className=="object",ce=e=>e.tagName==="image",Qe=e=>e.tagName==="use",V=e=>I(e)&&typeof e.style!="undefined"&&!H(e),Ze=e=>e.nodeType===8,et=e=>e.nodeType===3,$=e=>e.tagName==="IMG",Y=e=>e.tagName==="VIDEO",tt=e=>e.tagName==="CANVAS",rt=e=>e.tagName==="TEXTAREA",nt=e=>e.tagName==="INPUT",ot=e=>e.tagName==="STYLE",at=e=>e.tagName==="SCRIPT",st=e=>e.tagName==="SELECT",it=e=>e.tagName==="SLOT",lt=e=>e.tagName==="IFRAME",ct=(...e)=>console.warn(se,...e);function ut(e){var r;const t=(r=e==null?void 0:e.createElement)==null?void 0:r.call(e,"canvas");return t&&(t.height=t.width=1),!!t&&"toDataURL"in t&&!!t.toDataURL("image/webp").includes("image/webp")}const re=e=>e.startsWith("data:");function ue(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(U&&e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i)||!U)return e;const r=J().implementation.createHTMLDocument(),n=r.createElement("base"),i=r.createElement("a");return r.head.appendChild(n),r.body.appendChild(i),t&&(n.href=t),i.href=e,i.href}function J(e){var t;return(t=e&&I(e)?e==null?void 0:e.ownerDocument:e)!=null?t:window.document}const K="http://www.w3.org/2000/svg";function fe(e,t,r){const n=J(r).createElementNS(K,"svg");return n.setAttributeNS(null,"width",e.toString()),n.setAttributeNS(null,"height",t.toString()),n.setAttributeNS(null,"viewBox",`0 0 ${e} ${t}`),n}function de(e,t){let r=new XMLSerializer().serializeToString(e);return t&&(r=r.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu,"")),`data:image/svg+xml;charset=utf-8,${encodeURIComponent(r)}`}function ft(e,t="image/png",r=1){return C(this,null,function*(){try{return yield new Promise((n,i)=>{e.toBlob(a=>{a?n(a):i(new Error("Blob is null"))},t,r)})}catch(n){if(ie)return dt(e.toDataURL(t,r));throw n}})}function dt(e){var o,c;const[t,r]=e.split(","),n=(c=(o=t.match(/data:(.+);/))==null?void 0:o[1])!=null?c:void 0,i=window.atob(r),a=i.length,s=new Uint8Array(a);for(let u=0;u<a;u+=1)s[u]=i.charCodeAt(u);return new Blob([s],{type:n})}function ge(e,t){return new Promise((r,n)=>{const i=new FileReader;i.onload=()=>r(i.result),i.onerror=()=>n(i.error),i.onabort=()=>n(new Error(`Failed read blob to ${t}`)),t==="dataUrl"?i.readAsDataURL(e):t==="arrayBuffer"&&i.readAsArrayBuffer(e)})}const gt=e=>ge(e,"dataUrl"),mt=e=>ge(e,"arrayBuffer");function _(e,t){const r=J(t).createElement("img");return r.Line truncated
.______background-clip--text {
background-clip: text;
-webkit-background-clip: text;
}
`);return t.appendChild(r),t}function pt(e,t){let{width:r,height:n}=t;if(I(e)&&(!r||!n)){const i=e.getBoundingClientRect();r=r||i.width||Number(e.getAttribute("width"))||0,n=n||i.height||Number(e.getAttribute("height"))||0}return{width:r,height:n}}function yt(e,t){return C(this,null,function*(){const{log:r,timeout:n,drawImageCount:i,drawImageInterval:a}=t;r.time("image to canvas");const s=yield L(e,{timeout:n,onWarn:t.log.warn}),{canvas:o,context2d:c}=bt(e.ownerDocument,t),u=()=>{try{c==null||c.drawImage(s,0,0,o.width,o.height)}catch(l){t.log.warn("Failed to drawImage",l)}};if(u(),t.isEnable("fixSvgXmlDecode"))for(let l=0;l<i;l++)yield new Promise(d=>{setTimeout(()=>{c==null||c.clearRect(0,0,o.width,o.height),u(),d()},l+a)});return t.drawImageCount=0,r.timeEnd("image to canvas"),o})}function bt(e,t){const{width:r,height:n,scale:i,backgroundColor:a,maximumCanvasSize:s}=t,o=e.createElement("canvas");o.width=Math.floor(r*i),o.height=Math.floor(n*i),o.style.width=`${r}px`,o.style.height=`${n}px`,s&&(o.width>s||o.height>s)&&(o.width>s&&o.height>s?o.width>o.height?(o.height*=s/o.width,o.width=s):(o.width*=s/o.height,o.height=s):o.width>s?(o.height*=s/o.width,o.width=s):(o.width*=s/o.height,o.height=s));const c=o.getContext("2d");return c&&a&&(c.fillStyle=a,c.fillRect(0,0,o.width,o.height)),{canvas:o,context2d:c}}function Se(e,t){if(e.ownerDocument)try{const a=e.toDataURL();if(a!=="data:,")return _(a,e.ownerDocument)}catch(a){t.log.warn("Failed to clone canvas",a)}const r=e.cloneNode(!1),n=e.getContext("2d"),i=r.getContext("2d");try{return n&&i&&i.putImageData(n.getImageData(0,0,e.width,e.height),0,0),r}catch(a){t.log.warn("Failed to clone canvas",a)}return r}function St(e,t){var r;try{if((r=e==null?void 0:e.contentDocument)!=null&&r.documentElement)return ne(e.contentDocument.documentElement,t)}catch(n){t.log.warn("Failed to clone iframe",n)}return e.cloneNode(!1)}function Et(e){const t=e.cloneNode(!1);return e.currentSrc&&e.currentSrc!==e.src&&(t.src=e.currentSrc,t.srcset=""),t.loading==="lazy"&&(t.loading="eager"),t}function Ct(e,t){return C(this,null,function*(){if(e.ownerDocument&&!e.currentSrc&&e.poster)return _(e.poster,e.ownerDocument);const r=e.cloneNode(!1);r.crossOrigin="anonymous",e.currentSrc&&e.currentSrc!==e.src&&(r.src=e.currentSrc);const n=r.ownerDocument;if(n){let i=!0;if(yield L(r,{onError:()=>i=!1,onWarn:t.log.warn}),!i)return e.poster?_(e.poster,e.ownerDocument):r;r.currentTime=e.currentTime,yield new Promise(s=>{r.addEventListener("seeked",s,{once:!0})});const a=n.createElement("canvas");a.width=e.offsetWidth,a.height=e.offsetHeight;try{const s=a.getContext("2d");s&&s.drawImage(r,0,0,a.width,a.height)}catch(s){return t.log.warn("Failed to clone video",s),e.poster?_(e.poster,e.ownerDocument):r}return Se(a,t)}return r})}function Tt(e,t){return tt(e)?Se(e,t):lt(e)?St(e,t):$(e)?Et(e):Y(e)?Ct(e,t):e.cloneNode(!1)}function vt(e){let t=e.sandbox;if(!t){const{ownerDocument:r}=e;try{r&&(t=r.createElement("iframe"),t.id=`__SANDBOX__${he()}`,t.width="0",t.height="0",t.style.visibility="hidden",t.style.position="fixed",r.body.appendChild(t),t.srcdoc='<!DOCTYPE html><meta charset="UTF-8"><title></title><body>',e.sandbox=t)}catch(n){e.log.warn("Failed to getSandBox",n)}}return t}const At=["width","height","-webkit-text-fill-color"],Nt=["stroke","fill"];function Ee(e,t,r){const{defaultComputedStyles:n}=r,i=e.nodeName.toLowerCase(),a=H(e)&&i!=="svg",s=a?Nt.map(g=>[g,e.getAttribute(g)]).filter(([,g])=>g!==null):[],o=[a&&"svg",i,s.map((g,p)=>`${g}=${p}`).join(","),t].filter(Boolean).join(":");if(n.has(o))return n.get(o);const c=vt(r),u=c==null?void 0:c.contentWindow;if(!u)return new Map;const l=u==null?void 0:u.document;let d,m;a?(d=l.createElementNS(K,"svg"),m=d.ownerDocument.createElementNS(d.namespaceURI,i),s.forEach(([g,p])=>{m.setAttributeNS(null,g,p)}),d.appendChild(m)):d=m=l.createElement(i),m.textContent=" ",l.body.appendChild(d);const f=u.getComputedStyle(m,t),h=new Map;for(let g=f.length,p=0;p<g;p++){const E=f.item(p);At.includes(E)||h.set(E,f.getPropertyValue(E))}return l.body.removeChild(d),n.set(o,h),h}function Ce(e,t,r){var o;const n=new Map,i=[],a=new Map;if(r)for(const c of r)s(c);else for(let c=e.length,u=0;u<c;u++){const l=e.item(u);s(l)}for(let c=i.length,u=0;u<c;u++)(o=a.get(i[u]))==null||o.forEach((l,d)=>n.set(d,l));function s(c){const u=e.getPropertyValue(c),l=e.getPropertyPriority(c),d=c.lastIndexOf("-"),m=d>-1?c.substring(0,d):void 0;if(m){let f=a.get(m);f||(f=new Map,a.set(m,f)),f.set(c,[u,l])}t.get(c)===u&&!l||(m?i.push(m):n.set(c,[u,l]))}return n}function Rt(e,t,r,n){var d,m,f,h;const{ownerWindow:i,includeStyleProperties:a,currentParentNodeStyle:s}=n,o=t.style,c=i.getComputedStyle(e),u=Ee(e,null,n);s==null||s.forEach((g,p)=>{u.delete(p)});const l=Ce(c,u,a);l.delete("transition-property"),l.delete("all"),l.delete("d"),l.delete("content"),r&&(l.delete("position"),l.delete("margin-top"),l.delete("margin-right"),l.delete("margin-bottom"),l.delete("margin-left"),l.delete("margin-block-st Line truncated
`);let b=o.get(E);b||(b=[],o.set(E,b)),b.push(`.${f[0]}${l}`)}kt.forEach(u),r&&Dt.forEach(u)}const Te=new Set(["symbol"]);function ve(e,t,r,n,i){return C(this,null,function*(){if(I(r)&&(ot(r)||at(r))||n.filter&&!n.filter(r))return;Te.has(t.nodeName)||Te.has(r.nodeName)?n.currentParentNodeStyle=void 0:n.currentParentNodeStyle=n.currentNodeStyle;const a=yield ne(r,n,!1,i);n.isEnable("restoreScrollPosition")&&Ut(e,a),t.appendChild(a)})}function Ae(e,t,r,n){return C(this,null,function*(){var a;let i=e.firstChild;I(e)&&e.shadowRoot&&(i=(a=e.shadowRoot)==null?void 0:a.firstChild,r.shadowRoots.push(e.shadowRoot));for(let s=i;s;s=s.nextSibling)if(!Ze(s))if(I(s)&&it(s)&&typeof s.assignedNodes=="function"){const o=s.assignedNodes();for(let c=0;c<o.length;c++)yield ve(e,t,o[c],r,n)}else yield ve(e,t,s,r,n)})}function Ut(e,t){if(!V(e)||!V(t))return;const{scrollTop:r,scrollLeft:n}=e;if(!r&&!n)return;const{transform:i}=t.style,a=new DOMMatrix(i),{a:s,b:o,c,d:u}=a;a.a=1,a.b=0,a.c=0,a.d=1,a.translateSelf(-n,-r),a.a=s,a.b=o,a.c=c,a.d=u,t.style.transform=a.toString()}function _t(e,t){const{backgroundColor:r,width:n,height:i,style:a}=t,s=e.style;if(r&&s.setProperty("background-color",r,"important"),n&&s.setProperty("width",`${n}px`,"important"),i&&s.setProperty("height",`${i}px`,"important"),a)for(const o in a)s[o]=a[o]}const Ft=/^[\w-:]+$/;function ne(e,t,r=!1,n){return C(this,null,function*(){var u,l,d,m;const{ownerDocument:i,ownerWindow:a,fontFamilies:s,onCloneEachNode:o}=t;if(i&&et(e))return n&&/\S/.test(e.data)&&n(e.data),i.createTextNode(e.data);if(i&&a&&I(e)&&(V(e)||H(e))){const f=yield Tt(e,t);if(t.isEnable("removeAbnormalAttributes")){const w=f.getAttributeNames();for(let S=w.length,T=0;T<S;T++){const A=w[T];Ft.test(A)||f.removeAttribute(A)}}const h=t.currentNodeStyle=Rt(e,f,r,t);r&&_t(f,t);let g=!1;if(t.isEnable("copyScrollbar")){const w=[(u=h.get("overflow-x"))==null?void 0:u[0],(l=h.get("overflow-y"))==null?void 0:l[0]];g=w.includes("scroll")||(w.includes("auto")||w.includes("overlay"))&&(e.scrollHeight>e.clientHeight||e.scrollWidth>e.clientWidth)}const p=(d=h.get("text-transform"))==null?void 0:d[0],E=we((m=h.get("font-family"))==null?void 0:m[0]),b=E?w=>{p==="uppercase"?w=w.toUpperCase():p==="lowercase"?w=w.toLowerCase():p==="capitalize"&&(w=w[0].toUpperCase()+w.substring(1)),E.forEach(S=>{let T=s.get(S);T||s.set(S,T=new Set),w.split("").forEach(A=>T.add(A))})}:void 0;return Pt(e,f,g,t,b),It(e,f),Y(e)||(yield Ae(e,f,t,b)),yield o==null?void 0:o(f),f}const c=e.cloneNode(!1);return yield Ae(e,c,t),yield o==null?void 0:o(c),c})}function Ne(e){if(e.ownerDocument=void 0,e.ownerWindow=void 0,e.svgStyleElement=void 0,e.svgDefsElement=void 0,e.svgStyles.clear(),e.defaultComputedStyles.clear(),e.sandbox){try{e.sandbox.remove()}catch(t){e.log.warn("Failed to destroyContext",t)}e.sandbox=void 0}e.workers=[],e.fontFamilies.clear(),e.fontCssTexts.clear(),e.requests.clear(),e.tasks=[],e.shadowRoots=[]}function Bt(e){const o=e,{url:t,timeout:r,responseType:n}=o,i=je(o,["url","timeout","responseType"]),a=new AbortController,s=r?setTimeout(()=>a.abort(),r):void 0;return fetch(t,D({signal:a.signal},i)).then(c=>{if(!c.ok)throw new Error("Failed fetch, not 2xx response",{cause:c});switch(n){case"arrayBuffer":return c.arrayBuffer();case"dataUrl":return c.blob().then(gt);case"text":default:return c.text()}}).finally(()=>clearTimeout(s))}function z(e,t){const{url:r,requestType:n="text",responseType:i="text",imageDom:a}=t;let s=r;const{timeout:o,acceptOfImage:c,requests:u,fetchFn:l,fetch:{requestInit:d,bypassingCache:m,placeholderImage:f},font:h,workers:g,fontFamilies:p}=e;n==="image"&&(G||te)&&e.drawImageCount++;let E=u.get(r);if(!E){m&&m instanceof RegExp&&m.test(s)&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());const b=n.startsWith("font")&&h&&h.minify,w=new Set;b&&n.split(";")[1].split(",").forEach(F=>{p.has(F)&&p.get(F).forEach(B=>w.add(B))});const S=b&&w.size,T=D({url:s,timeout:o,responseType:S?"arrayBuffer":i,headers:n==="image"?{accept:c}:void 0},d);E={type:n,resolve:void 0,reject:void 0,response:null},E.response=C(this,null,function*(){if(l&&n==="image"){const A=yield l(r);if(A)return A}return!G&&r.startsWith("http")&&g.length?new Promise((A,F)=>{g[u.size&g.length-1].postMessage(D({rawUrl:r},T)),E.resolve=A,E.reject=F}):Bt(T)}).catch(A=>{if(u.delete(r),n==="image"&&f)return e.log.warn("Failed to fetch image base64, trying to use placeholder image",s),typeof f=="string"?f:f(a);throw A}),u.set(r,E)}return E.response}function Re(e,t,r,n){return C(this,null,function*(){if(!Ie(e))return e;for(const[i,a]of $t(e,t))try{const s=yield z(r,{url:a,requestType:n?"image":"text",responseType:"dataUrl"});e=e.replace(Lt(i),`$1${s}$3`)}catch(s){r.log.warn("Failed to fetch css data url",i,s)}return e})}function Ie(e){return/url\((['"]?)([^'"]+?)\1\)/.test(e)}const ke=/url\((['"]?)([^'"]+?)\1\)/g;function $t(e,t){const r=[];return e.replace(ke,(n,i,a)=>(r.push([a,ue(a,t)]),n)),r.filter(([n])=>!re(n))}function Lt(e){const t=e.replace(/([.*+ Line truncated
`))}else{const c=Array.from(r.styleSheets).filter(f=>{try{return"cssRules"in f&&!!f.cssRules.length}catch(h){return t.log.warn(`Error while reading CSS rules from ${f.href}`,h),!1}}),u=r.implementation.createHTMLDocument(""),l=u.createElement("style");u.head.appendChild(l);const d=l.sheet;yield Promise.all(c.flatMap(f=>Array.from(f.cssRules).map(h=>C(this,null,function*(){if(Je(h)){const g=h.href;let p="";try{p=yield z(t,{url:g,requestType:"text",responseType:"text"})}catch(b){t.log.warn(`Error fetch remote css import from ${g}`,b)}const E=p.replace(ke,(b,w,S)=>b.replace(S,ue(S,g)));for(const b of Ht(E))try{d.insertRule(b,d.cssRules.length)}catch(w){t.log.warn("Error inserting rule from remote css import",{rule:b,error:w})}}})))),d.cssRules.length&&c.push(d);const m=[];c.forEach(f=>{oe(f.cssRules,m)}),m.filter(f=>{var h;return Ye(f)&&Ie(f.style.getPropertyValue("src"))&&((h=we(f.style.getPropertyValue("font-family")))==null?void 0:h.some(g=>i.has(g)))}).forEach(f=>{const h=f,g=a.get(h.cssText);g?n.appendChild(r.createTextNode(`${g}
`)):s.push(Re(h.cssText,h.parentStyleSheet?h.parentStyleSheet.href:null,t).then(p=>{p=Ue(p,t),a.set(h.cssText,p),n.appendChild(r.createTextNode(`${p}
`))}))})}})}const Wt=/(\/\*[\s\S]*?\*\/)/g,Pe=/((@.*?keyframes [\s\S]*?){([\s\S]*?}\s*?)})/gi;function Ht(e){if(e==null)return[];const t=[];let r=e.replace(Wt,"");for(;;){const a=Pe.exec(r);if(!a)break;t.push(a[0])}r=r.replace(Pe,"");const n=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,i=new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");for(;;){let a=n.exec(r);if(a)i.lastIndex=n.lastIndex;else if(a=i.exec(r),a)n.lastIndex=i.lastIndex;else break;t.push(a[0])}return t}const Vt=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,zt=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function Ue(e,t){const{font:r}=t,n=r?r==null?void 0:r.preferredFormat:void 0;return n?e.replace(zt,i=>{for(;;){const[a,,s]=Vt.exec(i)||[];if(!s)return"";if(s===n)return`src: ${a};`}}):e}function oe(e,t=[]){for(const r of Array.from(e))Ke(r)?t.push(...oe(r.cssRules)):"cssRules"in r?oe(r.cssRules,t):t.push(r);return t}const Xt=/\bx?link:?href\s*=\s*["'](?!data:)[^"']+["']/i;function Gt(e){return Xt.test(e.innerHTML)}function _e(e,t){return C(this,null,function*(){const r=yield k(e,t);if(I(r.node)&&H(r.node)&&!Gt(r.node))return r.node;const{ownerDocument:n,log:i,tasks:a,svgStyleElement:s,svgDefsElement:o,svgStyles:c,font:u,progress:l,autoDestruct:d,onCloneNode:m,onEmbedNode:f,onCreateForeignObjectSvg:h}=r;i.time("clone node");const g=yield ne(r.node,r,!0);if(s&&n){let S="";c.forEach((T,A)=>{S+=`${T.join(`,
`)} {
${A}
}
`}),s.appendChild(n.createTextNode(S))}i.timeEnd("clone node"),yield m==null?void 0:m(g),u!==!1&&I(g)&&(i.time("embed web font"),yield qt(g,r),i.timeEnd("embed web font")),i.time("embed node"),De(g,r);const p=a.length;let E=0;const b=()=>C(this,null,function*(){for(;;){const S=a.pop();if(!S)break;try{yield S}catch(T){r.log.warn("Failed to run task",T)}l==null||l(++E,p)}});l==null||l(E,p),yield Promise.all([...Array.from({length:4})].map(b)),i.timeEnd("embed node"),yield f==null?void 0:f(g);const w=Yt(g,r);return o&&w.insertBefore(o,w.children[0]),s&&w.insertBefore(s,w.children[0]),d&&Ne(r),yield h==null?void 0:h(w),w})}function Yt(e,t){const{width:r,height:n}=t,i=fe(r,n,e.ownerDocument),a=i.ownerDocument.createElementNS(i.namespaceURI,"foreignObject");return a.setAttributeNS(null,"x","0%"),a.setAttributeNS(null,"y","0%"),a.setAttributeNS(null,"width","100%"),a.setAttributeNS(null,"height","100%"),a.append(e),i.appendChild(a),i}function Q(e,t){return C(this,null,function*(){var s;const r=yield k(e,t),n=yield _e(r),i=de(n,r.isEnable("removeControlCharacter"));r.autoDestruct||(r.svgStyleElement=be(r.ownerDocument),r.svgDefsElement=(s=r.ownerDocument)==null?void 0:s.createElementNS(K,"defs"),r.svgStyles.clear());const a=_(i,n.ownerDocument);return yield yt(a,r)})}function Jt(e,t){return C(this,null,function*(){const r=yield k(e,t),{log:n,type:i,quality:a,dpi:s}=r,o=yield Q(r);n.time("canvas to blob");const c=yield ft(o,i,a);if(["image/png","image/jpeg"].includes(i)&&s){const u=yield mt(c.slice(0,33));let l=new Uint8Array(u);return i==="image/png"?l=ae(l,s):i==="image/jpeg"&&(l=v(l,s)),n.timeEnd("canvas to blob"),new Blob([l,c.slice(33)],{type:i})}return n.timeEnd("canvas to blob"),c})}function x(e,t){return C(this,null,function*(){const r=yield k(e,t),{log:n,quality:i,type:a,dpi:s}=r,o=yield Q(r);n.time("canvas to data url");let c=o.toDataURL(a,i);if(["image/png","image/jpeg"].includes(a)&&s&&ie&&Xe){const[u,l]=c.split(",");let d=0,m=!1;if(a==="image/png"){const w=Ve(l);w>=0?(d=Math.ceil((w+28)/3)*4,m=!0):d=33/3*4}else a==="image/jpeg"&&(d=18/3*4);const f=l.substring(0,d),h=l.substring(d),g=window.atob(f),p=new Uint8Array(g.length);for(let w=0;w<p.length;w++)p[w]=g.charCodeAt(w);const E=a==="image/png"?ae(p,s,m):v(p,s),b=window.btoa(String.fromCharCode(...E));c=[u,",",b,h].join("")}return n.timeEnd("canvas to data url"),c})}function Fe(e,t){return C(this,null,function*(){const r=yield k(e,t),{width:n,height:i,ownerDocument:a}=r,s=yield x(r),o=fe(n,i,a),c=o.ownerDocument.createElementNS(o.namespaceURI,"image");return c.setAttributeNS(null,"href",s),c.setAttributeNS(null,"height","100%"),c.setAttributeNS(null,"width","100%"),o.appendChild(c),de(o,r.isEnable("removeControlCharacter"))})}function Kt(e,t){return C(this,null,function*(){const r=yield k(e,t),{ownerDocument:n,width:i,height:a,scale:s,type:o}=r,c=o==="image/svg+xml"?yield Fe(r):yield x(r),u=_(c,n);return u.width=Math.floor(i*s),u.height=Math.floor(a*s),u.style.width=`${i}px`,u.style.height=`${a}px`,u})}function Qt(e,t){return C(this,null,function*(){return x(yield k(e,M(D({},t),{type:"image/jpeg"})))})}function Zt(e,t){return C(this,null,function*(){const r=yield k(e,t),n=yield Q(r);return n.getContext("2d").getImageData(0,0,n.width,n.height).data})}function er(e,t){return C(this,null,function*(){return x(yield k(e,M(D({},t),{type:"image/png"})))})}function tr(e,t){return C(this,null,function*(){return x(yield k(e,M(D({},t),{type:"image/webp"})))})}y.createContext=ye,y.destroyContext=Ne,y.domToBlob=Jt,y.domToCanvas=Q,y.domToDataUrl=x,y.domToForeignObjectSvg=_e,y.domToImage=Kt,y.domToJpeg=Qt,y.domToPixel=Zt,y.domToPng=er,y.domToSvg=Fe,y.domToWebp=tr,y.loadMedia=L,y.waitUntilLoad=me,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})});