Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add: Host Redirect #1455

Merged
merged 1 commit into from
May 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .github/workflows/compile_host_redirect_js.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: Compile host-redirect.min.js

on:
workflow_dispatch:
push:
branches:
- main
paths:
- "firebase.json"
- "tool/host-redirect/**"

permissions:
contents: write

env:
NODE_VERSION: 20

jobs:
compile_host_redirect_js:
if: ${{ github.actor.login != 'cfug-dev' &&
github.repository == 'cfug/flutter.cn' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
- name: Build JS
run: bash ./tool/host-redirect/build.sh
shell: bash
632 changes: 629 additions & 3 deletions firebase.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions src/content/404.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
body_class: landing-page not-found
permalink: /404.html
sitemap: false
js:
- url: /assets/js/host-redirect.min.js
---

<div class="not-found__wrapper">
Expand Down
2 changes: 2 additions & 0 deletions src/content/assets/js/host-redirect.min.js

Large diffs are not rendered by default.

11 changes: 11 additions & 0 deletions tool/host-redirect/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
node_modules/
build/
report/
coverage/
.AppleDouble
.vscode/
/.development
/.developmentx
/.xdevelopment

src/data/
21 changes: 21 additions & 0 deletions tool/host-redirect/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Amos<[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
24 changes: 24 additions & 0 deletions tool/host-redirect/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
## 临时的重定向方案

由于 OSS 部分限制的问题,
无法将大量重定向逻辑在服务端直接使用(类似 Nginx、Apache 等),

所有无法访问的链接会被重定向至 404 页,
该方案利用 404 页,
将 firebase.json 内的重定向逻辑运行在 404 页面。

关于 firebase.json 内重定向的相关资料:
> https://firebase.google.cn/docs/hosting/full-config?hl=zh-cn#redirects

### 环境

- node v20.11.0
- npm v10.2.4

### 使用

```sh
npm install

npm run build # ./build/host-redirect.min.js
```
16 changes: 16 additions & 0 deletions tool/host-redirect/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#!/usr/bin/bash

cd tool/host-redirect
npm install
npm run build

cd -
cp ./tool/host-redirect/build/host-redirect.min.js ./src/content/assets/js/host-redirect.min.js

git init
git config --global user.name "cfug-dev"
git config --global user.email "[email protected]"

git add ./src/content/assets/js/host-redirect.min.js
git commit -m "[sync] Update: host-redirect.min.js"
git push -u -f
21 changes: 21 additions & 0 deletions tool/host-redirect/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "host_redirect",
"version": "1.0.0",
"description": "",
"main": "./src/index.js",
"scripts": {
"build": "node ./src/generate_firebase_data.js && webpack"
},
"author": "AmosHuKe",
"homepage": "https://github.com/cfug/flutter.cn/tree/main/tool/host-redirect",
"license": "MIT",
"devDependencies": {
"webpack": "^5.91.0",
"webpack-cli": "^5.1.4"
},
"dependencies": {
"minimatch": "^9.0.4",
"path-to-regexp": "^6.2.2",
"re2js": "^0.4.1"
}
}
40 changes: 40 additions & 0 deletions tool/host-redirect/src/generate_firebase_data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* 读取 firebase.json 并
* 生成 firebase_json.js 文件
*/

const fs = require('fs')

// firebase.json 文件路径
const READ_FILE_FIREBASE_JSON = '../../firebase.json'
// 生成 firebase_json.js 的文件路径
const WRITE_FILE_FIREBASE_JSON_JS = './src/data/'

// 读取 JSON 文件
fs.readFile(READ_FILE_FIREBASE_JSON, 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:', err)
return
}
try {
const jsonData = JSON.parse(data)
// 生成包含 JSON 数据的 JavaScript 文件内容
const jsContent = `const data = ${JSON.stringify(jsonData, null, 2)}; export default data;`
fs.mkdir(WRITE_FILE_FIREBASE_JSON_JS, { recursive: true }, (err) => {
if (err) {
console.error('Failed to create directory:', err)
return
}
// 写入到新的 JavaScript 文件
fs.writeFile(`${WRITE_FILE_FIREBASE_JSON_JS}firebase_json.js`, jsContent, 'utf8', (err) => {
if (err) {
console.error('Error writing the file:', err)
return
}
console.log('firebase_json.js file has been generated successfully!')
})
})
} catch (parseErr) {
console.error('Error parsing JSON:', parseErr)
}
})
83 changes: 83 additions & 0 deletions tool/host-redirect/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { RE2JS } from 're2js'
import { minimatch } from 'minimatch'
import { pathToRegexp, match, parse, compile } from 'path-to-regexp'
import data from './data/firebase_json.js'

const currentPath = window.location.pathname
const redirect = getRedirect(currentPath)
console.log('Redirect: ', redirect)
if (redirect) {
window.location.href = redirect
}

/**
* 获取重定向路由
*
* @param {String} currentPath 当前路由
* @returns {String | null} 重定向路由
*/
function getRedirect(currentPath) {
const redirects = data.hosting.redirects
for (const redirect of redirects) {
try {
// redirects[].regex
if (redirect.regex) {
const regexp = RE2JS.compile(redirect.regex)
const regexpMatcher = regexp.matcher(currentPath)
if (regexpMatcher.matches()) {
let destination = redirect.destination

// 处理有命名的变量(类似 P<name>)
const namedGroups = regexp.namedGroups()
if (Object.keys(namedGroups).length > 0) {
for (const name in namedGroups) {
destination = destination.replace(`:${name}`, regexpMatcher.group(name))
}
}

// 处理未命名的变量
const groupCount = regexpMatcher.groupCount()
if (groupCount > 0) {
for (let i = 0; i < groupCount; i++) {
destination = destination.replace(`:${i}`, regexpMatcher.group(i))
}
}
return destination
}
}

// redirects[].source
if (redirect.source) {
// Glob
const globMatch = minimatch(currentPath, redirect.source)
if (globMatch) {
return redirect.destination
}

// Regexp
const regexpMatch = pathToRegexp(redirect.source).exec(currentPath)
if (regexpMatch) {
let destination = redirect.destination
const params = parse(redirect.source)
for (let i = 0; i < params.length; i++) {
const { name, modifier } = params[i]
// 处理有命名的变量(类似 :name 、:name* 、:name? 等)
if (name) {
destination = destination.replace(`:${name}${modifier}`, regexpMatch[i])
}

// 处理未命名的变量
if (!name) {
destination = destination.replace(`:${i}`, params[i])
}
}
return destination
}

}
} catch (error) { }
}
return null
}

export { getRedirect }
15 changes: 15 additions & 0 deletions tool/host-redirect/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const path = require('path');

module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'host-redirect.min.js',
library: 'hostRedirect',
},
mode: 'production',
performance: {
maxEntrypointSize: 512000,
maxAssetSize: 512000,
},
};
Loading