plugins: Discover's list comes from a file CI builds, not GitHub from each desktop (River_WLan on X)

Plugins -> Discover read GitHub's topic search plus a package.json, an npm
answer and an entry file for ~400 repositories on every desktop. Where GitHub
is unreachable or rate-limited the page said "Couldn't ask GitHub".

Now the community repo's `tagged` workflow (plugins repo, scripts/tagged.mjs,
every half hour) builds tagged.json on its dist branch, usemagpie.ai serves
it at /api/plugins/tagged (worker, edge-cached 10 min, jsDelivr and the last
whole copy as fallbacks), and magpie asks: usemagpie.ai, the dist branch
(jsDelivr with the China-mirror switch), then GitHub as before. parseCatalog
keeps only entries whose spec is github:<repo> or the package named from it,
and drops a file older than 48h. Degrades: a tagged repo shows within the
hour, not ten minutes; stars/https icons are as of the last build; owner
avatars and https icon URLs still come from GitHub hosts (data: icons work).

Run (wsl-run, mote's disk is full): go vet + go test ./internal/plugin,
node --test site/worker.test.mjs (21 pass), scripts/tagged.mjs against the
real GitHub (367 plugins, 253 with icons, 0 unread; workflow run green and
tagged.json on dist), usemagpie.ai/api/plugins/tagged after wrangler deploy
(200, 4.8MB). Broken by hand: skipping askCatalog turns
TestTaggedReposFromTheBuiltList red. Not tried: a real desktop with GitHub
blocked; GUI suites (no GUI file changed); Windows/darwin vet.
This commit is contained in:
yetone
2026-11-11 15:07:54 +08:00
parent bd6a016156
commit 14be7f69df
6 changed files with 317 additions and 925 deletions
+2
View File
@@ -235,6 +235,8 @@ Plugins are installed from, and magpie's own npm questions (a package's newest v
## A GitHub listing's licence
The Discover list is not read from GitHub by each desktop: the community repo's `tagged` workflow (`scripts/tagged.mjs` there, the same reading as `readTagged`) builds `tagged.json` on its `dist` branch every half hour, usemagpie.ai passes it on at `/api/plugins/tagged` (`taggedPlugins` in `site/worker.js`), and `askCatalog` ([`catalog.go`](../../internal/plugin/catalog.go)) asks usemagpie.ai, then the dist branch (jsDelivr with the 「国内镜像」 switch), and only then GitHub's own search. `parseCatalog` keeps just entries whose spec is `github:<repo>` or the package named from it, drops a file older than 48 hours, and never trusts an address the file makes up. Stars, owner avatars and https icons are as the build read them, up to an hour old; a tagged repository shows within the hour, not ten minutes. `MAGPIE_PLUGIN_CATALOG` puts an address first, `off` keeps to GitHub. Tests: `TestTaggedReposFromTheBuiltList`, `site/worker.test.mjs`.
A repository tagged `magpie-plugin` shows the licence GitHub's search reads from its `LICENSE` file. GitHub gives `NOASSERTION` for a file it can't match to one (MIT's text with a line of credit added) and nothing for none, and magpie drops `NOASSERTION`, so such a card had no licence while the same package on npm shows its `package.json` `license`. `readTagged` in [`github.go`](../../internal/plugin/github.go) now keeps `package.json`'s `license` (a string) as `PkgLicense`, and `License` falls back to it, on a fresh read and on one kept across searches (`fresh`) ([magpie-community/plugins#468](https://github.com/magpie-community/plugins/issues/468)). `TestTaggedRepos` covers both cases and the one with neither.
A tagged repository's kind (`Tagged.Kind`, the card's chip and the GitHub strip's kind filter) comes from what its `package.json` declares. `magpie.agent` makes it an agent whether or not it has a `main` or `exports`: an agent that needs a runtime (a poller, a file watched) ships its agent file in moejs and a Bun module as `main`, and read only by the absence of `main` it was listed as a provider (miaocell/magpie-agent-deva, [magpie-community/plugins#737](https://github.com/magpie-community/plugins/issues/737)). Middleware, a page and request hooks are still a kind only when that is all the package is, since a page or a hook beside a provider's module is that provider's accessory. A package with a module of its own has that module checked as committed (its `main`, the agent's too), else the one file it declares (`TestTaggedAgentWithMain`). One card has one kind, the declared one winning; an Installed row wears every chip it has, and an agent's wears Provider only when its module serves a provider (`plugin-agent.test.cjs`).
+114
View File
@@ -0,0 +1,114 @@
package plugin
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"sort"
"strings"
"time"
)
// The Discover list, built for magpie. Reading it takes a topic search and
// a package.json, an npm answer and an entry file for each of ~400
// repositories, all at GitHub (and npm), which a desktop that can't reach
// GitHub or is rate-limited there never gets through (River_WLan on X). The
// community repo's `tagged` workflow reads them every half hour instead,
// onto its dist branch (scripts/tagged.mjs there, the same reading as
// readTagged), and usemagpie.ai passes the file on. magpie asks there
// first, then the dist branch itself (through the 「国内镜像」 jsDelivr copy
// with the switch on), and reads GitHub only when neither answers.
// catalogURLs is where the list is asked, in order; moved by tests.
// MAGPIE_PLUGIN_CATALOG puts one address in front, and "off" keeps to
// GitHub.
var catalogURLs = []string{
"https://usemagpie.ai/api/plugins/tagged",
"https://raw.githubusercontent.com/magpie-community/plugins/dist/tagged.json",
}
// catalogMaxAge is how old the file may be: the workflow runs every half
// hour, so one this old means it stopped, and GitHub is asked after all.
const catalogMaxAge = 48 * time.Hour
type catalogFile struct {
Version int `json:"version"`
Generated string `json:"generated"`
Plugins []Tagged `json:"plugins"`
}
// parseCatalog reads the file, keeping what the page could install: a
// repository's github: spec or its npm name, and a picture as ownIcon
// takes one. An empty list, an unknown version or a file past
// catalogMaxAge is an error, as is any that isn't JSON.
func parseCatalog(b []byte, now time.Time) ([]Tagged, error) {
var f catalogFile
if err := json.Unmarshal(b, &f); err != nil {
return nil, err
}
if f.Version != 1 {
return nil, fmt.Errorf("list version %d", f.Version)
}
at, err := time.Parse(time.RFC3339, f.Generated)
if err != nil {
return nil, fmt.Errorf("list has no date: %w", err)
}
if now.Sub(at) > catalogMaxAge {
return nil, fmt.Errorf("list is from %s", f.Generated)
}
out := make([]Tagged, 0, len(f.Plugins))
for _, t := range f.Plugins {
if t.Repo == "" || strings.Count(t.Repo, "/") != 1 || !pkgName.MatchString(t.Package) {
continue
}
// what Install adds is the repository or the package named from
// it, never an address the file made up
if t.Spec != "github:"+t.Repo && t.Spec != t.Package {
continue
}
switch t.Kind {
case "", "middleware", "agent", "page":
default:
continue
}
t.Icon = ownIcon(t.Icon)
out = append(out, t)
}
if len(out) == 0 {
return nil, errors.New("list has no plugins")
}
sort.SliceStable(out, func(i, j int) bool { return out[i].Stars > out[j].Stars })
return out, nil
}
// askCatalog is the list the workflow built, from the first address that
// answers.
func askCatalog(ctx context.Context) ([]Tagged, error) {
urls := catalogURLs
switch v := os.Getenv("MAGPIE_PLUGIN_CATALOG"); v {
case "off":
return nil, errors.New("catalog is off")
case "":
default:
urls = append([]string{v}, urls...)
}
var last error
for _, u := range urls {
c, cancel := context.WithTimeout(ctx, 12*time.Second)
b, err := fetchJSON(c, u, 16<<20)
cancel()
if err == nil {
var l []Tagged
if l, err = parseCatalog(b, time.Now()); err == nil {
return l, nil
}
}
last = err
if ctx.Err() != nil {
break
}
}
return nil, last
}
+105
View File
@@ -0,0 +1,105 @@
package plugin
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync/atomic"
"testing"
"time"
)
// The Discover list is asked of the built file first, so a desktop that
// can't reach GitHub still has it (River_WLan on X): with GitHub's API
// refused, the list still comes, in stars order, with what the file kept
// and nothing it made up.
func TestTaggedReposFromTheBuiltList(t *testing.T) {
file := func(at time.Time, ps ...Tagged) []byte {
b, _ := json.Marshal(catalogFile{Version: 1, Generated: at.UTC().Format(time.RFC3339), Plugins: ps})
return b
}
good := []Tagged{
{Spec: "github:a/few", Repo: "a/few", Package: "few", Stars: 2, Icon: "data:image/svg+xml;base64,AAAA"},
{Spec: "github:b/many", Repo: "b/many", Package: "many", Stars: 90, Kind: "page"},
{Spec: "mine", Repo: "c/mine", Package: "mine", Stars: 5},
{Spec: "https://evil.example/x.tgz", Repo: "d/evil", Package: "evil", Stars: 999},
{Spec: "github:e/odd", Repo: "e/odd", Package: "odd", Kind: "shell", Stars: 999},
{Spec: "github:f/bad", Repo: "f/bad", Package: "Not A Name", Stars: 999},
}
body := file(time.Now(), good...)
var asked atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
asked.Add(1)
w.Write(body)
}))
defer srv.Close()
var gh atomic.Int32
hub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gh.Add(1)
http.Error(w, "unreachable", 503)
}))
defer hub.Close()
api, raw, urls := githubAPI, githubRaw, catalogURLs
githubAPI, githubRaw, catalogURLs = hub.URL, hub.URL+"/raw", []string{srv.URL}
t.Cleanup(func() {
githubAPI, githubRaw, catalogURLs = api, raw, urls
taggedMu.Lock()
taggedL = nil
taggedMu.Unlock()
_ = os.Remove(taggedCache())
})
forget := func() {
taggedMu.Lock()
taggedL = nil
taggedMu.Unlock()
_ = os.Remove(taggedCache())
}
forget()
l, err := TaggedRepos(context.Background())
if err != nil {
t.Fatal(err)
}
var got []string
for _, x := range l {
got = append(got, x.Repo)
}
if strings.Join(got, " ") != "b/many c/mine a/few" {
t.Fatalf("listed %v", got)
}
if l[2].Icon == "" {
t.Error("the icon the file kept was dropped")
}
if gh.Load() != 0 {
t.Fatalf("GitHub was asked %d times with the list at hand", gh.Load())
}
// the file stopped being built: GitHub is asked after all (and its
// refusal is what the page says)
forget()
body = file(time.Now().Add(-catalogMaxAge-time.Hour), good...)
if _, err := TaggedRepos(context.Background()); err == nil || gh.Load() == 0 {
t.Fatalf("a list from days ago stood: err %v, GitHub asked %d", err, gh.Load())
}
// the address down: the next one answers
forget()
srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(file(time.Now(), good...)) }))
defer srv2.Close()
catalogURLs = []string{"http://127.0.0.1:1", srv2.URL}
if l, err := TaggedRepos(context.Background()); err != nil || len(l) != 3 {
t.Fatalf("second address: %d, %v", len(l), err)
}
// off keeps to GitHub
forget()
t.Setenv("MAGPIE_PLUGIN_CATALOG", "off")
before := gh.Load()
if _, err := TaggedRepos(context.Background()); err == nil || gh.Load() == before {
t.Fatalf("off still read the list: err %v", err)
}
}
+11 -1
View File
@@ -184,7 +184,7 @@ func TaggedRepos(ctx context.Context) ([]Tagged, error) {
if last == nil {
last = taggedOnDisk()
}
if l, whole, missing, err := askTagged(ctx, last); err == nil {
if l, whole, missing, err := askListOrGitHub(ctx, last); err == nil {
taggedL, taggedAt, taggedWhy = l, time.Now(), nil
if !whole {
taggedAt = time.Now().Add(-taggedTTL + taggedRetry)
@@ -610,3 +610,13 @@ func githubRepo(spec string) string {
}
return p[0] + "/" + p[1]
}
// askListOrGitHub is the list the community repo's workflow built (see
// catalog.go) when it can be had, else GitHub's own answer, as askTagged
// gives it. GitHub's error is the one reported when neither answers.
func askListOrGitHub(ctx context.Context, last []Tagged) ([]Tagged, bool, *TaggedMissing, error) {
if l, err := askCatalog(ctx); err == nil {
return l, true, nil, nil
}
return askTagged(ctx, last)
}
+63 -514
View File
@@ -1,14 +1,9 @@
// usemagpie.ai. Releases live on GitHub (yetone/magpie-releases); this
// worker turns the newest one into the update feed the app reads and into
// download links that never go stale, and serves their files from R2,
// copied there from GitHub (files.js).
// download links that never go stale.
//
// /api/latest {version, notes, url, published, assets: {name: {url, api, size, sha256}}}
// /api/latest?channel=stable
// the same for Settings' Stable channel: a release a
// week, an urgent one at once ("The Stable channel"
// below), with channel and urgent; 503 while unknown
// /api/notes?after=&upto=&limit= {releases: [{version, notes, url, published}]}, newest
// /api/latest {version, notes, url, published, assets: {name: {url, size, sha256}}}
// /api/notes?after=&upto= {releases: [{version, notes, url, published}]}, newest
// first: what changed since the version an app last ran
// Both take ?lang=zh for the notes in Chinese, where a
// release has them (below its <!-- lang:zh --> marker);
@@ -24,23 +19,11 @@
// a picture a plugin, market or import link names,
// fetched here so its host sees Cloudflare, not the
// user (the app fetches every remote icon this way)
// /docs/contributors, /docs/zh/contributors, /docs/ja/contributors
// the contributors page, its table put in from
// public/contributors/<lang>.html (credits-cli.mjs
// wall, at each deploy)
// /download the Apple Silicon dmg
// /download/mac-arm64 the same; /download/mac-intel the Intel dmg
// /download/windows the Windows app (x64); /download/windows-arm64
// /download/linux the Linux app (x86-64); /download/linux-arm64
// /download/<file> any file of the newest release, by name
// /files/<tag>/<file> a release's file from R2 (files.js), the feed's
// url and /download's for the files R2 holds;
// GitHub's own address for any it doesn't
// /dl/<tag>/<file> a release's file through GitHub's API, the feed's
// url while github.com's download address fails
// /r/... the pages' PostHog snippet, passed on to PostHog
// (relay, below) so a blocker that knows its host
// doesn't drop the count
// /docs, /docs/zh, /docs/ja the getting-started guide: /docs/start, /docs/<lang>/start
// /zh/, /ja/, /de/ the home page in Chinese, Japanese, German (i18n.js);
// / sends a browser that prefers one of them there,
@@ -52,11 +35,8 @@
import { LANGS } from "./i18n.js";
import { PARTNERS } from "./partners.js";
import { SPONSORS } from "./sponsors.js";
import { serve as serveFile, held, onR2, mirror, githubFile } from "./files.js";
import { handle as pluginStats, prune as prunePlugins } from "./pluginstats.js";
const REPO = "yetone/magpie-releases";
const SITE = "https://usemagpie.ai";
const TTL = 300; // seconds the newest release is remembered
const SHORT = {
@@ -73,9 +53,6 @@ const SHORT = {
// The bare docs paths open the getting-started guide.
const DOCS = { "/docs": "/docs/start", "/docs/zh": "/docs/zh/start", "/docs/ja": "/docs/ja/start" };
// pages that moved, from the old path (no .html) to the new one: the MCP
// hub was renamed the MCP router
const MOVED = { "/docs/mcp-hub": "/docs/mcp-router", "/docs/zh/mcp-hub": "/docs/zh/mcp-router", "/docs/ja/mcp-hub": "/docs/ja/mcp-router" };
// the languages the docs are written in besides English
const DOC_LANGS = ["zh", "ja"];
@@ -86,22 +63,11 @@ export default {
url.hostname = url.hostname.slice(4);
return Response.redirect(url.toString(), 301);
}
if (url.pathname.startsWith("/api/plugins/")) {
const got = await pluginStats(req, env, ctx);
if (got) return got;
}
if (url.pathname === "/api/latest") {
const lang = url.searchParams.get("lang");
// Settings' Stable channel; any other channel, or none, is every
// version as it comes out
if (url.searchParams.get("channel") === "stable") {
const got = await stable(ctx, env, Date.now());
if (!got) return json({ error: "the stable version isn't known yet" }, 503, NO_STORE);
return json({ ...(await fromR2(ctx, env, got.rel)), notes: inLang(got.rel.notes, lang) }, 200, cacheFor(got));
}
const got = await latest(ctx, env);
if (!got) return json({ error: "no release yet" }, 503, NO_STORE);
return json({ ...(await fromR2(ctx, env, got.rel)), notes: inLang(got.rel.notes, lang) }, 200, cacheFor(got));
const lang = url.searchParams.get("lang");
return json({ ...got.rel, notes: inLang(got.rel.notes, lang) }, 200, cacheFor(got));
}
if (url.pathname === "/api/partners") {
const now = Date.now();
@@ -125,41 +91,22 @@ export default {
if (!got) return json({ error: "no releases" }, 503, NO_STORE);
const after = url.searchParams.get("after"), upto = url.searchParams.get("upto");
const lang = url.searchParams.get("lang");
// limit: the newest that many alone (Settings' "this version and the
// 10 before it", Linka), so an app asking for 11 isn't sent 100
const limit = parseInt(url.searchParams.get("limit"), 10);
const within = (r) => (!after || newer(r.version, after)) && (!upto || !newer(r.version, upto));
let pick = got.list.filter(within);
// the hundred newest are a day of releases: a range reaching further
// back (a Stable app's week, an app long unopened) is read on from
// the ledger
const oldest = got.list.at(-1);
const short = after ? !oldest || newer(oldest.version, after) : limit > 0 ? pick.length < limit : !pick.some((r) => r.version === upto);
if (short && upto) pick = [...pick, ...(await fromLedger(env, oldest && oldest.version, after, upto, limit > 0 ? limit - pick.length : LEDGER_MOST))];
pick = pick.slice(0, limit > 0 ? limit : undefined).map((r) => ({ ...r, notes: inLang(r.notes, lang) }));
const pick = got.list
.filter((r) => (!after || newer(r.version, after)) && (!upto || !newer(r.version, upto)))
.map((r) => ({ ...r, notes: inLang(r.notes, lang) }));
return json({ releases: pick }, 200, cacheFor(got));
}
if (url.pathname === "/api/plugins/tagged") return taggedPlugins(ctx);
if (url.pathname === "/api/icon") return icon(url.searchParams.get("url"));
const file = url.pathname.match(/^\/files\/(v[0-9][0-9A-Za-z.+-]*)\/([0-9A-Za-z._+-]+)$/);
if (file) return serveFile(req, env, REPO, file[1], file[2]);
const dl = url.pathname.match(/^\/dl\/(v[0-9][0-9A-Za-z.+-]*)\/([0-9A-Za-z._+-]+)$/);
if (dl) return detour(ctx, env, dl[1], dl[2]);
if (url.pathname.startsWith(RELAY)) return relay(req, url);
if (url.pathname === "/download" || url.pathname.startsWith("/download/")) {
const want = url.pathname.split("/")[2] || "mac-arm64";
const got = await latest(ctx, env);
const rel = got && (await fromR2(ctx, env, got.rel));
const asset = rel && rel.assets && rel.assets[SHORT[want] || want];
const asset = got && got.rel.assets && got.rel.assets[SHORT[want] || want];
if (!asset) return new Response("not found\n", { status: 404 });
if (req.method === "GET") ctx.waitUntil(capture("magpie site download", { link: want, file: SHORT[want] || want, client: client(req), country: country(req) }));
return Response.redirect(asset.url, 302);
}
// crawlers and old browsers ask for /favicon.ico whatever the page links
if (url.pathname === "/favicon.ico") return Response.redirect(new URL("/favicon.png", url).toString(), 301);
const guide = DOCS[url.pathname.replace(/\/+$/, "")];
if (guide) return Response.redirect(new URL(guide, url).toString(), 302);
const moved = MOVED[url.pathname.replace(/(\.html)?\/*$/, "")];
if (moved) return Response.redirect(new URL(moved + url.search, url).toString(), 301);
// an English docs page, to a browser whose language has its own: as /
// does, until a language is picked
const doc = url.pathname.match(/^\/docs\/([a-z-]+)(\.html)?$/);
@@ -170,7 +117,7 @@ export default {
// a page not written in that language yet stays English
if (DOC_LANGS.includes(lang) && (await env.ASSETS.fetch(new Request(new URL(there, url), { method: "HEAD" }))).ok)
return new Response(null, { status: 302, headers: { Location: there + url.search, ...vary } });
const res = beacon(await withWall(await env.ASSETS.fetch(req), env, url));
const res = beacon(await env.ASSETS.fetch(req));
const out = new Response(res.body, res);
out.headers.append("Vary", "Accept-Language, Cookie");
out.headers.set("Cache-Control", "no-cache");
@@ -193,19 +140,7 @@ export default {
out.headers.append("Vary", "Accept-Language, Cookie");
return out;
}
if (url.pathname === "/install.sh" && req.method === "GET")
ctx.waitUntil(capture("magpie site install script", { client: client(req), country: country(req) }));
return beacon(await withWall(await env.ASSETS.fetch(req), env, url));
},
// the crons (wrangler.jsonc's triggers): every quarter hour the ledger
// the Stable channel is chosen from and Discover's old counts pruned, every five minutes the newest and
// the Stable release's files into R2
async scheduled(event, env, ctx) {
if (event.cron === MIRROR_CRON) ctx.waitUntil(keepFiles(ctx, env));
else {
ctx.waitUntil(keepLedger(env, Date.now()));
ctx.waitUntil(prunePlugins(env));
}
return beacon(await env.ASSETS.fetch(req));
},
};
@@ -232,13 +167,10 @@ function live(p, now) {
// served is the list the app gets: those whose term hasn't ended (an
// ended one stays in partners.js, so the /go links of providers added from
// it keep working), with their website and key page as /go links. A
// website's own host goes beside it as siteHost, for the editor's link to
// read (www.kimi.com, not usemagpie.ai).
// it keep working), with their website and key page as /go links.
export function served(list, now) {
const go = (p, what, r) => GO + [p.id, what, r && r.id].filter(Boolean).map(encodeURIComponent).join("/");
const host = (u) => { try { return new URL(u).host; } catch { return ""; } };
const linked = (o, p, r) => ({ ...o, ...(o.website && { website: go(p, "site", r), siteHost: host(o.website) }), ...(o.keysUrl && { keysUrl: go(p, "keys", r) }) });
const linked = (o, p, r) => ({ ...o, ...(o.website && { website: go(p, "site", r) }), ...(o.keysUrl && { keysUrl: go(p, "keys", r) }) });
return list
.filter((p) => !p.until || now < Date.parse(p.until))
.map((p) => ({ ...linked(p, p), ...(p.regions && { regions: p.regions.map((r) => linked(r, p, r)) }) }));
@@ -277,11 +209,6 @@ function fromMagpie(to) {
}
}
// client says whether a browser asked, or a command (curl, wget, a script).
function client(req) {
return /^Mozilla\//.test(req.headers.get("User-Agent") || "") ? "browser" : "command";
}
function country(req) {
return (req.cf && req.cf.country) || "";
}
@@ -355,60 +282,10 @@ function translate(res, lang) {
return rw.transform(out);
}
// relay passes a request of the pages' PostHog snippet (under RELAY) on to
// PostHog: the library and its config from the assets host, the rest from
// the ingestion host. The visitor's address goes as X-Forwarded-For, which
// PostHog reads for the country, and the site's cookies stay here.
const RELAY = "/r/";
export async function relay(req, url) {
const path = url.pathname.slice(RELAY.length - 1);
const host = /^\/(static|array)\//.test(path) ? "us-assets.i.posthog.com" : "us.i.posthog.com";
const headers = new Headers(req.headers);
for (const h of ["Cookie", "Host"]) headers.delete(h);
const ip = req.headers.get("CF-Connecting-IP");
if (ip) headers.set("X-Forwarded-For", ip);
const body = req.method === "GET" || req.method === "HEAD" ? null : req.body;
try {
return await fetch(`https://${host}${path}${url.search}`, { method: req.method, headers, body, redirect: "manual" });
} catch {
return new Response("", { status: 502 });
}
}
// beacon adds PostHog's Web Analytics to a page; every page passes through
// this one. Cloudflare Web Analytics is not added here: Cloudflare injects
// its own beacon into worker responses now, and that one reports to this
// site's /cdn-cgi/rum. A second, manual beacon loaded first and won, and
// reported to cloudflareinsights.com, which answers 404 for this site's
// token, so Web Analytics counted no visits at all. PostHog's requests go through RELAY
// on this site. PostHog keeps its visitor id in
// localStorage, never a cookie: these pages vary on Cookie (the lang
// cookie), and a per-visitor cookie would ride on every request. It isn't
// cookieless, since cookieless drops the address before GeoIP and the
// country with it. It sends page views and leaves, clicks (autocapture,
// for heatmaps, dead clicks too), Web Vitals and network timings, uncaught
// errors, and a session recording with every input masked; the recording
// and the rest of the project's settings come from its remote config, so
// flags aren't turned off. Nothing is loaded under Do Not Track or Global
// Privacy Control. Its project is the daily count's.
const WEB_ANALYTICS = `<script>if(!(navigator.doNotTrack=="1"||window.doNotTrack=="1"||navigator.globalPrivacyControl)){!function(t,e){var o,n,p,r;e.__SV||(window.posthog&&window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+" (stub)"},o="capture register unregister opt_out_capturing opt_in_capturing has_opted_out_capturing set_config".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init("${POSTHOG_KEY}",{api_host:location.origin+"/r",ui_host:"https://us.posthog.com",persistence:"localStorage",person_profiles:"identified_only",capture_pageview:true,capture_pageleave:true,autocapture:true,enable_heatmaps:true,capture_dead_clicks:true,capture_exceptions:true,capture_performance:{web_vitals:true,network_timing:true},session_recording:{maskAllInputs:true},disable_surveys:true,respect_dnt:true})}</script>`;
const BEACON = WEB_ANALYTICS;
// The contributors page: its #wall gets the table credits-cli.mjs rendered
// for that language at deploy. Without it (a deploy that couldn't build
// it) the page keeps the line it is written with.
const WALL_PAGE = /^\/docs\/(?:(zh|ja)\/)?contributors(?:\.html)?$/;
export async function withWall(res, env, url) {
const m = url.pathname.match(WALL_PAGE);
if (!m || !res.ok || !(res.headers.get("Content-Type") || "").startsWith("text/html")) return res;
let table = "";
try {
const got = await env.ASSETS.fetch(new Request(new URL(`/contributors/${m[1] || "en"}.html`, url)));
if (got.ok) table = await got.text();
} catch {}
if (!table.includes("<table")) return res;
return new HTMLRewriter().on("#wall", { element: (el) => el.setInnerContent(table, { html: true }) }).transform(res);
}
// beacon adds Cloudflare Web Analytics to a page. The dashboard's automatic
// injection skips whatever a worker returns, and every page passes through
// this one.
const BEACON = `<script defer src="https://static.cloudflareinsights.com/beacon.min.js" data-cf-beacon='{"token": "c09e76abf16b40b2aa5571c196efb847"}'></script>`;
function beacon(res) {
if (!(res.headers.get("Content-Type") || "").startsWith("text/html")) return res;
@@ -460,10 +337,8 @@ async function latest(ctx, env) {
if (hit && hit.rel && hit.rel.version) return hit;
const full = await fromAPI(env);
if (full) {
// a feed sending the files by /dl is kept briefly: github.com's own
// address is given again as soon as it answers
const got = { rel: full, degraded: detoured(full) };
remember(ctx, "latest", got, got.degraded ? BRIEF : TTL);
const got = { rel: full, degraded: false };
remember(ctx, "latest", got, TTL);
remember(ctx, "latest-good", full, KEEP);
return got;
}
@@ -481,46 +356,6 @@ async function latest(ctx, env) {
const UA = { "User-Agent": "usemagpie.ai" };
const MIRROR_CRON = "*/5 * * * *";
// fromR2 is rel with the files R2 holds at /files (onR2); what R2 holds
// of a tag is asked once a minute.
async function fromR2(ctx, env, rel) {
if (!rel || !env.RELEASES) return rel;
const tag = "v" + rel.version;
let have = await cached("r2/" + tag);
if (!have || typeof have !== "object") {
have = await held(env, tag);
if (have) remember(ctx, "r2/" + tag, have, BRIEF);
}
return onR2(rel, have, REPO, SITE);
}
// keepFiles is the five-minute cron's run: the newest release's files and
// the Stable one's into R2, each from github.com's address or, when that
// fails, by way of GitHub's API (located).
async function keepFiles(ctx, env) {
if (!env.RELEASES) return;
const rels = [];
const got = await latest(ctx, env);
if (got) rels.push(got.rel);
const st = await stable(ctx, env, Date.now()).catch((e) => console.log("r2: stable", String(e)));
if (st) rels.push(st.rel);
const open = async (name, a, tag) => {
let res = null;
try {
res = await fetch(githubFile(REPO, tag, name), { headers: UA });
} catch (e) {
console.log("r2: github.com", name, String(e));
}
if (res && res.ok) return res;
const to = a.api && (await located(a.api, env));
return to ? fetch(to, { headers: UA }) : res;
};
const done = await mirror(env, rels, open);
if (done.copied.length || done.failed.length) console.log("r2", JSON.stringify(done));
}
// api asks GitHub's API, with the GITHUB_TOKEN secret where one is set.
function api(path, env) {
const headers = { ...UA, Accept: "application/vnd.github+json" };
@@ -528,12 +363,10 @@ function api(path, env) {
return fetch(`https://api.github.com/repos/${REPO}/${path}`, { headers });
}
// fromAPI is a release from GitHub's API: the newest, or the one path names
// (releases/tags/v0.1.2), or null.
async function fromAPI(env, path = "releases/latest") {
async function fromAPI(env) {
let res;
try {
res = await api(path, env);
res = await api("releases/latest", env);
} catch (e) {
console.log("github api", e);
return null;
@@ -544,84 +377,16 @@ async function fromAPI(env, path = "releases/latest") {
}
const gh = await res.json();
const tag = gh.tag_name;
const listed = gh.assets.find((a) => a.name === "SHA256SUMS");
const got = await checksums(tag, env, listed && listed.url);
if (!got) return null;
const sums = await checksums(tag);
if (!sums) return null;
const rel = { version: tag.replace(/^v/, ""), notes: gh.body || "", url: gh.html_url, published: gh.published_at, assets: {} };
for (const a of gh.assets) {
if (a.name === "SHA256SUMS") continue;
// api: the file's address in GitHub's API, which an app asks when
// url is busy. With github.com's download address failing (504 for
// hours on 2026-11-08), url is the site's /dl, which redirects
// through the API: an app too old to know api follows it, and still
// checks the file against sha256.
const url = got.direct ? a.browser_download_url : `${SITE}/dl/${tag}/${encodeURIComponent(a.name)}`;
rel.assets[a.name] = { url, api: a.url, size: a.size, sha256: got.sums[a.name] || "" };
rel.assets[a.name] = { url: a.browser_download_url, size: a.size, sha256: sums[a.name] || "" };
}
return rel;
}
// detoured: whether rel's files go by the site's /dl
function detoured(rel) {
return Object.values(rel.assets || {}).some((a) => a.url && a.url.startsWith(SITE + "/dl/"));
}
// located is where GitHub's API sends an ask for a release file's bytes
// (Accept: application/octet-stream): a signed address on GitHub's asset
// host, good for some minutes, or null. The redirect is read, not
// followed, so no Authorization goes to the asset host.
async function located(apiURL, env) {
const headers = { ...UA, Accept: "application/octet-stream" };
if (env && env.GITHUB_TOKEN) headers.Authorization = `Bearer ${env.GITHUB_TOKEN}`;
let res;
try {
res = await fetch(apiURL, { headers, redirect: "manual" });
} catch (e) {
console.log("github asset", e);
return null;
}
const to = res.headers.get("Location") || "";
let host = "";
try {
host = new URL(to).hostname;
} catch {}
if (res.status < 300 || res.status > 399 || !to.startsWith("https://") || !(host.endsWith(".githubusercontent.com") || host === "github.com")) {
console.log("github asset", res.status, to.slice(0, 80));
return null;
}
return to;
}
// detour is /dl/<tag>/<file>: a redirect to the release's file by way of
// GitHub's API (located), for when github.com's download address fails.
// Where GitHub's API sends is kept five minutes, and each release's list
// of files an hour, so a worker IP's 60 anonymous asks an hour go far.
// The file is checked by whoever downloads it, against the feed's hash.
async function detour(ctx, env, tag, name) {
const key = `dl/${tag}/${name}`;
let to = await cached(key);
if (typeof to !== "string" || !to) {
let files = await cached(`dl-files/${tag}`);
if (!files || typeof files !== "object") {
let res = null;
try {
res = await api(`releases/tags/${tag}`, env);
} catch (e) {
console.log("github api", tag, e);
}
if (!res || !res.ok) return new Response("GitHub didn't say where the file is; try again in a minute\n", { status: 502, headers: NO_STORE });
files = {};
for (const a of (await res.json()).assets || []) files[a.name] = a.url;
remember(ctx, `dl-files/${tag}`, files, 3600);
}
if (!files[name]) return new Response("not found\n", { status: 404 });
to = await located(files[name], env);
if (!to) return new Response("GitHub didn't hand out the file; try again in a minute\n", { status: 502, headers: NO_STORE });
remember(ctx, key, to, 300);
}
return new Response(null, { status: 302, headers: { Location: to, ...NO_STORE } });
}
async function fromPages() {
let res;
try {
@@ -635,18 +400,10 @@ async function fromPages() {
console.log("github latest redirect", res.status);
return null;
}
const feed = await fromFeed();
return fromSums(tag, (feed || []).find((r) => r.version === tag.replace(/^v/, "")));
}
// fromSums is tag's release from its SHA256SUMS alone, with its notes and
// date from entry ({notes, published}) where there is one: every file, its
// size unknown (0). null when SHA256SUMS can't be read.
async function fromSums(tag, entry) {
const got = await checksums(tag);
if (!got) return null;
const sums = got.sums;
const [sums, feed] = await Promise.all([checksums(tag), fromFeed()]);
if (!sums) return null;
const url = `https://github.com/${REPO}/releases/tag/${tag}`;
const entry = (feed || []).find((r) => r.version === tag.replace(/^v/, ""));
const rel = { version: tag.replace(/^v/, ""), notes: entry ? entry.notes : "", url, published: entry ? entry.published : null, assets: {} };
for (const [name, sha256] of Object.entries(sums)) {
rel.assets[name] = { url: `https://github.com/${REPO}/releases/download/${tag}/${name}`, size: 0, sha256 };
@@ -691,230 +448,6 @@ async function releases(ctx, env) {
return got;
}
// The Stable channel (Settings' Update channel, ssharpcc on X): magpie
// releases many times a day, and someone who reads every changelog before
// updating wants fewer, older ones. /api/latest?channel=stable is the
// update feed for them, chosen here from the release list and never by
// hand:
//
// - once a week, as the week turns (Monday 00:00 UTC), Stable becomes
// the newest release that was out SOAK (three days) by then;
// - an urgent release (a security hole, a ban risk, lost data) is Stable
// as soon as it is out, until a weekly pick passes it.
//
// A release is urgent when its notes have a line that starts with
// URGENT_MARK: "**Urgent release:** why". magpie-releases' release run
// writes it from an `Urgent:` trailer on any commit since the version
// before, and it can be added to a published release's notes by hand
// (gh release edit) within a day, while the release is on the ledger's
// first page. GitHub releases are never marked pre-release for this:
// /download and the Latest mark go by them.
//
// A hundred releases are a day or so of magpie, so the list GitHub's API
// gives in one ask doesn't reach a week back. The ledger does: a KV
// namespace (LEDGER) the cron fills every quarter hour, its "index" every
// release of the last LEDGER_DAYS ({v, p: published, u: urgent}, newest
// first) and "notes:<UTC day>" each day's notes by version, which
// /api/notes reads for a range older than the hundred newest. Without the
// ledger, or one that doesn't reach back to the week's cut, Stable isn't
// known and the feed says so (503) rather than guess. The Docker image's
// stable tag follows this feed (.github/workflows/docker-stable.yml).
const DAY = 86400e3;
const SOAK = 3 * DAY;
const LEDGER_DAYS = 45;
const LEDGER_REACH = 21 * DAY; // how far back the cron fills the ledger
const LEDGER_PAGES = 4; // GitHub API asks one cron run makes at most
const LEDGER_MOST = 1500; // releases /api/notes reads from the ledger at most
export const URGENT_MARK = "**Urgent release:**";
// urgentIn says whether a release's notes mark it urgent: a line (or a
// quoted one) that starts with URGENT_MARK, in any case.
export function urgentIn(notes) {
return /^[ \t]*(?:>[ \t]*)?\*\*urgent release:\*\*/im.test(notes || "");
}
// weekStart is the Monday 00:00 UTC on or before now, in ms.
export function weekStart(now) {
const d = new Date(now);
return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()) - ((d.getUTCDay() + 6) % 7) * DAY;
}
// stableOf is the Stable release at now among list ([{version, published,
// urgent}], any order): the newer of the newest release out SOAK before
// this week began and the newest urgent one. null when the list doesn't
// reach back to that cut and has no urgent release either: unknown.
export function stableOf(list, now) {
const cut = weekStart(now) - SOAK;
let weekly = null, rush = null, reaches = false;
for (const r of list) {
const at = Date.parse(r.published);
if (!(at <= now)) continue; // a date not known, or not yet
if (at <= cut) {
reaches = true;
if (!weekly || newer(r.version, weekly.version)) weekly = r;
}
if (r.urgent && (!rush || newer(r.version, rush.version))) rush = r;
}
if (!reaches) return rush;
return rush && newer(rush.version, weekly.version) ? rush : weekly;
}
// readIndex is the ledger's index, null when there is no ledger, and
// undefined when it can't be read: unknown, never an empty one.
async function readIndex(env, cacheTtl) {
if (!env || !env.LEDGER) return null;
try {
const ix = await env.LEDGER.get("index", cacheTtl ? { type: "json", cacheTtl } : { type: "json" });
if (ix === null) return { list: [] };
return Array.isArray(ix && ix.list) ? ix : undefined;
} catch (e) {
console.log("ledger index", e);
return undefined;
}
}
// stable is the Stable release, condensed as latest's is: {rel, degraded},
// or null when it isn't known. rel also says it is Stable's (channel) and
// whether it went there as urgent.
async function stable(ctx, env, now) {
const hit = await cached("stable");
if (hit && hit.rel && hit.rel.version) return hit;
const ix = await readIndex(env, 60);
if (!ix) return null;
const pick = stableOf(ix.list.map((r) => ({ version: r.v, published: r.p, urgent: !!r.u })), now);
if (!pick) return null;
const tag = "v" + pick.version;
let rel = await fromAPI(env, "releases/tags/" + tag);
let degraded = !!rel && detoured(rel);
if (!rel) {
// the API said no: the files from SHA256SUMS, the notes from the ledger
const [entry] = await fromLedger(env, null, null, pick.version, 1);
rel = await fromSums(tag, entry && entry.version === pick.version ? entry : { notes: "", published: pick.published });
degraded = true;
}
if (!rel) return null;
const got = { rel: { ...rel, channel: "stable", urgent: !!pick.urgent }, degraded };
remember(ctx, "stable", got, degraded ? BRIEF : TTL);
return got;
}
// fromLedger is the notes of the releases the ledger has older than below
// (every one when null), after after (exclusive, "" for any) up to upto,
// newest first, at most most: [{version, notes, url, published}].
async function fromLedger(env, below, after, upto, most) {
const ix = await readIndex(env, 300);
if (!ix || !(most > 0)) return [];
const want = ix.list
.filter((r) => (!below || newer(below, r.v)) && (!after || newer(r.v, after)) && !newer(r.v, upto))
.sort((a, b) => (newer(a.v, b.v) ? -1 : newer(b.v, a.v) ? 1 : 0))
.slice(0, most);
const days = [...new Set(want.map((r) => dayOf(r.p)))];
const books = await Promise.all(days.map((d) => env.LEDGER.get("notes:" + d, { type: "json", cacheTtl: 300 }).catch(() => null)));
const by = Object.fromEntries(days.map((d, i) => [d, books[i] || {}]));
return want.map((r) => ({ version: r.v, notes: by[dayOf(r.p)][r.v] || "", url: `https://github.com/${REPO}/releases/tag/v${r.v}`, published: r.p }));
}
function dayOf(iso) {
return String(iso || "").slice(0, 10);
}
// keepLedger is the cron's run: GitHub's newest hundred releases into the
// ledger (or the releases feed's ten, when the API says no), the pages
// after them while the ledger has a hole or doesn't yet reach
// LEDGER_REACH back, at most LEDGER_PAGES asks. A ledger that can't be
// read is left alone, never written over as an empty one.
export async function keepLedger(env, now) {
const ix = await readIndex(env);
if (!ix) return;
const kv = env.LEDGER;
const had = new Map(ix.list.map((r) => [r.v, r]));
const got = new Map(); // version: {version, notes, published}
let asks = 0, bottom = !!ix.bottom;
const page = async (n) => {
asks++;
let res;
try {
res = await api(`releases?per_page=100&page=${n}`, env);
} catch (e) {
console.log("ledger page", n, e);
return null;
}
if (!res.ok) {
console.log("ledger page", n, res.status);
return null;
}
const rels = (await res.json())
.filter((r) => !r.draft && !r.prerelease)
.map((r) => ({ version: r.tag_name.replace(/^v/, ""), notes: r.body || "", published: r.published_at }));
if (rels.length < 100) bottom = true;
for (const r of rels) got.set(r.version, r);
return rels;
};
const first = await page(1);
if (!first) for (const r of (await fromFeed()) || []) got.set(r.version, r);
// a hole (the cron stopped for a day): the pages after the first until
// one meets what the ledger had
let n = 1;
for (let last = first; last && last.length === 100 && had.size && !last.some((r) => had.has(r.version)) && asks < LEDGER_PAGES; ) last = await page(++n);
// reaching back: the page where the ledger's oldest is, then on
const oldest = () => {
let o = null;
for (const r of [...had.values(), ...[...got.values()].map((g) => ({ v: g.version, p: g.published }))]) if (!o || newer(o.v, r.v)) o = r;
return o;
};
let deep = Math.max(n + 1, Math.floor((had.size || got.size) / 100) + 1);
while (first && !bottom && asks < LEDGER_PAGES) {
const o = oldest();
if (o && Date.parse(o.p) <= now - LEDGER_REACH) break;
if (!(await page(deep++))) break;
}
// the index: what was had, what came, nothing older than LEDGER_DAYS
const keep = now - LEDGER_DAYS * DAY;
const merged = new Map(had);
for (const r of got.values()) {
// the feed's date is when the release was last edited: the API's, or
// the one the ledger has, is when it came out
const was = merged.get(r.version);
merged.set(r.version, { v: r.version, p: !first && was ? was.p : r.published, u: urgentIn(r.notes) });
}
const list = [...merged.values()]
.filter((r) => r.v && Date.parse(r.p) >= keep)
.sort((a, b) => (newer(a.v, b.v) ? -1 : newer(b.v, a.v) ? 1 : 0));
const next = { list, bottom };
if (JSON.stringify(next) !== JSON.stringify({ list: ix.list, bottom: !!ix.bottom })) await kv.put("index", JSON.stringify(next));
// each day's notes, written where they changed
const days = new Map();
for (const r of got.values()) {
// by the day the index has it out (the feed's date is its last edit)
const p = merged.get(r.version).p;
if (!p || Date.parse(p) < keep) continue;
const d = dayOf(p);
if (!days.has(d)) days.set(d, []);
days.get(d).push(r);
}
for (const [d, rels] of days) {
const key = "notes:" + d;
let book;
try {
book = (await kv.get(key, { type: "json" })) || {};
} catch (e) {
console.log("ledger notes", d, e);
continue; // unreadable: left as it is
}
let changed = false;
for (const r of rels) {
// the feed's notes (HTML made markdown, the Chinese marker guessed)
// never replace the API's
if (!first && book[r.version]) continue;
if (book[r.version] !== r.notes) {
book[r.version] = r.notes;
changed = true;
}
}
if (changed) await kv.put(key, JSON.stringify(book), { expirationTtl: (LEDGER_DAYS + 15) * 86400 });
}
}
// fromFeed is the newest releases from GitHub's releases feed (Atom), which
// isn't the API and so isn't limited by it: [{version, notes, url,
// published}], newest first, or null. The feed has each release's notes as
@@ -1043,35 +576,22 @@ function newer(a, b) {
return x.pre > y.pre;
}
// checksums reads a release's SHA256SUMS: {sums: {file name: hash},
// direct}, or null. direct says github.com's download address gave it;
// when that fails, viaAPI (the file's address in GitHub's API) is asked.
async function checksums(tag, env, viaAPI) {
let r = null;
// checksums reads a release's SHA256SUMS: {file name: hash}.
async function checksums(tag) {
let r;
try {
r = await fetch(`https://github.com/${REPO}/releases/download/${tag}/SHA256SUMS`, { headers: UA });
} catch (e) {
console.log("SHA256SUMS", e);
return null;
}
let direct = !!r && r.ok;
if (!direct) {
if (r) console.log("SHA256SUMS", r.status);
const to = viaAPI && (await located(viaAPI, env));
if (!to) return null;
try {
r = await fetch(to, { headers: UA });
} catch (e) {
console.log("SHA256SUMS through the API", e);
return null;
}
if (!r.ok) return null;
}
if (!r.ok) return null;
const sums = {};
for (const line of (await r.text()).split("\n")) {
const [hash, name] = line.trim().split(/\s+\*?/);
if (hash && name) sums[name] = hash;
}
return { sums, direct };
return sums;
}
// ---- icons ------------------------------------------------------------------
@@ -1083,6 +603,35 @@ async function checksums(tag, env, viaAPI) {
// on, only the picture comes back, and Cloudflare keeps it a day.
export const ICON_MAX = 1 << 20; // the app's MaxIcon
// taggedPlugins is the Plugins page's Discover list, built every half hour
// by the plugins repo's `tagged` workflow onto its dist branch, passed on
// for the desktops that can't reach GitHub (River_WLan on X). The edge
// keeps it ten minutes, and the last whole copy stands in for a failed ask.
const TAGGED = [
"https://raw.githubusercontent.com/magpie-community/plugins/dist/tagged.json",
"https://cdn.jsdelivr.net/gh/magpie-community/plugins@dist/tagged.json",
];
export async function taggedPlugins(ctx) {
const hit = await cached("tagged");
if (hit && Array.isArray(hit.plugins)) return json(hit, 200, { "Cache-Control": "public, max-age=600" });
for (const u of TAGGED) {
try {
const res = await fetch(u, { headers: UA });
if (!res.ok) continue;
const got = await res.json();
if (got.version !== 1 || !Array.isArray(got.plugins) || !got.plugins.length) continue;
remember(ctx, "tagged", got, 600);
remember(ctx, "tagged-good", got, KEEP);
return json(got, 200, { "Cache-Control": "public, max-age=600" });
} catch (e) {
console.log("tagged", u, e);
}
}
const good = await cached("tagged-good");
if (good && Array.isArray(good.plugins)) return json(good, 200, { "Cache-Control": "public, max-age=60" });
return json({ error: "no list yet" }, 503, NO_STORE);
}
export async function icon(raw) {
let u;
try {
+22 -410
View File
@@ -3,7 +3,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import worker, { served, goTarget, sponsorTarget } from "./worker.js";
import { bucket, sha } from "./r2stub.mjs";
const EN = "### Features\n\n- One thing (#1)\n\n### Install\n\nDownload it.";
const ZH = "### 新功能\n\n- 一件事 (#1)";
@@ -24,9 +23,6 @@ globalThis.caches = {
// pagesDown for github.com itself failing too. seen keeps each API ask's
// headers.
let apiDown = false, pagesDown = false;
// downloadsDown: github.com's download address answering 504 while the
// API serves the same files (2026-11-08)
let downloadsDown = false;
const seen = [];
const FEED = `<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
@@ -58,37 +54,20 @@ const FEED = `<?xml version="1.0" encoding="UTF-8"?>
</feed>`;
// what the worker sent PostHog
const captured = [];
// what the worker passed on to PostHog for the pages' snippet (relay)
const relayed = [];
globalThis.fetch = async (u, init = {}) => {
u = String(u);
if (u === "https://us.i.posthog.com/i/v0/e/") {
captured.push(JSON.parse(init.body));
return new Response("{}");
}
if (/^https:\/\/us(-assets)?\.i\.posthog\.com\//.test(u)) {
relayed.push({ u, method: init.method, headers: new Headers(init.headers), body: init.body && (await new Response(init.body).text()) });
return new Response("relayed");
}
if (u.startsWith("https://api.github.com/")) {
seen.push(new Headers(init.headers));
if (apiDown) return new Response('{"message":"API rate limit exceeded"}', { status: 403 });
const asset = u.match(/\/releases\/assets\/(\d+)$/);
if (asset) {
if (new Headers(init.headers).get("Accept") !== "application/octet-stream") return Response.json({ id: +asset[1] });
return new Response(null, { status: 302, headers: { Location: `https://release-assets.githubusercontent.com/a/${asset[1]}?sig=1` } });
}
} else if (pagesDown) return new Response("unicorn", { status: 503 });
if (downloadsDown && u.includes("/releases/download/")) return new Response("", { status: 504 });
if (u === "https://release-assets.githubusercontent.com/a/2?sig=1") return new Response("abc magpie-linux-amd64\n");
if (u === "https://github.com/yetone/magpie-releases/releases/latest")
return new Response(null, { status: 302, headers: { Location: "https://github.com/yetone/magpie-releases/releases/tag/v0.1.3" } });
if (u.endsWith("/releases.atom")) return new Response(FEED);
const gh = (tag) => ({ tag_name: tag, body: BODIES[tag], html_url: "https://github.com/r/" + tag, published_at: "2026-10-01T00:00:00Z", draft: false, prerelease: false, assets: [
{ name: "magpie-linux-amd64", size: 1, browser_download_url: "https://dl/x", url: "https://api.github.com/repos/yetone/magpie-releases/releases/assets/1" },
{ name: "SHA256SUMS", size: 1, browser_download_url: "https://dl/sums", url: "https://api.github.com/repos/yetone/magpie-releases/releases/assets/2" },
] });
if (u.endsWith("/releases/tags/v0.1.3")) return Response.json(gh("v0.1.3"));
const gh = (tag) => ({ tag_name: tag, body: BODIES[tag], html_url: "https://github.com/r/" + tag, published_at: "2026-10-01T00:00:00Z", draft: false, prerelease: false, assets: [{ name: "magpie-linux-amd64", size: 1, browser_download_url: "https://dl/x" }] });
if (u.endsWith("/releases/latest")) return Response.json(gh("v0.1.3"));
if (u.includes("/releases?per_page=")) return Response.json(Object.keys(BODIES).map(gh));
if (u.endsWith("/SHA256SUMS")) return new Response("abc magpie-linux-amd64\n");
@@ -125,16 +104,6 @@ test("notes: each release in the language, English where it has no Chinese", asy
assert.equal(again[0].notes, ZH);
});
test("notes: limit keeps the newest that many up to upto", async () => {
const two = (await get("/api/notes?upto=0.1.3&limit=2")).body.releases;
assert.deepEqual(two.map((r) => r.version), ["0.1.3", "0.1.2"]);
const one = (await get("/api/notes?upto=0.1.2&limit=1")).body.releases;
assert.deepEqual(one.map((r) => r.version), ["0.1.2"]);
for (const q of ["", "&limit=0", "&limit=x", "&limit=-1"]) {
assert.equal((await get("/api/notes?upto=0.1.3" + q)).body.releases.length, 3, q);
}
});
test("i18n: every string the home page marks has its Chinese, and no other", async () => {
const { readFile } = await import("node:fs/promises");
const { LANGS } = await import("./i18n.js");
@@ -187,25 +156,6 @@ test("docs: the bare docs paths open each language's guide", async () => {
}
});
test("site: /favicon.ico goes to the icon the pages link", async () => {
const env = { ASSETS: { fetch: async () => new Response("asset") } };
const res = await worker.fetch(new Request("https://usemagpie.ai/favicon.ico"), env, ctx);
assert.equal(res.status, 301);
assert.equal(res.headers.get("Location"), "https://usemagpie.ai/favicon.png");
});
test("docs: the MCP hub's old pages go to the MCP router's, keeping the query", async () => {
const env = { ASSETS: { fetch: async () => new Response("asset") } };
for (const [from, to] of [["/docs/mcp-hub", "/docs/mcp-router"], ["/docs/mcp-hub.html", "/docs/mcp-router"], ["/docs/zh/mcp-hub/", "/docs/zh/mcp-router"], ["/docs/ja/mcp-hub.html?x=1", "/docs/ja/mcp-router?x=1"]]) {
const res = await worker.fetch(new Request("https://usemagpie.ai" + from), env, ctx);
assert.equal(res.status, 301, from);
const got = new URL(res.headers.get("Location"));
assert.equal(got.pathname + got.search, to, from);
}
const res = await worker.fetch(new Request("https://usemagpie.ai/docs/mcp-router"), env, ctx);
assert.equal(await res.text(), "asset");
});
// #661: the update window showed no notes while GitHub's API limited the
// worker, and the failure was kept for five minutes.
const ask = (path, env = {}) => worker.fetch(new Request("https://usemagpie.ai" + path), env, ctx);
@@ -304,64 +254,6 @@ test("download: a platform's link goes to that asset of the latest release", asy
assert.equal((await ask("/download/nothing-like-it")).status, 404);
});
test("download: each link followed is counted, with the platform, the country and a browser or a command", async () => {
captured.length = 0;
const req = new Request("https://usemagpie.ai/download/linux", { headers: { "User-Agent": "curl/8.7.1" } });
req.cf = { country: "BR" };
assert.equal((await worker.fetch(req, {}, ctx)).status, 302);
await new Promise((ok) => setTimeout(ok, 0));
assert.equal(captured.length, 1);
assert.equal(captured[0].event, "magpie site download");
assert.deepEqual(captured[0].properties, { link: "linux", file: "magpie-linux-amd64", client: "command", country: "BR", $process_person_profile: false });
captured.length = 0;
await worker.fetch(new Request("https://usemagpie.ai/download/linux", { headers: { "User-Agent": "Mozilla/5.0 (Macintosh)" } }), {}, ctx);
await new Promise((ok) => setTimeout(ok, 0));
assert.equal(captured[0].properties.client, "browser");
// a HEAD, or a file the release doesn't have, isn't counted
captured.length = 0;
await worker.fetch(new Request("https://usemagpie.ai/download/linux", { method: "HEAD" }), {}, ctx);
await ask("/download/nothing-like-it");
await new Promise((ok) => setTimeout(ok, 0));
assert.deepEqual(captured, []);
});
test("install.sh: each fetch is counted", async () => {
const env = { ASSETS: { fetch: async () => new Response("#!/bin/sh\n", { headers: { "Content-Type": "text/x-sh" } }) } };
captured.length = 0;
const res = await worker.fetch(new Request("https://usemagpie.ai/install.sh", { headers: { "User-Agent": "curl/8.7.1" } }), env, ctx);
assert.equal(await res.text(), "#!/bin/sh\n");
await new Promise((ok) => setTimeout(ok, 0));
assert.equal(captured.length, 1);
assert.equal(captured[0].event, "magpie site install script");
assert.equal(captured[0].properties.client, "command");
});
test("relay: the snippet's requests reach PostHog with the visitor's address and without the site's cookies", async () => {
relayed.length = 0;
const post = new Request("https://usemagpie.ai/r/e/?ip=0&ver=1.442.1", {
method: "POST",
body: "gzipped",
headers: { Cookie: "lang=zh", "CF-Connecting-IP": "203.0.113.7", "Content-Type": "text/plain", "User-Agent": "Mozilla/5.0" },
});
assert.equal(await (await worker.fetch(post, {}, ctx)).text(), "relayed");
await worker.fetch(new Request("https://usemagpie.ai/r/static/array.js"), {}, ctx);
await worker.fetch(new Request("https://usemagpie.ai/r/array/phc_x/config.js"), {}, ctx);
await worker.fetch(new Request("https://usemagpie.ai/r/flags/?v=2"), {}, ctx);
assert.deepEqual(relayed.map((r) => r.u), [
"https://us.i.posthog.com/e/?ip=0&ver=1.442.1",
"https://us-assets.i.posthog.com/static/array.js",
"https://us-assets.i.posthog.com/array/phc_x/config.js",
"https://us.i.posthog.com/flags/?v=2",
]);
const [e] = relayed;
assert.equal(e.method, "POST");
assert.equal(e.body, "gzipped");
assert.equal(e.headers.get("X-Forwarded-For"), "203.0.113.7");
assert.equal(e.headers.get("Cookie"), null);
assert.equal(e.headers.get("User-Agent"), "Mozilla/5.0");
});
test("docs: an English docs page sends a browser that prefers Chinese or Japanese to its own, until a language is picked", async () => {
const have = new Set(["/docs/start", "/docs/zh/start", "/docs/ja/start", "/docs/only-en"]);
const env = { ASSETS: { fetch: async (r) => new Response(have.has(new URL(r.url).pathname) ? "<html></html>" : "nf", { status: have.has(new URL(r.url).pathname) ? 200 : 404, headers: { "Content-Type": "text/plain" } }) } };
@@ -430,10 +322,6 @@ test("partners: links go through /go", () => {
assert.equal(acme.chat, LIST[0].chat);
assert.equal(acme.regions[0].keysUrl, "https://usemagpie.ai/go/acme/keys/cn");
assert.equal(acme.regions[0].website, undefined);
// the editor names a /go website by the host it sends the browser to
assert.equal(acme.siteHost, "acme.example");
assert.equal(acme.regions[0].siteHost, undefined);
assert.equal(plain.siteHost, undefined);
assert.equal(acme.regions[1].keysUrl, undefined);
assert.deepEqual(plain, LIST[1]);
// partners.js itself is left as it is
@@ -596,314 +484,38 @@ test("sponsors: the home page and the READMEs link every sponsor through /go", a
if (s[where]) assert.equal(text.includes(s[where]), false, `${f.pathname} links ${s.id} directly`);
// the home page links its own /go; a README, on GitHub, the site's
const go = (where === "home" ? "" : "https://usemagpie.ai") + `/go/${s.id}/${where}`;
// as an <a href> or a Markdown link (Kimi's thanks line, e6b9d1199)
if (text.includes(`/go/${s.id}/`)) assert.ok(s[where] && (text.includes(`href="${go}"`) || text.includes(`](${go})`)), `${f.pathname}: ${go}`);
if (text.includes(`/go/${s.id}/`)) assert.ok(s[where] && text.includes(`href="${go}"`), `${f.pathname}: ${go}`);
}
}
const home = readFileSync(pages.home[0], "utf8");
for (const s of SPONSORS.filter((s) => s.home)) assert.ok(home.includes(`href="/go/${s.id}/home"`), s.id);
});
// HTMLRewriter is Cloudflare's; this stands in for the two uses here: a
// selector's inner content set, and the body appended to
class FakeRewriter {
constructor() { this.h = []; }
on(sel, h) { this.h.push([sel, h]); return this; }
transform(res) {
const hs = this.h;
return new Response(new ReadableStream({
async start(c) {
let t = await res.text();
for (const [sel, h] of hs) {
let inner, tail = "";
h.element({ setInnerContent: (x) => (inner = x), append: (x) => (tail += x) });
if (sel === "#wall" && inner !== undefined) t = t.replace(/(<div id="wall">)[\s\S]*?(<\/div>)/, (_, a, b) => a + inner + b);
if (sel === "body") t = t.replace("</body>", tail + "</body>");
}
c.enqueue(new TextEncoder().encode(t));
c.close();
},
}), res);
}
}
test("contributors: each language's page gets its own table, and keeps its line without one", async () => {
const { readFileSync } = await import("node:fs");
const { renderWall } = await import("./credits.mjs");
const data = { people: [{ name: "packinggoodsllc_07668", via: ["Discord"], releases: [{ v: "0.1.2581", what: ["a contributors page"] }] }] };
const page = (p) => new URL(`./public${p}.html`, import.meta.url);
let fragments = true;
const asked = [];
const env = {
ASSETS: {
fetch: async (r) => {
const p = new URL(r.url).pathname.replace(/\.html$/, "");
asked.push(p);
const m = p.match(/^\/contributors\/(en|zh|ja)$/);
if (m) return fragments ? new Response(renderWall(data, m[1]), { headers: { "Content-Type": "text/html" } }) : new Response("nf", { status: 404 });
try { return new Response(readFileSync(page(p), "utf8"), { headers: { "Content-Type": "text/html; charset=utf-8" } }); } catch { return new Response("nf", { status: 404 }); }
},
},
};
const was = globalThis.HTMLRewriter;
globalThis.HTMLRewriter = FakeRewriter;
try {
const get = async (path) => (await worker.fetch(new Request(`https://usemagpie.ai${path}`, { headers: { Cookie: "lang=en" } }), env, ctx)).text();
for (const [path, lang, head] of [["/docs/contributors", "en", "What came of it"], ["/docs/zh/contributors", "zh", "带来的改动"], ["/docs/ja/contributors.html", "ja", "そこから生まれた"]]) {
const html = await get(path);
assert.match(html, /<div id="wall"><div class="table-wrap"><table class="cw">/, path);
assert.ok(html.includes(head), `${path} has the ${lang} table`);
assert.ok(html.includes("packinggoodsllc_07668") && html.includes("v0.1.2581"), path);
assert.match(html, /posthog\.init\(/, `${path} keeps the analytics`);
assert.doesNotMatch(html, /cloudflareinsights/, `${path} leaves Cloudflare's beacon to Cloudflare`);
}
fragments = false;
const bare = await get("/docs/zh/contributors");
assert.ok(!bare.includes('<table class="cw">'));
assert.match(bare, /<div id="wall"><p>名单在每次部署网站时/);
// no other page asks for a table
asked.length = 0;
await get("/docs/start");
assert.deepEqual(asked, ["/docs/start"]);
} finally {
globalThis.HTMLRewriter = was;
}
});
test("contributors: the pages say how to be left off, and every docs footer links them", async () => {
const { readFileSync, readdirSync } = await import("node:fs");
const dir = (d) => new URL(`./public/docs/${d}`, import.meta.url);
for (const [pre, file] of [["/docs/", "contributors.html"], ["/docs/zh/", "zh/contributors.html"], ["/docs/ja/", "ja/contributors.html"]]) {
const html = readFileSync(dir(file), "utf8");
assert.match(html, /<div id="wall">/, file);
assert.ok(html.includes("site/contributors-exclude.txt"), file);
for (const l of ["en", "zh", "ja"]) assert.ok(html.includes(`hreflang="${l}" href="https://usemagpie.ai/docs/${l === "en" ? "" : l + "/"}contributors"`), `${file} ${l}`);
assert.ok(!/privacy" hreflang=|og:url" content="[^"]*privacy/.test(html), `${file} still points at the page it was made from`);
}
for (const sub of ["", "zh/", "ja/"]) {
const pre = `/docs/${sub}`;
for (const f of readdirSync(dir(sub)).filter((f) => f.endsWith(".html"))) {
const foot = readFileSync(dir(sub + f), "utf8").split("<footer")[1];
assert.ok(foot.includes(`<a href="${pre}contributors">`), `${sub}${f}'s footer`);
}
}
assert.ok(readFileSync(new URL("./public/index.html", import.meta.url), "utf8").includes('<a href="/docs/contributors" data-i18n="foot.contrib">'));
});
test("seo: the sitemap lists the home pages and every docs page, each its own canonical", async () => {
const { readFile, readdir } = await import("node:fs/promises");
const { LANGS } = await import("./i18n.js");
const pub = new URL("./public/", import.meta.url);
const xml = await readFile(new URL("sitemap.xml", pub), "utf8");
const listed = [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => m[1]);
const want = ["https://usemagpie.ai/", ...Object.keys(LANGS).map((l) => `https://usemagpie.ai/${l}/`)];
for (const dir of ["docs/", "docs/zh/", "docs/ja/"])
for (const f of (await readdir(new URL(dir, pub))).filter((f) => f.endsWith(".html")).sort())
want.push(`https://usemagpie.ai/${dir}${f.slice(0, -5)}`);
assert.deepEqual([...listed].sort(), [...want].sort());
const home = await readFile(new URL("index.html", pub), "utf8");
assert.match(home, /<link rel="canonical" data-i18n-attr="href:meta.url" href="https:\/\/usemagpie.ai\/">/);
for (const [l, { dict }] of Object.entries(LANGS)) assert.equal(dict["meta.url"], `https://usemagpie.ai/${l}/`);
for (const u of listed.filter((u) => u.includes("/docs/"))) {
const html = await readFile(new URL(u.slice("https://usemagpie.ai/".length) + ".html", pub), "utf8");
const canon = [...html.matchAll(/<link rel="canonical" href="([^"]+)">/g)].map((m) => m[1]);
assert.deepEqual(canon, [u], `${u} canonical`);
assert.ok(html.includes(`<link rel="alternate" hreflang="x-default" href="https://usemagpie.ai/docs/${u.split("/").pop()}">`), `${u} x-default`);
assert.ok(!/name="robots" content="[^"]*noindex/.test(html), `${u} is noindex`);
// every alternate is a page that exists, so none is listed as a 404
for (const [, alt] of html.matchAll(/<link rel="alternate" hreflang="[a-z-]+" href="([^"]+)">/g))
assert.ok(listed.includes(alt), `${u}: ${alt}`);
}
});
test("seo: robots.txt names the sitemap and keeps crawlers off the counted links", async () => {
const { readFile } = await import("node:fs/promises");
const txt = await readFile(new URL("./public/robots.txt", import.meta.url), "utf8");
assert.match(txt, /^Sitemap: https:\/\/usemagpie.ai\/sitemap.xml$/m);
for (const p of ["/api/", "/go/", "/r/", "/download"]) assert.match(txt, new RegExp(`^Disallow: ${p}$`, "m"));
});
test("seo: llms.txt lists every English docs page and links only to listed pages", async () => {
const { readFile, readdir } = await import("node:fs/promises");
const pub = new URL("./public/", import.meta.url);
const txt = await readFile(new URL("llms.txt", pub), "utf8");
const xml = await readFile(new URL("sitemap.xml", pub), "utf8");
const listed = new Set([...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => m[1]));
assert.match(txt, /^# magpie\n\n> /);
const links = [...txt.matchAll(/\]\((https:\/\/usemagpie\.ai\/[^)]*)\)/g)].map((m) => m[1]);
for (const u of links) assert.ok(listed.has(u), `llms.txt links ${u}, which the sitemap doesn't list`);
const docs = (await readdir(new URL("docs/", pub))).filter((f) => f.endsWith(".html") && f !== "contributors.html");
for (const f of docs) assert.ok(links.includes(`https://usemagpie.ai/docs/${f.slice(0, -5)}`), `llms.txt misses docs/${f}`);
});
test("seo: llms-full.txt is current and holds every English docs page", async () => {
const { readFile, readdir } = await import("node:fs/promises");
const { build } = await import("./llms-full.mjs");
const pub = new URL("./public/", import.meta.url);
const txt = await readFile(new URL("llms-full.txt", pub), "utf8");
assert.equal(txt, await build(), "public/llms-full.txt is stale: run `node llms-full.mjs` in site/");
const docs = (await readdir(new URL("docs/", pub))).filter((f) => f.endsWith(".html") && f !== "contributors.html");
for (const f of docs) assert.ok(txt.includes(`Source: https://usemagpie.ai/docs/${f.slice(0, -5)}\n`), `llms-full.txt misses docs/${f}`);
assert.doesNotMatch(txt.replace(/^```\n[\s\S]*?\n```$/gm, ""), /<\/?(p|div|span|li|td|code|a)\b/, "llms-full.txt has HTML left outside its code blocks");
});
test("seo: the home page's structured data parses and its title is in every language", async () => {
const { readFile } = await import("node:fs/promises");
const { LANGS } = await import("./i18n.js");
const html = await readFile(new URL("./public/index.html", import.meta.url), "utf8");
const ld = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
const app = JSON.parse(ld[1])["@graph"].find((n) => n["@type"] === "SoftwareApplication");
assert.equal(app.offers.price, "0");
assert.match(html, /<title data-i18n="meta.title">[^<]{20,70}<\/title>/);
for (const [l, { dict }] of Object.entries(LANGS)) assert.ok(dict["meta.title"].startsWith("magpie"), l);
});
// 2026-11-08: github.com answered 504 for every release file for hours,
// while GitHub's API served the same ones. The feed then reads the
// checksums through the API and sends each file by the site's /dl, which
// an app too old to know the api field follows; it is kept a minute, so
// github.com's own address comes back as soon as it answers.
test("latest: github.com's downloads failing, the files go by /dl, through GitHub's API", async () => {
store.clear();
downloadsDown = true;
try {
const res = await ask("/api/latest");
assert.equal(res.status, 200);
assert.equal(res.headers.get("Cache-Control"), "public, max-age=60");
const a = (await res.json()).assets["magpie-linux-amd64"];
assert.deepEqual(a, {
url: "https://usemagpie.ai/dl/v0.1.3/magpie-linux-amd64",
api: "https://api.github.com/repos/yetone/magpie-releases/releases/assets/1",
size: 1,
sha256: "abc",
});
seen.length = 0;
// each ask's writes to the edge's cache are waited for before the next
const pending = [];
const keeping = { waitUntil: (p) => void pending.push(p) };
for (let i = 0; i < 2; i++) {
const dl = await worker.fetch(new Request("https://usemagpie.ai/dl/v0.1.3/magpie-linux-amd64"), {}, keeping);
await Promise.all(pending);
assert.equal(dl.status, 302);
assert.equal(dl.headers.get("Location"), "https://release-assets.githubusercontent.com/a/1?sig=1");
assert.equal(dl.headers.get("Cache-Control"), "no-store");
}
// the release's files once, where one is once: the second is the edge's
assert.equal(seen.length, 2);
assert.equal(seen[1].get("Accept"), "application/octet-stream");
assert.equal((await ask("/dl/v0.1.3/magpie-nothing")).status, 404);
} finally {
downloadsDown = false;
}
// github.com answering again: its own address, and api beside it
store.clear();
const res = await ask("/api/latest");
assert.equal(res.headers.get("Cache-Control"), "public, max-age=300");
const a = (await res.json()).assets["magpie-linux-amd64"];
assert.equal(a.url, "https://dl/x");
assert.equal(a.api, "https://api.github.com/repos/yetone/magpie-releases/releases/assets/1");
});
test("dl: a redirect GitHub's API gives anywhere but its asset host is not passed on", async () => {
store.clear();
test("plugins/tagged: the dist branch's list passed on, jsDelivr and the last copy when it fails", async () => {
const was = globalThis.fetch;
globalThis.fetch = async (u, init = {}) =>
/\/releases\/assets\/\d+$/.test(String(u)) ? new Response(null, { status: 302, headers: { Location: "https://evil.example/x" } }) : was(u, init);
try {
const res = await ask("/dl/v0.1.3/magpie-linux-amd64");
assert.equal(res.status, 502);
assert.equal(res.headers.get("Cache-Control"), "no-store");
} finally {
globalThis.fetch = was;
}
});
// R2 holding a file under the hash the release gives, as the cron leaves it
const holding = async (b, tag, name, body, hash = sha(body)) =>
b.put(`${tag}/${name}`, body, { httpMetadata: { contentType: "application/octet-stream" }, customMetadata: { sha256: hash } });
test("r2: the feed and /download name the site's /files for a file R2 holds, with github.com's address beside it", async () => {
store.clear();
const env = { RELEASES: bucket() };
// the fixture's SHA256SUMS says "abc"
await holding(env.RELEASES, "v0.1.3", "magpie-linux-amd64", "bytes", "abc");
const res = await ask("/api/latest", env);
assert.equal(res.status, 200);
assert.deepEqual((await res.json()).assets["magpie-linux-amd64"], {
url: "https://usemagpie.ai/files/v0.1.3/magpie-linux-amd64",
api: "https://api.github.com/repos/yetone/magpie-releases/releases/assets/1",
size: 1,
sha256: "abc",
github: "https://github.com/yetone/magpie-releases/releases/download/v0.1.3/magpie-linux-amd64",
});
const dl = await ask("/download/linux", env);
assert.equal(dl.status, 302);
assert.equal(dl.headers.get("Location"), "https://usemagpie.ai/files/v0.1.3/magpie-linux-amd64");
const file = await ask("/files/v0.1.3/magpie-linux-amd64", env);
assert.equal(file.status, 200);
assert.equal(await file.text(), "bytes");
// a tag R2 no longer keeps goes to GitHub
const old = await ask("/files/v0.1.1/magpie-linux-amd64", env);
assert.equal(old.status, 302);
assert.equal(old.headers.get("Location"), "https://github.com/yetone/magpie-releases/releases/download/v0.1.1/magpie-linux-amd64");
});
test("r2: bytes R2 holds under another hash than the release's are not named; github.com's address is", async () => {
store.clear();
const env = { RELEASES: bucket() };
await holding(env.RELEASES, "v0.1.3", "magpie-linux-amd64", "older");
const a = (await (await ask("/api/latest", env)).json()).assets["magpie-linux-amd64"];
assert.equal(a.url, "https://dl/x");
assert.equal(a.github, "https://github.com/yetone/magpie-releases/releases/download/v0.1.3/magpie-linux-amd64");
// R2 failing: the feed as GitHub has it
store.clear();
env.RELEASES.fail = true;
const res = await ask("/api/latest", env);
assert.equal(res.status, 200);
assert.equal((await res.json()).assets["magpie-linux-amd64"].url, "https://dl/x");
});
test("r2: the five-minute cron copies the newest release's files from github.com, by GitHub's API when that fails", async () => {
const body = "the linux build";
const was = globalThis.fetch;
const asked = [];
globalThis.fetch = async (u, init = {}) => {
const list = { version: 1, plugins: [{ repo: "a/b", spec: "github:a/b", stars: 3 }] };
let rawDown = false, cdnDown = false;
globalThis.fetch = async (u) => {
u = String(u);
if (u.endsWith("/SHA256SUMS") || u === "https://release-assets.githubusercontent.com/a/2?sig=1") return new Response(`${sha(body)} magpie-linux-amd64\n`);
if (u === "https://github.com/yetone/magpie-releases/releases/download/v0.1.3/magpie-linux-amd64") {
asked.push("github.com");
return downloadsDown ? new Response("", { status: 504 }) : new Response(body);
}
if (u === "https://release-assets.githubusercontent.com/a/1?sig=1") {
asked.push("api");
return new Response(body);
}
return was(u, init);
if (u.startsWith("https://raw.githubusercontent.com/magpie-community/plugins/dist/")) return rawDown ? new Response("x", { status: 503 }) : Response.json(list);
if (u.startsWith("https://cdn.jsdelivr.net/gh/magpie-community/plugins@dist/")) return cdnDown ? new Response("x", { status: 503 }) : Response.json(list);
throw new Error("a test reached " + u);
};
try {
for (const down of [false, true]) {
store.clear();
downloadsDown = down;
asked.length = 0;
const env = { RELEASES: bucket() };
const pending = [];
await worker.scheduled({ cron: "*/5 * * * *" }, env, { waitUntil: (p) => void pending.push(p) });
await Promise.all(pending);
assert.deepEqual(asked, down ? ["github.com", "api"] : ["github.com"]);
const o = env.RELEASES.objs.get("v0.1.3/magpie-linux-amd64");
assert.ok(o, "copied");
assert.equal(new TextDecoder().decode(o.bytes), body);
assert.equal(o.customMetadata.sha256, sha(body));
// the quarter-hour cron is the ledger's, and copies nothing
const other = { RELEASES: bucket(), LEDGER: { get: async () => null, put: async () => {} } };
const p2 = [];
await worker.scheduled({ cron: "*/15 * * * *" }, other, { waitUntil: (p) => void p2.push(p.catch(() => {})) });
await Promise.all(p2);
assert.equal(other.RELEASES.objs.size, 0);
}
store.delete("https://usemagpie.ai/__v2/tagged");
const ask = () => worker.fetch(new Request("https://usemagpie.ai/api/plugins/tagged"), {}, ctx);
let res = await ask();
assert.equal(res.status, 200);
assert.deepEqual((await res.json()).plugins, list.plugins);
store.delete("https://usemagpie.ai/__v2/tagged");
rawDown = true;
assert.equal((await (await ask()).json()).plugins[0].repo, "a/b", "jsDelivr stands in");
store.delete("https://usemagpie.ai/__v2/tagged");
cdnDown = true;
assert.equal((await (await ask()).json()).plugins[0].repo, "a/b", "the last whole copy stands in");
store.delete("https://usemagpie.ai/__v2/tagged-good");
assert.equal((await ask()).status, 503);
} finally {
globalThis.fetch = was;
downloadsDown = false;
store.clear();
}
});