From adf6804b37bc82d43a5fdbeeed9cb2e83ece515b Mon Sep 17 00:00:00 2001 From: lizheming Date: Tue, 1 Dec 2026 03:17:18 +0800 Subject: [PATCH] feat(simply-static): add static site export and publishing plugin --- README.md | 2 + packages/simply-static/IMPLEMENTATION.md | 57 + packages/simply-static/README.md | 248 ++++ packages/simply-static/assets/comments.js | 18 + packages/simply-static/assets/search.css | 30 + packages/simply-static/assets/search.html | 22 + packages/simply-static/assets/search.js | 54 + packages/simply-static/bin/cli.js | 128 ++ .../simply-static/lib/additional-files.js | 38 + packages/simply-static/lib/automation.js | 48 + packages/simply-static/lib/deploy.js | 54 + packages/simply-static/lib/exporter.js | 200 +++ packages/simply-static/lib/fetch-resource.js | 100 ++ packages/simply-static/lib/integrations.js | 65 + packages/simply-static/lib/invalidation.js | 61 + packages/simply-static/lib/jobs.js | 224 +++ packages/simply-static/lib/optimize-image.js | 24 + packages/simply-static/lib/optimize.js | 35 + packages/simply-static/lib/publish-bunny.js | 59 + .../simply-static/lib/publish-cloudflare.js | 47 + packages/simply-static/lib/publish-git.js | 65 + packages/simply-static/lib/publish-local.js | 65 + packages/simply-static/lib/publish-netlify.js | 36 + packages/simply-static/lib/publish-s3.js | 37 + packages/simply-static/lib/publish-sftp.js | 57 + packages/simply-static/lib/resource-cache.js | 39 + packages/simply-static/lib/settings.js | 46 + packages/simply-static/lib/transform.js | 106 ++ packages/simply-static/lib/urls.js | 90 ++ packages/simply-static/package.json | 57 + packages/simply-static/plugin.js | 205 +++ .../test/additional-files.test.js | 32 + .../simply-static/test/automation.test.js | 49 + packages/simply-static/test/cli.test.js | 75 + packages/simply-static/test/deploy.test.js | 31 + packages/simply-static/test/exporter.test.js | 129 ++ .../simply-static/test/fetch-resource.test.js | 63 + .../test/fixtures/create-site.js | 53 + .../simply-static/test/integrations.test.js | 46 + .../simply-static/test/invalidation.test.js | 31 + packages/simply-static/test/jobs.test.js | 130 ++ packages/simply-static/test/live-site.test.js | 81 ++ .../simply-static/test/optimize-image.test.js | 25 + packages/simply-static/test/optimize.test.js | 27 + packages/simply-static/test/plugin.test.js | 51 + .../simply-static/test/publish-bunny.test.js | 45 + .../test/publish-cloudflare.test.js | 34 + .../simply-static/test/publish-git.test.js | 35 + .../simply-static/test/publish-local.test.js | 34 + .../test/publish-netlify.test.js | 36 + .../simply-static/test/publish-s3.test.js | 31 + .../simply-static/test/publish-sftp.test.js | 37 + .../simply-static/test/resource-cache.test.js | 34 + packages/simply-static/test/resume.test.js | 38 + packages/simply-static/test/search-ui.test.js | 55 + packages/simply-static/test/settings.test.js | 22 + packages/simply-static/test/transform.test.js | 50 + packages/simply-static/test/urls.test.js | 53 + pnpm-lock.yaml | 1219 +++++++++++++++++ 59 files changed, 4863 insertions(+) create mode 100644 packages/simply-static/IMPLEMENTATION.md create mode 100644 packages/simply-static/README.md create mode 100644 packages/simply-static/assets/comments.js create mode 100644 packages/simply-static/assets/search.css create mode 100644 packages/simply-static/assets/search.html create mode 100644 packages/simply-static/assets/search.js create mode 100755 packages/simply-static/bin/cli.js create mode 100644 packages/simply-static/lib/additional-files.js create mode 100644 packages/simply-static/lib/automation.js create mode 100644 packages/simply-static/lib/deploy.js create mode 100644 packages/simply-static/lib/exporter.js create mode 100644 packages/simply-static/lib/fetch-resource.js create mode 100644 packages/simply-static/lib/integrations.js create mode 100644 packages/simply-static/lib/invalidation.js create mode 100644 packages/simply-static/lib/jobs.js create mode 100644 packages/simply-static/lib/optimize-image.js create mode 100644 packages/simply-static/lib/optimize.js create mode 100644 packages/simply-static/lib/publish-bunny.js create mode 100644 packages/simply-static/lib/publish-cloudflare.js create mode 100644 packages/simply-static/lib/publish-git.js create mode 100644 packages/simply-static/lib/publish-local.js create mode 100644 packages/simply-static/lib/publish-netlify.js create mode 100644 packages/simply-static/lib/publish-s3.js create mode 100644 packages/simply-static/lib/publish-sftp.js create mode 100644 packages/simply-static/lib/resource-cache.js create mode 100644 packages/simply-static/lib/settings.js create mode 100644 packages/simply-static/lib/transform.js create mode 100644 packages/simply-static/lib/urls.js create mode 100644 packages/simply-static/package.json create mode 100644 packages/simply-static/plugin.js create mode 100644 packages/simply-static/test/additional-files.test.js create mode 100644 packages/simply-static/test/automation.test.js create mode 100644 packages/simply-static/test/cli.test.js create mode 100644 packages/simply-static/test/deploy.test.js create mode 100644 packages/simply-static/test/exporter.test.js create mode 100644 packages/simply-static/test/fetch-resource.test.js create mode 100644 packages/simply-static/test/fixtures/create-site.js create mode 100644 packages/simply-static/test/integrations.test.js create mode 100644 packages/simply-static/test/invalidation.test.js create mode 100644 packages/simply-static/test/jobs.test.js create mode 100644 packages/simply-static/test/live-site.test.js create mode 100644 packages/simply-static/test/optimize-image.test.js create mode 100644 packages/simply-static/test/optimize.test.js create mode 100644 packages/simply-static/test/plugin.test.js create mode 100644 packages/simply-static/test/publish-bunny.test.js create mode 100644 packages/simply-static/test/publish-cloudflare.test.js create mode 100644 packages/simply-static/test/publish-git.test.js create mode 100644 packages/simply-static/test/publish-local.test.js create mode 100644 packages/simply-static/test/publish-netlify.test.js create mode 100644 packages/simply-static/test/publish-s3.test.js create mode 100644 packages/simply-static/test/publish-sftp.test.js create mode 100644 packages/simply-static/test/resource-cache.test.js create mode 100644 packages/simply-static/test/resume.test.js create mode 100644 packages/simply-static/test/search-ui.test.js create mode 100644 packages/simply-static/test/settings.test.js create mode 100644 packages/simply-static/test/transform.test.js create mode 100644 packages/simply-static/test/urls.test.js diff --git a/README.md b/README.md index 4dbc898..72bb003 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,8 @@ packages through `pnpm-workspace.yaml`. - [`firekylin-plugin-embed`](packages/embed): automatically embed supported standalone media and code URLs. +- [`firekylin-plugin-simply-static`](packages/simply-static): export public sites as static HTML/ZIP, with a durable worker, static search, forms/comments integration, and hosting adapters. + ## Publishing Packages are published automatically through npm trusted publishing after their diff --git a/packages/simply-static/IMPLEMENTATION.md b/packages/simply-static/IMPLEMENTATION.md new file mode 100644 index 0000000..6ba8660 --- /dev/null +++ b/packages/simply-static/IMPLEMENTATION.md @@ -0,0 +1,57 @@ +# Feature mapping and validation + +Independent Firekylin implementation of the publishing capabilities described by +[Simply Static](https://wordpress.org/plugins/simply-static/), including the public +Pro feature categories. No Firekylin core files are changed. WordPress-specific +page builders, WP-CLI, form plugins and language plugins are replaced by the +Firekylin rendered-page crawler, CLI and explicit integration settings. Commercial +support and hosted Studio are services, not features provided by this package. + +| Capability | Implementation / boundary | +| --- | --- | +| Full site / theme export | Anonymous HTML, linked pages, pagination, CSS imports, scripts, images, srcset, fonts; additional URL seeds for unlinked/plugin/language routes | +| ZIP / directory / URLs | Complete snapshot and ZIP; absolute or relative links; Unicode filenames, canonical/meta URL rewriting | +| Sitemap / feeds / robots / errors | XML link rewriting; robots Sitemap rewrite; explicit error-page URL produces 404.html | +| Incremental / single page | ETag response reuse; baseline checkpoints refresh selected pages and direct referrers; full snapshots still published | +| Admin / CLI | Settings, enqueue, progress, request logs, ZIP download, single-page form; standalone worker/status/cancel/recover commands | +| Automation | Debounced content events and Cron while the web process runs; durable filesystem queue with serialized execution | +| Destinations | Local managed symlink, Git/GitHub branch, Netlify ZIP API, Cloudflare Wrangler, S3-compatible AWS CLI, Bunny Storage API, SFTP | +| Search | Local JSON index and browser search UI; built-in search routes/forms adapted; no Algolia account required | +| Forms | CSS-selector mappings to HTTPS POST services; arbitrary AJAX form handlers require theme-specific adaptation | +| Comments | Existing external scripts retained; Firekylin Waline containers can target an external Waline server while preserving original page identity | +| Multilingual | Crawl linked language routes, preserve hreflang links; explicitly seed unlinked language entry points | +| Optimization | Optional HTML/CSS/JS minification and optional sharp PNG/JPEG/WebP optimization | +| Recovery | Per-resource checksummed checkpoints, same-host dead-worker recovery; uncertain remote publication is not automatically repeated | + +## Publication semantics + +Local publication switches a managed symlink after staging. Git makes a snapshot +commit without force pushes. Netlify waits for the deployment to become ready; +Cloudflare reports the official command result. S3 and Bunny sync individual +objects and are not atomic. SFTP stages a directory and performs two renames with +rollback on switch failure, leaving a brief gap. Credentials come from the worker +environment, SSH keys or provider tooling, not generated pages. + +## Validation + +- Unit/integration tests cover crawler boundaries, private responses, redirects, + size limits, XML/CSS/HTML transforms, jobs, recovery, scheduling, deployment + failures, forms/comments mapping and browser search execution in jsdom. +- CLI tests use a real local HTTP server and separate worker process, including + single-page updates. Local and Git adapters use real directories and a local + bare Git remote. +- Optional real-core tests register the admin declarations and export an isolated + SQLite-backed Firekylin website with the default theme. Private, draft, future + and password-protected content must not occur in the generated pages/index. +- Remote hosting adapters use mocked transports/commands; real account deployments + and browser visual comparison are not claimed. + +## Operational boundaries + +A persistent shared filesystem and separate worker are required for admin jobs. +Serverless/ephemeral web deployments should execute exports in a persistent CI or +worker environment. Search, forms and comments do not turn authentication, +payments, arbitrary JavaScript APIs or server-side business logic into static HTML. +JavaScript runtime imports/requests are not recursively interpreted by the crawler. +Full export is required after global theme/navigation/visibility changes. Export +memory, provider-specific non-atomic publication and cleanup are documented in README. diff --git a/packages/simply-static/README.md b/packages/simply-static/README.md new file mode 100644 index 0000000..6f86148 --- /dev/null +++ b/packages/simply-static/README.md @@ -0,0 +1,248 @@ +# Firekylin Simply Static + +将 Firekylin 公开网站导出为独立静态文件。复用源站匿名访客看到的 +HTML 和主题资源,不修改 Firekylin core。 + +> 要求 Firekylin 2.19.4+、Node.js 22.13+。这是独立实现,非 Simply Static 官方产品。 +> 功能对照与验证边界见 [IMPLEMENTATION.md](IMPLEMENTATION.md)。 + +## 安装与后台 + +在网站项目中安装此包并启用插件,后台会出现「静态发布」。 +配置源站地址、静态网站地址,然后选择「生成静态网站」。 +源站需要能从工作进程访问。后台发起的导出包含 sitemap.xml、rss.xml +以及自行添加的页面地址。使用源站 sitemap 中的公开链接补充内容发现。 + +源站地址可以包含子目录;目标地址也可包含子目录。相对链接模式允许 +把同一份输出移动到不同的域名或子目录。 + +外部图片、字体和 CSS 默认保留远程引用;如需下载,逐行填写允许的 +外部资源源站,例如 `https://cdn.example.com`。不要把私有服务加入此列表。 + +## 工作进程 + +后台只负责创建任务。请在同一网站项目目录运行独立工作进程: + +```sh +npx --no-install firekylin-static worker --store .firekylin/simply-static/jobs +``` + +使用进程管理器保持其运行。工作进程和 Web 进程需要共享同一持久化目录。 +纯临时文件系统的部署不能依赖这个本地队列;应在持久化执行环境运行 +CLI,例如 CI 中直接执行下面的 `export` 命令。 + +定时生成使用 Cron 表达式与 IANA 时区。定时触发器运行在 Firekylin +进程内,网站进程停止期间不会补跑。自动生成合并短时间内的内容更新, +多个实例会复用相同的待执行任务。 + +## 独立命令行 + +创建 `static.config.json`: + +```json +{ + "sourceUrl": "https://cms.example.com/", + "destinationUrl": "https://www.example.com/", + "relative": false, + "incremental": true, + "additionalUrls": ["/sitemap.xml", "/rss.xml"], + "exclude": ["/private"], + "assetOrigins": ["https://cdn.example.com"] +} +``` + +```sh +npx --no-install firekylin-static export --config static.config.json +npx --no-install firekylin-static enqueue --config static.config.json +npx --no-install firekylin-static worker --once +npx --no-install firekylin-static status --id JOB_ID +npx --no-install firekylin-static cancel --id JOB_ID +``` + +CLI 默认任务目录是 `.firekylin/static-jobs`,可通过 `--store` 显式指定。 +每个任务保存状态和进度,成功后生成 `output/` 和 `output.zip`。 +取消任务会保留诊断信息,不会将未完成的输出发布出去。 + +## 本地发布 + +配置 `localDestination` 为绝对路径。插件在目标旁创建完整发布目录, +通过替换符号链接切换版本。目标必须不存在或为插件创建的发布链接, +不会覆盖已有普通目录。旧版本保留以便人工恢复,暂不自动清理。 +Web 服务器须允许跟随此发布链接。此方式依赖支持符号链接的文件系统。 + +## Git 发布 + +配置 `gitRepository` 与 `gitBranch`(默认 `gh-pages`)。工作进程使用 +Git 凭据助手或 SSH 身份验证;不要把密码或 Token 放到仓库 URL。 +插件创建完整静态快照提交,清理分支上旧的静态文件,不使用强制推送。 +发布分支应专用于静态输出,不能指向网站源码分支。 + +每个任务只能配置一个发布目标。GitHub Pages 或其他托管平台仍需配置为读取 +指定发布分支;提交分支成功不代表托管平台已经部署完成。 + +## 搜索和动态功能 + +输出包含 `static-search.html`、脚本、样式和公开页面搜索索引。可将导航 +链接指向这个页面。搜索在浏览器端执行,不依赖 Firekylin 后台。 + +现有独立评论服务脚本会随页面保留,但仍需要评论服务可访问。依赖源站 +API 的登录和动态请求不会自动变成静态功能。普通表单可配置外部端点; +内置评论可通过 `commentServerUrl` 指向独立 Waline 服务(HTTPS)。插件保留 +原页面 pathname 作为评论标识,移动静态站子目录不会产生新的评论线程。 +服务端须允许静态站域名的跨域请求,并配置验证码域名;原站登录状态不会 +传递到独立评论服务。默认保留既有第三方评论脚本,未适配的内置评论会记录警告。 + +## 目前的验证范围 + +测试覆盖 URL 映射、下载限制和重定向、HTML/CSS/XML 解析、目录和 ZIP +生成、条件请求缓存、持久化队列、定时触发、真实本地 HTTP 抓取、本地 +发布切换及真实本地 Git 远端发布。可使用真实 core 后台注册器验证声明: + +```sh +FIREKYLIN_CORE_PATH=/absolute/path/to/firekylin node --test test/*.test.js +``` + +另有真实 SQLite Firekylin 默认主题导出测试,验证草稿、私密、未来发布和 +密码保护内容不泄露。搜索 UI 通过 jsdom 执行测试;未进行真实浏览器外观验收。 +远程平台使用模拟传输/进程测试,未使用真实账号部署。 + +## Netlify 发布 + +后台填写 `netlifySiteId`,或在 CLI 配置中设置同名字段。工作进程环境 +需要 `NETLIFY_AUTH_TOKEN`。不要将该令牌放进配置 JSON、任务记录或代码仓库。 +插件上传完整 ZIP 并轮询部署状态,只有 Netlify 返回 `ready` 才判定成功。 +如果超过等待次数,错误中保留部署 ID,应先检查已有部署,避免重复上传。 +每个任务只能配置一个发布目标。当前只有模拟接口测试,尚未在真实账号验收。 + +## 中断任务恢复 + +工作进程异常退出后,可在原执行主机使用: + +```sh +npx --no-install firekylin-static recover --id JOB_ID --store .firekylin/simply-static/jobs +``` + +恢复前会检查锁文件中的主机和进程,活跃进程、其他主机或无法确认的 +所有者不会被抢占。恢复重新排队执行抓取,启用增量缓存时可以复用条件 +请求结果。若中断发生在发布阶段,必须先核对远端结果,不会自动重试发布。 + +## 额外文件与表单适配 + +CLI 配置可添加未被页面引用的文件或目录: + +```json +{ + "additionalFiles": [{"source": "public-downloads", "target": "downloads"}], + "searchSelectors": ["form.site-search"], + "forms": [{"selector": "form.contact", "endpoint": "https://forms.example/submit"}] +} +``` + +`source` 相对于工作进程的工作目录,`target` 相对于导出根目录。额外文件 +拒绝隐藏文件、符号链接、路径越界和已生成文件冲突;仍需确认指定目录 +只包含可公开资料。 + +搜索适配会将匹配表单的查询字段改为 `q` 并指向静态搜索页。表单适配 +仅适用于普通 HTML POST 表单,外部服务需接受对应字段;第三方脚本绑定 +的 AJAX 表单可能需要另行适配。未匹配表单会在导出清单中记录警告。 + +## 输出优化 + +`minify` 启用保守的 HTML/CSS/JavaScript 压缩,不改变量名、不合并 HTML +文本空白。`optimizeImages` 使用可选依赖 sharp,保持图片格式、尺寸及 URL, +仅在结果更小时替换。PNG 使用无损压缩;JPEG/WebP 使用质量 85 的有损压缩。 +动画、带方向信息或 ICC 配置的图片保持原样。缺少 sharp 时开启图片优化 +会明确报错,关闭此功能仍可正常导出。 + +## Cloudflare Pages 发布 + +后台配置 `cloudflareProject` 和 `cloudflareBranch`。工作进程 PATH 中需 +预先安装 Wrangler,环境提供 `CLOUDFLARE_API_TOKEN` 与 `CLOUDFLARE_ACCOUNT_ID`。 +分支匹配 Pages 项目的生产分支时发布生产版本,否则发布预览版本。 +插件在隔离工作目录中运行官方 `wrangler pages deploy`,不会自动安装 CLI。 +返回 `command-completed` 表示 Wrangler 成功退出,仍应查看 Pages 部署详情 +核对自定义域名的上线情况。当前测试使用模拟执行器,未操作真实账号。 + +恢复任务会读取任务专属抓取检查点,复用成功下载的原始响应,并重新解析 +链接来重建未完成队列。检查点代表该次导出看到的版本;若源站已发生较大 +变化,应创建新任务而非恢复旧任务,以获取最新内容。 + +## S3 兼容存储 + +配置 `s3Destination`(例如 `s3://example/site/`),可选 `s3Endpoint` 指向 +HTTPS 兼容服务。工作进程 PATH 需安装 AWS CLI,使用它的标准环境或配置 +文件提供凭据。目标前缀应专用于静态网站;同步会删除该前缀中源目录不存在 +的文件。当前为逐对象同步,非原子切换,中断可能留下混合版本,需重试修复。 +需要原子发布时请使用本地版本切换、Git 或支持版本化部署的托管目标。 + +## Bunny Storage 发布 + +配置 `bunnyZone`、不含首尾斜杠的专用目录 `bunnyPrefix`,以及可选的 +区域存储主机 `bunnyHostname`。工作进程通过 `BUNNY_STORAGE_PASSWORD` +读取存储密码,不能使用普通账户 API Key 替代存储密码。 +全部上传成功后才枚举并删除专用目录中的旧文件。上传使用 SHA-256 校验, +不跟随 HTTP 重定向。同步不是原子操作;需另行清除 CDN 缓存并核对线上结果, +当前完成状态只代表存储同步,不能代表所有边缘节点已更新。 + +## SFTP 发布 + +配置 `sftpHost`、`sftpUsername`、`sftpDestination`,可选 `sftpPort`(默认 22)。 +`sftpFingerprint` 必须为通过可信渠道确认的服务器主机公钥 SHA-256 +十六进制摘要(64 个字符)。未匹配的主机密钥会拒绝连接。 + +工作进程环境通过 `STATIC_SFTP_KEY_FILE` 指定私钥文件,可选 +`STATIC_SFTP_KEY_PASSPHRASE`,或使用 `STATIC_SFTP_PASSWORD`。凭据不保存在 +后台设置中。目标路径必须为专用目录,父目录需已存在且允许写入。 + +上传先写入同级暂存目录,完成后将旧目录改名为备份,再将新目录改名到 +目标路径。第二次改名失败时尝试恢复旧目录。两次改名之间有短暂不可用 +窗口,所以不能称为原子发布;旧备份和失败暂存目录暂时保留,便于恢复。 +目前测试使用模拟客户端,尚未在真实 SFTP 服务完成验收。 + +## 单页、增量与完整快照 + +后台「更新单页」填写一个已完成任务 ID 和页面地址,或执行: + +```sh +npx --no-install firekylin-static update-page --id BASELINE_ID --url /post/example.html --store .firekylin/simply-static/jobs +``` + +任务沿用基线配置,更新目标、首页、直接引用目标的页面、Feed/Sitemap 和 +资源文件;复用其余 HTML 下载检查点,然后重新生成完整快照、搜索索引和 ZIP。 +目标明确返回 404/410 时移除该页。主题、菜单、全局挂件、权限或列表布局变化 +应执行全站导出,不应使用单页模式。发布仍传输完整快照,单页模式优化抓取阶段。 + +`incremental` 使用 HTTP ETag 条件请求减少下载;源站未提供 ETag 时正常下载。 +每次全站导出重新发现链接,因此不会沿用上次已删除的页面。CLI 默认只以首页 +为入口,`additionalUrls` 可加入 Sitemap、RSS、robots.txt、多语言首页和插件路由。 +隐藏在脚本运行结果中、未被 HTML/Sitemap 引用的地址也应明确添加。 + +可选 `errorPageUrl` 指向源站的一个不存在页面,允许其返回 404 并导出为 +`404.html`(不加入搜索索引);静态托管平台需要配置使用这个错误页。 +robots.txt 的 Sitemap 地址随目标地址改写,其他爬虫规则保持原样。 + +## 执行与资源边界 + +同一个任务目录只允许一个工作进程执行导出/发布,避免旧快照覆盖新版本。 +中断抓取可恢复;中断发布必须先检查远端是否已生效。不同任务目录不共享锁, +不要让它们同时发布到同一目标。取消发布可能发生在远端已接受请求之后,应核对 +远端状态;取消不等于回滚。 + +默认限制为 10,000 个资源、单资源 32 MiB、总下载 512 MiB,每次下载 60 秒, +暂时性错误最多重试两次。可通过 CLI 配置 `maxPages`、`maxResourceBytes`、 +`maxTotalBytes`、`timeout`。导出器在内存中解析并压缩 ZIP,内存应明显大于 +总下载限制;大型站点应降低单次范围或提高工作进程内存。额外文件有独立大小限制。 + +队列、检查点、日志和本地历史发布不会自动清理,请按保留策略清理已结束任务。 +若进程恰在入队时崩溃留下 `.enqueue-lock`,停止所有使用该目录的 Web/worker +进程后再删除该锁;不要在进程仍运行时强行解锁。 + +## 运行测试 + +仓库根目录执行 `pnpm test`。可选真实 Firekylin 集成测试: + +```sh +FIREKYLIN_CORE_PATH=/absolute/path/to/waterkylin STATIC_LIVE_TEST=1 pnpm --filter firekylin-plugin-simply-static test +``` + +集成测试创建临时 SQLite 网站与独立服务,不使用线上管理员 Cookie 或线上数据。 diff --git a/packages/simply-static/assets/comments.js b/packages/simply-static/assets/comments.js new file mode 100644 index 0000000..950c98f --- /dev/null +++ b/packages/simply-static/assets/comments.js @@ -0,0 +1,18 @@ +'use strict'; + +for (const container of document.querySelectorAll('.fk-comment-container[data-comment-config]')) { + const config = JSON.parse(container.dataset.commentConfig); + const resources = config.resources; + delete config.resources; + config.el = container; + const style = document.createElement('link'); + style.rel = 'stylesheet'; + style.href = resources.style; + document.head.appendChild(style); + import(resources.script).then(client => { + container.textContent = ''; + client.init(config); + }).catch(() => { + container.textContent = config.loadError || '评论加载失败'; + }); +} diff --git a/packages/simply-static/assets/search.css b/packages/simply-static/assets/search.css new file mode 100644 index 0000000..192d6c4 --- /dev/null +++ b/packages/simply-static/assets/search.css @@ -0,0 +1,30 @@ +:root { + color-scheme: light dark; + font-family: system-ui, sans-serif; + line-height: 1.6; +} +main { + max-width: 48rem; + margin: 3rem auto; + padding: 0 1rem; +} +form { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + align-items: center; +} +input { + flex: 1; + min-width: 10rem; + padding: 0.6rem; +} +button { + padding: 0.6rem 1rem; +} +li { + margin-bottom: 1.5rem; +} +p { + overflow-wrap: anywhere; +} diff --git a/packages/simply-static/assets/search.html b/packages/simply-static/assets/search.html new file mode 100644 index 0000000..1d1d906 --- /dev/null +++ b/packages/simply-static/assets/search.html @@ -0,0 +1,22 @@ + + + + + + 站内搜索 + + + + +
+

站内搜索

+
+ + + +
+

正在加载搜索索引…

+
    +
    + + diff --git a/packages/simply-static/assets/search.js b/packages/simply-static/assets/search.js new file mode 100644 index 0000000..fed305d --- /dev/null +++ b/packages/simply-static/assets/search.js @@ -0,0 +1,54 @@ +'use strict'; + +(async function initializeSearch() { + const form = document.querySelector('[data-static-search]'); + if (!form) return; + const input = form.querySelector('input'); + const results = document.querySelector('[data-search-results]'); + const status = document.querySelector('[data-search-status]'); + let index; + try { + const response = await fetch(new URL('static-search.json', document.baseURI)); + if (!response.ok) throw new Error('Search index unavailable'); + index = await response.json(); + } catch { + status.textContent = '搜索索引加载失败,请稍后重试。'; + return; + } + const search = () => { + const query = input.value.trim().toLocaleLowerCase(); + results.replaceChildren(); + if (!query) { + status.textContent = '请输入搜索词。'; + return; + } + const terms = query.split(/\s+/); + const matches = index.filter(page => { + const content = (page.title + ' ' + page.text).toLocaleLowerCase(); + return terms.every(term => content.includes(term)); + }).sort((a, b) => Number(b.title.toLocaleLowerCase().includes(query)) - + Number(a.title.toLocaleLowerCase().includes(query))); + status.textContent = `找到 ${matches.length} 个结果。`; + for (const page of matches.slice(0, 100)) { + const item = document.createElement('li'); + const link = document.createElement('a'); + link.textContent = page.title || page.url; + const url = new URL(page.url, document.baseURI); + if (!['http:', 'https:'].includes(url.protocol)) continue; + link.href = url.href; + const snippet = document.createElement('p'); + const match = page.text.toLocaleLowerCase().indexOf(terms[0]); + const start = Math.max(0, match - 60); + snippet.textContent = (start ? '…' : '') + page.text.slice(start, start + 240); + item.append(link, snippet); + results.append(item); + } + }; + form.addEventListener('submit', event => { + event.preventDefault(); + search(); + }); + input.addEventListener('input', search); + input.value = new URL(location.href).searchParams.get('q') || ''; + search(); +})(); diff --git a/packages/simply-static/bin/cli.js b/packages/simply-static/bin/cli.js new file mode 100755 index 0000000..1becc48 --- /dev/null +++ b/packages/simply-static/bin/cli.js @@ -0,0 +1,128 @@ +#!/usr/bin/env node +'use strict'; + +const fs = require('node:fs/promises'); +const path = require('node:path'); +const {setTimeout: delay} = require('node:timers/promises'); +const {JobStore} = require('../lib/jobs'); +const {exportSite} = require('../lib/exporter'); +const {deploy, validateDeployment} = require('../lib/deploy'); +const {preparePageUpdate} = require('../lib/invalidation'); + +async function main(args = process.argv.slice(2)) { + const [command, ...rest] = args; + const options = {}; + for (let index = 0; index < rest.length; index++) { + const key = rest[index]; + if (!key.startsWith('--')) throw new Error(`Unexpected argument: ${key}`); + if (key === '--once') options.once = true; + else { + const value = rest[++index]; + if (!value || value.startsWith('--')) throw new Error(`Missing value for ${key}`); + options[key.slice(2)] = value; + } + } + const store = new JobStore(options.store || path.join(process.cwd(), '.firekylin', 'static-jobs')); + if (command === 'enqueue' || command === 'export') { + if (!options.config) throw new Error('--config is required'); + const config = JSON.parse(await fs.readFile(options.config, 'utf8')); + const job = await store.create(config, config.additionalUrls || []); + if (command === 'enqueue') { + process.stdout.write(JSON.stringify({id: job.id, status: job.status}) + '\n'); + return; + } + const result = await run(store, job.id); + process.stdout.write(JSON.stringify(result) + '\n'); + if (!result || result.status !== 'completed') process.exitCode = 1; + return; + } + if (command === 'update-page') { + if (!options.id || !options.url) throw new Error('--id and --url are required'); + const previous = await store.read(options.id); + if (previous.status !== 'completed') throw new Error('Page updates require a completed baseline export'); + const config = {...previous.config, pageUpdate: {baseId: previous.id, urls: [options.url]}}; + const job = await store.enqueue(config, previous.seeds); + process.stdout.write(JSON.stringify({id: job.id, status: job.status}) + '\n'); + return; + } + if (command === 'status') { + process.stdout.write(JSON.stringify(options.id ? await store.read(options.id) : await store.list(), null, 2) + '\n'); + return; + } + if (command === 'recover') { + if (!options.id) throw new Error('--id is required'); + await store.recover(options.id); + return; + } + if (command === 'cancel') { + if (!options.id) throw new Error('--id is required'); + await store.cancel(options.id); + return; + } + if (command === 'worker') { + let stopping = false; + const stop = () => { stopping = true; }; + process.once('SIGTERM', stop); + process.once('SIGINT', stop); + try { + do { + const jobs = (await store.list()).reverse(); + for (const job of jobs) { + if (stopping) break; + if (job.status === 'queued') await run(store, job.id); + } + if (!options.once && !stopping) await delay(1000); + } while (!options.once && !stopping); + } finally { + process.removeListener('SIGTERM', stop); + process.removeListener('SIGINT', stop); + } + return; + } + throw new Error('Usage: firekylin-static export|enqueue --config FILE [--store DIR]; worker [--once]; status|cancel|recover --id ID; update-page --id BASELINE --url URL'); +} + +async function run(store, id) { + return store.run(id, async(job, context) => { + validateDeployment(job.config); + if (job.config.pageUpdate) { + const {baseId, urls} = job.config.pageUpdate; + const baseline = await store.read(baseId); + if (baseline.status !== 'completed') throw new Error('Page update baseline is not complete'); + const stripUpdate = value => { + const copy = {...value}; + delete copy.pageUpdate; + return JSON.stringify(copy); + }; + if (stripUpdate(baseline.config) !== stripUpdate(job.config)) { + throw new Error('Page update settings differ from baseline; run a full export'); + } + await preparePageUpdate({ + previousCheckpoint: path.join(store.location(baseId), 'checkpoint'), + checkpointDirectory: path.join(store.location(job.id), 'checkpoint'), + config: job.config, urls + }); + } + await fs.rm(context.directory, {recursive: true, force: true}); + const manifest = await exportSite(job.config, { + ...context, seeds: [...job.seeds, ...(job.config.pageUpdate?.urls || [])], + checkpointDirectory: path.join(store.location(job.id), 'checkpoint'), + cacheDirectory: job.config.incremental ? path.join(store.root, '.resource-cache') : undefined + }); + await context.onPhase('deploying'); + const deployment = await deploy(context.directory, job.config, { + signal: context.signal, onProgress: context.onProgress + }); + return {resources: manifest.resources.length, directory: context.directory, + archive: context.directory + '.zip', deployment}; + }); +} + +if (require.main === module) { + main().catch(error => { + process.stderr.write(error.message + '\n'); + process.exitCode = 1; + }); +} + +module.exports = {main, run}; diff --git a/packages/simply-static/lib/additional-files.js b/packages/simply-static/lib/additional-files.js new file mode 100644 index 0000000..8713951 --- /dev/null +++ b/packages/simply-static/lib/additional-files.js @@ -0,0 +1,38 @@ +'use strict'; + +const fs = require('node:fs/promises'); +const path = require('node:path'); + +async function additionalFiles(entries = [], {baseDirectory = process.cwd(), maxBytes = 64 * 1024 * 1024} = {}) { + const output = new Map(); + let size = 0; + async function collect(source, target) { + const stat = await fs.lstat(source); + if (stat.isSymbolicLink()) throw new Error('Additional files cannot be symlinks'); + if (stat.isDirectory()) { + for (const child of await fs.readdir(source)) { + await collect(path.join(source, child), path.posix.join(target, child)); + } + return; + } + if (!stat.isFile()) throw new Error('Additional files must be regular files'); + if (target.split('/').some(part => part.startsWith('.'))) { + throw new Error('Hidden files cannot be added to a public export'); + } + if (output.has(target)) throw new Error(`Duplicate additional file: ${target}`); + size += stat.size; + if (size > maxBytes) throw new Error('Additional files exceed size limit'); + output.set(target, await fs.readFile(source)); + } + for (const entry of entries) { + if (!entry || typeof entry.source !== 'string' || typeof entry.target !== 'string' || + !entry.target || entry.target.startsWith('/') || /[\\\x00-\x1f]/.test(entry.target) || + entry.target.split('/').some(part => !part || part === '..' || part === '.')) { + throw new Error('Invalid additional file mapping'); + } + await collect(path.resolve(baseDirectory, entry.source), entry.target); + } + return output; +} + +module.exports = {additionalFiles}; diff --git a/packages/simply-static/lib/automation.js b/packages/simply-static/lib/automation.js new file mode 100644 index 0000000..21b9099 --- /dev/null +++ b/packages/simply-static/lib/automation.js @@ -0,0 +1,48 @@ +'use strict'; + +const {Cron} = require('croner'); + +class ExportAutomation { + constructor({enqueue, logger = console, debounceMs = 2000}) { + this.enqueue = enqueue; + this.logger = logger; + this.debounceMs = debounceMs; + this.enabled = false; + this.closed = false; + this.pending = null; + } + + configure({autoPublish = false, schedule = '', timezone = 'UTC'} = {}) { + const next = schedule ? new Cron(schedule, {timezone, paused: true}, () => this.trigger()) : null; + this.cron?.stop(); + this.cron = next; + this.enabled = autoPublish === true; + this.cron?.resume(); + } + + changed() { + if (!this.enabled || this.closed) return; + clearTimeout(this.timer); + this.timer = setTimeout(() => void this.trigger(), this.debounceMs); + this.timer.unref?.(); + } + + async trigger() { + if (this.closed) return; + if (this.pending) return this.pending; + this.pending = Promise.resolve().then(() => this.enqueue()).catch(error => { + this.logger.error(`Static export scheduling failed: ${error.message}`); + }).finally(() => { + this.pending = null; + }); + return this.pending; + } + + stop() { + this.closed = true; + clearTimeout(this.timer); + this.cron?.stop(); + } +} + +module.exports = {ExportAutomation}; diff --git a/packages/simply-static/lib/deploy.js b/packages/simply-static/lib/deploy.js new file mode 100644 index 0000000..8682423 --- /dev/null +++ b/packages/simply-static/lib/deploy.js @@ -0,0 +1,54 @@ +'use strict'; + +const {publishLocal} = require('./publish-local'); +const {publishGit} = require('./publish-git'); +const {publishNetlify} = require('./publish-netlify'); +const {publishCloudflare} = require('./publish-cloudflare'); +const {publishS3} = require('./publish-s3'); +const {publishBunny} = require('./publish-bunny'); +const {publishSftp} = require('./publish-sftp'); + +function validateDeployment(config) { + const targets = [config.localDestination, config.gitRepository, config.netlifySiteId, config.cloudflareProject, config.s3Destination, config.bunnyZone, config.sftpHost].filter(Boolean); + if (targets.length > 1) throw new Error('Configure only one publication destination per export'); + if (config.netlifySiteId && !/^[a-z0-9][a-z0-9.-]*$/i.test(config.netlifySiteId)) { + throw new Error('Invalid Netlify site ID'); + } +} + +async function deploy(directory, config, {signal, onProgress, adapters = {publishLocal, publishGit, publishNetlify, publishCloudflare, publishS3, publishBunny, publishSftp}} = {}) { + validateDeployment(config); + signal?.throwIfAborted(); + if (config.sftpHost) { + return adapters.publishSftp(directory, {host: config.sftpHost, username: config.sftpUsername, + destination: config.sftpDestination, fingerprint: config.sftpFingerprint, + port: Number(config.sftpPort) || 22, signal}); + } + if (config.bunnyZone) { + return adapters.publishBunny(directory, { + zone: config.bunnyZone, prefix: config.bunnyPrefix, hostname: config.bunnyHostname || undefined, signal + }); + } + if (config.s3Destination) { + return adapters.publishS3(directory, {destination: config.s3Destination, endpoint: config.s3Endpoint, signal}); + } + if (config.cloudflareProject) { + return adapters.publishCloudflare(directory, { + project: config.cloudflareProject, branch: config.cloudflareBranch, signal + }); + } + if (config.netlifySiteId) { + return adapters.publishNetlify(directory + '.zip', { + siteId: config.netlifySiteId, signal, onProgress + }); + } + if (config.gitRepository) { + return adapters.publishGit(directory, { + repository: config.gitRepository, branch: config.gitBranch || 'gh-pages', signal + }); + } + if (config.localDestination) return adapters.publishLocal(directory, config.localDestination); + return null; +} + +module.exports = {deploy, validateDeployment}; diff --git a/packages/simply-static/lib/exporter.js b/packages/simply-static/lib/exporter.js new file mode 100644 index 0000000..1765f5b --- /dev/null +++ b/packages/simply-static/lib/exporter.js @@ -0,0 +1,200 @@ +'use strict'; + +const fs = require('node:fs/promises'); +const path = require('node:path'); +const {createHash} = require('node:crypto'); +const {zipSync} = require('fflate'); +const {UrlPolicy} = require('./urls'); +const {fetchResource} = require('./fetch-resource'); +const {ResourceCache} = require('./resource-cache'); +const {integrateHtml} = require('./integrations'); +const {optimize} = require('./optimize'); +const {optimizeImage} = require('./optimize-image'); +const {additionalFiles} = require('./additional-files'); +const {transformHtml, transformCss, transformXml, transformRobots} = require('./transform'); + +async function exportSite(config, {directory, seeds = [], fetcher = fetch, signal, + cacheDirectory, checkpointDirectory, onLog = async() => {}, onProgress = async() => {}} = {}) { + const policy = new UrlPolicy(config); + const cache = cacheDirectory ? new ResourceCache(cacheDirectory) : null; + const checkpoint = checkpointDirectory ? new ResourceCache(checkpointDirectory) : null; + const queue = new Map(); + const records = new Map(); + const removed = new Set(); + const updateTargets = new Set((config.pageUpdate?.urls || []).map(value => policy.resolve(value).href)); + const files = new Map(); + const maxPages = config.maxPages || 10000; + const maxTotalBytes = config.maxTotalBytes || 512 * 1024 * 1024; + let totalBytes = 0; + function discover(value, asset = false, base = policy.source) { + const url = policy.resolve(value, base); + if (!policy.allowed(url, asset)) return null; + if (!queue.has(url.href)) { + if (queue.size >= maxPages) throw new Error('Export resource count limit exceeded'); + queue.set(url.href, {url, asset}); + } + return url; + } + const errorPage = config.errorPageUrl ? policy.resolve(config.errorPageUrl).href : null; + if (errorPage) discover(errorPage); + discover(policy.source.href); + for (const seed of seeds) discover(seed); + const references = (base, collect) => (value, asset, relativeBase = base) => { + if (!value || /^(#|data:|mailto:|tel:|javascript:|blob:)/i.test(value.trim())) return value; + let resolved; + try { + resolved = policy.resolve(value, relativeBase); + } catch { + return value; + } + if (!policy.allowed(resolved, asset)) return value; + const relativePath = resolved.pathname.slice(policy.source.pathname.length); + if (!asset && config.staticSearch !== false && /^search(?:\.html)?\/?$/.test(relativePath)) { + if (collect) return value; + const query = resolved.searchParams.get('keyword') || resolved.searchParams.get('q'); + const searchLink = policy.link('static-search.html', records.get(base).file); + return searchLink + (query ? '?q=' + encodeURIComponent(query) : ''); + } + + if (collect) { + discover(resolved.href, asset); + return value; + } + const target = records.get(resolved.href); + if (!target && removed.has(resolved.href)) { + return new URL(resolved.pathname.slice(policy.source.pathname.length), policy.destination).href; + } + if (!target) throw new Error(`Unresolved exported reference: ${resolved.pathname}`); + const fragment = new URL(value, relativeBase).hash; + return policy.link(target.file, records.get(base).file, fragment); + }; + // Map iteration visits newly discovered resources in insertion order. + for (const [key, entry] of queue) { + signal?.throwIfAborted(); + let response; + const attempts = []; + try { + response = await checkpoint?.read(key); + if (response) { + const resumedUrl = policy.resolve(response.url); + if (!policy.allowed(resumedUrl, entry.asset)) throw new Error('Checkpoint URL is outside export scope'); + if (response.body.length > (config.maxResourceBytes || 32 * 1024 * 1024)) { + throw new Error('Checkpoint resource exceeds size limit'); + } + response = {...response, resumed: true}; + } else { + response = await fetchResource(key, { + policy, asset: entry.asset, fetcher, signal, acceptedStatuses: key === errorPage ? [404] : [], cached: await cache?.read(key), + timeout: config.timeout || 60000, maxBytes: config.maxResourceBytes || 32 * 1024 * 1024, + onAttempt: attempt => attempts.push(attempt) + }); + await checkpoint?.write(response); + } + await onLog({stage: 'fetch', url: key, status: response.status, + reused: response.reused === true, resumed: response.resumed === true, bytes: response.body.length, attempts: attempts.length}); + } catch (error) { + await onLog({stage: 'fetch', url: key, status: error.status || null, + error: error.message, attempts: attempts.length}); + if ([404, 410].includes(error.status) && updateTargets.has(key)) { + removed.add(key); + continue; + } + throw error; + } + await cache?.write(response); + totalBytes += response.body.length; + if (totalBytes > maxTotalBytes) throw new Error('Export total download size limit exceeded'); + const html = /\btext\/html\b/i.test(response.contentType); + const css = /\btext\/css\b/i.test(response.contentType); + const xml = /(?:xml|rss|atom)/i.test(response.contentType); + const finalUrl = policy.resolve(response.url); + const robots = finalUrl.pathname.endsWith('/robots.txt'); + const filename = key === errorPage ? '404.html' : policy.file(finalUrl, html); + if (files.has(filename) && files.get(filename) !== response.url) { + const existing = records.get(files.get(filename)); + if (existing.contentType === response.contentType && existing.body.equals(response.body)) { + records.set(key, existing); + records.set(response.url, existing); + continue; + } + throw new Error(`Output path collision: ${filename}`); + } + files.set(filename, response.url); + const record = {...response, file: filename, html, css, xml, robots}; + records.set(key, record); + records.set(response.url, record); + const rewrite = references(response.url, true); + if (html) transformHtml(response.body.toString('utf8'), {url: response.url, rewrite}); + if (css) transformCss(response.body.toString('utf8'), rewrite); + if (robots) transformRobots(response.body.toString('utf8'), rewrite); + if (xml) transformXml(response.body.toString('utf8'), rewrite); + await onProgress({completed: files.size, discovered: queue.size, bytes: totalBytes, url: key}); + } + await fs.mkdir(directory, {recursive: true}); + const archive = {}; + const manifest = {schemaVersion: 1, createdAt: new Date().toISOString(), resources: [], warnings: [], removed: [...removed]}; + const search = []; + for (const record of new Set(records.values())) { + signal?.throwIfAborted(); + let body = record.body; + const rewrite = references(record.url, false); + if (record.html) { + const transformed = transformHtml(body.toString('utf8'), {url: record.url, rewrite}); + const integrated = integrateHtml(transformed.html, { + pageUrl: record.url, commentServerUrl: config.commentServerUrl, + commentScriptUrl: policy.link('static-comments.js', record.file), searchUrl: policy.link('static-search.html', record.file), + forms: config.forms || [], searchSelectors: [ + ...(config.staticSearch !== false ? ['form[action="/search.html"]', 'form[action="/search"]'] : []), + ...(config.searchSelectors || []) + ] + }); + manifest.warnings.push(...integrated.warnings); + body = Buffer.from(integrated.html); + if (record.url !== errorPage) search.push({url: policy.link(record.file, 'index.html'), title: transformed.title, text: transformed.text}); + } else if (record.robots) { + body = Buffer.from(transformRobots(body.toString('utf8'), rewrite)); + } else if (record.xml) { + body = Buffer.from(transformXml(body.toString('utf8'), rewrite)); + } else if (record.css) { + body = Buffer.from(transformCss(body.toString('utf8'), rewrite)); + } + body = await optimize(body, record.contentType, config.minify); + body = await optimizeImage(body, record.contentType, config.optimizeImages); + const output = path.join(directory, record.file); + await fs.mkdir(path.dirname(output), {recursive: true}); + await fs.writeFile(output, body); + archive[record.file] = body; + manifest.resources.push({url: record.url, file: record.file, bytes: body.length, + hash: createHash('sha256').update(body).digest('hex')}); + } + for (const [source, filename] of Object.entries({ + 'comments.js': 'static-comments.js', 'search.html': 'static-search.html', 'search.js': 'static-search.js', 'search.css': 'static-search.css' + })) { + if (files.has(filename)) throw new Error(`Reserved export path collision: ${filename}`); + archive[filename] = await fs.readFile(path.join(__dirname, '../assets', source)); + await fs.writeFile(path.join(directory, filename), archive[filename]); + } + if (files.has('static-search.json') || files.has('export-manifest.json')) { + throw new Error('Reserved export metadata path collision'); + } + archive['static-search.json'] = Buffer.from(JSON.stringify(search)); + await fs.writeFile(path.join(directory, 'static-search.json'), archive['static-search.json']); + const extras = await additionalFiles(config.additionalFiles || []); + for (const [filename, body] of extras) { + if (Object.hasOwn(archive, filename) || filename === 'export-manifest.json') { + throw new Error(`Additional file conflicts with generated output: ${filename}`); + } + const output = path.join(directory, filename); + await fs.mkdir(path.dirname(output), {recursive: true}); + await fs.writeFile(output, body); + archive[filename] = body; + manifest.resources.push({file: filename, bytes: body.length, + hash: createHash('sha256').update(body).digest('hex'), source: 'additional-file'}); + } + await fs.writeFile(path.join(directory, 'export-manifest.json'), JSON.stringify(manifest, null, 2)); + signal?.throwIfAborted(); + await fs.writeFile(directory + '.zip', zipSync(archive)); + return manifest; +} + +module.exports = {exportSite}; diff --git a/packages/simply-static/lib/fetch-resource.js b/packages/simply-static/lib/fetch-resource.js new file mode 100644 index 0000000..5cf765d --- /dev/null +++ b/packages/simply-static/lib/fetch-resource.js @@ -0,0 +1,100 @@ +'use strict'; + +const {setTimeout: delay} = require('node:timers/promises'); + +class ExportFetchError extends Error { + constructor(message, {status, retryable = false, cause} = {}) { + super(message, {cause}); + this.status = status; + this.retryable = retryable; + } +} + +async function fetchResource(value, {policy, asset = false, fetcher = fetch, + signal, cached, timeout = 60000, maxBytes = 32 * 1024 * 1024, retries = 2, + retryDelay = 500, acceptedStatuses = [], onAttempt = () => {}}) { + const initial = policy.resolve(value); + for (let attempt = 0; attempt <= retries; attempt++) { + signal?.throwIfAborted(); + const timeoutSignal = AbortSignal.timeout(timeout); + const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal; + let current = initial; + try { + for (let redirects = 0; redirects <= 5; redirects++) { + if (!policy.allowed(current, asset)) { + throw new ExportFetchError('Export URL is outside the allowed scope'); + } + onAttempt({url: current.href, attempt}); + const response = await fetcher(current, { + redirect: 'manual', signal: requestSignal, credentials: 'omit', + headers: { + 'user-agent': 'Firekylin-Simply-Static/1', accept: '*/*', + ...(cached?.url === current.href && cached.etag ? {'if-none-match': cached.etag} : {}) + } + }); + if ([301, 302, 303, 307, 308].includes(response.status)) { + const location = response.headers.get('location'); + await response.body?.cancel(); + if (!location) throw new ExportFetchError('Redirect has no location'); + current = policy.resolve(location, current); + continue; + } + if (response.status === 304 && cached?.url === current.href && cached.etag) { + await response.body?.cancel(); + if (cached.body.length > maxBytes) throw new ExportFetchError('Cached resource exceeds size limit'); + return {...cached, reused: true}; + } + if (!response.ok && !acceptedStatuses.includes(response.status)) { + await response.body?.cancel(); + throw new ExportFetchError(`HTTP ${response.status}`, { + status: response.status, + retryable: [408, 429, 500, 502, 503, 504].includes(response.status) + }); + } + if (/\bprivate\b|\bno-store\b/i.test(response.headers.get('cache-control') || '')) { + await response.body?.cancel(); + throw new ExportFetchError('Response is marked private or no-store'); + } + if (Number(response.headers.get('content-length')) > maxBytes) { + await response.body?.cancel(); + throw new ExportFetchError('Resource exceeds the download size limit'); + } + const chunks = []; + let size = 0; + if (response.body) { + const reader = response.body.getReader(); + try { + while (true) { + requestSignal.throwIfAborted(); + const {done, value: chunk} = await reader.read(); + if (done) break; + size += chunk.byteLength; + if (size > maxBytes) { + await reader.cancel(); + throw new ExportFetchError('Resource exceeds the download size limit'); + } + chunks.push(Buffer.from(chunk)); + } + } finally { + reader.releaseLock(); + } + } + return { + url: current.href, requestedUrl: initial.href, status: response.status, + contentType: response.headers.get('content-type') || 'application/octet-stream', + etag: response.headers.get('etag'), body: Buffer.concat(chunks) + }; + } + throw new ExportFetchError('Too many redirects'); + } catch (cause) { + signal?.throwIfAborted(); + const error = cause instanceof ExportFetchError ? cause : new ExportFetchError( + `Download failed: ${cause.cause?.code || cause.code || cause.name}`, {cause, retryable: true} + ); + if (!error.retryable || attempt === retries) throw error; + await delay(retryDelay * (2 ** attempt), undefined, {signal}); + } + } +} + +module.exports = {fetchResource, ExportFetchError}; diff --git a/packages/simply-static/lib/integrations.js b/packages/simply-static/lib/integrations.js new file mode 100644 index 0000000..6b6dc34 --- /dev/null +++ b/packages/simply-static/lib/integrations.js @@ -0,0 +1,65 @@ +'use strict'; + +const cheerio = require('cheerio'); + +function integrateHtml(html, {pageUrl, searchUrl, forms = [], searchSelectors = [], commentServerUrl, commentScriptUrl}) { + const $ = cheerio.load(html); + const warnings = []; + for (const selector of searchSelectors) { + $(selector).each((index, element) => { + const form = $(element); + if (element.tagName !== 'form') throw new Error('Search selector must identify forms'); + form.attr('action', searchUrl).attr('method', 'get'); + const input = form.find('input[type="search"], input[name="keyword"], input[name="q"]').first(); + if (!input.length) throw new Error('Search form has no supported query input'); + input.attr('name', 'q'); + form.attr('data-static-integrated', 'search'); + }); + } + for (const mapping of forms) { + const endpoint = new URL(mapping.endpoint); + if (endpoint.protocol !== 'https:' || endpoint.username || endpoint.password) { + throw new Error('Form endpoints must use HTTPS without embedded credentials'); + } + $(mapping.selector).each((index, element) => { + if (element.tagName !== 'form') throw new Error('Form selector must identify forms'); + const form = $(element); + form.attr('action', endpoint.href).attr('method', 'post'); + form.removeAttr('onsubmit'); + form.find('input[name="_csrf"], input[name="csrf"], input[name="csrfToken"]').remove(); + form.attr('data-static-integrated', 'external'); + }); + } + if (commentServerUrl) { + const endpoint = new URL(commentServerUrl); + if (endpoint.protocol !== 'https:' || endpoint.username || endpoint.password) { + throw new Error('Comment server must use HTTPS without credentials'); + } + $('.fk-comment-container[data-comment-config]').each((index, element) => { + const container = $(element); + const config = JSON.parse(container.attr('data-comment-config')); + config.serverURL = endpoint.href.replace(/\/$/, ''); + config.path = new URL(pageUrl).pathname; + container.attr('data-comment-config', JSON.stringify(config)); + const initializer = container.next('script'); + if (initializer.length) initializer.remove(); + }); + if ($('.fk-comment-container[data-comment-config]').length) { + $('').attr('src', commentScriptUrl).attr('defer', '').appendTo('body'); + } + } else if ($('.fk-comment-container[data-comment-config]').length) { + warnings.push({type: 'dynamic-comments', pageUrl, + message: 'Configure an external Waline server or allow static-origin requests on the original comment service.'}); + } + $('form').each((index, element) => { + const form = $(element); + if (!form.attr('data-static-integrated')) { + warnings.push({type: 'dynamic-form', pageUrl, action: form.attr('action') || '', + message: 'This form has no static integration; verify its external service before publishing.'}); + } + form.removeAttr('data-static-integrated'); + }); + return {html: $.html(), warnings}; +} + +module.exports = {integrateHtml}; diff --git a/packages/simply-static/lib/invalidation.js b/packages/simply-static/lib/invalidation.js new file mode 100644 index 0000000..291f356 --- /dev/null +++ b/packages/simply-static/lib/invalidation.js @@ -0,0 +1,61 @@ +'use strict'; + +const fs = require('node:fs/promises'); +const path = require('node:path'); +const {ResourceCache} = require('./resource-cache'); +const {UrlPolicy} = require('./urls'); +const {transformHtml, transformCss, transformXml} = require('./transform'); + +async function preparePageUpdate({previousCheckpoint, checkpointDirectory, config, urls}) { + const policy = new UrlPolicy(config); + const targets = new Set(urls.map(value => policy.resolve(value).href)); + if (!targets.size || [...targets].some(value => !policy.allowed(new URL(value)))) { + throw new Error('Page update requires public source URLs'); + } + const previous = new ResourceCache(previousCheckpoint); + const next = new ResourceCache(checkpointDirectory); + const records = []; + for (const filename of await fs.readdir(previousCheckpoint)) { + if (!/^[a-f0-9]{64}\.json$/.test(filename)) continue; + const metadata = JSON.parse(await fs.readFile(path.join(previousCheckpoint, filename), 'utf8')); + const record = await previous.read(metadata.requestedUrl); + if (record) records.push(record); + } + const dependencies = new Map(); + for (const record of records) { + const links = new Set(); + const collect = (value, asset, base = record.url) => { + try { + links.add(policy.resolve(value, base).href); + } catch {} + return value; + }; + if (/text\/html/i.test(record.contentType)) { + transformHtml(record.body.toString(), {url: record.url, rewrite: collect}); + } else if (/text\/css/i.test(record.contentType)) { + transformCss(record.body.toString(), collect); + } else if (/xml|rss|atom/i.test(record.contentType)) { + transformXml(record.body.toString(), collect); + } + dependencies.set(record.requestedUrl, links); + } + const invalidated = new Set(targets); + // Re-fetch public index/feeds so new content, removed links and pagination + // changes are discovered even if the previous snapshot did not link to it. + invalidated.add(policy.source.href); + for (const record of records) { + const links = dependencies.get(record.requestedUrl); + if ([...targets].some(url => links.has(url)) || !/text\/html/i.test(record.contentType)) { + invalidated.add(record.requestedUrl); + } + } + let reused = 0; + for (const record of records) { + if (invalidated.has(record.requestedUrl) || invalidated.has(record.url)) continue; + await next.write(record); + reused++; + } + return {invalidated: [...invalidated], reused}; +} + +module.exports = {preparePageUpdate}; diff --git a/packages/simply-static/lib/jobs.js b/packages/simply-static/lib/jobs.js new file mode 100644 index 0000000..638c213 --- /dev/null +++ b/packages/simply-static/lib/jobs.js @@ -0,0 +1,224 @@ +'use strict'; + +const fs = require('node:fs/promises'); +const path = require('node:path'); +const os = require('node:os'); +const {randomUUID, createHash} = require('node:crypto'); +const {setTimeout: delay} = require('node:timers/promises'); + +async function atomicJson(file, value) { + const temporary = file + '.' + randomUUID() + '.tmp'; + await fs.writeFile(temporary, JSON.stringify(value, null, 2), {mode: 0o600}); + await fs.rename(temporary, file); +} + +class JobStore { + constructor(root) { + this.root = path.resolve(root); + } + + location(id) { + if (!/^[a-f0-9-]{36}$/.test(id)) throw new Error('Invalid export job ID'); + return path.join(this.root, id); + } + + async create(config, seeds = []) { + await fs.mkdir(this.root, {recursive: true, mode: 0o700}); + const id = randomUUID(); + const directory = this.location(id); + await fs.mkdir(directory, {mode: 0o700}); + const job = {id, status: 'queued', createdAt: new Date().toISOString(), config, seeds}; + await atomicJson(path.join(directory, 'job.json'), job); + return job; + } + + async enqueue(config, seeds = []) { + await fs.mkdir(this.root, {recursive: true, mode: 0o700}); + const signature = createHash('sha256').update(JSON.stringify({config, seeds})).digest('hex'); + const lockPath = path.join(this.root, '.enqueue-lock'); + let lock; + for (let attempt = 0; attempt < 100; attempt++) { + try { + lock = await fs.open(lockPath, 'wx', 0o600); + break; + } catch (error) { + if (error.code !== 'EEXIST') throw error; + await delay(20); + } + } + if (!lock) throw new Error('Export queue is busy; retry shortly'); + try { + const queued = (await this.list()).find(job => job.status === 'queued' && job.signature === signature); + if (queued) { + try { + await fs.access(path.join(this.location(queued.id), 'cancel')); + } catch (error) { + if (error.code === 'ENOENT') return queued; + throw error; + } + } + const job = await this.create(config, seeds); + job.signature = signature; + await atomicJson(path.join(this.location(job.id), 'job.json'), job); + return job; + } finally { + await lock.close(); + await fs.unlink(lockPath); + } + } + + async read(id) { + return JSON.parse(await fs.readFile(path.join(this.location(id), 'job.json'), 'utf8')); + } + + async list() { + await fs.mkdir(this.root, {recursive: true, mode: 0o700}); + const entries = await fs.readdir(this.root, {withFileTypes: true}); + const jobs = []; + for (const entry of entries) { + if (!entry.isDirectory() || !/^[a-f0-9-]{36}$/.test(entry.name)) continue; + try { + jobs.push(await this.read(entry.name)); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } + } + return jobs.sort((a, b) => b.createdAt.localeCompare(a.createdAt)); + } + + async recover(id, {hostname = os.hostname(), isAlive = pid => { + try { + process.kill(pid, 0); + return true; + } catch (error) { + if (error.code === 'ESRCH') return false; + return true; + } + }} = {}) { + const directory = this.location(id); + const recoveryPath = path.join(directory, 'recovery-lock'); + const recovery = await fs.open(recoveryPath, 'wx', 0o600); + try { + const job = await this.read(id); + if (!['running', 'queued'].includes(job.status)) throw new Error('Only interrupted running or queued jobs can be recovered'); + let workerOwner; + const workerPath = path.join(this.root, '.worker-lock'); + try { + workerOwner = JSON.parse(await fs.readFile(workerPath, 'utf8')); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } + if (workerOwner && (workerOwner.id !== id || workerOwner.hostname !== hostname || + !Number.isSafeInteger(workerOwner.pid) || workerOwner.pid <= 0 || isAlive(workerOwner.pid))) { + throw new Error('Another worker owns this queue or is still active'); + } + let owner; + try { + owner = JSON.parse(await fs.readFile(path.join(directory, 'lock'), 'utf8')); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } + if (owner) { + if (owner.hostname !== hostname) throw new Error('Recover this job on its original worker host'); + if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0 || isAlive(owner.pid)) { + throw new Error('Export worker is still active or its ownership cannot be verified'); + } + } + // A deployment may already have reached its provider. Never automatically + // republish such a task without checking the remote deployment first. + if (job.progress?.provider || job.phase === 'deploying') { + throw new Error('Check the interrupted remote publication before retrying'); + } + job.status = 'queued'; + job.recoveredAt = new Date().toISOString(); + job.recoveries = (job.recoveries || 0) + 1; + delete job.error; + await atomicJson(path.join(directory, 'job.json'), job); + await fs.rm(path.join(directory, 'lock'), {force: true}); + if (workerOwner) await fs.unlink(workerPath); + return job; + } finally { + await recovery.close(); + await fs.unlink(recoveryPath); + } + } + + async cancel(id) { + await this.read(id); + await fs.writeFile(path.join(this.location(id), 'cancel'), '', {mode: 0o600}); + } + + async run(id, execute) { + const workerPath = path.join(this.root, '.worker-lock'); + let worker; + try { + worker = await fs.open(workerPath, 'wx', 0o600); + } catch (error) { + if (error.code === 'EEXIST') return null; + throw error; + } + try { + await worker.writeFile(JSON.stringify({id, pid: process.pid, hostname: os.hostname()})); + return await this.runExclusive(id, execute); + } finally { + await worker.close(); + await fs.unlink(workerPath); + } + } + + async runExclusive(id, execute) { + const directory = this.location(id); + let lock; + try { + lock = await fs.open(path.join(directory, 'lock'), 'wx', 0o600); + } catch (error) { + if (error.code === 'EEXIST') return null; + throw error; + } + const controller = new AbortController(); + let timer; + try { + await lock.writeFile(JSON.stringify({pid: process.pid, hostname: os.hostname(), startedAt: new Date().toISOString()})); + const job = await this.read(id); + if (job.status !== 'queued') return null; + const checkCancellation = async() => { + try { + await fs.access(path.join(directory, 'cancel')); + controller.abort(new Error('Export cancelled')); + } catch (error) { + if (error.code !== 'ENOENT') controller.abort(error); + } + }; + await checkCancellation(); + timer = setInterval(() => void checkCancellation(), 250); + timer.unref(); + const update = async changes => { + Object.assign(job, changes, {updatedAt: new Date().toISOString()}); + await atomicJson(path.join(directory, 'job.json'), job); + }; + await update({status: 'running'}); + try { + controller.signal.throwIfAborted(); + const result = await execute(job, { + directory: path.join(directory, 'output'), signal: controller.signal, + onProgress: progress => update({progress}), + onPhase: phase => update({phase}), + onLog: async entry => { + const record = {...entry, timestamp: new Date().toISOString()}; + await fs.appendFile(path.join(directory, 'requests.jsonl'), JSON.stringify(record) + '\n', {mode: 0o600}); + } + }); + await update({status: 'completed', result}); + } catch (error) { + await update({status: controller.signal.aborted ? 'cancelled' : 'failed', error: error.message}); + } + return job; + } finally { + clearInterval(timer); + await lock.close(); + await fs.unlink(path.join(directory, 'lock')); + } + } +} + +module.exports = {JobStore, atomicJson}; diff --git a/packages/simply-static/lib/optimize-image.js b/packages/simply-static/lib/optimize-image.js new file mode 100644 index 0000000..0bb9c7d --- /dev/null +++ b/packages/simply-static/lib/optimize-image.js @@ -0,0 +1,24 @@ +'use strict'; + +async function optimizeImage(body, contentType, enabled = false) { + if (!enabled || !/^image\/(png|jpeg|webp)(?:;|$)/i.test(contentType)) return body; + let sharp; + try { + sharp = require('sharp'); + } catch { + throw new Error('Image optimization requires the optional sharp dependency'); + } + const image = sharp(body, {limitInputPixels: 40000000}); + const metadata = await image.metadata(); + // Keep animations, orientation metadata and colour profiles untouched. + if (metadata.pages > 1 || metadata.orientation || metadata.icc) return body; + let pipeline; + if (metadata.format === 'png') pipeline = image.png({compressionLevel: 9, adaptiveFiltering: true}); + else if (metadata.format === 'jpeg') pipeline = image.jpeg({quality: 85, mozjpeg: true}); + else if (metadata.format === 'webp') pipeline = image.webp({quality: 85, effort: 5}); + else return body; + const optimized = await pipeline.toBuffer(); + return optimized.length < body.length ? optimized : body; +} + +module.exports = {optimizeImage}; diff --git a/packages/simply-static/lib/optimize.js b/packages/simply-static/lib/optimize.js new file mode 100644 index 0000000..dd680c6 --- /dev/null +++ b/packages/simply-static/lib/optimize.js @@ -0,0 +1,35 @@ +'use strict'; + +const {minify: minifyHtml} = require('html-minifier-terser'); +const CleanCSS = require('clean-css'); +const {minify: minifyJs} = require('terser'); + +async function optimize(body, contentType, enabled = false) { + if (!enabled) return body; + const source = body.toString('utf8'); + if (/\btext\/html\b/i.test(contentType)) { + return Buffer.from(await minifyHtml(source, { + removeComments: true, + collapseWhitespace: false, + minifyCSS: false, + minifyJS: false, + removeAttributeQuotes: false + })); + } + if (/\btext\/css\b/i.test(contentType)) { + const result = new CleanCSS({rebase: false, level: 1}).minify(source); + if (result.errors.length) throw new Error('CSS optimization failed: ' + result.errors.join('; ')); + return Buffer.from(result.styles); + } + if (/(?:javascript|ecmascript)/i.test(contentType)) { + const result = await minifyJs(source, { + compress: false, + mangle: false, + format: {comments: /^!|@license|@preserve/} + }); + return Buffer.from(result.code); + } + return body; +} + +module.exports = {optimize}; diff --git a/packages/simply-static/lib/publish-bunny.js b/packages/simply-static/lib/publish-bunny.js new file mode 100644 index 0000000..124d0c3 --- /dev/null +++ b/packages/simply-static/lib/publish-bunny.js @@ -0,0 +1,59 @@ +'use strict'; + +const fs = require('node:fs/promises'); +const path = require('node:path'); +const {createHash} = require('node:crypto'); +const {validateTree} = require('./publish-local'); + +async function publishBunny(directory, {zone, prefix, hostname = 'storage.bunnycdn.com', + token = process.env.BUNNY_STORAGE_PASSWORD, fetcher = fetch, signal}) { + if (!/^[a-z0-9-]+$/i.test(zone || '') || !token || !prefix || + prefix.split('/').some(part => !part || part === '.' || part === '..') || /[\\\x00-\x1f]/.test(prefix)) { + throw new Error('Bunny storage zone, password and dedicated prefix are required'); + } + if (!/^(?:[a-z0-9-]+\.)?storage\.bunnycdn\.com$/.test(hostname)) throw new Error('Invalid Bunny storage host'); + await validateTree(directory); + const encode = value => value.split('/').map(encodeURIComponent).join('/'); + const request = async(file, method, body) => { + const timeout = AbortSignal.timeout(60000); + const response = await fetcher(`https://${hostname}/${encode(zone + '/' + prefix + '/' + file)}`, { + method, body, redirect: 'error', signal: signal ? AbortSignal.any([signal, timeout]) : timeout, + headers: {AccessKey: token, ...(body ? {'Content-Type': 'application/octet-stream', + Checksum: createHash('sha256').update(body).digest('hex').toUpperCase()} : {})} + }); + if (method === 'GET' && response.status === 404) return []; + if (!response.ok) throw new Error(`Bunny storage HTTP ${response.status}`); + if (method === 'GET') return response.json(); + await response.body?.cancel(); + }; + const uploaded = new Set(); + async function upload(relative = '') { + for (const entry of await fs.readdir(path.join(directory, relative), {withFileTypes: true})) { + const name = path.posix.join(relative, entry.name); + if (entry.isDirectory()) await upload(name); + else { + await request(name, 'PUT', await fs.readFile(path.join(directory, name))); + uploaded.add(name); + } + } + } + async function clean(relative = '', depth = 0) { + if (depth > 50) throw new Error('Bunny directory depth limit exceeded'); + const entries = await request(relative ? relative + '/' : '', 'GET'); + if (!Array.isArray(entries)) throw new Error('Invalid Bunny directory response'); + for (const entry of entries) { + if (typeof entry.ObjectName !== 'string' || !entry.ObjectName || + /[\\/\x00-\x1f]/.test(entry.ObjectName) || ['.', '..'].includes(entry.ObjectName)) { + throw new Error('Invalid Bunny remote filename'); + } + const name = path.posix.join(relative, entry.ObjectName); + if (entry.IsDirectory) await clean(name, depth + 1); + else if (!uploaded.has(name)) await request(name, 'DELETE'); + } + } + await upload(); + await clean(); + return {type: 'bunny', zone, prefix, files: uploaded.size, state: 'synced', atomic: false}; +} + +module.exports = {publishBunny}; diff --git a/packages/simply-static/lib/publish-cloudflare.js b/packages/simply-static/lib/publish-cloudflare.js new file mode 100644 index 0000000..b255f19 --- /dev/null +++ b/packages/simply-static/lib/publish-cloudflare.js @@ -0,0 +1,47 @@ +'use strict'; + +const {execFile} = require('node:child_process'); +const {promisify} = require('node:util'); +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const {validateTree} = require('./publish-local'); +const execute = promisify(execFile); + +async function publishCloudflare(directory, {project, branch, signal, runner = execute, + environment = process.env}) { + if (!/^[a-z0-9][a-z0-9-]*$/.test(project || '')) throw new Error('Invalid Cloudflare Pages project'); + if (!environment.CLOUDFLARE_API_TOKEN || !environment.CLOUDFLARE_ACCOUNT_ID) { + throw new Error('CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are required'); + } + if (!branch || branch.startsWith('-') || /[\x00-\x1f]/.test(branch)) { + throw new Error('An explicit Cloudflare deployment branch is required'); + } + await validateTree(directory); + // Run outside the source project so unrelated Wrangler configurations and + // Pages Functions cannot be picked up during a static-only deployment. + const cwd = await fs.mkdtemp(path.join(os.tmpdir(), 'static-cloudflare-')); + try { + for (const reserved of ['_worker.js', 'functions']) { + try { + await fs.access(path.join(directory, reserved)); + throw new Error('Static export contains Cloudflare executable resources'); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } + } + await runner('wrangler', ['pages', 'deploy', path.resolve(directory), + '--project-name', project, '--branch', branch, '--commit-dirty=true'], { + cwd, signal, timeout: 600000, maxBuffer: 4 * 1024 * 1024, + env: {...environment, CI: 'true', WRANGLER_SEND_METRICS: 'false'} + }); + return {type: 'cloudflare', project, branch, state: 'command-completed'}; + } catch (error) { + if (error.code === 'ENOENT') throw new Error('Install Wrangler in the worker PATH before publishing'); + throw new Error(`Cloudflare deployment failed (${error.code || error.name})`); + } finally { + await fs.rm(cwd, {recursive: true, force: true}); + } +} + +module.exports = {publishCloudflare}; diff --git a/packages/simply-static/lib/publish-git.js b/packages/simply-static/lib/publish-git.js new file mode 100644 index 0000000..360375b --- /dev/null +++ b/packages/simply-static/lib/publish-git.js @@ -0,0 +1,65 @@ +'use strict'; + +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const {execFile} = require('node:child_process'); +const {promisify} = require('node:util'); +const {validateTree} = require('./publish-local'); +const execute = promisify(execFile); + +async function publishGit(source, {repository, branch = 'gh-pages', + authorName = 'Firekylin Static', authorEmail = 'static@localhost', signal}) { + if (typeof repository !== 'string' || !repository || repository.startsWith('-')) { + throw new Error('Invalid Git repository'); + } + if (/^https?:\/\//.test(repository)) { + const url = new URL(repository); + if (url.username || url.password) throw new Error('Use Git credential helpers instead of credentials in URLs'); + } + const git = async(args, cwd) => { + try { + return await execute('git', args, { + cwd, signal, timeout: 120000, maxBuffer: 2 * 1024 * 1024, + env: {...process.env, GIT_TERMINAL_PROMPT: '0'} + }); + } catch (cause) { + // Do not expose remote stderr, which can contain credential-bearing URLs. + throw new Error(`Git ${args[0]} failed (${cause.code || cause.name})`); + } + }; + await validateTree(source); + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'firekylin-static-git-')); + try { + await git(['check-ref-format', '--branch', branch], root); + await git(['init', '--quiet'], root); + await git(['remote', 'add', 'origin', repository], root); + const remote = await git(['ls-remote', '--heads', 'origin', `refs/heads/${branch}`], root); + if (remote.stdout.trim()) { + await git(['fetch', '--depth=1', 'origin', `refs/heads/${branch}`], root); + await git(['checkout', '-B', branch, 'FETCH_HEAD'], root); + } else { + await git(['checkout', '--orphan', branch], root); + } + for (const entry of await fs.readdir(root)) { + if (entry !== '.git') await fs.rm(path.join(root, entry), {recursive: true, force: true}); + } + for (const entry of await fs.readdir(source)) { + if (entry === '.git') throw new Error('Export contains reserved Git metadata'); + await fs.cp(path.join(source, entry), path.join(root, entry), {recursive: true}); + } + await fs.writeFile(path.join(root, '.nojekyll'), ''); + await git(['add', '--all'], root); + const status = await git(['status', '--porcelain'], root); + if (!status.stdout.trim()) return {type: 'git', branch, changed: false}; + await git(['-c', `user.name=${authorName}`, '-c', `user.email=${authorEmail}`, + 'commit', '--quiet', '-m', 'chore: publish static website'], root); + await git(['push', 'origin', `HEAD:refs/heads/${branch}`], root); + const commit = await git(['rev-parse', 'HEAD'], root); + return {type: 'git', branch, changed: true, commit: commit.stdout.trim()}; + } finally { + await fs.rm(root, {recursive: true, force: true}); + } +} + +module.exports = {publishGit}; diff --git a/packages/simply-static/lib/publish-local.js b/packages/simply-static/lib/publish-local.js new file mode 100644 index 0000000..55faf36 --- /dev/null +++ b/packages/simply-static/lib/publish-local.js @@ -0,0 +1,65 @@ +'use strict'; + +const fs = require('node:fs/promises'); +const path = require('node:path'); +const {randomUUID} = require('node:crypto'); + +async function validateTree(directory) { + for (const entry of await fs.readdir(directory, {withFileTypes: true})) { + const file = path.join(directory, entry.name); + if (entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory())) { + throw new Error('Export artifacts must contain only regular files and directories'); + } + if (entry.isDirectory()) await validateTree(file); + } +} + +async function publishLocal(source, destination, {copy = fs.cp} = {}) { + const input = await fs.realpath(source); + let target = path.resolve(destination); + if (target === path.parse(target).root) throw new Error('Cannot publish to filesystem root'); + if (target === input || target.startsWith(input + path.sep)) { + throw new Error('Publish destination cannot be inside export artifacts'); + } + await validateTree(input); + await fs.mkdir(path.dirname(target), {recursive: true}); + const parent = await fs.realpath(path.dirname(target)); + target = path.join(parent, path.basename(target)); + if (target === input || target.startsWith(input + path.sep)) { + throw new Error('Publish destination cannot be inside export artifacts'); + } + const releases = path.join(parent, '.' + path.basename(target) + '-releases'); + await fs.mkdir(releases, {recursive: true}); + const lockPath = path.join(releases, '.publish-lock'); + const lock = await fs.open(lockPath, 'wx', 0o600); + const id = randomUUID(); + const release = path.join(releases, id); + const pointer = path.join(parent, '.' + path.basename(target) + '-' + id); + try { + let previous; + try { + const stat = await fs.lstat(target); + if (!stat.isSymbolicLink()) { + throw new Error('Publish destination must be absent or a managed release symlink'); + } + previous = path.resolve(parent, await fs.readlink(target)); + if (path.dirname(previous) !== releases) throw new Error('Destination is not a managed release'); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } + await copy(input, release, {recursive: true, errorOnExist: true, force: false}); + await validateTree(release); + await fs.symlink(path.relative(parent, release), pointer, 'dir'); + await fs.rename(pointer, target); + return {type: 'local', destination: target, release, previous: previous || null}; + } catch (error) { + await fs.rm(pointer, {force: true}); + await fs.rm(release, {recursive: true, force: true}); + throw error; + } finally { + await lock.close(); + await fs.unlink(lockPath); + } +} + +module.exports = {publishLocal, validateTree}; diff --git a/packages/simply-static/lib/publish-netlify.js b/packages/simply-static/lib/publish-netlify.js new file mode 100644 index 0000000..8ada26b --- /dev/null +++ b/packages/simply-static/lib/publish-netlify.js @@ -0,0 +1,36 @@ +'use strict'; + +const fs = require('node:fs/promises'); +const {setTimeout: delay} = require('node:timers/promises'); + +async function publishNetlify(archive, {siteId, token = process.env.NETLIFY_AUTH_TOKEN, + fetcher = fetch, signal, pollInterval = 2000, attempts = 150, onProgress = async() => {}}) { + if (!siteId || !token) throw new Error('Netlify site ID and NETLIFY_AUTH_TOKEN are required'); + const request = async(endpoint, options = {}) => { + const timeout = AbortSignal.timeout(120000); + const response = await fetcher('https://api.netlify.com/api/v1' + endpoint, { + ...options, redirect: 'error', + signal: signal ? AbortSignal.any([signal, timeout]) : timeout, + headers: {Authorization: `Bearer ${token}`, ...options.headers} + }); + if (!response.ok) throw new Error(`Netlify API HTTP ${response.status}`); + return response.json(); + }; + let deploy = await request(`/sites/${encodeURIComponent(siteId)}/deploys`, { + method: 'POST', headers: {'Content-Type': 'application/zip'}, body: await fs.readFile(archive) + }); + if (typeof deploy.id !== 'string' || !deploy.id) throw new Error('Netlify returned no deployment ID'); + const id = deploy.id; + for (let attempt = 0; attempt < attempts; attempt++) { + await onProgress({provider: 'netlify', id, state: deploy.state}); + if (deploy.state === 'ready') { + return {type: 'netlify', id, state: 'ready', url: deploy.ssl_url || deploy.url}; + } + if (['error', 'rejected'].includes(deploy.state)) throw new Error(`Netlify deployment ${id} failed`); + await delay(pollInterval, undefined, {signal}); + deploy = await request(`/deploys/${encodeURIComponent(id)}`); + } + throw new Error(`Netlify deployment ${id} is still processing; check its status before retrying`); +} + +module.exports = {publishNetlify}; diff --git a/packages/simply-static/lib/publish-s3.js b/packages/simply-static/lib/publish-s3.js new file mode 100644 index 0000000..85af7ca --- /dev/null +++ b/packages/simply-static/lib/publish-s3.js @@ -0,0 +1,37 @@ +'use strict'; + +const path = require('node:path'); +const {execFile} = require('node:child_process'); +const {promisify} = require('node:util'); +const {validateTree} = require('./publish-local'); +const execute = promisify(execFile); + +async function publishS3(directory, {destination, endpoint, signal, runner = execute}) { + const match = /^s3:\/\/([a-z0-9][a-z0-9.-]+)\/(.+)$/.exec(destination || ''); + if (!match || match[2].replace(/\/$/, '').split('/').some(part => !part || part === '..' || part === '.') || + /[\\\x00-\x20?#]/.test(match[2])) { + throw new Error('S3 destination must specify a dedicated bucket prefix'); + } + const args = ['s3', 'sync', path.resolve(directory), destination, '--delete', '--no-follow-symlinks', + '--only-show-errors', '--no-progress']; + if (endpoint) { + const url = new URL(endpoint); + if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) { + throw new Error('S3 endpoint must be HTTPS without credentials or query parameters'); + } + args.push('--endpoint-url', url.href); + } + await validateTree(directory); + try { + await runner('aws', args, { + signal, timeout: 600000, maxBuffer: 4 * 1024 * 1024, + env: {...process.env, AWS_PAGER: '', AWS_CLI_AUTO_PROMPT: 'off'} + }); + } catch (error) { + if (error.code === 'ENOENT') throw new Error('Install AWS CLI in the worker PATH before publishing'); + throw new Error(`S3 publication failed (${error.code || error.name}); destination may be partially updated`); + } + return {type: 's3', destination, state: 'synced', atomic: false}; +} + +module.exports = {publishS3}; diff --git a/packages/simply-static/lib/publish-sftp.js b/packages/simply-static/lib/publish-sftp.js new file mode 100644 index 0000000..feab1a5 --- /dev/null +++ b/packages/simply-static/lib/publish-sftp.js @@ -0,0 +1,57 @@ +'use strict'; + +const fs = require('node:fs/promises'); +const {randomUUID} = require('node:crypto'); +const Client = require('ssh2-sftp-client'); +const {validateTree} = require('./publish-local'); + +async function publishSftp(directory, {host, username, destination, fingerprint, port = 22, + signal, client = new Client(), environment = process.env}) { + if (!host || !username || !/^\/[a-z0-9_./-]+$/i.test(destination || '') || + destination === '/' || destination.endsWith('/') || destination.split('/').includes('..')) { + throw new Error('SFTP requires host, username and an absolute dedicated destination'); + } + if (!/^[a-f0-9]{64}$/i.test(fingerprint || '')) throw new Error('SFTP SHA-256 host fingerprint is required'); + await validateTree(directory); + signal?.throwIfAborted(); + const id = randomUUID(); + const staging = destination + '.staging-' + id; + const backup = destination + '.previous-' + id; + let moved = false; + const abort = () => { void client.end().catch(() => {}); }; + signal?.addEventListener('abort', abort, {once: true}); + try { + const privateKey = environment.STATIC_SFTP_KEY_FILE ? await fs.readFile(environment.STATIC_SFTP_KEY_FILE) : undefined; + await client.connect({host, port, username, privateKey, + password: environment.STATIC_SFTP_PASSWORD, + passphrase: environment.STATIC_SFTP_KEY_PASSPHRASE, + hostHash: 'sha256', hostVerifier: hash => hash.toLowerCase() === fingerprint.toLowerCase(), + readyTimeout: 20000}); + const existing = await client.exists(destination); + if (existing && existing !== 'd') throw new Error('SFTP destination must be a directory'); + await client.uploadDir(directory, staging, {useFastput: false}); + signal?.throwIfAborted(); + if (existing) { + await client.rename(destination, backup); + moved = true; + } + try { + await client.rename(staging, destination); + } catch (error) { + if (moved) { + try { + await client.rename(backup, destination); + } catch { + throw new Error(`SFTP publication needs recovery from ${backup}`); + } + } + throw error; + } + return {type: 'sftp', destination, previous: moved ? backup : null, atomic: false}; + } finally { + signal?.removeEventListener('abort', abort); + await client.end(); + } +} + +module.exports = {publishSftp}; diff --git a/packages/simply-static/lib/resource-cache.js b/packages/simply-static/lib/resource-cache.js new file mode 100644 index 0000000..efb9581 --- /dev/null +++ b/packages/simply-static/lib/resource-cache.js @@ -0,0 +1,39 @@ +'use strict'; + +const fs = require('node:fs/promises'); +const path = require('node:path'); +const {createHash} = require('node:crypto'); +const {atomicJson} = require('./jobs'); + +class ResourceCache { + constructor(root) { + this.root = root; + } + + file(url) { + return path.join(this.root, createHash('sha256').update(url).digest('hex') + '.json'); + } + + async read(url) { + try { + const record = JSON.parse(await fs.readFile(this.file(url), 'utf8')); + if (record.requestedUrl !== url || typeof record.body !== 'string') return null; + const body = Buffer.from(record.body, 'base64'); + if (createHash('sha256').update(body).digest('hex') !== record.hash) return null; + return {...record, body}; + } catch (error) { + if (error.code === 'ENOENT' || error instanceof SyntaxError) return null; + throw error; + } + } + + async write(record) { + await fs.mkdir(this.root, {recursive: true, mode: 0o700}); + await atomicJson(this.file(record.requestedUrl), { + ...record, body: record.body.toString('base64'), + hash: createHash('sha256').update(record.body).digest('hex') + }); + } +} + +module.exports = {ResourceCache}; diff --git a/packages/simply-static/lib/settings.js b/packages/simply-static/lib/settings.js new file mode 100644 index 0000000..a6de07f --- /dev/null +++ b/packages/simply-static/lib/settings.js @@ -0,0 +1,46 @@ +'use strict'; + +function lines(value) { + return String(value || '').split(/\r?\n/).map(item => item.trim()).filter(Boolean); +} + +function arraySetting(value, label) { + if (!value) return []; + let parsed; + try { + parsed = typeof value === 'string' ? JSON.parse(value) : value; + } catch { + throw new Error(`${label} must be valid JSON`); + } + if (!Array.isArray(parsed)) throw new Error(`${label} must be an array`); + return parsed; +} + +function integrationSettings(values) { + if (values.commentServerUrl) { + const endpoint = new URL(values.commentServerUrl); + if (endpoint.protocol !== 'https:' || endpoint.username || endpoint.password) { + throw new Error('Comment server must use HTTPS without credentials'); + } + } + const forms = arraySetting(values.forms, 'Form mappings'); + for (const form of forms) { + if (!form || typeof form.selector !== 'string' || !form.selector.trim() || typeof form.endpoint !== 'string') { + throw new Error('Each form mapping requires a selector and endpoint'); + } + const endpoint = new URL(form.endpoint); + if (endpoint.protocol !== 'https:' || endpoint.username || endpoint.password) { + throw new Error('Form endpoints must be HTTPS without credentials'); + } + } + const additionalFiles = arraySetting(values.additionalFiles, 'Additional files'); + for (const file of additionalFiles) { + if (!file || typeof file.source !== 'string' || !file.source || typeof file.target !== 'string' || !file.target) { + throw new Error('Each additional file requires source and target paths'); + } + } + return {forms, additionalFiles, searchSelectors: Array.isArray(values.searchSelectors) ? + values.searchSelectors : lines(values.searchSelectors)}; +} + +module.exports = {lines, arraySetting, integrationSettings}; diff --git a/packages/simply-static/lib/transform.js b/packages/simply-static/lib/transform.js new file mode 100644 index 0000000..16ddd1a --- /dev/null +++ b/packages/simply-static/lib/transform.js @@ -0,0 +1,106 @@ +'use strict'; + +const cheerio = require('cheerio'); +const postcss = require('postcss'); +const values = require('postcss-value-parser'); +const parseSrcset = require('parse-srcset'); + +function cssValue(value, rewrite) { + const tree = values(value); + tree.walk(node => { + if (node.type !== 'function' || node.value.toLowerCase() !== 'url') return; + const original = values.stringify(node.nodes).trim().replace(/^(['"])(.*)\1$/, '$2'); + const replacement = rewrite(original, true); + node.nodes = [{type: 'string', quote: '"', value: replacement}]; + return false; + }); + return tree.toString(); +} + +function transformCss(source, rewrite) { + const root = postcss.parse(source); + root.walkDecls(declaration => { + declaration.value = cssValue(declaration.value, rewrite); + }); + root.walkAtRules('import', rule => { + const parsed = values(rule.params); + const first = parsed.nodes.find(node => node.type !== 'space' && node.type !== 'comment'); + if (first?.type === 'string') { + first.value = rewrite(first.value, true); + rule.params = parsed.toString(); + } else { + rule.params = cssValue(rule.params, rewrite); + } + }); + return root.toString(); +} + +function transformHtml(source, {url, rewrite}) { + const $ = cheerio.load(source); + let base = url; + const baseHref = $('base[href]').first().attr('href'); + if (baseHref) base = new URL(baseHref, url).href; + $('base').remove(); + const replace = (value, asset) => rewrite(value, asset, base); + $('*').each((index, element) => { + const node = $(element); + const tag = element.tagName; + for (const attribute of ['src', 'poster', 'data-src']) { + const value = node.attr(attribute); + if (value) node.attr(attribute, replace(value, true)); + } + if (node.attr('href')) { + const asset = tag === 'link' && /stylesheet|icon|preload|modulepreload/i.test(node.attr('rel') || ''); + node.attr('href', replace(node.attr('href'), asset)); + } + for (const attribute of ['srcset', 'data-srcset']) { + const value = node.attr(attribute); + if (!value) continue; + node.attr(attribute, parseSrcset(value).map(candidate => { + const descriptor = candidate.w ? ` ${candidate.w}w` : candidate.d ? ` ${candidate.d}x` : ''; + return replace(candidate.url, true) + descriptor; + }).join(', ')); + } + if (node.attr('style')) { + const wrapped = transformCss(`a{${node.attr('style')}}`, replace); + node.attr('style', wrapped.slice(wrapped.indexOf('{') + 1, wrapped.lastIndexOf('}'))); + } + if (tag === 'style') node.text(transformCss(node.text(), replace)); + if (tag === 'meta') { + const property = node.attr('property') || node.attr('name') || ''; + if (/^(og:url|og:image|twitter:image)$/.test(property) && node.attr('content')) { + node.attr('content', replace(node.attr('content'), property !== 'og:url')); + } + } + }); + const title = $('title').text(); + const text = $('main, article').first().text() || $('body').text(); + return {html: $.html(), title, text: text.replace(/\s+/g, ' ').trim()}; +} + +module.exports = {transformHtml, transformCss}; + +function transformXml(source, rewrite) { + const $ = cheerio.load(source, {xmlMode: true}); + $('loc, link, guid, enclosure').each((index, element) => { + const node = $(element); + if (element.tagName === 'guid' && node.attr('isPermaLink') === 'false') return; + for (const attribute of ['href', 'url']) { + if (node.attr(attribute)) { + node.attr(attribute, rewrite(node.attr(attribute), element.tagName === 'enclosure')); + return; + } + } + const value = node.text().trim(); + if (/^https?:\/\//i.test(value)) node.text(rewrite(value, false)); + }); + return $.xml(); +} + +module.exports.transformXml = transformXml; + +function transformRobots(source, rewrite) { + return source.replace(/^(Sitemap:\s*)(https?:\/\/\S+)/gim, (line, prefix, url) => prefix + rewrite(url, false)); +} + +module.exports.transformRobots = transformRobots; diff --git a/packages/simply-static/lib/urls.js b/packages/simply-static/lib/urls.js new file mode 100644 index 0000000..d38b9fe --- /dev/null +++ b/packages/simply-static/lib/urls.js @@ -0,0 +1,90 @@ +'use strict'; + +const path = require('node:path'); +const {createHash} = require('node:crypto'); + +function httpUrl(value) { + const url = new URL(value); + if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) { + throw new Error('Expected an HTTP(S) URL without credentials'); + } + return url; +} + +function safeSegments(pathname) { + return pathname.split('/').filter(Boolean).map(segment => { + const decoded = decodeURIComponent(segment); + if (decoded === '.' || decoded === '..' || /[\\/\x00-\x1f\x7f]/.test(decoded)) { + throw new Error('Unsafe URL path'); + } + // Keep encoded names portable, including Windows reserved characters. + return decoded.replace(/[<>:"|?*%]/g, character => + '%' + character.charCodeAt(0).toString(16).toUpperCase()); + }); +} + +class UrlPolicy { + constructor({sourceUrl, destinationUrl, relative = false, exclude = [], assetOrigins = []}) { + this.source = httpUrl(sourceUrl); + this.destination = httpUrl(destinationUrl); + for (const url of [this.source, this.destination]) { + if (url.search || url.hash) throw new Error('Site URLs cannot contain queries or fragments'); + if (!url.pathname.endsWith('/')) url.pathname += '/'; + } + this.relative = relative; + this.exclude = exclude; + this.assetOrigins = new Set(assetOrigins.map(value => httpUrl(value).origin)); + } + + resolve(value, base = this.source) { + const url = httpUrl(new URL(value, base).href); + safeSegments(url.pathname); + url.hash = ''; + return url; + } + + isSite(url) { + return url.origin === this.source.origin && url.pathname.startsWith(this.source.pathname); + } + + allowed(url, asset = false) { + if (!this.isSite(url)) return asset && this.assetOrigins.has(url.origin); + const relative = decodeURIComponent(url.pathname.slice(this.source.pathname.length)); + if (/^(admin|api|mcp)(\/|$)/i.test(relative)) return false; + if ([...url.searchParams.keys()].some(key => /^(preview|token|password|secret|authorization)$/i.test(key))) { + return false; + } + return !this.exclude.some(prefix => url.pathname.startsWith(prefix)); + } + + file(url, html = false) { + const external = !this.isSite(url); + const pathname = external ? url.pathname : url.pathname.slice(this.source.pathname.length); + let parts = safeSegments(pathname); + if (external) { + const origin = createHash('sha256').update(url.origin).digest('hex').slice(0, 16); + parts = ['_external', origin, ...parts]; + } + let filename = parts.join('/'); + if (!filename || url.pathname.endsWith('/') || (html && !path.posix.extname(filename))) { + filename = path.posix.join(filename, 'index.html'); + } + if (url.search) { + const extension = path.posix.extname(filename); + const digest = createHash('sha256').update(url.search).digest('hex').slice(0, 16); + filename = filename.slice(0, filename.length - extension.length) + '.' + digest + extension; + } + return filename; + } + + link(filename, fromFile, fragment = '') { + if (this.relative) { + const relative = path.posix.relative(path.posix.dirname(fromFile), filename); + const encoded = relative.split('/').map(encodeURIComponent).join('/'); + return (encoded || encodeURIComponent(path.posix.basename(filename))) + fragment; + } + return new URL(filename.split('/').map(encodeURIComponent).join('/'), this.destination).href + fragment; + } +} + +module.exports = {UrlPolicy, httpUrl, safeSegments}; diff --git a/packages/simply-static/package.json b/packages/simply-static/package.json new file mode 100644 index 0000000..006c9a8 --- /dev/null +++ b/packages/simply-static/package.json @@ -0,0 +1,57 @@ +{ + "name": "firekylin-plugin-simply-static", + "version": "0.1.0", + "description": "Static site export and publishing for Firekylin", + "main": "plugin.js", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/firekylin/plugins.git", + "directory": "packages/simply-static" + }, + "engines": { + "node": ">=22.13.0", + "firekylin": ">=2.19.4" + }, + "scripts": { + "test": "node --test test/*.test.js" + }, + "dependencies": { + "cheerio": "1.1.2", + "postcss": "8.5.6", + "postcss-value-parser": "4.2.0", + "parse-srcset": "1.0.2", + "fflate": "0.8.2", + "croner": "^10.0.1", + "html-minifier-terser": "^7.2.0", + "clean-css": "^5.3.3", + "terser": "^5.44.1", + "ssh2-sftp-client": "^12.0.1" + }, + "firekylin": { + "type": "plugin", + "id": "simply-static", + "entry": "plugin.js", + "permissions": [ + "network:fetch", + "filesystem:write" + ] + }, + "files": [ + "lib", + "bin", + "plugin.js", + "README.md", + "IMPLEMENTATION.md", + "assets" + ], + "bin": { + "firekylin-static": "bin/cli.js" + }, + "optionalDependencies": { + "sharp": "^0.34.5" + }, + "devDependencies": { + "jsdom": "^27.0.1" + } +} diff --git a/packages/simply-static/plugin.js b/packages/simply-static/plugin.js new file mode 100644 index 0000000..ff097f8 --- /dev/null +++ b/packages/simply-static/plugin.js @@ -0,0 +1,205 @@ +'use strict'; + +const fs = require('node:fs'); +const promises = require('node:fs/promises'); +const path = require('node:path'); +const {JobStore, atomicJson} = require('./lib/jobs'); +const {UrlPolicy} = require('./lib/urls'); +const {ExportAutomation} = require('./lib/automation'); +const {validateDeployment} = require('./lib/deploy'); +const {lines, integrationSettings} = require('./lib/settings'); + +let automation; + +module.exports = { + register(ctx) { + const project = process.env.FIREKYLIN_PROJECT_PATH || process.cwd(); + const root = path.join(project, '.firekylin', 'simply-static'); + const store = new JobStore(path.join(root, 'jobs')); + const settingsFile = path.join(root, 'settings.json'); + const settings = async() => { + try { + return JSON.parse(await promises.readFile(settingsFile, 'utf8')); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + return {sourceUrl: '', destinationUrl: '', relative: false, additionalUrls: '', exclude: ''}; + } + }; + const enqueue = async() => { + const values = await settings(); + const config = {...values, ...integrationSettings(values), exclude: lines(values.exclude), assetOrigins: lines(values.assetOrigins)}; + new UrlPolicy(config); + return store.enqueue(config, [ + new URL('sitemap.xml', config.sourceUrl.endsWith('/') ? config.sourceUrl : config.sourceUrl + '/').href, + new URL('rss.xml', config.sourceUrl.endsWith('/') ? config.sourceUrl : config.sourceUrl + '/').href, + ...lines(values.additionalUrls) + ]); + }; + automation = new ExportAutomation({enqueue, logger: ctx.logger}); + ctx.events.on('app.ready', async() => { + const values = await settings(); + automation.configure({...values, timezone: values.timezone || 'UTC'}); + }); + for (const event of ['post.created', 'post.updated', 'post.deleted', 'page.created', 'page.updated', 'page.deleted']) { + ctx.events.on(event, () => automation.changed()); + } + ctx.admin.registerPanel({id: 'simply-static', title: '静态发布', icon: 'download', order: 86}); + ctx.admin.registerPage({ + id: 'exports', panel: 'simply-static', title: '静态网站导出', + description: '将公开网站导出为独立 HTML、资源文件和 ZIP。', + load: async() => { + const jobs = (await store.list()).slice(0, 20); + return {sections: [ + {type: 'form', id: 'settings'}, + {type: 'form', id: 'update-page'}, + {type: 'actions', ids: ['generate']}, + {type: 'markdown', title: '任务执行', content: + '导出由独立工作进程执行。请按插件文档启动工作进程;任务状态可刷新查看。'}, + ...jobs.map(job => ({type: 'description', title: job.createdAt, items: [ + {label: '任务', value: job.id}, + {label: '状态', value: job.status}, + {label: '进度', value: `${job.progress?.completed || 0} / ${job.progress?.discovered || 0}`}, + {label: '错误', value: job.error || ''} + ]})), + {type: 'links', title: '请求日志', items: jobs.filter(job => job.status !== 'queued').map(job => ({ + label: job.createdAt, href: `/api/plugins/simply-static/logs/${job.id}`, description: '逐资源请求记录' + }))}, + {type: 'links', title: '下载已完成的导出', items: jobs.filter(job => job.status === 'completed').map(job => ({ + label: job.createdAt, href: `/api/plugins/simply-static/download/${job.id}`, description: 'ZIP 静态网站' + }))} + ]}; + } + }); + ctx.admin.registerForm({ + id: 'settings', page: 'exports', title: '导出设置', submitLabel: '保存设置', + fields: [ + {name: 'sourceUrl', type: 'text', label: '源站地址', required: true}, + {name: 'destinationUrl', type: 'text', label: '静态网站地址', required: true}, + {name: 'errorPageUrl', type: 'text', label: '404 页面源地址(可选)'}, + {name: 'relative', type: 'switch', label: '使用相对链接'}, + {name: 'optimizeImages', type: 'switch', label: '优化 PNG、JPEG 和 WebP 图片'}, + {name: 'minify', type: 'switch', label: '压缩 HTML、CSS 和 JavaScript'}, + {name: 'incremental', type: 'switch', label: '使用条件请求复用未变化资源'}, + {name: 'localDestination', type: 'text', label: '本地发布路径', + description: '留空则仅生成下载文件;目标须不存在或为插件管理的发布链接。'}, + {name: 'gitRepository', type: 'text', label: 'Git 发布仓库', + description: '使用工作进程的 Git 凭据,不要在地址中填写密码。'}, + {name: 'sftpHost', type: 'text', label: 'SFTP 主机'}, + {name: 'sftpPort', type: 'number', label: 'SFTP 端口', placeholder: '22'}, + {name: 'sftpUsername', type: 'text', label: 'SFTP 用户名'}, + {name: 'sftpDestination', type: 'text', label: 'SFTP 专用发布目录'}, + {name: 'sftpFingerprint', type: 'text', label: 'SFTP 主机 SHA-256 指纹(十六进制)'}, + {name: 'bunnyZone', type: 'text', label: 'Bunny Storage 区域名称'}, + {name: 'bunnyPrefix', type: 'text', label: 'Bunny 专用发布目录'}, + {name: 'bunnyHostname', type: 'text', label: 'Bunny 存储主机', placeholder: 'storage.bunnycdn.com'}, + {name: 's3Destination', type: 'text', label: 'S3 发布位置', placeholder: 's3://bucket/site/'}, + {name: 's3Endpoint', type: 'text', label: 'S3 兼容服务地址(可选)'}, + {name: 'cloudflareProject', type: 'text', label: 'Cloudflare Pages 项目名'}, + {name: 'cloudflareBranch', type: 'text', label: 'Cloudflare 发布分支', + description: '应与 Pages 项目配置的生产分支一致,或填写预览分支。'}, + {name: 'netlifySiteId', type: 'text', label: 'Netlify 站点 ID', + description: '需在工作进程环境设置 NETLIFY_AUTH_TOKEN。'}, + {name: 'gitBranch', type: 'text', label: 'Git 发布分支', placeholder: 'gh-pages'}, + {name: 'autoPublish', type: 'switch', label: '内容变更后自动生成'}, + {name: 'schedule', type: 'text', label: '定时生成 Cron 表达式'}, + {name: 'timezone', type: 'text', label: '定时时区', placeholder: 'UTC'}, + {name: 'commentServerUrl', type: 'text', label: '独立 Waline 评论服务地址(HTTPS)'}, + {name: 'forms', type: 'textarea', label: '外部表单映射(JSON 数组)', + description: '每项包含 selector 和 HTTPS endpoint,详细示例见插件文档。'}, + {name: 'searchSelectors', type: 'textarea', label: '搜索表单选择器(每行一项)'}, + {name: 'additionalFiles', type: 'textarea', label: '额外文件(JSON 数组)', + description: '每项包含本地 source 路径和导出 target 路径。仅指定可公开资料。'}, + {name: 'additionalUrls', type: 'textarea', label: '额外页面地址(每行一项)'}, + {name: 'exclude', type: 'textarea', label: '排除路径前缀(每行一项)'}, + {name: 'assetOrigins', type: 'textarea', label: '允许下载的外部资源源站(每行一项)'} + ], + load: settings, + submit: async values => { + integrationSettings(values); + new UrlPolicy({...values, exclude: lines(values.exclude), assetOrigins: lines(values.assetOrigins)}); + const saved = {}; + for (const key of ['sourceUrl', 'destinationUrl', 'errorPageUrl', 'relative', 'additionalUrls', 'exclude', 'assetOrigins', 'autoPublish', 'schedule', 'timezone', + 'optimizeImages', 'minify', 'incremental', 'localDestination', 'gitRepository', 'gitBranch', 'netlifySiteId', 'cloudflareProject', 'cloudflareBranch', 's3Destination', 's3Endpoint', 'bunnyZone', 'bunnyPrefix', 'bunnyHostname', 'sftpHost', 'sftpPort', 'sftpUsername', + 'sftpDestination', 'sftpFingerprint', 'commentServerUrl', 'forms', 'searchSelectors', 'additionalFiles']) { + saved[key] = values[key] ?? (key === 'relative' ? false : ''); + } + validateDeployment(saved); + if (saved.gitRepository && /^https?:\/\//.test(saved.gitRepository)) { + const remote = new URL(saved.gitRepository); + if (remote.username || remote.password) throw new Error('Git 仓库地址不能包含凭据。'); + } + if (!saved.gitBranch) saved.gitBranch = 'gh-pages'; + automation.configure({...saved, timezone: saved.timezone || 'UTC'}); + await promises.mkdir(root, {recursive: true, mode: 0o700}); + await atomicJson(settingsFile, saved); + return {message: '静态导出设置已保存。'}; + } + }); + ctx.admin.registerForm({ + id: 'update-page', page: 'exports', title: '更新单页', submitLabel: '排队更新', + fields: [ + {name: 'baseId', type: 'text', label: '已完成的基线任务 ID', required: true}, + {name: 'url', type: 'text', label: '需要更新的页面地址', required: true} + ], + load: async() => ({baseId: '', url: ''}), + submit: async values => { + const baseline = await store.read(values.baseId); + if (baseline.status !== 'completed') throw new Error('请选择已完成的导出任务作为基线。'); + const policy = new UrlPolicy(baseline.config); + const url = policy.resolve(values.url); + if (!policy.allowed(url)) throw new Error('页面地址不在公开源站范围内。'); + const config = {...baseline.config, pageUpdate: {baseId: baseline.id, urls: [url.href]}}; + const job = await store.enqueue(config, baseline.seeds); + return {message: '单页更新已排队。', result: {id: job.id}}; + } + }); + ctx.admin.registerAction({ + id: 'generate', page: 'exports', label: '生成静态网站', type: 'primary', + handler: async() => { + const job = await enqueue(); + return {message: '导出任务已排队。', result: {id: job.id}}; + } + }); + ctx.routes.register({ + method: 'GET', path: '/jobs', auth: 'admin', csrf: false, + handler: async() => (await store.list()).map(({id, status, progress, error, createdAt}) => + ({id, status, progress, error, createdAt})) + }); + ctx.routes.register({ + method: 'POST', path: '/cancel/:id', auth: 'admin', csrf: true, + handler: async({params}) => { + await store.cancel(params.id); + return {cancelled: true}; + } + }); + ctx.routes.register({ + method: 'GET', path: '/logs/:id', auth: 'admin', csrf: false, + handler: async({params, ctx: request}) => { + await store.read(params.id); + const file = path.join(store.location(params.id), 'requests.jsonl'); + try { + await promises.access(file); + } catch (error) { + if (error.code === 'ENOENT') return request.throw(404, 'No export logs yet'); + throw error; + } + request.type = 'application/x-ndjson'; + request.set('Content-Disposition', `attachment; filename="static-${params.id}.jsonl"`); + request.body = fs.createReadStream(file); + } + }); + ctx.routes.register({ + method: 'GET', path: '/download/:id', auth: 'admin', csrf: false, + handler: async({params, ctx: request}) => { + const job = await store.read(params.id); + if (job.status !== 'completed') return request.throw(409, 'Export is not complete'); + request.type = 'application/zip'; + request.set('Content-Disposition', `attachment; filename="static-${job.id}.zip"`); + request.body = fs.createReadStream(path.join(store.location(job.id), 'output.zip')); + } + }); + }, + deactivate() { + automation?.stop(); + } +}; diff --git a/packages/simply-static/test/additional-files.test.js b/packages/simply-static/test/additional-files.test.js new file mode 100644 index 0000000..fb82c15 --- /dev/null +++ b/packages/simply-static/test/additional-files.test.js @@ -0,0 +1,32 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const {additionalFiles} = require('../lib/additional-files'); + +test('collects explicit files and directories while rejecting unsafe output paths', async() => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-extra-')); + try { + await fs.mkdir(path.join(root, 'docs')); + await fs.writeFile(path.join(root, 'docs/manual.txt'), 'manual'); + const files = await additionalFiles([{source: 'docs', target: 'downloads'}], {baseDirectory: root}); + assert.equal(files.get('downloads/manual.txt').toString(), 'manual'); + await assert.rejects(additionalFiles([{source: root, target: '../outside'}]), /Invalid/); + await assert.rejects(additionalFiles([{source: 'docs', target: 'downloads'}], { + baseDirectory: root, maxBytes: 1 + }), /size limit/); + await fs.writeFile(path.join(root, 'docs/.env'), 'secret'); + await assert.rejects(additionalFiles([{source: 'docs', target: 'downloads'}], { + baseDirectory: root + }), /Hidden/); + await fs.symlink(path.join(root, 'docs/manual.txt'), path.join(root, 'link')); + await assert.rejects(additionalFiles([{source: 'link', target: 'manual.txt'}], { + baseDirectory: root + }), /symlinks/); + } finally { + await fs.rm(root, {recursive: true, force: true}); + } +}); diff --git a/packages/simply-static/test/automation.test.js b/packages/simply-static/test/automation.test.js new file mode 100644 index 0000000..6c567b5 --- /dev/null +++ b/packages/simply-static/test/automation.test.js @@ -0,0 +1,49 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const {setTimeout: delay} = require('node:timers/promises'); +const {ExportAutomation} = require('../lib/automation'); + +test('coalesces rapid edits, respects disabled settings and cleans up timers', async() => { + let calls = 0; + const automation = new ExportAutomation({enqueue: async() => { calls++; }, debounceMs: 5}); + try { + automation.changed(); + await delay(15); + assert.equal(calls, 0); + automation.configure({autoPublish: true}); + automation.changed(); + automation.changed(); + automation.changed(); + await delay(30); + assert.equal(calls, 1); + automation.changed(); + automation.stop(); + await delay(20); + assert.equal(calls, 1); + } finally { + automation.stop(); + } +}); + +test('validates schedules and avoids overlapping enqueue calls', async() => { + let release; + let calls = 0; + const automation = new ExportAutomation({enqueue: async() => { + calls++; + await new Promise(resolve => { release = resolve; }); + }}); + try { + assert.throws(() => automation.configure({schedule: 'invalid'})); + automation.configure({schedule: '0 3 * * *', timezone: 'Asia/Shanghai'}); + const first = automation.trigger(); + const second = automation.trigger(); + await delay(0); + assert.equal(calls, 1); + release(); + await Promise.all([first, second]); + } finally { + automation.stop(); + } +}); diff --git a/packages/simply-static/test/cli.test.js b/packages/simply-static/test/cli.test.js new file mode 100644 index 0000000..32496b9 --- /dev/null +++ b/packages/simply-static/test/cli.test.js @@ -0,0 +1,75 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const http = require('node:http'); +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const {execFile} = require('node:child_process'); +const {promisify} = require('node:util'); +const execute = promisify(execFile); +const cli = path.join(__dirname, '../bin/cli.js'); + +test('CLI queues work then exports an actual anonymous HTTP site in a separate process', async() => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-cli-')); + const server = http.createServer((request, response) => { + assert.equal(request.headers.cookie, undefined); + response.setHeader('Content-Type', 'text/html'); + response.end('Live fixture
    Public content
    '); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + const configFile = path.join(root, 'config.json'); + await fs.writeFile(configFile, JSON.stringify({ + sourceUrl: `http://127.0.0.1:${server.address().port}/`, destinationUrl: 'https://static.example/' + })); + const store = path.join(root, 'jobs'); + const queued = await execute(process.execPath, [cli, 'enqueue', '--config', configFile, '--store', store]); + const {id} = JSON.parse(queued.stdout); + await execute(process.execPath, [cli, 'worker', '--once', '--store', store]); + const status = await execute(process.execPath, [cli, 'status', '--id', id, '--store', store]); + const job = JSON.parse(status.stdout); + assert.equal(job.status, 'completed'); + assert.match(await fs.readFile(path.join(job.result.directory, 'index.html'), 'utf8'), /Public content/); + assert.ok((await fs.stat(job.result.archive)).size > 0); + } finally { + await new Promise(resolve => server.close(resolve)); + await fs.rm(root, {recursive: true, force: true}); + } +}); + +test('single-page update publishes a complete snapshot and refreshes referencing pages', async() => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-page-update-')); + let version = 'old'; + const requests = []; + const server = http.createServer((request, response) => { + requests.push(request.url); + response.setHeader('Content-Type', 'text/html'); + const html = request.url === '/' ? `${version}Other` : + request.url === '/post' ? `
    ${version}
    ` : '
    Unrelated
    '; + response.end(html); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + const config = path.join(root, 'config.json'); + const store = path.join(root, 'jobs'); + await fs.writeFile(config, JSON.stringify({sourceUrl: `http://127.0.0.1:${server.address().port}/`, + destinationUrl: 'https://static.example/'})); + const first = JSON.parse((await execute(process.execPath, [cli, 'export', '--config', config, '--store', store])).stdout); + version = 'new'; + requests.length = 0; + const next = JSON.parse((await execute(process.execPath, [cli, 'update-page', '--id', first.id, + '--url', '/post', '--store', store])).stdout); + await execute(process.execPath, [cli, 'worker', '--once', '--store', store]); + const updated = JSON.parse((await execute(process.execPath, [cli, 'status', '--id', next.id, '--store', store])).stdout); + assert.equal(updated.status, 'completed'); + assert.deepEqual(requests.sort(), ['/', '/post']); + assert.match(await fs.readFile(path.join(updated.result.directory, 'index.html'), 'utf8'), />new server.close(resolve)); + await fs.rm(root, {recursive: true, force: true}); + } +}); diff --git a/packages/simply-static/test/deploy.test.js b/packages/simply-static/test/deploy.test.js new file mode 100644 index 0000000..1ccf72c --- /dev/null +++ b/packages/simply-static/test/deploy.test.js @@ -0,0 +1,31 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const {deploy, validateDeployment} = require('../lib/deploy'); + +test('dispatches one configured provider without passing configuration secrets', async() => { + const calls = []; + const adapters = Object.fromEntries(['publishLocal', 'publishGit', 'publishNetlify', 'publishCloudflare', 'publishS3', 'publishBunny', 'publishSftp'].map(name => [name, + async(...args) => { calls.push({name, args}); return {type: name}; } + ])); + await deploy('/output', {netlifySiteId: 'site'}, {adapters}); + assert.equal(calls[0].name, 'publishNetlify'); + assert.equal(calls[0].args[0], '/output.zip'); + assert.equal(calls[0].args[1].token, undefined); + await deploy('/output', {gitRepository: 'git@example.com:site.git'}, {adapters}); + assert.equal(calls[1].args[1].branch, 'gh-pages'); + await deploy('/output', {cloudflareProject: 'site', cloudflareBranch: 'main'}, {adapters}); + assert.equal(calls[2].name, 'publishCloudflare'); + assert.equal(calls[2].args[1].branch, 'main'); + await deploy('/output', {s3Destination: 's3://example/site/'}, {adapters}); + assert.equal(calls[3].name, 'publishS3'); + await deploy('/output', {bunnyZone: 'example', bunnyPrefix: 'site'}, {adapters}); + assert.equal(calls[4].name, 'publishBunny'); + await deploy('/output', {sftpHost: 'example.com', sftpPort: '2222'}, {adapters}); + assert.equal(calls[5].name, 'publishSftp'); + assert.equal(calls[5].args[1].port, 2222); + assert.equal(await deploy('/output', {}, {adapters}), null); + assert.throws(() => validateDeployment({netlifySiteId: 'site', localDestination: '/public'}), /only one/); + assert.throws(() => validateDeployment({netlifySiteId: '../site'}), /Invalid/); +}); diff --git a/packages/simply-static/test/exporter.test.js b/packages/simply-static/test/exporter.test.js new file mode 100644 index 0000000..846d899 --- /dev/null +++ b/packages/simply-static/test/exporter.test.js @@ -0,0 +1,129 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const {unzipSync} = require('fflate'); +const {exportSite} = require('../lib/exporter'); + +const config = {sourceUrl: 'https://source.example/', destinationUrl: 'https://static.example/'}; + +test('exports linked pages and recursive resources into usable HTML and ZIP', async() => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-export-')); + const directory = path.join(root, 'release'); + const fixtures = { + '/': ['text/html', 'HomePost'], + '/post': ['text/html', 'Post
    Article text
    Home'], + '/main.css': ['text/css', '@import "extra.css";body{background:url(photo.png)}'], + '/extra.css': ['text/css', 'body{color:red}'], + '/photo.png': ['image/png', Buffer.from([1, 2, 3])] + }; + try { + const manifest = await exportSite(config, {directory, fetcher: async url => { + const fixture = fixtures[new URL(url).pathname]; + assert.ok(fixture, String(url)); + return new Response(fixture[1], {headers: {'content-type': fixture[0]}}); + }}); + assert.equal(manifest.resources.length, 5); + const html = await fs.readFile(path.join(directory, 'index.html'), 'utf8'); + assert.match(html, /https:\/\/static.example\/post\/index.html/); + const zip = unzipSync(await fs.readFile(directory + '.zip')); + assert.deepEqual(Buffer.from(zip['photo.png']), Buffer.from([1, 2, 3])); + assert.ok(zip['post/index.html']); + assert.ok(zip['static-search.html']); + assert.ok(zip['static-search.js']); + assert.ok(zip['static-search.css']); + const search = JSON.parse(Buffer.from(zip['static-search.json']).toString()); + assert.ok(search.some(item => item.title === 'Post' && item.text.includes('Article text'))); + } finally { + await fs.rm(root, {recursive: true, force: true}); + } +}); + +test('merges identical slash aliases but rejects different pages sharing a file', async() => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-alias-')); + try { + const fetcher = async url => new Response(new URL(url).pathname === '/' ? + 'AboutAlso about' : '
    About
    ', + {headers: {'content-type': 'text/html'}}); + const manifest = await exportSite(config, {directory: path.join(root, 'good'), fetcher}); + assert.equal(manifest.resources.filter(item => item.file === 'about/index.html').length, 1); + await assert.rejects(exportSite(config, { + directory: path.join(root, 'bad'), fetcher: async url => new URL(url).pathname === '/about/' ? + new Response('Different', {headers: {'content-type': 'text/html'}}) : fetcher(url) + }), /collision/); + } finally { + await fs.rm(root, {recursive: true, force: true}); + } +}); + +test('routes built-in search and hot-word links to the static search UI without crawling queries', async() => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-search-links-')); + try { + const requests = []; + await exportSite(config, {directory: root, fetcher: async url => { + requests.push(String(url)); + return new Response('Search' + + '中文' + + '
    ', + {headers: {'content-type': 'text/html'}}); + }}); + assert.equal(requests.length, 1); + const html = await fs.readFile(path.join(root, 'index.html'), 'utf8'); + assert.match(html, /static-search.html\?q=%E4%B8%AD%E6%96%87/); + assert.match(html, /action="https:\/\/static.example\/static-search.html"/); + assert.match(html, /name="q"/); + } finally { + await fs.rm(root, {recursive: true, force: true}); + await fs.rm(root + '.zip', {force: true}); + } +}); + +test('removes explicitly updated deleted pages but does not suppress unrelated 404s', async() => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-delete-')); + try { + const fetcher = async url => new URL(url).pathname === '/' ? + new Response('
    Home without deleted article
    ', {headers: {'content-type': 'text/html'}}) : + new Response('Gone', {status: 404}); + const manifest = await exportSite({...config, pageUpdate: {urls: ['/deleted']}}, { + directory: path.join(root, 'updated'), seeds: ['/deleted'], fetcher + }); + assert.deepEqual(manifest.removed, ['https://source.example/deleted']); + assert.equal(manifest.resources.length, 1); + const search = await fs.readFile(path.join(root, 'updated/static-search.json'), 'utf8'); + assert.ok(!search.includes('https://static.example/deleted')); + await assert.rejects(exportSite(config, {directory: path.join(root, 'failed'), seeds: ['/deleted'], fetcher}), /404/); + } finally { + await fs.rm(root, {recursive: true, force: true}); + } +}); + +test('exports explicit error pages and robots sitemap references without indexing errors', async() => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-errors-')); + try { + const routes = { + '/': ['中文Next', 'text/html', 200], + '/zh/文章.html': ['
    中文文章
    ', 'text/html', 200], + '/en/page/2': ['
    Page two
    ', 'text/html', 200], + '/missing': ['
    Not found
    ', 'text/html', 404], + '/robots.txt': ['User-agent: *\nSitemap: https://source.example/sitemap.xml', 'text/plain', 200], + '/sitemap.xml': ['https://source.example/', 'application/xml', 200] + }; + await exportSite({...config, errorPageUrl: '/missing'}, { + directory: root, seeds: ['/robots.txt'], fetcher: async url => { + const [body, type, status] = routes[decodeURIComponent(new URL(url).pathname)]; + return new Response(body, {status, headers: {'content-type': type}}); + } + }); + assert.match(await fs.readFile(path.join(root, '404.html'), 'utf8'), /Not found/); + assert.match(await fs.readFile(path.join(root, 'robots.txt'), 'utf8'), /https:\/\/static.example\/sitemap.xml/); + assert.match(await fs.readFile(path.join(root, 'zh/文章.html'), 'utf8'), /中文文章/); + assert.match(await fs.readFile(path.join(root, 'en/page/2/index.html'), 'utf8'), /Page two/); + assert.ok(!(await fs.readFile(path.join(root, 'static-search.json'), 'utf8')).includes('Not found')); + } finally { + await fs.rm(root, {recursive: true, force: true}); + await fs.rm(root + '.zip', {force: true}); + } +}); diff --git a/packages/simply-static/test/fetch-resource.test.js b/packages/simply-static/test/fetch-resource.test.js new file mode 100644 index 0000000..694b13d --- /dev/null +++ b/packages/simply-static/test/fetch-resource.test.js @@ -0,0 +1,63 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const {UrlPolicy} = require('../lib/urls'); +const {fetchResource} = require('../lib/fetch-resource'); +const policy = new UrlPolicy({sourceUrl: 'https://source.example/', destinationUrl: 'https://static.example/'}); + +function download(fetcher, options = {}) { + return fetchResource('https://source.example/', {policy, fetcher, retryDelay: 0, ...options}); +} + +test('follows allowed redirects anonymously and returns final URL', async() => { + let calls = 0; + const result = await download(async(url, options) => { + assert.equal(options.credentials, 'omit'); + assert.equal(options.headers.cookie, undefined); + assert.equal(options.redirect, 'manual'); + calls++; + return calls === 1 ? new Response(null, {status: 302, headers: {location: '/article'}}) : + new Response('article', {headers: {'content-type': 'text/html'}}); + }); + assert.equal(result.url, 'https://source.example/article'); + assert.equal(result.body.toString(), 'article'); + assert.equal(calls, 2); +}); + +test('does not follow redirects to admin or unapproved origins', async() => { + for (const location of ['/admin', 'https://other.example/']) { + let calls = 0; + await assert.rejects(download(async() => { + calls++; + return new Response(null, {status: 302, headers: {location}}); + }), /allowed scope/); + assert.equal(calls, 1); + } +}); + +test('retries temporary failures but not missing or private content', async() => { + let calls = 0; + const result = await download(async() => ++calls === 1 ? + new Response('busy', {status: 503}) : new Response('ok')); + assert.equal(calls, 2); + assert.equal(result.body.toString(), 'ok'); + for (const response of [() => new Response('missing', {status: 404}), + () => new Response('secret', {headers: {'cache-control': 'private'}})]) { + calls = 0; + await assert.rejects(download(async() => { + calls++; + return response(); + })); + assert.equal(calls, 1); + } +}); + +test('enforces streamed size limits and honors cancellation before requesting', async() => { + await assert.rejects(download(async() => new Response('oversized'), {maxBytes: 3}), /size limit/); + const controller = new AbortController(); + controller.abort(); + await assert.rejects(download(async() => assert.fail('must not request'), { + signal: controller.signal + }), {name: 'AbortError'}); +}); diff --git a/packages/simply-static/test/fixtures/create-site.js b/packages/simply-static/test/fixtures/create-site.js new file mode 100644 index 0000000..8e1bcf1 --- /dev/null +++ b/packages/simply-static/test/fixtures/create-site.js @@ -0,0 +1,53 @@ +'use strict'; + +const fs = require('node:fs/promises'); +const path = require('node:path'); + +async function createSite(core, target, port) { + const {scaffold, projectConfig} = require(path.join(core, 'lib/cli')); + const {initialize} = require(path.join(core, 'lib/installer')); + const options = {dbType: 'sqlite', dbPath: 'data/firekylin.sqlite', dbPrefix: 'fk_', + skipInstall: true, siteTitle: 'Static export fixture', siteUrl: `http://127.0.0.1:${port}`}; + scaffold(target, options); + const config = projectConfig(options); + config.server = {host: '127.0.0.1', port, proxy: false}; + await fs.writeFile(path.join(target, 'firekylin.config.js'), + "'use strict';\nmodule.exports = " + JSON.stringify(config, null, 2) + ';\n'); + await initialize(target, config, {title: options.siteTitle, siteUrl: options.siteUrl, + username: 'fixture-admin', password: 'local-test-only-password', email: 'fixture@example.invalid'}); + return {target, config}; +} + +module.exports = {createSite}; + +async function seedVisibility(core, target) { + const {createRequire} = require('node:module'); + const coreRequire = createRequire(path.join(core, 'package.json')); + const adapterRequire = createRequire(coreRequire.resolve('think-model-sqlite')); + const Database = adapterRequire('better-sqlite3'); + const worker = await fs.readFile(path.join(core, 'src/bootstrap/worker.js'), 'utf8'); + const constants = Object.fromEntries([...worker.matchAll(/\b(POST_[A-Z_]+):\s*(\d+)/g)] + .map(match => [match[1], Number(match[2])])); + const db = new Database(path.join(target, 'data/firekylin.sqlite')); + try { + const insert = db.prepare('INSERT INTO fk_post (user_id,type,status,title,pathname,summary,markdown_content,content,allow_comment,create_time,update_time,is_public,comment_num,options) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)'); + const rows = [ + {slug: 'public-fixture', secret: 'PUBLIC_FIXTURE_TEXT'}, + {slug: 'private-fixture', secret: 'PRIVATE_SECRET_MARKER', private: true}, + {slug: 'draft-fixture', secret: 'DRAFT_SECRET_MARKER', draft: true}, + {slug: 'future-fixture', secret: 'FUTURE_SECRET_MARKER', future: true}, + {slug: 'protected-fixture', secret: 'PASSWORD_SECRET_MARKER', protected: true} + ]; + for (const row of rows) { + insert.run(1, constants.POST_ARTICLE, row.draft ? constants.POST_DRAFT : constants.POST_PUBLISH, + row.slug, row.slug, row.secret, row.secret, `

    ${row.secret}

    `, 0, + row.future ? '2099-01-01 00:00:00' : '2020-01-01 00:00:00', '2020-01-01 00:00:00', + row.private ? 0 : constants.POST_PUBLIC, 0, + row.protected ? JSON.stringify({postPasswordHash: 'fixture-protected-hash'}) : '{}'); + } + } finally { + db.close(); + } +} + +module.exports.seedVisibility = seedVisibility; diff --git a/packages/simply-static/test/integrations.test.js b/packages/simply-static/test/integrations.test.js new file mode 100644 index 0000000..e4aec97 --- /dev/null +++ b/packages/simply-static/test/integrations.test.js @@ -0,0 +1,46 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const cheerio = require('cheerio'); +const {integrateHtml} = require('../lib/integrations'); + +test('maps external forms, removes old CSRF input and converts search query names', () => { + const result = integrateHtml('
    ' + + '
    ' + + '
    ', { + pageUrl: 'https://source.example/', searchUrl: '../static-search.html', + forms: [{selector: '#contact', endpoint: 'https://forms.example/submit'}], searchSelectors: ['#search'] + }); + const $ = cheerio.load(result.html); + assert.equal($('#contact').attr('action'), 'https://forms.example/submit'); + assert.equal($('#contact').attr('method'), 'post'); + assert.equal($('#contact').attr('onsubmit'), undefined); + assert.equal($('input[name="csrfToken"]').length, 0); + assert.equal($('#search').attr('action'), '../static-search.html'); + assert.equal($('#search input').attr('name'), 'q'); + assert.equal(result.warnings.length, 1); + assert.equal(result.warnings[0].action, '/dynamic'); +}); + +test('rejects insecure form endpoints and invalid selector targets', () => { + assert.throws(() => integrateHtml('
    ', { + forms: [{selector: 'form', endpoint: 'http://forms.example/'}] + }), /HTTPS/); + assert.throws(() => integrateHtml('
    ', { + forms: [{selector: 'div', endpoint: 'https://forms.example/'}] + }), /identify forms/); +}); + +test('external comments keep original page identity across static subdirectory moves', () => { + const result = integrateHtml('
    ', { + pageUrl: 'https://source.example/post.html', commentServerUrl: 'https://comments.example/', + commentScriptUrl: '../static-comments.js' + }); + const $ = cheerio.load(result.html); + const config = JSON.parse($('.fk-comment-container').attr('data-comment-config')); + assert.equal(config.serverURL, 'https://comments.example'); + assert.equal(config.path, '/post.html'); + assert.equal($('script').attr('src'), '../static-comments.js'); + assert.ok(!result.html.includes('oldInitializer')); +}); diff --git a/packages/simply-static/test/invalidation.test.js b/packages/simply-static/test/invalidation.test.js new file mode 100644 index 0000000..8170391 --- /dev/null +++ b/packages/simply-static/test/invalidation.test.js @@ -0,0 +1,31 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const path = require('node:path'); +const os = require('node:os'); +const {ResourceCache} = require('../lib/resource-cache'); +const {preparePageUpdate} = require('../lib/invalidation'); + +test('invalidates changed page, referrers and feeds while reusing unrelated content', async() => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-invalidation-')); + try { + const previousCheckpoint = path.join(root, 'previous'); + const checkpointDirectory = path.join(root, 'next'); + const cache = new ResourceCache(previousCheckpoint); + for (const [pathname, html] of [['/', 'Post'], + ['/category', 'Post'], ['/post', '

    old

    '], ['/unrelated', '

    unrelated

    ']]) { + const url = 'https://example.com' + pathname; + await cache.write({requestedUrl: url, url, body: Buffer.from(html), contentType: 'text/html', status: 200}); + } + const result = await preparePageUpdate({previousCheckpoint, checkpointDirectory, + config: {sourceUrl: 'https://example.com/', destinationUrl: 'https://static.example/'}, urls: ['/post']}); + assert.equal(result.reused, 1); + assert.ok(result.invalidated.includes('https://example.com/category')); + assert.equal(await new ResourceCache(checkpointDirectory).read('https://example.com/post'), null); + assert.ok(await new ResourceCache(checkpointDirectory).read('https://example.com/unrelated')); + } finally { + await fs.rm(root, {recursive: true, force: true}); + } +}); diff --git a/packages/simply-static/test/jobs.test.js b/packages/simply-static/test/jobs.test.js new file mode 100644 index 0000000..1e16ca7 --- /dev/null +++ b/packages/simply-static/test/jobs.test.js @@ -0,0 +1,130 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const path = require('node:path'); +const os = require('node:os'); +const {JobStore} = require('../lib/jobs'); + +async function fixture(fn) { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'export-jobs-')); + try { + await fn(new JobStore(root)); + } finally { + await fs.rm(root, {recursive: true, force: true}); + } +} + +test('persists queue, progress and completion across store instances', () => fixture(async store => { + const job = await store.create({sourceUrl: 'https://example.com'}, ['/page']); + const second = new JobStore(store.root); + assert.equal((await second.list())[0].id, job.id); + const finished = await second.run(job.id, async(value, context) => { + assert.deepEqual(value.seeds, ['/page']); + await context.onProgress({completed: 2}); + return {pages: 2}; + }); + assert.equal(finished.status, 'completed'); + assert.deepEqual((await store.read(job.id)).progress, {completed: 2}); + assert.equal(await store.run(job.id, () => assert.fail('must not run twice')), null); +})); + +test('only one worker claims a job', () => fixture(async store => { + const job = await store.create({}); + let release; + let started; + const ready = new Promise(resolve => { started = resolve; }); + const first = store.run(job.id, async() => { + started(); + await new Promise(resolve => { release = resolve; }); + }); + await ready; + assert.equal(await store.run(job.id, () => assert.fail('duplicate worker')), null); + release(); + await first; +})); + +test('records failures and honors queued cancellation', () => fixture(async store => { + const failed = await store.create({}); + await store.run(failed.id, async() => { throw new Error('Download unavailable'); }); + assert.equal((await store.read(failed.id)).status, 'failed'); + const cancelled = await store.create({}); + await store.cancel(cancelled.id); + await store.run(cancelled.id, () => assert.fail('cancelled job executed')); + assert.equal((await store.read(cancelled.id)).status, 'cancelled'); + assert.throws(() => store.location('../secret'), /Invalid/); +})); + +test('deduplicates queued exports across stores and retains one follow-up while running', () => fixture(async store => { + const second = new JobStore(store.root); + const config = {sourceUrl: 'https://example.com'}; + const jobs = await Promise.all([store.enqueue(config), second.enqueue(config), store.enqueue(config)]); + assert.equal(new Set(jobs.map(job => job.id)).size, 1); + let release; + let started; + const ready = new Promise(resolve => { started = resolve; }); + const running = store.run(jobs[0].id, async() => { + started(); + await new Promise(resolve => { release = resolve; }); + }); + await ready; + try { + const next = await second.enqueue(config); + assert.notEqual(next.id, jobs[0].id); + assert.equal((await store.enqueue(config)).id, next.id); + await store.cancel(next.id); + assert.notEqual((await second.enqueue(config)).id, next.id); + } finally { + release(); + await running; + } +})); + +test('recovers only stopped local workers and refuses ambiguous publication retries', () => fixture(async store => { + const {atomicJson} = require('../lib/jobs'); + const job = await store.create({}); + const directory = store.location(job.id); + await atomicJson(path.join(directory, 'job.json'), {...job, status: 'running'}); + await fs.writeFile(path.join(directory, 'lock'), JSON.stringify({pid: 123, hostname: 'worker'})); + await assert.rejects(store.recover(job.id, {hostname: 'other', isAlive: () => false}), /original worker/); + await assert.rejects(store.recover(job.id, {hostname: 'worker', isAlive: () => true}), /still active/); + const recovered = await store.recover(job.id, {hostname: 'worker', isAlive: () => false}); + assert.equal(recovered.status, 'queued'); + assert.equal(recovered.recoveries, 1); + await store.run(job.id, async() => ({ok: true})); + assert.equal((await store.read(job.id)).status, 'completed'); + await atomicJson(path.join(directory, 'job.json'), {...job, status: 'running', phase: 'deploying'}); + await assert.rejects(store.recover(job.id), /publication/); +})); + +test('persists structured request logs alongside task state', () => fixture(async store => { + const job = await store.create({}); + await store.run(job.id, async(value, context) => { + await context.onLog({stage: 'fetch', url: 'https://example.com/', status: 200}); + await context.onLog({stage: 'fetch', url: 'https://example.com/missing', status: 404}); + throw new Error('HTTP 404'); + }); + const records = (await fs.readFile(path.join(store.location(job.id), 'requests.jsonl'), 'utf8')) + .trim().split('\n').map(line => JSON.parse(line)); + assert.deepEqual(records.map(record => record.status), [200, 404]); + assert.ok(records.every(record => record.timestamp)); + assert.equal((await store.read(job.id)).status, 'failed'); +})); + +test('serializes distinct jobs so older snapshots cannot overwrite newer publications', () => fixture(async store => { + const first = await store.create({}); + const second = await store.create({}); + let release; + let started; + const ready = new Promise(resolve => { started = resolve; }); + const running = store.run(first.id, async() => { + started(); + await new Promise(resolve => { release = resolve; }); + }); + await ready; + assert.equal(await store.run(second.id, () => assert.fail('concurrent publication')), null); + release(); + await running; + assert.equal((await store.run(second.id, async() => ({}))).status, 'completed'); +})); diff --git a/packages/simply-static/test/live-site.test.js b/packages/simply-static/test/live-site.test.js new file mode 100644 index 0000000..c26881c --- /dev/null +++ b/packages/simply-static/test/live-site.test.js @@ -0,0 +1,81 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const {spawn} = require('node:child_process'); +const {setTimeout: delay} = require('node:timers/promises'); +const net = require('node:net'); +const {createSite, seedVisibility} = require('./fixtures/create-site'); +const {exportSite} = require('../lib/exporter'); +const core = process.env.FIREKYLIN_CORE_PATH; + +test('exports a real SQLite-backed Firekylin site with its default theme', { + skip: !core || !process.env.STATIC_LIVE_TEST, timeout: 60000 +}, async() => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-live-test-')); + const probe = net.createServer(); + await new Promise(resolve => probe.listen(0, '127.0.0.1', resolve)); + const port = probe.address().port; + await new Promise(resolve => probe.close(resolve)); + let child; + try { + const site = path.join(root, 'site'); + await createSite(core, site, port); + await seedVisibility(core, site); + const runner = path.join(root, 'server.cjs'); + await fs.writeFile(runner, "'use strict';\n" + + `process.chdir(${JSON.stringify(site)});\n` + + `process.env.FIREKYLIN_PROJECT_PATH = ${JSON.stringify(site)};\n` + + `require(${JSON.stringify(path.join(core, 'lib/start'))})().catch(error => {\n` + + ' console.error(error.message);\n process.exit(1);\n});\n'); + child = spawn(process.execPath, [runner], {detached: true, stdio: ['ignore', 'pipe', 'pipe']}); + let serverLog = ''; + child.stdout.on('data', chunk => { serverLog += chunk; }); + child.stderr.on('data', chunk => { serverLog += chunk; }); + const sourceUrl = `http://127.0.0.1:${port}/`; + let ready = false; + for (let attempt = 0; attempt < 300; attempt++) { + if (child.exitCode !== null) throw new Error('Fixture server exited before readiness'); + try { + const response = await fetch(sourceUrl, {signal: AbortSignal.timeout(1000)}); + await response.body?.cancel(); + if (response.ok) { + ready = true; + break; + } + } catch {} + await delay(100); + } + assert.ok(ready, 'Fixture server should become ready: ' + serverLog.slice(-5000)); + const directory = path.join(root, 'export'); + const manifest = await exportSite({sourceUrl, destinationUrl: 'https://static.example/'}, { + directory, seeds: ['/sitemap.xml', '/rss.xml'] + }); + assert.ok(manifest.resources.some(item => item.file === 'post/hello-world-via-firekylin.html')); + assert.ok(manifest.resources.some(item => item.file.endsWith('/res/css/article.css'))); + assert.match(await fs.readFile(path.join(directory, 'index.html'), 'utf8'), /https:\/\/static.example\//); + assert.ok((await fs.stat(directory + '.zip')).size > 0); + const textFiles = manifest.resources.filter(item => /\.(html|xml|json)$/.test(item.file)); + const allText = (await Promise.all(textFiles.map(item => + fs.readFile(path.join(directory, item.file), 'utf8')))).join('\n') + + await fs.readFile(path.join(directory, 'static-search.json'), 'utf8'); + assert.match(allText, /PUBLIC_FIXTURE_TEXT/); + for (const marker of ['PRIVATE_SECRET_MARKER', 'DRAFT_SECRET_MARKER', 'FUTURE_SECRET_MARKER', 'PASSWORD_SECRET_MARKER']) { + assert.ok(!allText.includes(marker), `Export must not contain ${marker}`); + } + + } finally { + if (child?.pid) { + try { + process.kill(-child.pid, 'SIGTERM'); + } catch (error) { + if (error.code !== 'ESRCH') throw error; + } + await delay(300); + } + await fs.rm(root, {recursive: true, force: true}); + } +}); diff --git a/packages/simply-static/test/optimize-image.test.js b/packages/simply-static/test/optimize-image.test.js new file mode 100644 index 0000000..519e488 --- /dev/null +++ b/packages/simply-static/test/optimize-image.test.js @@ -0,0 +1,25 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const {optimizeImage} = require('../lib/optimize-image'); +let sharp; +try { + sharp = require('sharp'); +} catch { + sharp = null; +} + +test('image optimization keeps format, dimensions and PNG pixels while reducing size', {skip: !sharp}, async() => { + const source = await sharp({create: {width: 64, height: 64, channels: 4, background: '#f04c7a'}}) + .png({compressionLevel: 0}).toBuffer(); + const output = await optimizeImage(source, 'image/png', true); + assert.ok(output.length < source.length); + const metadata = await sharp(output).metadata(); + assert.equal(metadata.width, 64); + assert.equal(metadata.height, 64); + assert.equal(metadata.format, 'png'); + assert.deepEqual(await sharp(output).raw().toBuffer(), await sharp(source).raw().toBuffer()); + assert.equal(await optimizeImage(source, 'image/png', false), source); + assert.equal(await optimizeImage(source, 'image/gif', true), source); +}); diff --git a/packages/simply-static/test/optimize.test.js b/packages/simply-static/test/optimize.test.js new file mode 100644 index 0000000..210433f --- /dev/null +++ b/packages/simply-static/test/optimize.test.js @@ -0,0 +1,27 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const vm = require('node:vm'); +const {optimize} = require('../lib/optimize'); + +test('optional optimization preserves HTML whitespace and script behavior', async() => { + const html = Buffer.from('
      a\n b
    '); + assert.equal(await optimize(html, 'text/html'), html); + const optimized = await optimize(html, 'text/html', true); + assert.match(optimized.toString(), /
      a\n b<\/pre>/);
    +  assert.ok(!optimized.toString().includes('internal note'));
    +  const script = Buffer.from('function add(a, b) {\n  return a + b;\n}\nglobalThis.answer = add(2, 3);');
    +  const result = await optimize(script, 'application/javascript', true);
    +  const context = {};
    +  vm.runInNewContext(result.toString(), context);
    +  assert.equal(context.answer, 5);
    +  assert.ok(result.length < script.length);
    +});
    +
    +test('CSS optimization retains relative resource paths and binary assets remain unchanged', async() => {
    +  const result = await optimize(Buffer.from('body {\n  background: url(../image.png);\n  color: red;\n}'), 'text/css', true);
    +  assert.match(result.toString(), /\.\.\/image.png/);
    +  const png = Buffer.from([0, 255, 3]);
    +  assert.equal(await optimize(png, 'image/png', true), png);
    +});
    diff --git a/packages/simply-static/test/plugin.test.js b/packages/simply-static/test/plugin.test.js
    new file mode 100644
    index 0000000..bc5915e
    --- /dev/null
    +++ b/packages/simply-static/test/plugin.test.js
    @@ -0,0 +1,51 @@
    +'use strict';
    +
    +const test = require('node:test');
    +const assert = require('node:assert/strict');
    +const fs = require('node:fs/promises');
    +const path = require('node:path');
    +const os = require('node:os');
    +
    +const core = process.env.FIREKYLIN_CORE_PATH;
    +
    +test('registers with real Firekylin admin API and queues configured exports', {skip: !core}, async() => {
    +  const AdminRegistry = require(path.join(core, 'src/plugin/admin'));
    +  const registry = new AdminRegistry();
    +  const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-plugin-'));
    +  const previous = process.env.FIREKYLIN_PROJECT_PATH;
    +  process.env.FIREKYLIN_PROJECT_PATH = root;
    +  try {
    +    const routes = [];
    +    const admin = {};
    +    for (const method of ['registerPanel', 'registerPage', 'registerForm', 'registerAction']) {
    +      admin[method] = definition => registry[method](definition, 'simply-static');
    +    }
    +    require('../plugin').register({admin, events: {on() {}}, routes: {register: route => routes.push(route)}});
    +    await registry.loadPage('simply-static', 'exports', {});
    +    await registry.submitForm('simply-static', 'settings', {
    +      sourceUrl: 'https://source.example/', destinationUrl: 'https://static.example/',
    +      relative: true, additionalUrls: '/unlinked', exclude: '/private', assetOrigins: ''
    +    }, {});
    +    const queued = await registry.runAction('simply-static', 'generate', {}, {});
    +    assert.ok(queued.result.id);
    +    const listing = routes.find(route => route.path === '/jobs');
    +    assert.equal(listing.auth, 'admin');
    +    const jobs = await listing.handler();
    +    assert.equal(jobs[0].status, 'queued');
    +    assert.equal(jobs[0].config, undefined);
    +    const cancel = routes.find(route => route.path === '/cancel/:id');
    +    assert.equal(cancel.auth, 'admin');
    +    assert.equal(cancel.csrf, true);
    +    const download = routes.find(route => route.path === '/download/:id');
    +    assert.equal(download.auth, 'admin');
    +    let status;
    +    await download.handler({params: {id: queued.result.id}, ctx: {throw(code) { status = code; }}});
    +    assert.equal(status, 409);
    +    await registry.loadPage('simply-static', 'exports', {});
    +  } finally {
    +    require('../plugin').deactivate();
    +    if (previous === undefined) delete process.env.FIREKYLIN_PROJECT_PATH;
    +    else process.env.FIREKYLIN_PROJECT_PATH = previous;
    +    await fs.rm(root, {recursive: true, force: true});
    +  }
    +});
    diff --git a/packages/simply-static/test/publish-bunny.test.js b/packages/simply-static/test/publish-bunny.test.js
    new file mode 100644
    index 0000000..e08df99
    --- /dev/null
    +++ b/packages/simply-static/test/publish-bunny.test.js
    @@ -0,0 +1,45 @@
    +'use strict';
    +
    +const test = require('node:test');
    +const assert = require('node:assert/strict');
    +const fs = require('node:fs/promises');
    +const path = require('node:path');
    +const os = require('node:os');
    +const {publishBunny} = require('../lib/publish-bunny');
    +
    +test('uploads with checksums then removes only stale files under the configured prefix', async() => {
    +  const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-bunny-'));
    +  try {
    +    await fs.writeFile(path.join(root, 'index.html'), 'site');
    +    const calls = [];
    +    const options = {zone: 'example', prefix: 'site', token: 'fixture', fetcher: async(url, init) => {
    +      calls.push({url, init});
    +      assert.equal(init.redirect, 'error');
    +      assert.equal(init.headers.AccessKey, 'fixture');
    +      if (init.method === 'PUT') {
    +        assert.match(init.headers.Checksum, /^[A-F0-9]{64}$/);
    +        return new Response('', {status: 201});
    +      }
    +      if (init.method === 'GET') return Response.json([
    +        {ObjectName: 'index.html', IsDirectory: false}, {ObjectName: 'old.html', IsDirectory: false}
    +      ]);
    +      return new Response('', {status: 200});
    +    }};
    +    const result = await publishBunny(root, options);
    +    assert.equal(result.files, 1);
    +    assert.deepEqual(calls.map(call => call.init.method), ['PUT', 'GET', 'DELETE']);
    +    assert.equal(calls[2].url, 'https://storage.bunnycdn.com/example/site/old.html');
    +    let failedCalls = 0;
    +    await assert.rejects(publishBunny(root, {...options, fetcher: async() => {
    +      failedCalls++;
    +      return new Response('', {status: 500});
    +    }}), /HTTP 500/);
    +    assert.equal(failedCalls, 1);
    +    await assert.rejects(publishBunny(root, {...options, prefix: '../other'}), /prefix/);
    +    await assert.rejects(publishBunny(root, {...options, fetcher: async(url, init) =>
    +      init.method === 'GET' ? Response.json([{ObjectName: '../other', IsDirectory: false}]) :
    +        new Response('', {status: 201})}), /remote filename/);
    +  } finally {
    +    await fs.rm(root, {recursive: true, force: true});
    +  }
    +});
    diff --git a/packages/simply-static/test/publish-cloudflare.test.js b/packages/simply-static/test/publish-cloudflare.test.js
    new file mode 100644
    index 0000000..3451d5c
    --- /dev/null
    +++ b/packages/simply-static/test/publish-cloudflare.test.js
    @@ -0,0 +1,34 @@
    +'use strict';
    +
    +const test = require('node:test');
    +const assert = require('node:assert/strict');
    +const fs = require('node:fs/promises');
    +const os = require('node:os');
    +const path = require('node:path');
    +const {publishCloudflare} = require('../lib/publish-cloudflare');
    +
    +test('invokes Wrangler with isolated working directory and explicit branch', async() => {
    +  const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-cf-test-'));
    +  try {
    +    await fs.writeFile(path.join(root, 'index.html'), 'site');
    +    let calls = 0;
    +    const options = {project: 'example', branch: 'main',
    +      environment: {CLOUDFLARE_API_TOKEN: 'fixture', CLOUDFLARE_ACCOUNT_ID: 'account'},
    +      runner: async(command, args, settings) => {
    +        calls++;
    +        assert.equal(command, 'wrangler');
    +        assert.ok(args.includes('--branch'));
    +        assert.ok(args.includes('main'));
    +        assert.notEqual(settings.cwd, root);
    +        assert.equal(settings.env.CI, 'true');
    +        assert.ok(!args.includes('fixture'));
    +      }
    +    };
    +    assert.equal((await publishCloudflare(root, options)).state, 'command-completed');
    +    await fs.writeFile(path.join(root, '_worker.js'), 'unsafe');
    +    await assert.rejects(publishCloudflare(root, options));
    +    assert.equal(calls, 1);
    +  } finally {
    +    await fs.rm(root, {recursive: true, force: true});
    +  }
    +});
    diff --git a/packages/simply-static/test/publish-git.test.js b/packages/simply-static/test/publish-git.test.js
    new file mode 100644
    index 0000000..0cb9bf8
    --- /dev/null
    +++ b/packages/simply-static/test/publish-git.test.js
    @@ -0,0 +1,35 @@
    +'use strict';
    +
    +const test = require('node:test');
    +const assert = require('node:assert/strict');
    +const fs = require('node:fs/promises');
    +const os = require('node:os');
    +const path = require('node:path');
    +const {execFile} = require('node:child_process');
    +const {promisify} = require('node:util');
    +const execute = promisify(execFile);
    +const {publishGit} = require('../lib/publish-git');
    +
    +test('publishes snapshots to a real Git remote, removes stale files and skips unchanged commits', async() => {
    +  const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-git-test-'));
    +  try {
    +    const repository = path.join(root, 'remote.git');
    +    const source = path.join(root, 'output');
    +    await execute('git', ['init', '--bare', repository]);
    +    await fs.mkdir(source);
    +    await fs.writeFile(path.join(source, 'index.html'), 'first');
    +    await fs.writeFile(path.join(source, 'old.html'), 'obsolete');
    +    assert.equal((await publishGit(source, {repository})).changed, true);
    +    assert.equal((await publishGit(source, {repository})).changed, false);
    +    await fs.unlink(path.join(source, 'old.html'));
    +    await fs.writeFile(path.join(source, 'index.html'), 'second');
    +    await publishGit(source, {repository});
    +    const content = await execute('git', ['--git-dir', repository, 'show', 'gh-pages:index.html']);
    +    assert.equal(content.stdout, 'second');
    +    const tree = await execute('git', ['--git-dir', repository, 'ls-tree', '--name-only', 'gh-pages']);
    +    assert.ok(!tree.stdout.includes('old.html'));
    +    await assert.rejects(publishGit(source, {repository, branch: '-invalid'}));
    +  } finally {
    +    await fs.rm(root, {recursive: true, force: true});
    +  }
    +});
    diff --git a/packages/simply-static/test/publish-local.test.js b/packages/simply-static/test/publish-local.test.js
    new file mode 100644
    index 0000000..05543bc
    --- /dev/null
    +++ b/packages/simply-static/test/publish-local.test.js
    @@ -0,0 +1,34 @@
    +'use strict';
    +
    +const test = require('node:test');
    +const assert = require('node:assert/strict');
    +const fs = require('node:fs/promises');
    +const path = require('node:path');
    +const os = require('node:os');
    +const {publishLocal} = require('../lib/publish-local');
    +
    +test('publishes complete releases and keeps old content on copy failure', async() => {
    +  const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-publish-'));
    +  try {
    +    const source = path.join(root, 'build');
    +    const target = path.join(root, 'public');
    +    await fs.mkdir(source);
    +    await fs.writeFile(path.join(source, 'index.html'), 'old');
    +    const first = await publishLocal(source, target);
    +    assert.equal(await fs.readFile(path.join(target, 'index.html'), 'utf8'), 'old');
    +    await fs.writeFile(path.join(source, 'index.html'), 'new');
    +    await assert.rejects(publishLocal(source, target, {
    +      copy: async() => { throw new Error('Disk full'); }
    +    }), /Disk full/);
    +    assert.equal(await fs.readFile(path.join(target, 'index.html'), 'utf8'), 'old');
    +    const second = await publishLocal(source, target);
    +    assert.equal(second.previous, first.release);
    +    assert.equal(await fs.readFile(path.join(target, 'index.html'), 'utf8'), 'new');
    +    assert.equal(await fs.readFile(path.join(first.release, 'index.html'), 'utf8'), 'old');
    +    await assert.rejects(publishLocal(source, source), /inside/);
    +    await fs.symlink('/etc/passwd', path.join(source, 'unsafe'));
    +    await assert.rejects(publishLocal(source, target), /regular files/);
    +  } finally {
    +    await fs.rm(root, {recursive: true, force: true});
    +  }
    +});
    diff --git a/packages/simply-static/test/publish-netlify.test.js b/packages/simply-static/test/publish-netlify.test.js
    new file mode 100644
    index 0000000..ea84e3f
    --- /dev/null
    +++ b/packages/simply-static/test/publish-netlify.test.js
    @@ -0,0 +1,36 @@
    +'use strict';
    +
    +const test = require('node:test');
    +const assert = require('node:assert/strict');
    +const fs = require('node:fs/promises');
    +const os = require('node:os');
    +const path = require('node:path');
    +const {publishNetlify} = require('../lib/publish-netlify');
    +
    +test('uploads ZIP once and waits for confirmed ready state', async() => {
    +  const root = await fs.mkdtemp(path.join(os.tmpdir(), 'netlify-export-'));
    +  try {
    +    const archive = path.join(root, 'site.zip');
    +    await fs.writeFile(archive, 'zip fixture');
    +    const calls = [];
    +    const result = await publishNetlify(archive, {
    +      siteId: 'site', token: 'fixture-token', pollInterval: 0,
    +      fetcher: async(url, options) => {
    +        calls.push({url, options});
    +        return Response.json(calls.length === 1 ? {id: 'deploy', state: 'processing'} :
    +          {id: 'deploy', state: 'ready', ssl_url: 'https://site.example'});
    +      }
    +    });
    +    assert.equal(result.state, 'ready');
    +    assert.equal(calls.length, 2);
    +    assert.equal(calls[0].options.method, 'POST');
    +    assert.equal(calls[0].options.body.toString(), 'zip fixture');
    +    assert.equal(calls[1].url, 'https://api.netlify.com/api/v1/deploys/deploy');
    +    await assert.rejects(publishNetlify(archive, {
    +      siteId: 'site', token: 'fixture-token',
    +      fetcher: async() => new Response('secret details', {status: 401})
    +    }), /HTTP 401/);
    +  } finally {
    +    await fs.rm(root, {recursive: true, force: true});
    +  }
    +});
    diff --git a/packages/simply-static/test/publish-s3.test.js b/packages/simply-static/test/publish-s3.test.js
    new file mode 100644
    index 0000000..a53f2f7
    --- /dev/null
    +++ b/packages/simply-static/test/publish-s3.test.js
    @@ -0,0 +1,31 @@
    +'use strict';
    +
    +const test = require('node:test');
    +const assert = require('node:assert/strict');
    +const fs = require('node:fs/promises');
    +const os = require('node:os');
    +const path = require('node:path');
    +const {publishS3} = require('../lib/publish-s3');
    +
    +test('syncs only a dedicated prefix and supports HTTPS compatible endpoints', async() => {
    +  const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-s3-'));
    +  try {
    +    await fs.writeFile(path.join(root, 'index.html'), 'site');
    +    const result = await publishS3(root, {
    +      destination: 's3://example/site/', endpoint: 'https://s3.example.com',
    +      runner: async(command, args) => {
    +        assert.equal(command, 'aws');
    +        assert.ok(args.includes('--delete'));
    +        assert.ok(args.includes('--no-follow-symlinks'));
    +        assert.ok(args.includes('s3://example/site/'));
    +        assert.ok(args.includes('https://s3.example.com/'));
    +      }
    +    });
    +    assert.equal(result.atomic, false);
    +    for (const destination of ['s3://example/', 's3://example//', 's3://example/site//', 's3://example/site/../other', 's3://example/site?secret']) {
    +      await assert.rejects(publishS3(root, {destination}), /dedicated/);
    +    }
    +  } finally {
    +    await fs.rm(root, {recursive: true, force: true});
    +  }
    +});
    diff --git a/packages/simply-static/test/publish-sftp.test.js b/packages/simply-static/test/publish-sftp.test.js
    new file mode 100644
    index 0000000..50f6584
    --- /dev/null
    +++ b/packages/simply-static/test/publish-sftp.test.js
    @@ -0,0 +1,37 @@
    +'use strict';
    +
    +const test = require('node:test');
    +const assert = require('node:assert/strict');
    +const fs = require('node:fs/promises');
    +const os = require('node:os');
    +const path = require('node:path');
    +const {publishSftp} = require('../lib/publish-sftp');
    +
    +test('verifies host key, stages upload and restores old directory on switch failure', async() => {
    +  const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-sftp-'));
    +  const calls = [];
    +  try {
    +    const client = {
    +      connect: async config => {
    +        assert.equal(config.hostVerifier('a'.repeat(64)), true);
    +        assert.equal(config.hostVerifier('b'.repeat(64)), false);
    +      },
    +      exists: async() => 'd',
    +      uploadDir: async(source, target) => calls.push(['upload', target]),
    +      rename: async(from, to) => {
    +        calls.push(['rename', from, to]);
    +        if (from.includes('.staging-')) throw new Error('switch failed');
    +      },
    +      end: async() => calls.push(['end'])
    +    };
    +    await assert.rejects(publishSftp(root, {host: 'example.com', username: 'user',
    +      destination: '/www/site', fingerprint: 'a'.repeat(64), environment: {}, client}), /switch failed/);
    +    assert.equal(calls[0][0], 'upload');
    +    assert.equal(calls[1][1], '/www/site');
    +    assert.match(calls[3][1], /\.previous-/);
    +    assert.equal(calls[3][2], '/www/site');
    +    assert.equal(calls.at(-1)[0], 'end');
    +  } finally {
    +    await fs.rm(root, {recursive: true, force: true});
    +  }
    +});
    diff --git a/packages/simply-static/test/resource-cache.test.js b/packages/simply-static/test/resource-cache.test.js
    new file mode 100644
    index 0000000..207ae97
    --- /dev/null
    +++ b/packages/simply-static/test/resource-cache.test.js
    @@ -0,0 +1,34 @@
    +'use strict';
    +
    +const test = require('node:test');
    +const assert = require('node:assert/strict');
    +const fs = require('node:fs/promises');
    +const os = require('node:os');
    +const path = require('node:path');
    +const {exportSite} = require('../lib/exporter');
    +
    +test('incremental crawl revalidates and reuses responses while discovering new links', async() => {
    +  const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-cache-'));
    +  let round = 1;
    +  const requests = [];
    +  const fetcher = async(url, options) => {
    +    const pathname = new URL(url).pathname;
    +    requests.push({round, pathname, etag: options.headers['if-none-match']});
    +    if (round === 2 && pathname === '/old') return new Response(null, {status: 304});
    +    const html = pathname === '/' ? 'Old' +
    +      (round === 2 ? 'New' : '') : `
    ${pathname}
    `; + return new Response(html, {headers: {'content-type': 'text/html', etag: `"${pathname}-${round}"`}}); + }; + try { + const config = {sourceUrl: 'https://example.com/', destinationUrl: 'https://static.example/'}; + const common = {fetcher, cacheDirectory: path.join(root, 'cache')}; + await exportSite(config, {...common, directory: path.join(root, 'first')}); + round = 2; + await exportSite(config, {...common, directory: path.join(root, 'second')}); + assert.ok(requests.some(item => item.round === 2 && item.pathname === '/old' && item.etag === '"/old-1"')); + assert.match(await fs.readFile(path.join(root, 'second/old/index.html'), 'utf8'), /old/); + assert.match(await fs.readFile(path.join(root, 'second/new/index.html'), 'utf8'), /new/); + } finally { + await fs.rm(root, {recursive: true, force: true}); + } +}); diff --git a/packages/simply-static/test/resume.test.js b/packages/simply-static/test/resume.test.js new file mode 100644 index 0000000..76f4626 --- /dev/null +++ b/packages/simply-static/test/resume.test.js @@ -0,0 +1,38 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const path = require('node:path'); +const os = require('node:os'); +const {exportSite} = require('../lib/exporter'); + +test('resumes persisted crawl results and discovers the remaining resources', async() => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'static-resume-')); + const config = {sourceUrl: 'https://example.com/', destinationUrl: 'https://static.example/'}; + const directory = path.join(root, 'output'); + const checkpointDirectory = path.join(root, 'checkpoint'); + try { + await assert.rejects(exportSite(config, { + directory, checkpointDirectory, + fetcher: async url => new URL(url).pathname === '/' ? + new Response('Next', {headers: {'content-type': 'text/html'}}) : + new Response('missing', {status: 404}) + }), /HTTP 404/); + const requests = []; + const logs = []; + const manifest = await exportSite(config, { + directory, checkpointDirectory, onLog: async record => logs.push(record), + fetcher: async url => { + requests.push(new URL(url).pathname); + return new Response('
    Recovered
    ', {headers: {'content-type': 'text/html'}}); + } + }); + assert.deepEqual(requests, ['/remaining']); + assert.equal(manifest.resources.length, 2); + assert.equal(logs[0].resumed, true); + assert.match(await fs.readFile(path.join(directory, 'remaining/index.html'), 'utf8'), /Recovered/); + } finally { + await fs.rm(root, {recursive: true, force: true}); + } +}); diff --git a/packages/simply-static/test/search-ui.test.js b/packages/simply-static/test/search-ui.test.js new file mode 100644 index 0000000..dea46aa --- /dev/null +++ b/packages/simply-static/test/search-ui.test.js @@ -0,0 +1,55 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const path = require('node:path'); +const {JSDOM} = require('jsdom'); + +async function fixture(fetcher) { + const html = await fs.readFile(path.join(__dirname, '../assets/search.html'), 'utf8'); + const script = await fs.readFile(path.join(__dirname, '../assets/search.js'), 'utf8'); + const dom = new JSDOM(html, { + url: 'https://static.example/blog/static-search.html?q=' + encodeURIComponent('中文'), + runScripts: 'outside-only' + }); + dom.window.fetch = fetcher; + await dom.window.eval(script); + return dom; +} + +test('search UI supports Chinese, prioritizes titles and renders results as text', async() => { + const dom = await fixture(async url => { + assert.equal(String(url), 'https://static.example/blog/static-search.json'); + return {ok: true, json: async() => [ + {title: 'Other', text: '中文正文', url: 'other/index.html'}, + {title: '中文 ', text: '正文', url: 'post/index.html'}, + {title: 'Unrelated', text: 'Nothing', url: 'unrelated.html'} + ]}; + }); + try { + const document = dom.window.document; + assert.match(document.querySelector('[data-search-status]').textContent, /2/); + const links = [...document.querySelectorAll('[data-search-results] a')]; + assert.equal(links.length, 2); + assert.match(links[0].textContent, /^中文/); + assert.equal(links[0].href, 'https://static.example/blog/post/index.html'); + assert.equal(document.querySelectorAll('[data-search-results] img').length, 0); + const input = document.querySelector('input'); + input.value = 'missing'; + input.dispatchEvent(new dom.window.Event('input')); + assert.equal(document.querySelectorAll('[data-search-results] a').length, 0); + assert.match(document.querySelector('[data-search-status]').textContent, /0/); + } finally { + dom.window.close(); + } +}); + +test('search UI shows an actionable error when index download fails', async() => { + const dom = await fixture(async() => ({ok: false})); + try { + assert.match(dom.window.document.querySelector('[data-search-status]').textContent, /加载失败/); + } finally { + dom.window.close(); + } +}); diff --git a/packages/simply-static/test/settings.test.js b/packages/simply-static/test/settings.test.js new file mode 100644 index 0000000..3ef22e5 --- /dev/null +++ b/packages/simply-static/test/settings.test.js @@ -0,0 +1,22 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const {integrationSettings} = require('../lib/settings'); + +test('normalizes admin JSON mappings and line-separated search selectors', () => { + const result = integrationSettings({forms: '[{"selector":"#contact","endpoint":"https://forms.example/"}]', + additionalFiles: '[{"source":"public","target":"downloads"}]', searchSelectors: '#search\n\nform.search'}); + assert.equal(result.forms[0].selector, '#contact'); + assert.equal(result.additionalFiles[0].target, 'downloads'); + assert.deepEqual(result.searchSelectors, ['#search', 'form.search']); + assert.deepEqual(integrationSettings({}), {forms: [], additionalFiles: [], searchSelectors: []}); +}); + +test('rejects malformed or insecure mappings before saving configuration', () => { + for (const values of [{forms: '{'}, {forms: '{}'}, {forms: '[{}]'}, + {forms: '[{"selector":"form","endpoint":"javascript:alert(1)"}]'}, + {additionalFiles: '[{"source":"x"}]'}]) { + assert.throws(() => integrationSettings(values)); + } +}); diff --git a/packages/simply-static/test/transform.test.js b/packages/simply-static/test/transform.test.js new file mode 100644 index 0000000..7276f82 --- /dev/null +++ b/packages/simply-static/test/transform.test.js @@ -0,0 +1,50 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const {transformHtml, transformCss} = require('../lib/transform'); + +test('discovers HTML assets, responsive images, metadata and base-relative pages', () => { + const seen = []; + const result = transformHtml('Example
    Hello
    ' + + 'Read' + + '', { + url: 'https://example.com/', + rewrite(value, asset, base) { + seen.push({value, asset, base}); + return '/export/' + value; + } + }); + assert.equal(result.title, 'Example'); + assert.equal(result.text, 'Hello'); + assert.ok(!result.html.includes(' item.value === 'article' && !item.asset && item.base === 'https://example.com/nested/')); + for (const name of ['a.png', 'b.png', 'cover.png', 'bg.png']) { + assert.ok(seen.some(item => item.value === name && item.asset), name); + } + assert.match(result.html, /\/export\/b.png 2x/); +}); + +test('rewrites CSS imports and font URLs while retaining media conditions', () => { + const output = transformCss('@import "theme.css" screen; @font-face{src:url(font.woff2)}', + value => '/assets/' + value); + assert.match(output, /"\/assets\/theme.css" screen/); + assert.match(output, /url\("\/assets\/font.woff2"\)/); +}); + +test('XML rewriting discovers sitemap entries and preserves opaque feed identifiers', () => { + const {transformXml} = require('../lib/transform'); + const discovered = []; + const output = transformXml('https://example.com/unlinked' + + 'https://example.com/id' + + '', (url, asset) => { + discovered.push({url, asset}); + return url.replace('example.com', 'static.example'); + }); + assert.deepEqual(discovered, [ + {url: 'https://example.com/unlinked', asset: false}, + {url: 'https://example.com/audio.mp3', asset: true} + ]); + assert.match(output, /https:\/\/static.example\/unlinked/); + assert.match(output, /https:\/\/example.com\/id/); +}); diff --git a/packages/simply-static/test/urls.test.js b/packages/simply-static/test/urls.test.js new file mode 100644 index 0000000..a3cf27f --- /dev/null +++ b/packages/simply-static/test/urls.test.js @@ -0,0 +1,53 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const {UrlPolicy, safeSegments} = require('../lib/urls'); + +const config = {sourceUrl: 'https://source.example/blog/', destinationUrl: 'https://public.example/site/'}; + +test('maps public pages and query variants without merging their output', () => { + const policy = new UrlPolicy(config); + assert.equal(policy.file(policy.resolve('/blog/article'), true), 'article/index.html'); + assert.equal(policy.file(policy.resolve('/blog/page.html'), true), 'page.html'); + assert.notEqual(policy.file(policy.resolve('/blog/?page=2'), true), 'index.html'); + assert.notEqual(policy.file(policy.resolve('/blog/?page=2'), true), + policy.file(policy.resolve('/blog/?page=3'), true)); + assert.equal(policy.link('article/index.html', 'index.html', '#heading'), + 'https://public.example/site/article/index.html#heading'); +}); + +test('excludes control routes, authenticated URLs and other origins', () => { + const policy = new UrlPolicy({...config, exclude: ['/blog/hidden']}); + for (const value of ['/blog/admin', '/blog/api/private', '/blog/mcp', '/blog/%61dmin/', + '/blog/?preview=1', '/blog/hidden/page', '/outside', 'https://other.example/']) { + assert.equal(policy.allowed(policy.resolve(value)), false, value); + } + assert.equal(policy.allowed(policy.resolve('/blog/article')), true); +}); + +test('rejects ambiguous separators and control characters', () => { + for (const value of ['/a%2fb', '/a%5cb', '/%00', '/%2e%2e']) { + assert.throws(() => safeSegments(value), /Unsafe/); + } + assert.throws(() => new UrlPolicy({...config, sourceUrl: 'https://user:password@example.com'})); +}); + +test('supports relative links and explicit external asset origins', () => { + const policy = new UrlPolicy({...config, relative: true, assetOrigins: ['https://cdn.example']}); + const asset = policy.resolve('https://cdn.example/image.png'); + assert.equal(policy.allowed(asset), false); + assert.equal(policy.allowed(asset, true), true); + assert.match(policy.file(asset), /^_external\/[a-f0-9]{16}\/image.png$/); + assert.equal(policy.link('res/main.css', 'posts/example/index.html'), '../../res/main.css'); +}); + +test('Unicode output names round-trip through a static HTTP server URL decoder', () => { + for (const relative of [false, true]) { + const policy = new UrlPolicy({...config, relative}); + const filename = policy.file(policy.resolve('/blog/中文.html'), true); + const link = policy.link(filename, 'index.html'); + const decoded = decodeURIComponent(new URL(link, policy.destination).pathname); + assert.equal(decoded, '/site/' + filename); + } +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a1eb975..a6bef26 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -61,61 +61,1084 @@ importers: packages/say: {} + packages/simply-static: + dependencies: + cheerio: + specifier: 1.1.2 + version: 1.1.2 + clean-css: + specifier: ^5.3.3 + version: 5.3.3 + croner: + specifier: ^10.0.1 + version: 10.0.1 + fflate: + specifier: 0.8.2 + version: 0.8.2 + html-minifier-terser: + specifier: ^7.2.0 + version: 7.2.0 + parse-srcset: + specifier: 1.0.2 + version: 1.0.2 + postcss: + specifier: 8.5.6 + version: 8.5.6 + postcss-value-parser: + specifier: 4.2.0 + version: 4.2.0 + ssh2-sftp-client: + specifier: ^12.0.1 + version: 12.1.1 + terser: + specifier: ^5.44.1 + version: 5.51.4 + devDependencies: + jsdom: + specifier: ^27.0.1 + version: 27.4.0 + optionalDependencies: + sharp: + specifier: ^0.34.5 + version: 0.34.5 + packages: + '@acemir/cssom@0.9.33': + resolution: {integrity: sha512-52IMmrBsIsDZLp/KFM+KmaMLJ8GTj113K+iFGFCoOjstZSZbsAxMJE8KYtwao7bz1LsEG810ts1m5wvkVEqPlg==} + + '@asamuzakjp/css-color@4.1.2': + resolution: {integrity: sha512-NfBUvBaYgKIuq6E/RBLY1m0IohzNHAYyaJGuTK79Z23uNwmz2jl1mPsC5ZxCCxylinKhT1Amn5oNTlx1wN8cQg==} + + '@asamuzakjp/dom-selector@6.8.1': + resolution: {integrity: sha512-MvRz1nCqW0fsy8Qz4dnLIvhOlMzqDVBabZx6lH+YywFDdjXhMY37SmpV1XFX3JzG5GWHn63j6HX6QPr3lZXHvQ==} + + '@asamuzakjp/nwsapi@2.3.9': + resolution: {integrity: sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==} + + '@csstools/color-helpers@6.1.3': + resolution: {integrity: sha512-c6CpX5G1pvuOKTXiRFJ54Lzc8zQrZ3qUjp44QC5DJNt1OmA1vmfUxOMCcKdDqsvffVDG0/MHnY63J+Mn0nmdUg==} + engines: {node: '>=20.19.0'} + + '@csstools/css-calc@3.4.4': + resolution: {integrity: sha512-Jwo1Z8DUsZ8xVOLBdLMfhjJFvWD6pqaUTlBNQZ+qIB2i9g7yG8kd/UBJj2c9J9Twr+u87cjy9BjkmfvMbyOk3Q==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-parser-algorithms': ^4.0.3 + '@csstools/css-tokenizer': ^4.0.3 + + '@csstools/css-color-parser@4.2.8': + resolution: {integrity: sha512-JLsKBee9dmnA3L+H+vYK4lQ6n5CoY3yEnh33zdlMutRfrTxtqt+hFeoZ1maHRt5vLw67huDLpOkDb3rl9A51MQ==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-parser-algorithms': ^4.0.3 + '@csstools/css-tokenizer': ^4.0.3 + + '@csstools/css-parser-algorithms@4.0.3': + resolution: {integrity: sha512-EpCfUDaJtwohPHC7egoXxPGT/R1/WyyAhw87MKB/7BPPZvZU+IcEqo4er5FpLnby2Gvwt9Lpxy+WNEDyFjoXtA==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@csstools/css-tokenizer': ^4.0.3 + + '@csstools/css-syntax-patches-for-csstree@1.1.17': + resolution: {integrity: sha512-IPx9W33+t0Yt5TVb+Y7oICrThOIry0TY6GuXfSHOatxA0uiHqbzi98Gai905lpBAX1m/LH7iI96e9jcI7Dkvxw==} + peerDependencies: + css-tree: ^3.2.1 + peerDependenciesMeta: + css-tree: + optional: true + + '@csstools/css-tokenizer@4.0.3': + resolution: {integrity: sha512-gdkFe/Z4KU1q8Y5S3GYScXGcOnO56dgWwIs5+97Ij1VIKISItOIUlCXUq4VLbdnRclF+SSQ49sLsn3KeV111AA==} + engines: {node: '>=20.19.0'} + + '@emnapi/runtime@1.11.3': + resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} + + '@exodus/bytes@1.16.0': + resolution: {integrity: sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + peerDependencies: + '@noble/hashes': ^1.8.0 || ^2.0.0 + peerDependenciesMeta: + '@noble/hashes': + optional: true + + '@img/colour@1.1.0': + resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} + engines: {node: '>=18'} + + '@img/sharp-darwin-arm64@0.34.5': + resolution: {integrity: sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [arm64] + os: [darwin] + + '@img/sharp-darwin-x64@0.34.5': + resolution: {integrity: sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [x64] + os: [darwin] + + '@img/sharp-libvips-darwin-arm64@1.2.4': + resolution: {integrity: sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==} + cpu: [arm64] + os: [darwin] + + '@img/sharp-libvips-darwin-x64@1.2.4': + resolution: {integrity: sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==} + cpu: [x64] + os: [darwin] + + '@img/sharp-libvips-linux-arm64@1.2.4': + resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-arm@1.2.4': + resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-ppc64@1.2.4': + resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-riscv64@1.2.4': + resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-s390x@1.2.4': + resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-x64@1.2.4': + resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linuxmusl-arm64@1.2.4': + resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@img/sharp-libvips-linuxmusl-x64@1.2.4': + resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@img/sharp-linux-arm64@0.34.5': + resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-arm@0.34.5': + resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-ppc64@0.34.5': + resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-riscv64@0.34.5': + resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-s390x@0.34.5': + resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-x64@0.34.5': + resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@img/sharp-linuxmusl-arm64@0.34.5': + resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@img/sharp-linuxmusl-x64@0.34.5': + resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@img/sharp-wasm32@0.34.5': + resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [wasm32] + + '@img/sharp-win32-arm64@0.34.5': + resolution: {integrity: sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [arm64] + os: [win32] + + '@img/sharp-win32-ia32@0.34.5': + resolution: {integrity: sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [ia32] + os: [win32] + + '@img/sharp-win32-x64@0.34.5': + resolution: {integrity: sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [x64] + os: [win32] + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/resolve-uri@3.1.3': + resolution: {integrity: sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==} + engines: {node: '>=6.0.0'} + + '@jridgewell/source-map@0.3.11': + resolution: {integrity: sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@mixmark-io/domino@2.2.0': resolution: {integrity: sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==} + acorn@8.19.0: + resolution: {integrity: sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==} + engines: {node: '>=0.4.0'} + hasBin: true + + agent-base@7.1.4: + resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} + engines: {node: '>= 14'} + argparse@2.0.1: resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + asn1@0.2.6: + resolution: {integrity: sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==} + + bcrypt-pbkdf@1.0.2: + resolution: {integrity: sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==} + + bidi-js@1.1.0: + resolution: {integrity: sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==} + + boolbase@1.0.0: + resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} + + buffer-from@1.1.2: + resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} + + buildcheck@0.0.7: + resolution: {integrity: sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==} + engines: {node: '>=10.0.0'} + + camel-case@4.1.2: + resolution: {integrity: sha512-gxGWBrTT1JuMx6R+o5PTXMmUnhnVzLQ9SNutD4YqKtI6ap897t3tKECYla6gCWEkplXnlNybEkZg9GEGxKFCgw==} + + cheerio-select@2.1.0: + resolution: {integrity: sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==} + + cheerio@1.1.2: + resolution: {integrity: sha512-IkxPpb5rS/d1IiLbHMgfPuS0FgiWTtFIm/Nj+2woXDLTZ7fOT2eqzgYbdMlLweqlHbsZjxEChoVK+7iph7jyQg==} + engines: {node: '>=20.18.1'} + + clean-css@5.3.3: + resolution: {integrity: sha512-D5J+kHaVb/wKSFcyyV75uCn8fiY4sV38XJoe4CUyGQ+mOU/fMVYUdH1hJC+CJQ5uY3EnW27SbJYS4X8BiLrAFg==} + engines: {node: '>= 10.0'} + + commander@10.0.1: + resolution: {integrity: sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==} + engines: {node: '>=14'} + + commander@2.20.3: + resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==} + + concat-stream@2.0.0: + resolution: {integrity: sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==} + engines: {'0': node >= 6.0} + + cpu-features@0.0.10: + resolution: {integrity: sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==} + engines: {node: '>=10.0.0'} + croner@10.0.1: resolution: {integrity: sha512-ixNtAJndqh173VQ4KodSdJEI6nuioBWI0V1ITNKhZZsO0pEMoDxz539T4FTTbSZ/xIOSuDnzxLVRqBVSvPNE2g==} engines: {node: '>=18.0'} + css-select@5.2.2: + resolution: {integrity: sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==} + + css-tree@3.2.1: + resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==} + engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} + + css-what@6.2.2: + resolution: {integrity: sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==} + engines: {node: '>= 6'} + + cssstyle@5.3.7: + resolution: {integrity: sha512-7D2EPVltRrsTkhpQmksIu+LxeWAIEk6wRDMJ1qljlv+CKHJM+cJLlfhWIzNA44eAsHXSNe3+vO6DW1yCYx8SuQ==} + engines: {node: '>=20'} + + data-urls@6.0.1: + resolution: {integrity: sha512-euIQENZg6x8mj3fO6o9+fOW8MimUI4PpD/fZBhJfeioZVy9TUpM4UY7KjQNVZFlqwJ0UdzRDzkycB997HEq1BQ==} + engines: {node: '>=20'} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + decimal.js@10.6.0: + resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + dom-serializer@2.0.0: + resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==} + + domelementtype@2.3.0: + resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==} + + domhandler@5.0.3: + resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==} + engines: {node: '>= 4'} + + domutils@3.2.2: + resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==} + + dot-case@3.0.4: + resolution: {integrity: sha512-Kv5nKlh6yRrdrGvxeJ2e5y2eRUpkUosIW4A2AS38zwSz27zu7ufDwQPi5Jhs3XAlGNetl3bmnGhQsMtkKJnj3w==} + + encoding-sniffer@0.2.1: + resolution: {integrity: sha512-5gvq20T6vfpekVtqrYQsSCFZ1wEg5+wW0/QaZMWkFr6BqD3NfKs0rLCx4rrVlSWJeZb5NBJgVLswK/w2MWU+Gw==} + entities@4.5.0: resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} engines: {node: '>=0.12'} + entities@6.0.1: + resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} + engines: {node: '>=0.12'} + + entities@7.0.1: + resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} + engines: {node: '>=0.12'} + + entities@9.0.0: + resolution: {integrity: sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==} + engines: {node: '>=20.19.0'} + + fflate@0.8.2: + resolution: {integrity: sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==} + + html-encoding-sniffer@6.0.0: + resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + + html-minifier-terser@7.2.0: + resolution: {integrity: sha512-tXgn3QfqPIpGl9o+K5tpcj3/MN4SfLtsx2GWwBC3SSd0tXQGyF3gsSqad8loJgKZGM3ZxbYDd5yhiBIdWpmvLA==} + engines: {node: ^14.13.1 || >=16.0.0} + hasBin: true + + htmlparser2@10.1.0: + resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==} + + http-proxy-agent@7.0.2: + resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} + engines: {node: '>= 14'} + + https-proxy-agent@7.0.6: + resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} + engines: {node: '>= 14'} + + iconv-lite@0.6.3: + resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} + engines: {node: '>=0.10.0'} + + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + is-potential-custom-element-name@1.0.1: + resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + + jsdom@27.4.0: + resolution: {integrity: sha512-mjzqwWRD9Y1J1KUi7W97Gja1bwOOM5Ug0EZ6UDK3xS7j7mndrkwozHtSblfomlzyB4NepioNt+B2sOSzczVgtQ==} + engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + peerDependencies: + canvas: ^3.0.0 + peerDependenciesMeta: + canvas: + optional: true + linkify-it@5.0.2: resolution: {integrity: sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q==} + lower-case@2.0.2: + resolution: {integrity: sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg==} + + lru-cache@11.5.4: + resolution: {integrity: sha512-B8nJCTi8JuSaDBg0tBdnImV6j5O2CXaqKfdj24ZTCFbyivN8KZ2Z+RL3aHjwJAfLutD9cNnObG4SIgW4gMufiw==} + engines: {node: 20 || >=22} + markdown-it@14.3.3: resolution: {integrity: sha512-L//tDAkjTjJCU6pBUSBTgs3Kg4InVaZuUZog/b6V12UKhcDQ7S78877ibbCanRExwPuYP1CZD7Gd2dxSy1GXRg==} hasBin: true + mdn-data@2.27.1: + resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==} + mdurl@2.1.0: resolution: {integrity: sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==} + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + nan@2.30.0: + resolution: {integrity: sha512-P5mokDkSvCGBz6mZDD/2l+w9QoICRXdCyZ9ONGmTePr40oihJg3Kpn0YU3twKd6PJnwSlLBWNQeOT6yWEV2c4A==} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + no-case@3.0.4: + resolution: {integrity: sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg==} + nodemailer@7.0.13: resolution: {integrity: sha512-PNDFSJdP+KFgdsG3ZzMXCgquO7I6McjY2vlqILjtJd0hy8wEvtugS9xKRF2NWlPNGxvLCXlTNIae4serI7dinw==} engines: {node: '>=6.0.0'} + nth-check@2.1.1: + resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==} + + param-case@3.0.4: + resolution: {integrity: sha512-RXlj7zCYokReqWpOPH9oYivUzLYZ5vAPIfEmCTNViosC78F8F0H9y7T7gG2M39ymgutxF5gcFEsyZQSph9Bp3A==} + + parse-srcset@1.0.2: + resolution: {integrity: sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q==} + + parse5-htmlparser2-tree-adapter@7.1.0: + resolution: {integrity: sha512-ruw5xyKs6lrpo9x9rCZqZZnIUntICjQAd0Wsmp396Ul9lN/h+ifgVV1x1gZHi8euej6wTfpqX8j+BFQxF0NS/g==} + + parse5-parser-stream@7.1.2: + resolution: {integrity: sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow==} + + parse5@7.3.0: + resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==} + + parse5@8.1.1: + resolution: {integrity: sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==} + + pascal-case@3.1.2: + resolution: {integrity: sha512-uWlGT3YSnK9x3BQJaOdcZwrnV6hPpd8jFH1/ucpiLRPh/2zCVJKS19E4GvYHvaCcACn3foXZ0cLB9Wrx1KGe5g==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + postcss-value-parser@4.2.0: + resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==} + + postcss@8.5.6: + resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==} + engines: {node: ^10 || ^12 || >=14} + punycode.js@2.3.1: resolution: {integrity: sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==} engines: {node: '>=6'} + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + readable-stream@3.6.2: + resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==} + engines: {node: '>= 6'} + + relateurl@0.2.7: + resolution: {integrity: sha512-G08Dxvm4iDN3MLM0EsP62EDV9IuhXPR6blNz6Utcp7zyV3tr4HVNINt6MpaRWbxoOHT3Q7YN2P+jaHX8vUbgog==} + engines: {node: '>= 0.10'} + + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + + safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + + saxes@6.0.0: + resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} + engines: {node: '>=v12.22.7'} + + semver@7.8.6: + resolution: {integrity: sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==} + engines: {node: '>=10'} + hasBin: true + + sharp@0.34.5: + resolution: {integrity: sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + + source-map-js@1.3.0: + resolution: {integrity: sha512-pdUVfIWcK0kCgK831ibqkZDcL7I9zljjOu0TQFnA+fiQ6y1CYqYB7RkTOHHO45FGMg5P/Mvk/+4ToQ7gAYAL5Q==} + engines: {node: '>=6.0.0'} + + source-map-support@0.5.21: + resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==} + + source-map@0.6.1: + resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} + engines: {node: '>=0.10.0'} + + ssh2-sftp-client@12.1.1: + resolution: {integrity: sha512-wYVDgwkpcKG2iPGQQ+QR33xkWqLFIaVrYvA+uON4pmxTPaPuB81f1aooUEPN75e/9DCK6rrKYXb6zR6zP3+EtA==} + engines: {node: '>=18.20.4'} + + ssh2@1.17.0: + resolution: {integrity: sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==} + engines: {node: '>=10.16.0'} + + string_decoder@1.4.0: + resolution: {integrity: sha512-r8azg21Y67ckRmeG0hHol5CeDXMs4ZFkFT6eXMO39hX7khvJcopBcYTCeWZ0rQXkMoPh8lVdbjmsOMGL8krxRQ==} + + symbol-tree@3.2.4: + resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} + + terser@5.51.4: + resolution: {integrity: sha512-VPi1CkDvCWLGUVIToctNBG+NdHbSXwOPjHJnQ3pdB0XknaldnI76wSkAFOGxV2ZdkzOP5d6gpQ5c58XvDghRvw==} + engines: {node: '>=10'} + hasBin: true + + tldts-core@7.6.4: + resolution: {integrity: sha512-QywQ9lgQyZMuc3NVlqmuxHOhlwirSdvgD/vDLvX8dZYcYgy1cdri5rY/TXDHcF4J3VBSdJLcJNIJI6zGJ7jE+w==} + + tldts@7.6.4: + resolution: {integrity: sha512-wp+ZdvQyov404xynNcjbXoJyeGM28W/aCwMmry/rJ+Y0SsObukJYkWwuxWGbNpIjeqMaEbNUtXPNtPPfI5cTFA==} + hasBin: true + + tough-cookie@6.1.0: + resolution: {integrity: sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==} + engines: {node: '>=16'} + + tr46@6.0.0: + resolution: {integrity: sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==} + engines: {node: '>=20'} + + tslib@2.9.1: + resolution: {integrity: sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==} + turndown@7.2.4: resolution: {integrity: sha512-I8yFsfRzmzK0WV1pNNOA4A7y4RDfFxPRxb3t+e3ui14qSGOxGtiSP6GjeX+Y6CHb7HYaFj7ECUD7VE5kQMZWGQ==} engines: {node: '>=18', npm: '>=9'} + tweetnacl@0.14.5: + resolution: {integrity: sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==} + + typedarray@0.0.6: + resolution: {integrity: sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==} + uc.micro@2.1.0: resolution: {integrity: sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==} + undici@7.30.2: + resolution: {integrity: sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==} + engines: {node: '>=20.18.1'} + + util-deprecate@1.0.2: + resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + + w3c-xmlserializer@5.0.0: + resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==} + engines: {node: '>=18'} + + webidl-conversions@8.0.1: + resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==} + engines: {node: '>=20'} + + whatwg-encoding@3.1.1: + resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==} + engines: {node: '>=18'} + deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation + + whatwg-mimetype@4.0.0: + resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==} + engines: {node: '>=18'} + + whatwg-mimetype@5.0.0: + resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==} + engines: {node: '>=20'} + + whatwg-url@15.1.0: + resolution: {integrity: sha512-2ytDk0kiEj/yu90JOAp44PVPUkO9+jVhyf+SybKlRHSDlvOOZhdPIrr7xTH64l4WixO2cP+wQIcgujkGBPPz6g==} + engines: {node: '>=20'} + + ws@8.23.1: + resolution: {integrity: sha512-1rzWDSN0NOi3tpwgHsQExjWRoKUGtjCkJ2gZRaaRtzhYLboMytOI9pj9PU7yCgY37auqdd4OyLofZDbkeuZmPA==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + + xml-name-validator@5.0.0: + resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==} + engines: {node: '>=18'} + + xmlchars@2.2.0: + resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + snapshots: + '@acemir/cssom@0.9.33': {} + + '@asamuzakjp/css-color@4.1.2': + dependencies: + '@csstools/css-calc': 3.4.4(@csstools/css-parser-algorithms@4.0.3(@csstools/css-tokenizer@4.0.3))(@csstools/css-tokenizer@4.0.3) + '@csstools/css-color-parser': 4.2.8(@csstools/css-parser-algorithms@4.0.3(@csstools/css-tokenizer@4.0.3))(@csstools/css-tokenizer@4.0.3) + '@csstools/css-parser-algorithms': 4.0.3(@csstools/css-tokenizer@4.0.3) + '@csstools/css-tokenizer': 4.0.3 + lru-cache: 11.5.4 + + '@asamuzakjp/dom-selector@6.8.1': + dependencies: + '@asamuzakjp/nwsapi': 2.3.9 + bidi-js: 1.1.0 + css-tree: 3.2.1 + is-potential-custom-element-name: 1.0.1 + lru-cache: 11.5.4 + + '@asamuzakjp/nwsapi@2.3.9': {} + + '@csstools/color-helpers@6.1.3': {} + + '@csstools/css-calc@3.4.4(@csstools/css-parser-algorithms@4.0.3(@csstools/css-tokenizer@4.0.3))(@csstools/css-tokenizer@4.0.3)': + dependencies: + '@csstools/css-parser-algorithms': 4.0.3(@csstools/css-tokenizer@4.0.3) + '@csstools/css-tokenizer': 4.0.3 + + '@csstools/css-color-parser@4.2.8(@csstools/css-parser-algorithms@4.0.3(@csstools/css-tokenizer@4.0.3))(@csstools/css-tokenizer@4.0.3)': + dependencies: + '@csstools/color-helpers': 6.1.3 + '@csstools/css-calc': 3.4.4(@csstools/css-parser-algorithms@4.0.3(@csstools/css-tokenizer@4.0.3))(@csstools/css-tokenizer@4.0.3) + '@csstools/css-parser-algorithms': 4.0.3(@csstools/css-tokenizer@4.0.3) + '@csstools/css-tokenizer': 4.0.3 + + '@csstools/css-parser-algorithms@4.0.3(@csstools/css-tokenizer@4.0.3)': + dependencies: + '@csstools/css-tokenizer': 4.0.3 + + '@csstools/css-syntax-patches-for-csstree@1.1.17(css-tree@3.2.1)': + optionalDependencies: + css-tree: 3.2.1 + + '@csstools/css-tokenizer@4.0.3': {} + + '@emnapi/runtime@1.11.3': + dependencies: + tslib: 2.9.1 + optional: true + + '@exodus/bytes@1.16.0': {} + + '@img/colour@1.1.0': + optional: true + + '@img/sharp-darwin-arm64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-darwin-arm64': 1.2.4 + optional: true + + '@img/sharp-darwin-x64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-darwin-x64': 1.2.4 + optional: true + + '@img/sharp-libvips-darwin-arm64@1.2.4': + optional: true + + '@img/sharp-libvips-darwin-x64@1.2.4': + optional: true + + '@img/sharp-libvips-linux-arm64@1.2.4': + optional: true + + '@img/sharp-libvips-linux-arm@1.2.4': + optional: true + + '@img/sharp-libvips-linux-ppc64@1.2.4': + optional: true + + '@img/sharp-libvips-linux-riscv64@1.2.4': + optional: true + + '@img/sharp-libvips-linux-s390x@1.2.4': + optional: true + + '@img/sharp-libvips-linux-x64@1.2.4': + optional: true + + '@img/sharp-libvips-linuxmusl-arm64@1.2.4': + optional: true + + '@img/sharp-libvips-linuxmusl-x64@1.2.4': + optional: true + + '@img/sharp-linux-arm64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linux-arm64': 1.2.4 + optional: true + + '@img/sharp-linux-arm@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linux-arm': 1.2.4 + optional: true + + '@img/sharp-linux-ppc64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linux-ppc64': 1.2.4 + optional: true + + '@img/sharp-linux-riscv64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linux-riscv64': 1.2.4 + optional: true + + '@img/sharp-linux-s390x@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linux-s390x': 1.2.4 + optional: true + + '@img/sharp-linux-x64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linux-x64': 1.2.4 + optional: true + + '@img/sharp-linuxmusl-arm64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-arm64': 1.2.4 + optional: true + + '@img/sharp-linuxmusl-x64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-x64': 1.2.4 + optional: true + + '@img/sharp-wasm32@0.34.5': + dependencies: + '@emnapi/runtime': 1.11.3 + optional: true + + '@img/sharp-win32-arm64@0.34.5': + optional: true + + '@img/sharp-win32-ia32@0.34.5': + optional: true + + '@img/sharp-win32-x64@0.34.5': + optional: true + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.3': {} + + '@jridgewell/source-map@0.3.11': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.3 + '@jridgewell/sourcemap-codec': 1.6.0 + '@mixmark-io/domino@2.2.0': {} + acorn@8.19.0: {} + + agent-base@7.1.4: {} + argparse@2.0.1: {} + asn1@0.2.6: + dependencies: + safer-buffer: 2.1.2 + + bcrypt-pbkdf@1.0.2: + dependencies: + tweetnacl: 0.14.5 + + bidi-js@1.1.0: + dependencies: + require-from-string: 2.0.2 + + boolbase@1.0.0: {} + + buffer-from@1.1.2: {} + + buildcheck@0.0.7: + optional: true + + camel-case@4.1.2: + dependencies: + pascal-case: 3.1.2 + tslib: 2.9.1 + + cheerio-select@2.1.0: + dependencies: + boolbase: 1.0.0 + css-select: 5.2.2 + css-what: 6.2.2 + domelementtype: 2.3.0 + domhandler: 5.0.3 + domutils: 3.2.2 + + cheerio@1.1.2: + dependencies: + cheerio-select: 2.1.0 + dom-serializer: 2.0.0 + domhandler: 5.0.3 + domutils: 3.2.2 + encoding-sniffer: 0.2.1 + htmlparser2: 10.1.0 + parse5: 7.3.0 + parse5-htmlparser2-tree-adapter: 7.1.0 + parse5-parser-stream: 7.1.2 + undici: 7.30.2 + whatwg-mimetype: 4.0.0 + + clean-css@5.3.3: + dependencies: + source-map: 0.6.1 + + commander@10.0.1: {} + + commander@2.20.3: {} + + concat-stream@2.0.0: + dependencies: + buffer-from: 1.1.2 + inherits: 2.0.4 + readable-stream: 3.6.2 + typedarray: 0.0.6 + + cpu-features@0.0.10: + dependencies: + buildcheck: 0.0.7 + nan: 2.30.0 + optional: true + croner@10.0.1: {} + css-select@5.2.2: + dependencies: + boolbase: 1.0.0 + css-what: 6.2.2 + domhandler: 5.0.3 + domutils: 3.2.2 + nth-check: 2.1.1 + + css-tree@3.2.1: + dependencies: + mdn-data: 2.27.1 + source-map-js: 1.3.0 + + css-what@6.2.2: {} + + cssstyle@5.3.7: + dependencies: + '@asamuzakjp/css-color': 4.1.2 + '@csstools/css-syntax-patches-for-csstree': 1.1.17(css-tree@3.2.1) + css-tree: 3.2.1 + lru-cache: 11.5.4 + + data-urls@6.0.1: + dependencies: + whatwg-mimetype: 5.0.0 + whatwg-url: 15.1.0 + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + decimal.js@10.6.0: {} + + detect-libc@2.1.2: + optional: true + + dom-serializer@2.0.0: + dependencies: + domelementtype: 2.3.0 + domhandler: 5.0.3 + entities: 4.5.0 + + domelementtype@2.3.0: {} + + domhandler@5.0.3: + dependencies: + domelementtype: 2.3.0 + + domutils@3.2.2: + dependencies: + dom-serializer: 2.0.0 + domelementtype: 2.3.0 + domhandler: 5.0.3 + + dot-case@3.0.4: + dependencies: + no-case: 3.0.4 + tslib: 2.9.1 + + encoding-sniffer@0.2.1: + dependencies: + iconv-lite: 0.6.3 + whatwg-encoding: 3.1.1 + entities@4.5.0: {} + entities@6.0.1: {} + + entities@7.0.1: {} + + entities@9.0.0: {} + + fflate@0.8.2: {} + + html-encoding-sniffer@6.0.0: + dependencies: + '@exodus/bytes': 1.16.0 + transitivePeerDependencies: + - '@noble/hashes' + + html-minifier-terser@7.2.0: + dependencies: + camel-case: 4.1.2 + clean-css: 5.3.3 + commander: 10.0.1 + entities: 4.5.0 + param-case: 3.0.4 + relateurl: 0.2.7 + terser: 5.51.4 + + htmlparser2@10.1.0: + dependencies: + domelementtype: 2.3.0 + domhandler: 5.0.3 + domutils: 3.2.2 + entities: 7.0.1 + + http-proxy-agent@7.0.2: + dependencies: + agent-base: 7.1.4 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + https-proxy-agent@7.0.6: + dependencies: + agent-base: 7.1.4 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + iconv-lite@0.6.3: + dependencies: + safer-buffer: 2.1.2 + + inherits@2.0.4: {} + + is-potential-custom-element-name@1.0.1: {} + + jsdom@27.4.0: + dependencies: + '@acemir/cssom': 0.9.33 + '@asamuzakjp/dom-selector': 6.8.1 + '@exodus/bytes': 1.16.0 + cssstyle: 5.3.7 + data-urls: 6.0.1 + decimal.js: 10.6.0 + html-encoding-sniffer: 6.0.0 + http-proxy-agent: 7.0.2 + https-proxy-agent: 7.0.6 + is-potential-custom-element-name: 1.0.1 + parse5: 8.1.1 + saxes: 6.0.0 + symbol-tree: 3.2.4 + tough-cookie: 6.1.0 + w3c-xmlserializer: 5.0.0 + webidl-conversions: 8.0.1 + whatwg-mimetype: 4.0.0 + whatwg-url: 15.1.0 + ws: 8.23.1 + xml-name-validator: 5.0.0 + transitivePeerDependencies: + - '@noble/hashes' + - bufferutil + - supports-color + - utf-8-validate + linkify-it@5.0.2: dependencies: uc.micro: 2.1.0 + lower-case@2.0.2: + dependencies: + tslib: 2.9.1 + + lru-cache@11.5.4: {} + markdown-it@14.3.3: dependencies: argparse: 2.0.1 @@ -125,14 +1148,210 @@ snapshots: punycode.js: 2.3.1 uc.micro: 2.1.0 + mdn-data@2.27.1: {} + mdurl@2.1.0: {} + ms@2.1.3: {} + + nan@2.30.0: + optional: true + + nanoid@3.3.20: {} + + no-case@3.0.4: + dependencies: + lower-case: 2.0.2 + tslib: 2.9.1 + nodemailer@7.0.13: {} + nth-check@2.1.1: + dependencies: + boolbase: 1.0.0 + + param-case@3.0.4: + dependencies: + dot-case: 3.0.4 + tslib: 2.9.1 + + parse-srcset@1.0.2: {} + + parse5-htmlparser2-tree-adapter@7.1.0: + dependencies: + domhandler: 5.0.3 + parse5: 7.3.0 + + parse5-parser-stream@7.1.2: + dependencies: + parse5: 7.3.0 + + parse5@7.3.0: + dependencies: + entities: 6.0.1 + + parse5@8.1.1: + dependencies: + entities: 9.0.0 + + pascal-case@3.1.2: + dependencies: + no-case: 3.0.4 + tslib: 2.9.1 + + picocolors@1.1.1: {} + + postcss-value-parser@4.2.0: {} + + postcss@8.5.6: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.3.0 + punycode.js@2.3.1: {} + punycode@2.3.1: {} + + readable-stream@3.6.2: + dependencies: + inherits: 2.0.4 + string_decoder: 1.4.0 + util-deprecate: 1.0.2 + + relateurl@0.2.7: {} + + require-from-string@2.0.2: {} + + safe-buffer@5.2.1: {} + + safer-buffer@2.1.2: {} + + saxes@6.0.0: + dependencies: + xmlchars: 2.2.0 + + semver@7.8.6: + optional: true + + sharp@0.34.5: + dependencies: + '@img/colour': 1.1.0 + detect-libc: 2.1.2 + semver: 7.8.6 + optionalDependencies: + '@img/sharp-darwin-arm64': 0.34.5 + '@img/sharp-darwin-x64': 0.34.5 + '@img/sharp-libvips-darwin-arm64': 1.2.4 + '@img/sharp-libvips-darwin-x64': 1.2.4 + '@img/sharp-libvips-linux-arm': 1.2.4 + '@img/sharp-libvips-linux-arm64': 1.2.4 + '@img/sharp-libvips-linux-ppc64': 1.2.4 + '@img/sharp-libvips-linux-riscv64': 1.2.4 + '@img/sharp-libvips-linux-s390x': 1.2.4 + '@img/sharp-libvips-linux-x64': 1.2.4 + '@img/sharp-libvips-linuxmusl-arm64': 1.2.4 + '@img/sharp-libvips-linuxmusl-x64': 1.2.4 + '@img/sharp-linux-arm': 0.34.5 + '@img/sharp-linux-arm64': 0.34.5 + '@img/sharp-linux-ppc64': 0.34.5 + '@img/sharp-linux-riscv64': 0.34.5 + '@img/sharp-linux-s390x': 0.34.5 + '@img/sharp-linux-x64': 0.34.5 + '@img/sharp-linuxmusl-arm64': 0.34.5 + '@img/sharp-linuxmusl-x64': 0.34.5 + '@img/sharp-wasm32': 0.34.5 + '@img/sharp-win32-arm64': 0.34.5 + '@img/sharp-win32-ia32': 0.34.5 + '@img/sharp-win32-x64': 0.34.5 + optional: true + + source-map-js@1.3.0: {} + + source-map-support@0.5.21: + dependencies: + buffer-from: 1.1.2 + source-map: 0.6.1 + + source-map@0.6.1: {} + + ssh2-sftp-client@12.1.1: + dependencies: + concat-stream: 2.0.0 + ssh2: 1.17.0 + + ssh2@1.17.0: + dependencies: + asn1: 0.2.6 + bcrypt-pbkdf: 1.0.2 + optionalDependencies: + cpu-features: 0.0.10 + nan: 2.30.0 + + string_decoder@1.4.0: + dependencies: + safe-buffer: 5.2.1 + + symbol-tree@3.2.4: {} + + terser@5.51.4: + dependencies: + '@jridgewell/source-map': 0.3.11 + acorn: 8.19.0 + commander: 2.20.3 + source-map-support: 0.5.21 + + tldts-core@7.6.4: {} + + tldts@7.6.4: + dependencies: + tldts-core: 7.6.4 + + tough-cookie@6.1.0: + dependencies: + tldts: 7.6.4 + + tr46@6.0.0: + dependencies: + punycode: 2.3.1 + + tslib@2.9.1: {} + turndown@7.2.4: dependencies: '@mixmark-io/domino': 2.2.0 + tweetnacl@0.14.5: {} + + typedarray@0.0.6: {} + uc.micro@2.1.0: {} + + undici@7.30.2: {} + + util-deprecate@1.0.2: {} + + w3c-xmlserializer@5.0.0: + dependencies: + xml-name-validator: 5.0.0 + + webidl-conversions@8.0.1: {} + + whatwg-encoding@3.1.1: + dependencies: + iconv-lite: 0.6.3 + + whatwg-mimetype@4.0.0: {} + + whatwg-mimetype@5.0.0: {} + + whatwg-url@15.1.0: + dependencies: + tr46: 6.0.0 + webidl-conversions: 8.0.1 + + ws@8.23.1: {} + + xml-name-validator@5.0.0: {} + + xmlchars@2.2.0: {}