From eabf0782d43a3fe8a4794ee157b01c958e9652aa Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 16 Nov 2025 15:18:34 +0000 Subject: [PATCH] Convert Cloudflare Worker to Cloudflare Pages This commit converts the entire Xget application from a Cloudflare Worker to a Cloudflare Page, enabling static asset hosting while maintaining all existing functionality. Changes: - Add functions/[[path]].js: Catch-all Pages Function handler - Add public/index.html: Landing page with Xget information - Update src/index.js: Export handleRequest for Pages Function import - Update wrangler.toml: Configure for Pages deployment - Update package.json: Change scripts to use Pages commands - Update vitest.config.js: Include functions/ in coverage - Update .github/workflows/depoly.yml: Deploy to Pages - Update documentation: CLAUDE.md, README.md, README.en.md The conversion maintains full backward compatibility with existing tests and functionality. All caching strategies, security headers, and protocol handling remain unchanged. --- .github/workflows/depoly.yml | 5 +- CLAUDE.md | 27 ++++++-- README.en.md | 12 ++-- README.md | 14 ++-- functions/[[path]].js | 69 ++++++++++++++++++++ package.json | 14 ++-- public/index.html | 122 +++++++++++++++++++++++++++++++++++ src/index.js | 2 +- vitest.config.js | 2 +- wrangler.toml | 8 +-- 10 files changed, 240 insertions(+), 35 deletions(-) create mode 100644 functions/[[path]].js create mode 100644 public/index.html diff --git a/.github/workflows/depoly.yml b/.github/workflows/depoly.yml index 0f7ebe6..c968055 100644 --- a/.github/workflows/depoly.yml +++ b/.github/workflows/depoly.yml @@ -1,4 +1,4 @@ -name: Deploy Worker +name: Deploy to Cloudflare Pages permissions: contents: read @@ -25,8 +25,9 @@ jobs: timeout-minutes: 60 steps: - uses: actions/checkout@v5 - - name: Deploy Worker + - name: Deploy to Cloudflare Pages uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + command: pages deploy diff --git a/CLAUDE.md b/CLAUDE.md index 30d5857..a40fabf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project Overview -Xget is a high-performance acceleration engine for developer resources built on Cloudflare Workers. It provides unified acceleration for code repositories, package managers, container registries, AI inference providers, and more. The application proxies requests to various platforms, applies intelligent caching, and implements security measures while maintaining protocol compliance (Git, Docker/OCI, AI APIs). +Xget is a high-performance acceleration engine for developer resources built on Cloudflare Pages. It provides unified acceleration for code repositories, package managers, container registries, AI inference providers, and more. The application proxies requests to various platforms, applies intelligent caching, and implements security measures while maintaining protocol compliance (Git, Docker/OCI, AI APIs). **Key Features:** @@ -65,12 +65,12 @@ npm run format:check ### Deployment ```bash -# Deploy to Cloudflare Workers +# Deploy to Cloudflare Pages npm run deploy # or -wrangler deploy +wrangler pages deploy -# Start production preview +# Start local development server npm start ``` @@ -115,6 +115,19 @@ podman run -p 8080:8080 xget - Container registries: `cr-docker`, `cr-ghcr`, `cr-gcr`, etc. (prefix: `cr-`) - `transformPath()` - Converts prefixed URLs to actual platform URLs +**`functions/[[path]].js`** - Cloudflare Pages Function handler + +- `onRequest()` - Pages Function entry point that wraps handleRequest +- Catch-all route handler that processes all incoming requests +- Converts Pages Function context to Workers-compatible format +- Delegates to handleRequest for actual processing + +**`public/index.html`** - Landing page + +- Static HTML page served at the root URL +- Provides information about Xget features and usage examples +- Only served when accessing the root path directly + ### Request Flow ``` @@ -186,7 +199,7 @@ podman run -p 8080:8080 xget ## Environment Variables -Configure via Cloudflare Workers environment or `.dev.vars`: +Configure via Cloudflare Pages environment variables or `.dev.vars`: - `TIMEOUT_SECONDS` - Request timeout (default: 30) - `MAX_RETRIES` - Max retry attempts (default: 3) @@ -241,9 +254,9 @@ Configure via Cloudflare Workers environment or `.dev.vars`: ## Deployment Targets -1. **Cloudflare Workers** (primary): Zero-config deployment with global edge network +1. **Cloudflare Pages** (primary): Zero-config deployment with global edge network and built-in static asset hosting 2. **Docker/Podman**: Self-hosted with workerd runtime (see Dockerfile) -3. **Local development**: Wrangler dev server on localhost +3. **Local development**: Wrangler Pages dev server on localhost ## License diff --git a/README.en.md b/README.en.md index e14f501..0dc5ad2 100644 --- a/README.en.md +++ b/README.en.md @@ -4,7 +4,7 @@ xixu-me%2FXget | Trendshift -[![Cloudflare Workers](https://img.shields.io/badge/Cloudflare%20Workers-F38020?&logo=cloudflare&logoColor=white)](#deploy-to-cloudflare-workers) +[![Cloudflare Pages](https://img.shields.io/badge/Cloudflare%20Pages-F38020?&logo=cloudflare&logoColor=white)](#deploy-to-cloudflare-pages) [![Docker](https://img.shields.io/badge/Docker-2496ED?&logo=docker&logoColor=white)](#self-hosted-deployment) [![Podman](https://img.shields.io/badge/Podman-892CA0?&logo=podman&logoColor=white)](#self-hosted-deployment) [![Chromium](https://img.shields.io/badge/Chromium-4285F4?logo=googlechrome&logoColor=white)](#-ecosystem-integration) @@ -65,7 +65,7 @@ In-depth technical analysis article published: ***[Deep Dive into Xget: A High-P ### ⚡ Extreme Performance - Breaking Through Traditional Accelerator Bottlenecks -- **⚡ Millisecond Response**: Cloudflare's global 330+ edge nodes, average response time < 50ms +- **⚡ Millisecond Response**: Cloudflare Pages' global 330+ edge nodes, average response time < 50ms - **🌐 HTTP/3 Ultra-Fast Protocol**: Latest HTTP/3 protocol enabled, 40% reduction in connection latency, 30% increase in transmission speed - **📦 Intelligent Multi-Compression**: Triple compression algorithms (gzip, deflate, brotli), 60% improvement in transmission efficiency - **🔗 Zero-Latency Pre-Connection**: Connection warm-up and keep-alive, eliminating handshake overhead for second-level responses @@ -2351,7 +2351,7 @@ client = OpenAI( ## 🚀 Deployment -### Deploy to Cloudflare Workers +### Deploy to Cloudflare Pages #### Deployment Steps @@ -2372,16 +2372,16 @@ client = OpenAI( - Modifying only documentation files (`.md`), `LICENSE`, `.gitignore`, etc. will not trigger deployment - You can also manually trigger deployment in the GitHub Actions page -5. **Bind custom domain** (optional): Bind your custom domain in the Cloudflare Workers console +5. **Bind custom domain** (optional): Bind your custom domain in the Cloudflare Pages console After deployment completes, your Xget service will be available at: -- Worker domain: `your-worker-name.your-subdomain.workers.dev` +- Pages domain: `your-project-name.pages.dev` - Custom domain: `your-domain.com` (if bound) #### Environment Variable Configuration -You can set the following environment variables in the Cloudflare Workers console to customize configuration: +You can set the following environment variables in the Cloudflare Pages console (Settings → Environment variables) to customize configuration: - `TIMEOUT_SECONDS`: Request timeout (default: 30) - `MAX_RETRIES`: Maximum retry count (default: 3) diff --git a/README.md b/README.md index 9399baf..86d0ca6 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ xixu-me%2FXget | Trendshift -[![Cloudflare Workers](https://img.shields.io/badge/Cloudflare%20Workers-F38020?&logo=cloudflare&logoColor=white)](#部署到-cloudflare-workers) +[![Cloudflare Pages](https://img.shields.io/badge/Cloudflare%20Pages-F38020?&logo=cloudflare&logoColor=white)](#部署到-cloudflare-pages) [![Docker](https://img.shields.io/badge/Docker-2496ED?&logo=docker&logoColor=white)](#自托管部署) [![Podman](https://img.shields.io/badge/Podman-892CA0?&logo=podman&logoColor=white)](#自托管部署) [![Chromium](https://img.shields.io/badge/Chromium-4285F4?logo=googlechrome&logoColor=white)](#-生态系统集成) @@ -74,7 +74,7 @@ ### ⚡ 极速性能 - 突破传统加速器瓶颈 -- **⚡ 毫秒级响应**:Cloudflare 全球 330+ 边缘节点,平均响应时间 < 50ms +- **⚡ 毫秒级响应**:Cloudflare Pages 全球 330+ 边缘节点,平均响应时间 < 50ms - **🌐 HTTP/3 极速协议**:启用最新 HTTP/3 协议,连接延迟降低 40%,传输速度提升 30% - **📦 智能多重压缩**:gzip、deflate、brotli 三重压缩算法,传输效率提升 60% - **🔗 零延迟预连接**:连接预热和保持活跃,消除握手开销,实现秒级响应 @@ -2361,14 +2361,14 @@ client = OpenAI( ## 🚀 部署 -### 部署到 Cloudflare Workers +### 部署到 Cloudflare Pages #### 部署步骤 1. **fork 本存储库**:[Fork xixu-me/Xget](https://github.com/xixu-me/Xget/fork) 2. **获取 Cloudflare 凭证**: - - 访问[帐户 API 令牌](https://dash.cloudflare.com/?to=/:account/api-tokens)创建并记录 API 令牌,使用“编辑 Cloudflare Workers”模板 + - 访问[帐户 API 令牌](https://dash.cloudflare.com/?to=/:account/api-tokens)创建并记录 API 令牌,使用"编辑 Cloudflare Workers"模板 - 访问 [Workers 和 Pages](https://dash.cloudflare.com/?to=/:account/workers-and-pages) 记录 Account ID 3. **配置 GitHub Secrets**: @@ -2382,16 +2382,16 @@ client = OpenAI( - 仅修改文档文件(`.md`)、`LICENSE`、`.gitignore` 等不会触发部署 - 也可以在 GitHub Actions 页面手动触发部署 -5. **绑定自定义域名**(可选):在 Cloudflare Workers 控制台中绑定你的自定义域名 +5. **绑定自定义域名**(可选):在 Cloudflare Pages 控制台中绑定你的自定义域名 部署完成后,你的 Xget 服务将在以下地址可用: -- Worker 域名:`your-worker-name.your-subdomain.workers.dev` +- Pages 域名:`your-project-name.pages.dev` - 自定义域名:`your-domain.com`(如果已绑定) #### 环境变量配置 -你可以在 Cloudflare Workers 控制台中设置以下环境变量来自定义配置: +你可以在 Cloudflare Pages 控制台(Settings → Environment variables)中设置以下环境变量来自定义配置: - `TIMEOUT_SECONDS`:请求超时时间(默认:30) - `MAX_RETRIES`:最大重试次数(默认:3) diff --git a/functions/[[path]].js b/functions/[[path]].js new file mode 100644 index 0000000..e14aa6f --- /dev/null +++ b/functions/[[path]].js @@ -0,0 +1,69 @@ +/** + * Xget - High-performance acceleration engine for developer resources + * Copyright (C) 2025 Xi Xu + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +import { handleRequest } from '../src/index.js'; + +/** + * Cloudflare Pages Function handler for all routes. + * + * This catch-all route handler processes all incoming requests to the Xget + * acceleration engine. It delegates request processing to the main handleRequest + * function from the Worker code, maintaining full compatibility with the + * existing implementation. + * + * The [[path]] syntax in the filename creates a catch-all route that matches + * any path, allowing this single function to handle all requests to the Pages + * application. + * + * @param {Object} context - Cloudflare Pages Function context + * @param {Request} context.request - The incoming HTTP request + * @param {Object} context.env - Environment variables and bindings (KV, secrets, etc.) + * @param {Object} context.params - Route parameters (path segments from [[path]]) + * @param {Function} context.waitUntil - Extend function execution for background tasks + * @param {Function} context.next - Call next middleware in chain (not used here) + * @param {Object} context.data - Shared data between functions + * @returns {Promise} The HTTP response to return to the client + * + * @example + * // This is called automatically by Cloudflare Pages + * // User requests: https://xget.pages.dev/npm/lodash + * // Runtime invokes: onRequest(context) + * // Returns: Response with package data + * + * @example + * // Environment variables usage + * // wrangler.toml: [vars] TIMEOUT_SECONDS = "60" + * // context.env contains: { TIMEOUT_SECONDS: "60" } + * // handleRequest uses createConfig(env) to override defaults + */ +export async function onRequest(context) { + // Extract request, env, and create an execution context compatible with Workers + const { request, env, waitUntil } = context; + + // Create a minimal ExecutionContext-like object for compatibility + const ctx = { + waitUntil: waitUntil, + passThroughOnException: () => { + // Pages doesn't support passThroughOnException, so this is a no-op + console.warn('passThroughOnException is not supported in Pages Functions'); + } + }; + + // Delegate to the main request handler + return handleRequest(request, env, ctx); +} diff --git a/package.json b/package.json index b87bdd0..a9e106d 100644 --- a/package.json +++ b/package.json @@ -15,13 +15,13 @@ "name": "xget", "private": false, "scripts": { - "deploy": "wrangler deploy", - "dev": "wrangler dev", - "format": "prettier --write src/ test/ *.js *.json", - "format:check": "prettier --check src/ test/ *.js *.json", - "lint": "eslint src/ test/", - "lint:fix": "eslint src/ test/ --fix", - "start": "wrangler dev", + "deploy": "wrangler pages deploy", + "dev": "wrangler pages dev public --compatibility-flags=nodejs_compat", + "format": "prettier --write src/ test/ functions/ *.js *.json", + "format:check": "prettier --check src/ test/ functions/ *.js *.json", + "lint": "eslint src/ test/ functions/", + "lint:fix": "eslint src/ test/ functions/ --fix", + "start": "wrangler pages dev public --compatibility-flags=nodejs_compat", "test": "vitest", "test:coverage": "vitest run --coverage", "test:run": "vitest run", diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..37839f0 --- /dev/null +++ b/public/index.html @@ -0,0 +1,122 @@ + + + + + + Xget - High-performance acceleration engine + + + +
+

Xget

+

High-performance acceleration engine for developer resources built on Cloudflare Pages.

+ +
+

Features

+
    +
  • Multi-platform support (40+ platforms: GitHub, npm, PyPI, Docker Hub, etc.)
  • +
  • Smart caching with protocol-aware strategies
  • +
  • HTTP Range request support for partial downloads
  • +
  • Container registry authentication proxy
  • +
  • Retry logic with exponential backoff
  • +
  • Comprehensive security headers
  • +
+
+ +
+

Usage Examples

+

GitHub: https://your-domain.pages.dev/gh/user/repo/file.txt

+

npm: https://your-domain.pages.dev/npm/package-name

+

PyPI: https://your-domain.pages.dev/pypi/package-name

+

Docker: docker pull your-domain.pages.dev/cr-docker/library/nginx

+
+ + +
+ + diff --git a/src/index.js b/src/index.js index ba96d9f..5a58855 100644 --- a/src/index.js +++ b/src/index.js @@ -739,7 +739,7 @@ function responseUnauthorized(url) { * const response = await handleRequest(request, env, ctx); * // Uses 60s timeout and 1-hour cache instead of defaults */ -async function handleRequest(request, env, ctx) { +export async function handleRequest(request, env, ctx) { try { // Create config with environment variable overrides const config = env ? createConfig(env) : CONFIG; diff --git a/vitest.config.js b/vitest.config.js index 688213c..34df9e3 100644 --- a/vitest.config.js +++ b/vitest.config.js @@ -19,7 +19,7 @@ export default defineWorkersConfig({ '*.config.js', '*.config.ts' ], - include: ['src/**/*.js', 'src/**/*.ts'], + include: ['src/**/*.js', 'src/**/*.ts', 'functions/**/*.js', 'functions/**/*.ts'], thresholds: { global: { branches: 80, diff --git a/wrangler.toml b/wrangler.toml index c18a7e4..28ccfe7 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -1,12 +1,12 @@ #:schema node_modules/wrangler/config-schema.json name = "xget" -main = "src/index.js" +pages_build_output_dir = "public" compatibility_date = "2024-10-22" compatibility_flags = ["nodejs_compat"] -workers_dev = false -[placement] -mode = "smart" +# Pages-specific configuration +# Functions are automatically loaded from the functions/ directory +# Static assets are served from the public/ directory [observability] enabled = false