chore: apply codex repair updates (tracked files only)

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-11-29 21:51:04 +08:00
parent f40774ddd3
commit 42f0f41bf1
148 changed files with 5393 additions and 4784 deletions

View File

@ -65,6 +65,12 @@ WX_PAY_ENV=0
# PHOTON_BASE_URL=https://photon.komoot.io
# SOCIAL_GEO_USE_PB=true
# SOCIAL_TRIPS_COLLECTION=social_trips
# Hub fork of social (independent process :8025 locally)
# HUB_API_URL=https://nomadro.com
# HUB_ENABLED=true
# HUB_DB_PATH=
# HUB_GEO_USE_PB=true
# HUB_TRIPS_COLLECTION=hub_trips
# PB_URL=http://127.0.0.1:8090
# PB_ADMIN_EMAIL=
# PB_ADMIN_PASSWORD=

1
.gitignore vendored
View File

@ -18,6 +18,7 @@ node_modules/
# next.js / builds
/.next/
/.next-*/
/out/
/apps/**/.next/
/apps/**/out/

View File

@ -15,6 +15,7 @@ Follow `.cursor/rules/*.mdc`。
| Layer | Path |
|---|---|
| Next portal(.com 主 / .cn 同步) | `src/app` + `src/modules` |
| **Hub(social 独立副本)** | `/hub` · `src/modules/hub` + `src/app/hub` · `hub_svc` `/api/hub/v1` · `hub_main :8025` · 后台 `/{lane}/hub/*`。**勿改** `/social` 业务代码 |
| Remote work | 读 Planka/Etherpad 域模型后自研:Next `src/modules/work` + FastAPI `apps/api/services/work_svc`(`/api/work/v1`,`work_main.py :8021`)。禁止 iframe/二级域 |
| Notify | 读 Novu 域模型后自研:Next `src/modules/notify` + FastAPI `apps/api/services/notify_svc`(`/api/notify/v1`,`notify_main.py :8023`)。禁止 iframe/二级域 |
| Coffeechat booking | 读 Cal.com 域模型后自研:Next `src/modules/coffee` + FastAPI `coffee_svc`(`/api/coffee/v1`,`coffee_main.py :8024`),挂 `/social/coffeechat`。禁止 iframe/二级域 |
@ -33,6 +34,8 @@ Remote config: `POST /api/config/pull` · `WS /api/config/ws` · offline default
**全端小程序禁止 web-view**(微信 / 抖音 / 小红书 / H5 SoT):业务内容必须原生页;见 `.cursor/rules/no-webview-content.mdc`。
**受众模块**:`src/modules/audience/{cn,intl}` — 支付/登录/关注/文案/VIP/埋点/社群全模块化;`resolveAudienceBundle()`。后台登录后选 `/cn`|`/intl`。见 `audience-cn-intl.mdc`。
**受众模块**:`src/modules/audience/{cn,intl}` — 支付/登录/关注/文案/VIP/埋点/社群全模块化;`resolveAudienceBundle()`。见 `audience-cn-intl.mdc`。
**admin.nomadro.com 真分轨**:登录选轨后 **cn → `/cn/hub/*`(中文 Hub)** · **intl → `/intl/social/*`(国际 Social)**;侧栏互不混挂;误入对方社区路径自动改写。中文门户三大公开模块 = 导航 `/nav` · 小册 `/book` · Hub `/hub`(不是 `/social`)。
H5 游戏(Nomad Day 3D)冷冻:勿改 `apps/miniprogram/h5/src/modules/game` / `pages/game`,除非用户明确要求。

View File

@ -1,5 +1,7 @@
# Nomadro
> 2026-11-29 本地跨项目检查与修复:[审计记录、验证结果和剩余问题](docs/code-audit-2026-11-29.md)。日常检查:`pnpm typecheck:all`、`pnpm test:local`。本次修复未部署。
> **Hub `.com` 已发布**:`20261128T165939Z`(本地 2026-11-29),门户 [nomadro.com/hub](https://nomadro.com/hub) + Hub API + [admin.nomadro.com](https://admin.nomadro.com/) 中文轨。构建 `OfO3HMXd-HIAPfsB7UgKC`;[检查、发布与回滚记录](docs/hub-audit-2026-11-29.md)。未同步 `.cn`、VIP hackrobot 或小程序。
> **管理后台域名铁律(永远禁止混淆)**

View File

@ -42,6 +42,10 @@ apps/api/.venv/Scripts/python.exe -m unittest discover -s apps/api/tests -v
| `services/community_svc` | 原 community-api | `/api/v1/*` |
| `services/pay_svc` | 原 payjsapi | `/nomadvip` `/digital` `/api/meetup` … |
## Hub API(`hub_svc` · `:8025`)
中文游民社区独立进程:`hub_main.py` → `http://127.0.0.1:8025`,路由前缀 `/api/hub/v1`(presence / chat / roster / geo)。Centrifugo 频道用 `hub:` 前缀,与 `social_svc` 的 `social:` 隔离。体验台与 UGC 管理仍走 ebook 管理接口 `/api/admin/hub/ugc/*`(写 remote-config)。本地:`pnpm dev:hub-api` / `scripts/dev-hub.ps1`。
## 本地
```bash

View File

@ -24,12 +24,14 @@ def available_times(day: str, schedule: dict, event: dict, bookings: list[dict],
for window in schedule.get('availability') or []:
if local_date.strftime('%A') not in window.get('days', []): continue
first, last = int(window['startTime']), int(window['endTime'])
window_end = (midnight + timedelta(minutes=last)).astimezone(timezone.utc)
for minute in range(first, last - length + 1, interval):
start_local = midnight + timedelta(minutes=minute)
start = start_local.astimezone(timezone.utc)
# Skip nonexistent wall-clock times during a daylight-saving jump.
if start.astimezone(tz).replace(tzinfo=None) != start_local.replace(tzinfo=None): continue
end = start + timedelta(minutes=length)
if end > window_end: continue
if start <= now: continue
if any(start - before < busy_end and end + after > busy_start for busy_start, busy_end in occupied): continue
key = start.strftime('%Y-%m-%dT%H:%M:%SZ')

View File

@ -88,6 +88,9 @@ from ebook_svc.routers import social_ops_admin # noqa: E402
from ebook_svc.routers import social_ugc_admin # noqa: E402
from ebook_svc.routers import social_locale_geo_admin # noqa: E402
from ebook_svc.routers import social_blog_admin # noqa: E402
from ebook_svc.routers import hub_ugc_admin # noqa: E402
from ebook_svc.routers import hub_locale_geo_admin # noqa: E402
from ebook_svc.routers import hub_blog_admin # noqa: E402
from ebook_svc.routers import community_admin # noqa: E402
app.include_router(weapp_switches_admin.router)
@ -96,6 +99,9 @@ app.include_router(social_ops_admin.router)
app.include_router(social_ugc_admin.router)
app.include_router(social_locale_geo_admin.router)
app.include_router(social_blog_admin.router)
app.include_router(hub_ugc_admin.router)
app.include_router(hub_locale_geo_admin.router)
app.include_router(hub_blog_admin.router)
app.include_router(community_admin.router)
# 运营:ntfy 状态 / 试推(admin.nomadro.com)
from ebook_svc.routers import ops_admin # noqa: E402

View File

@ -30,6 +30,8 @@ MODULE_KEYS = (
"community",
"social",
"socialBlog",
"hub",
"hubBlog",
"vip",
"destinations",
"meetups",
@ -39,13 +41,18 @@ DEFAULT_MODULES: dict[str, dict[str, Any]] = {
"home": {"enabled": True, "title": "首页", "tabLabel": "首页"},
"nav": {"enabled": True, "title": "出海导航", "tabLabel": "导航"},
"book": {"enabled": True, "title": "数字游民小册", "tabLabel": "小册"},
"community": {"enabled": True, "title": "旅居社群", "tabLabel": "社群"},
# 对齐线上 remote-config:游民社区 / pages/social/index;缺省开启,写入只改 enabled
# 中文公开三大=导航/小册/Hub;旅居等默认关,后台可开
"community": {
"enabled": False,
"title": "旅居社群",
"tabLabel": "社群",
"note": "默认隐藏;后台可开",
},
"social": {
"enabled": True,
"title": "游民社区",
"tabLabel": "社区",
"note": "Taro 原生 pages/social · 开关不碰业务库",
"note": "国际 /social · 勿与中文 Hub 混用",
},
"socialBlog": {
"enabled": True,
@ -53,9 +60,21 @@ DEFAULT_MODULES: dict[str, dict[str, Any]] = {
"tabLabel": "Blog",
"note": "/social/blog · EN long-form · AdSense",
},
"hub": {
"enabled": True,
"title": "游民社区",
"tabLabel": "社区",
"note": "中文门户 /portal → /hub/home · 独立于 /social",
},
"hubBlog": {
"enabled": False,
"title": "Hub Blog",
"tabLabel": "Hub Blog",
"note": "/hub/blog",
},
"vip": {"enabled": False, "title": "会员中心"},
"destinations": {"enabled": True, "title": "目的地"},
"meetups": {"enabled": True, "title": "活动"},
"destinations": {"enabled": False, "title": "目的地", "note": "默认隐藏"},
"meetups": {"enabled": False, "title": "活动", "note": "默认隐藏"},
"game": {"enabled": False, "title": "数字游民", "note": "冻结隐藏 · 勿开入口"},
}

View File

@ -22,17 +22,17 @@ CENTRIFUGO_TOKEN_SECRET = os.getenv("CENTRIFUGO_TOKEN_SECRET", "")
# 浏览器 WebSocket(经 nginx 反代,与门户同域)
CENTRIFUGO_WS_URL = os.getenv(
"CENTRIFUGO_WS_URL",
"wss://nomadro.cn/rt/connection/websocket",
"wss://nomadro.com/rt/connection/websocket",
)
# 原生音视频厅(SRS RTMP 推 / HTTP-FLV 拉)— 微信 LivePusher/LivePlayer
LIVE_RTMP_PUSH_BASE = os.getenv(
"LIVE_RTMP_PUSH_BASE",
"rtmp://82.157.112.245/live",
"rtmp://nomadro.com/live",
)
LIVE_HTTP_PLAY_BASE = os.getenv(
"LIVE_HTTP_PLAY_BASE",
"https://nomadro.cn/live",
"https://nomadro.com/live",
)
LIVE_STREAM_SECRET = os.getenv(
"LIVE_STREAM_SECRET",

View File

@ -6,6 +6,7 @@ import time
from typing import Any
import httpx
from nomadro_pb import pb_quote
from .config import (
PB_ADMIN_EMAIL,
@ -91,11 +92,11 @@ def ensure_collection() -> bool:
body = {
"name": name,
"type": "base",
"listRule": "",
"viewRule": "",
"createRule": "",
"updateRule": "",
"deleteRule": "",
"listRule": None,
"viewRule": None,
"createRule": None,
"updateRule": None,
"deleteRule": None,
"fields": [
{"name": "guest_id", "type": "text", "required": True},
{"name": "city_id", "type": "text", "required": False},
@ -215,13 +216,13 @@ def list_trips(
ensure_collection()
filters: list[str] = []
if guest_id:
filters.append(f'guest_id="{guest_id}"')
filters.append(f'guest_id={pb_quote(guest_id)}')
if city_id:
filters.append(f'city_id="{city_id}"')
filters.append(f'city_id={pb_quote(city_id)}')
if visibility:
filters.append(f'visibility="{visibility}"')
filters.append(f'visibility={pb_quote(visibility)}')
if status:
filters.append(f'status="{status}"')
filters.append(f'status={pb_quote(status)}')
params: dict[str, Any] = {
"page": 1,
"perPage": max(1, min(limit, 500)),
@ -271,19 +272,12 @@ def upsert_trip(trip: dict[str, Any]) -> dict[str, Any] | None:
tid = trip.get("id") or ""
try:
with httpx.Client(timeout=10.0) as client:
if tid:
if tid and not tid.startswith("trip_"):
r = client.patch(
f"{base}/api/collections/{col}/records/{tid}",
headers=headers,
json=payload,
)
if r.status_code >= 400:
# maybe id is sqlite-local; create new
r = client.post(
f"{base}/api/collections/{col}/records",
headers=headers,
json=payload,
)
else:
r = client.post(
f"{base}/api/collections/{col}/records",

View File

@ -1,10 +1,11 @@
"""Trips store: SQLite always; PocketBase preferred SoT when reachable."""
"""Hub trips use PocketBase; legacy SQLite helpers remain inactive."""
from __future__ import annotations
import time
import uuid
from datetime import date
from typing import Any
from fastapi import HTTPException
from . import geo_pb
from .geo_cities import (
@ -104,7 +105,10 @@ def list_trips(**kwargs: Any) -> list[dict[str, Any]]:
pb = geo_pb.list_trips(**kwargs)
if pb is not None:
return pb
return list_trips_sqlite(**kwargs)
# Public city catalogs remain available without inventing live arrivals.
if kwargs.get("visibility") == "public" and not kwargs.get("guest_id"):
return []
raise HTTPException(status_code=503, detail="行程服务暂不可用,请稍后重试")
def save_trip_sqlite(trip: dict[str, Any]) -> dict[str, Any]:
@ -184,11 +188,9 @@ def create_trip(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
if trip["status"] not in {"here", "planned", "past"}:
trip["status"] = "planned"
pb = geo_pb.upsert_trip(trip)
if pb:
# keep local mirror with PB id
trip = pb
save_trip_sqlite(trip)
return trip
if pb is None:
raise HTTPException(status_code=503, detail="行程未保存,请稍后重试")
return pb
def update_trip(guest_id: str, trip_id: str, payload: dict[str, Any]) -> dict[str, Any] | None:
@ -197,10 +199,6 @@ def update_trip(guest_id: str, trip_id: str, payload: dict[str, Any]) -> dict[st
if t["id"] == trip_id:
existing = t
break
if not existing:
# try sqlite only
rows = list_trips_sqlite(guest_id=guest_id, visibility=None, limit=500)
existing = next((t for t in rows if t["id"] == trip_id), None)
if not existing:
return None
city = (payload.get("city") or existing["city"]).strip()
@ -247,26 +245,16 @@ def update_trip(guest_id: str, trip_id: str, payload: dict[str, Any]) -> dict[st
if trip["lat"] is not None and trip["lng"] is not None:
trip["h3_cell"] = latlng_to_cell(float(trip["lat"]), float(trip["lng"]))
pb = geo_pb.upsert_trip(trip)
if pb:
trip = pb
save_trip_sqlite(trip)
return trip
if pb is None:
raise HTTPException(status_code=503, detail="行程未保存,请稍后重试")
return pb
def delete_trip(guest_id: str, trip_id: str) -> bool:
pb = geo_pb.delete_trip(trip_id, guest_id)
ensure_trips_schema()
with db() as conn:
cur = conn.execute(
"DELETE FROM trips WHERE id = ? AND guest_id = ?",
(trip_id, guest_id),
)
local = cur.rowcount > 0
if pb is True:
return True
if pb is False and not local:
return False
return local or pb is not False
if pb is None:
raise HTTPException(status_code=503, detail="行程未删除,请稍后重试")
return pb
def map_cities() -> list[dict[str, Any]]:

View File

@ -13,6 +13,9 @@ log = logging.getLogger("hub_svc.photon")
def _norm_feature(f: dict[str, Any]) -> dict[str, Any] | None:
props = f.get("properties") or {}
# Hub's current city scope is CN. Retain global normalization below.
if str(props.get("countrycode") or "").upper() != "CN":
return None
geom = f.get("geometry") or {}
coords = geom.get("coordinates") or []
if len(coords) < 2:

View File

@ -18,7 +18,7 @@ from hub_svc.realtime import (
publish_live_event,
)
router = APIRouter(tags=["social"])
router = APIRouter(tags=["hub"])
def _guest(
@ -631,7 +631,7 @@ async def avatar_pose_challenge(
video: UploadFile | None = File(default=None),
email: str | None = Form(default=None),
x_hub_guest_id: str | None = Header(default=None),
x_social_email: str | None = Header(default=None),
x_social_email: str | None = Header(default=None, alias="X-Hub-Email"),
guest: str | None = Query(default=None),
):
"""Live selfie: front + turn frames + optional full camera recording for audit."""
@ -795,7 +795,9 @@ def liveness_audits(
limit: int = Query(default=40, ge=1, le=200),
x_hub_guest_id: str | None = Header(default=None),
):
"""Admin-oriented list of liveness recordings (guest header still required)."""
"""Recordings are available through authenticated admin UGC routes only."""
raise HTTPException(status_code=403, detail="自拍核验记录仅对管理后台开放")
_guest(x_hub_guest_id)
store.init_db()
return {
@ -1165,7 +1167,7 @@ def put_my_roster(
def post_feedback(
body: FeedbackIn,
x_hub_guest_id: str | None = Header(default=None),
x_social_email: str | None = Header(default=None),
x_social_email: str | None = Header(default=None, alias="X-Hub-Email"),
user_agent: str | None = Header(default=None, alias="User-Agent"),
):
guest = _guest(x_hub_guest_id)
@ -1534,6 +1536,10 @@ def resolve_report(
body: ReportResolveIn,
x_hub_guest_id: str | None = Header(default=None),
):
# Moderation is available only through the authenticated admin UGC API.
# A client-supplied guest ID is not an administrator credential.
raise HTTPException(status_code=403, detail="请通过管理后台处理举报")
from hub_svc import community_board as board
from hub_svc.notify_bridge import notify_report_result
@ -1562,6 +1568,8 @@ def get_reports(
limit: int = Query(default=40, ge=1, le=100),
x_hub_guest_id: str | None = Header(default=None),
):
raise HTTPException(status_code=403, detail="举报列表仅对管理后台开放")
from hub_svc import community_board as board
_guest(x_hub_guest_id)

View File

@ -14,7 +14,9 @@ log = logging.getLogger("nomadro_pb")
class PocketBaseError(RuntimeError):
pass
def __init__(self, message: str, *, status_code: int | None = None) -> None:
super().__init__(message)
self.status_code = status_code
def pb_quote(value: str) -> str:
@ -72,7 +74,7 @@ class PocketBaseClient:
detail = res.json()
except Exception:
detail = res.text
raise PocketBaseError(f"PocketBase {res.status_code}: {detail}")
raise PocketBaseError(f"PocketBase {res.status_code}: {detail}", status_code=res.status_code)
if not res.content:
return None
return res.json()
@ -111,8 +113,10 @@ class PocketBaseClient:
def get_collection(self, name: str) -> dict[str, Any] | None:
try:
return self.request("GET", f"/api/collections/{name}", admin=True)
except PocketBaseError:
except PocketBaseError as exc:
if exc.status_code == 404:
return None
raise
def create_collection(self, body: dict[str, Any]) -> dict[str, Any]:
return self.request("POST", "/api/collections", admin=True, json=body)

View File

@ -335,6 +335,40 @@ SOCIAL_ARCHIVES = _base(
],
)
def _hub_clone(social_spec: dict[str, Any]) -> dict[str, Any]:
"""Clone a social_* collection schema to hub_* (independent /hub fork)."""
name = str(social_spec["name"])
if not name.startswith("social_"):
raise ValueError(f"expected social_* collection, got {name}")
hub_name = "hub_" + name[len("social_") :]
indexes = []
for raw in social_spec.get("indexes") or []:
indexes.append(
str(raw)
.replace(f"idx_social_", "idx_hub_")
.replace(f" ON {name} ", f" ON {hub_name} ")
.replace(f" ON {name}(", f" ON {hub_name}(")
)
return _base(hub_name, list(social_spec["fields"]), indexes or None)
HUB_ROSTER = _hub_clone(SOCIAL_ROSTER)
HUB_LIVENESS = _hub_clone(SOCIAL_LIVENESS)
HUB_SKILLS = _hub_clone(SOCIAL_SKILLS)
HUB_REVIEWS = _hub_clone(SOCIAL_REVIEWS)
HUB_BLOCKS = _hub_clone(SOCIAL_BLOCKS)
HUB_REPORTS = _hub_clone(SOCIAL_REPORTS)
HUB_MESSAGES = _hub_clone(SOCIAL_MESSAGES)
HUB_CHANNEL_META = _hub_clone(SOCIAL_CHANNEL_META)
HUB_CHANNEL_READS = _hub_clone(SOCIAL_CHANNEL_READS)
HUB_FILES = _hub_clone(SOCIAL_FILES)
HUB_TRIPS = _hub_clone(SOCIAL_TRIPS)
HUB_CAFE_REVIEWS = _hub_clone(SOCIAL_CAFE_REVIEWS)
HUB_FEEDBACK = _hub_clone(SOCIAL_FEEDBACK)
HUB_JOIN_LEADS = _hub_clone(SOCIAL_JOIN_LEADS)
HUB_GIG_APPS = _hub_clone(SOCIAL_GIG_APPS)
HUB_ARCHIVES = _hub_clone(SOCIAL_ARCHIVES)
# —— Coffee ——
COFFEE_HOSTS = _base(
"coffee_hosts",
@ -559,6 +593,22 @@ ALL_COLLECTIONS: list[dict[str, Any]] = [
SOCIAL_JOIN_LEADS,
SOCIAL_GIG_APPS,
SOCIAL_ARCHIVES,
HUB_ROSTER,
HUB_LIVENESS,
HUB_SKILLS,
HUB_REVIEWS,
HUB_BLOCKS,
HUB_REPORTS,
HUB_MESSAGES,
HUB_CHANNEL_META,
HUB_CHANNEL_READS,
HUB_FILES,
HUB_TRIPS,
HUB_CAFE_REVIEWS,
HUB_FEEDBACK,
HUB_JOIN_LEADS,
HUB_GIG_APPS,
HUB_ARCHIVES,
COFFEE_HOSTS,
COFFEE_SCHEDULES,
COFFEE_EVENT_TYPES,

View File

@ -45,6 +45,13 @@ class CoffeeSchedulingTests(unittest.TestCase):
result = available_times('2026-11-09', schedule, self.event, [], datetime(2026, 1, 1, tzinfo=timezone.utc))
self.assertEqual(len(result), len({row['start'] for row in result}))
def test_dst_spring_forward_meeting_must_finish_within_window(self):
schedule = {'timezone': 'America/New_York', 'availability': [
{'days': ['Sunday'], 'startTime': 60, 'endTime': 180}]}
event = {'active': True, 'length_minutes': 60, 'slot_interval': 30}
result = available_times('2026-03-08', schedule, event, [], datetime(2026, 1, 1, tzinfo=timezone.utc))
self.assertEqual([row['local'] for row in result], ['01:00'])
if __name__ == '__main__':
unittest.main()

View File

@ -89,3 +89,18 @@ class PocketBaseClientTests(unittest.TestCase):
return httpx.Response(200, json={'token': 'legacy'})
self.assertEqual(self.client(handler).admin_token(), 'legacy')
def test_collection_lookup_only_treats_404_as_missing(self):
for status in [404, 403, 500, 503]:
with self.subTest(status=status):
def handler(request):
if request.url.path.endswith('auth-with-password'):
return httpx.Response(200, json={'token': 'valid'})
return httpx.Response(status, json={'message': 'lookup failed'})
client = self.client(handler)
if status == 404:
self.assertIsNone(client.get_collection('records'))
else:
with self.assertRaises(PocketBaseError) as raised:
client.get_collection('records')
self.assertEqual(raised.exception.status_code, status)

View File

@ -3,6 +3,7 @@
* 内容 SoT 仍是仓库 Markdown;本页管线上运营与广告展示。
*/
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import { api } from '../api/client'
import { useConfigLive } from '../lib/useConfigLive'
import { useDraft } from '../lib/useDraft'
@ -64,6 +65,9 @@ function draftFrom(overview: Overview) {
}
export default function Blog() {
const { lane } = useParams()
const community = lane === 'cn' ? 'hub' : 'social'
const endpoint = `/api/admin/${community}/blog`
const live = useConfigLive()
const [tab, setTab] = useState<TabKey>('posts')
const [ov, setOv] = useState<Overview | null>(null)
@ -89,8 +93,8 @@ export default function Blog() {
setErr('')
try {
const [overview, list] = await Promise.all([
api<Overview>('/api/admin/social/blog/overview'),
api<{ items?: Post[] }>('/api/admin/social/blog/posts'),
api<Overview>(`${endpoint}/overview`),
api<{ items?: Post[] }>(`${endpoint}/posts`),
])
setOv(overview)
setPosts(Array.isArray(list.items) ? list.items : [])
@ -99,13 +103,13 @@ export default function Blog() {
const msg = e instanceof Error ? e.message : '加载失败'
setErr(
/not found/i.test(msg)
? 'Blog 管理接口未部署(/api/admin/social/blog)。请联系运维推送 social_blog_admin。'
? `Blog 管理接口未部署(${endpoint})。请联系运维检查 ${community}_blog_admin。`
: msg,
)
} finally {
setLoading(false)
}
}, [])
}, [endpoint, community])
useEffect(() => {
void load()
@ -130,7 +134,7 @@ export default function Blog() {
setMsg('')
setErr('')
try {
const next = await api<Overview>('/api/admin/social/blog/ops', {
const next = await api<Overview>(`${endpoint}/ops`, {
method: 'PATCH',
body: JSON.stringify({ ...body, expectedVersion: ov.version }),
})
@ -138,7 +142,7 @@ export default function Blog() {
editor.accept(draftFrom(next), Object.keys(body) as Array<keyof typeof draft>)
setMsg(okHint)
try {
const list = await api<{ items?: Post[] }>('/api/admin/social/blog/posts')
const list = await api<{ items?: Post[] }>(`${endpoint}/posts`)
setPosts(Array.isArray(list.items) ? list.items : [])
} catch { setErr('修改已保存,文章列表刷新失败,请点刷新重试') }
} catch (e: unknown) {
@ -164,18 +168,17 @@ export default function Blog() {
<div className="com-page com-blog-admin">
<header className="com-page-head com-page-head-row">
<div>
<h1>Nomad Blog</h1>
<h1>{community === 'hub' ? 'Hub 游民手记' : 'Nomad Blog'}</h1>
<p>
管理 <code>/social/blog</code>:文章显隐、置顶、AdSense 与模块开关。正文仍在仓库 Markdown(Tina
式 Git SoT)。
管理 <code>/{community}/blog</code>:文章显隐、置顶与模块开关。正文在本轨独立内容目录维护。
</p>
<div className="com-chip-row">
<span className={`com-chip${ov?.moduleEnabled ? ' com-chip-ok' : ''}`}>
模块 {ov?.moduleEnabled ? '开' : '关'}
</span>
<span className={`com-chip${ov?.adsenseEnabled ? ' com-chip-ok' : ''}`}>
{community !== 'hub' ? <span className={`com-chip${ov?.adsenseEnabled ? ' com-chip-ok' : ''}`}>
AdSense {ov?.adsenseEnabled ? '展示中' : '关闭'}
</span>
</span> : null}
{ov?.version != null ? <span className="com-chip">v{ov.version}</span> : null}
</div>
</div>
@ -210,9 +213,9 @@ export default function Blog() {
<strong>{ov?.counts?.hidden ?? '—'}</strong>
</article>
<article className="com-stat">
<span className="com-stat-label">广告就绪</span>
<strong>{adsReady ? '是' : '否'}</strong>
<span className="com-stat-note">{adsReady ? 'client + slot' : '先填 clientId / slot'}</span>
<span className="com-stat-label">{community === 'hub' ? '内容受众' : '广告就绪'}</span>
<strong>{community === 'hub' ? '中文' : adsReady ? '是' : '否'}</strong>
<span className="com-stat-note">{community === 'hub' ? 'Hub 独立内容' : adsReady ? 'client + slot' : '先填 clientId / slot'}</span>
</article>
</div>
@ -236,7 +239,7 @@ export default function Blog() {
</div>
<nav className="com-tabs" aria-label="博客运营">
{TABS.map((t) => (
{TABS.filter((t) => community !== 'hub' || t.key !== 'adsense').map((t) => (
<button
key={t.key}
type="button"
@ -409,9 +412,9 @@ export default function Blog() {
<div className="com-panel-head">
<div>
<h2>模块与运营文案</h2>
<p>关闭 modules.socialBlog 可隐藏入口(需门户读配置)。</p>
<p>关闭 modules.{community}Blog 可隐藏本轨博客入口及文章。</p>
</div>
<label className="com-switch" title="socialBlog">
<label className="com-switch" title={`${community}Blog`}>
<input
type="checkbox"
aria-label="博客模块开关"

View File

@ -10,16 +10,11 @@ if (!process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY) {
}
}
/** 低配服务器构建:限制并行与 Turbopack 目标内存,避免 pnpm build 把机器拖死 / OOM */
/** 低配服务器构建限制并行;Node 堆上限由 package.json 的 build 命令控制。 */
const buildCpuCount = Math.max(
1,
Number.parseInt(process.env.NEXT_BUILD_CPUS ?? "1", 10) || 1,
);
const turbopackMemoryMb = Math.max(
256,
Number.parseInt(process.env.NEXT_BUILD_TURBOPACK_MEMORY_MB ?? "1536", 10) ||
1536,
);
const nextConfig: NextConfig = {
// 不暴露 X-Powered-By: Next.js
@ -63,7 +58,6 @@ const nextConfig: NextConfig = {
experimental: {
cpus: buildCpuCount,
memoryBasedWorkersCount: true,
turbopackMemoryLimit: turbopackMemoryMb * 1024 * 1024,
// 仅 next dev(NODE_ENV=development)建议开启,避免栈帧过滤读到 null source map 控制台报错
// 生产 build 默认关闭以省内存;需要 Sentry 等可设 NEXT_BUILD_TURBOPACK_SOURCE_MAPS=1
turbopackSourceMaps:

View File

@ -13,10 +13,10 @@
"geist": "^1.7.0",
"github-markdown-css": "^5.9.0",
"marked": "^17.0.4",
"next": "16.1.6",
"next": "16.4.6",
"pocketbase": "^0.26.8",
"react": "19.2.3",
"react-dom": "19.2.3",
"react": "19.2.9",
"react-dom": "19.2.9",
"three": "^0.183.2"
},
"devDependencies": {
@ -26,7 +26,7 @@
"@types/react-dom": "^19",
"@types/three": "^0.183.1",
"eslint": "^9",
"eslint-config-next": "16.1.6",
"eslint-config-next": "16.4.6",
"tailwindcss": "^4",
"typescript": "^5"
},

File diff suppressed because it is too large Load Diff

View File

@ -26,7 +26,7 @@ const h5ViteProxy = {
}
export default defineConfig(async (merge) => {
const baseConfig: UserConfigExport = {
const baseConfig: UserConfigExport<'vite'> = {
projectName: 'nomadro-h5',
date: '2026-3-30',
designWidth: 750,

View File

@ -2,7 +2,7 @@ const tabBar = {
color: '#8b93a7',
selectedColor: '#4ecdc4',
backgroundColor: '#0c0c0f',
borderStyle: 'black',
borderStyle: 'black' as const,
list: [
{
pagePath: 'pages/home/index',

View File

@ -1,6 +1,7 @@
import { Component, Fragment, useEffect } from 'react'
import type { PropsWithChildren, ReactNode } from 'react'
import Taro, { useDidHide, useDidShow, useLaunch } from '@tarojs/taro'
import { Text, View } from '@tarojs/components'
import { flush, trackAppLaunch } from './utils/track'
import {
loadRemoteConfig,
@ -63,7 +64,7 @@ function App({ children }: PropsWithChildren) {
applyH5Theme('dark')
// 公众号私信卡片:pages/...?userid=OA_openid
const oa = captureOaUseridFromOptions(
(options || {}) as Record<string, unknown>,
(options || {}) as unknown as Record<string, unknown>,
)
if (oa) {
void syncOaProfileBind(true).catch(() => undefined)

View File

@ -9,6 +9,7 @@ type BoxProps = {
id?: string
children?: ReactNode
onClick?: () => void
onLongPress?: () => void
html?: string
style?: CSSProperties
'aria-hidden'?: boolean
@ -32,6 +33,7 @@ export function H5Box({
id,
children,
onClick,
onLongPress,
html,
style,
'aria-hidden': ariaHidden,
@ -87,6 +89,7 @@ export function H5Box({
className={className}
style={style}
onClick={handleClick}
onLongPress={onLongPress}
onTouchStart={onTouchStart || onPointerDown}
onTouchMove={onTouchMove || onPointerMove}
onTouchEnd={onTouchEnd || onPointerUp}
@ -102,14 +105,16 @@ export function H5Txt({
className,
id,
children,
style,
}: {
className?: string
id?: string
children?: ReactNode
style?: CSSProperties
}) {
if (isH5) return <span id={id} className={className}>{children}</span>
if (isH5) return <span id={id} className={className} style={style}>{children}</span>
return (
<Text id={id} className={className}>
<Text id={id} className={className} style={style}>
{children}
</Text>
)

View File

@ -30,7 +30,7 @@
"id": "nomadcna",
"title": "nomadcna",
"subtitle": "国内数字游民社区",
"href": "https://nomadro.com/social",
"href": "https://nomadro.com/hub",
"icon": "/icons/nomadcna.webp"
}
]

View File

@ -793,6 +793,12 @@ export function nomadCodeReadPayload(): ReadPayload {
}
],
progress: { chapter_id: "00-前言", percent: 0 },
access: { unlocked: false, is_free: false },
unlocked: false,
unlock_percent: 30,
preview_ratio: 0.3,
access: {
book_id: "default", unlocked: false, is_free: false, unlock_percent: 30,
product_id: "nomad_lite", price_fen: 2900, updated_at: 0,
},
} as ReadPayload
}

View File

@ -418,7 +418,7 @@ export default function BookCoverPage() {
void loadRemoteConfig(true)
// 预下载阅读壳,避免提审点开黑屏
try {
void Taro.loadSubPackage?.({ name: 'vip-ebook' })
void Taro.loadSubPackage?.({ name: 'vip-ebook' } as Parameters<typeof Taro.loadSubPackage>[0])
} catch {
/* ignore */
}

View File

@ -214,7 +214,7 @@ function SocialHome() {
<H5El as='nav' className='social-path' aria-label='本页导航'>
<H5El className='container'>
<H5El className='social-path-track reveal visible'>
{PATH_CHIPS.filter((p) => !hiddenSections.includes(p.href.slice(1))).map((p) => (
{PATH_CHIPS.filter((p) => !hiddenSections.some(section => section === p.href.slice(1))).map((p) => (
<H5El
as='a'
key={p.href}

View File

@ -26,6 +26,8 @@ export type Destination = {
climate?: string
nomads_count?: string
highlights?: string[]
map_x?: number
map_y?: number
}
export type Meetup = {

View File

@ -7,6 +7,8 @@ export type ChapterMeta = {
id: string
title: string
order: number
emoji?: string
unlocked?: boolean
}
export type BookDetail = {
@ -42,6 +44,7 @@ export type ReadPayload = {
price_label?: string
offer_name?: string
updated_at?: number
progress?: { chapter_id: string; percent: number }
access?: AccessSnapshot
}

View File

@ -26,7 +26,6 @@ let pollTimer: ReturnType<typeof setInterval> | null = null
let knownVersion = 0
let knownFp = ''
let configInFlight: Promise<LoadResult> | null = null
let forceQueued = false
let appVisible = true
let socketTask: Taro.SocketTask | null = null
let socketReconnect: ReturnType<typeof setTimeout> | null = null
@ -35,23 +34,8 @@ let stoppedFlag = false
function configFingerprint(cfg: NomadroRemoteConfig): string {
try {
// 必须含 copy:VIP 价/道具/CTA、小册 live bump,否则后台改档 UI 不刷新
return JSON.stringify({
v: cfg.version,
at: cfg.updatedAt,
modules: cfg.modules,
flags: cfg.flags,
copy: {
vipPriceFen: cfg.copy?.vipPriceFen,
vipProductId: cfg.copy?.vipProductId,
vipCta: cfg.copy?.vipCta,
vipOfferKey: cfg.copy?.vipOfferKey,
booksOfferRev: (cfg.copy as { booksOfferRev?: number } | undefined)?.booksOfferRev,
booksOfferBookId: (cfg.copy as { booksOfferBookId?: string } | undefined)
?.booksOfferBookId,
},
bookAudit: cfg.platforms?.weapp?.bookAudit,
})
// Every configurable field matters, including nav content and page switches.
return JSON.stringify(cfg)
} catch {
return String(cfg.version || 0)
}
@ -156,7 +140,6 @@ export function loadRemoteConfig(force = false): Promise<LoadResult> {
if (!force && memory) return Promise.resolve(memory)
if (configInFlight) {
if (force) forceQueued = true
return configInFlight
}
@ -200,10 +183,6 @@ export function loadRemoteConfig(force = false): Promise<LoadResult> {
configInFlight = pending
void pending.finally(() => {
if (configInFlight === pending) configInFlight = null
if (forceQueued) {
forceQueued = false
void loadRemoteConfig(true)
}
})
return pending
}
@ -358,7 +337,10 @@ export function startRemoteConfigLiveSync(): () => void {
if (visible) void loadRemoteConfig(true)
}, FULL_POLL_MS)
void loadRemoteConfig(true)
// Coalesce startup with onAppShow and let an immediate hide suppress the pull.
void Promise.resolve().then(() => {
if (!stoppedFlag && appVisible) return loadRemoteConfig(true)
})
const stop = () => {
stoppedFlag = true

View File

@ -242,12 +242,15 @@ export const socialApi = {
channelId: string,
opts?: { limit?: number; since?: number; before?: number; q?: string },
) => {
const q = new URLSearchParams()
if (opts?.limit) q.set('limit', String(opts.limit))
if (opts?.since != null) q.set('since', String(opts.since))
if (opts?.before != null) q.set('before', String(opts.before))
if (opts?.q) q.set('q', opts.q)
const qs = q.toString()
// Mini-program engines do not consistently provide URLSearchParams.
const query: string[] = []
const add = (key: string, value: string | number) =>
query.push(`${key}=${encodeURIComponent(String(value))}`)
if (opts?.limit) add('limit', opts.limit)
if (opts?.since != null) add('since', opts.since)
if (opts?.before != null) add('before', opts.before)
if (opts?.q) add('q', opts.q)
const qs = query.join('&')
return req<{ items: SocialChatMessage[]; seq?: number }>(
`/channels/${encodeURIComponent(channelId)}/messages${qs ? `?${qs}` : ''}`,
)

View File

@ -1,10 +1,10 @@
{
"compilerOptions": {
"target": "ES2017",
"module": "commonjs",
"module": "esnext",
"jsx": "react-jsx",
"strict": true,
"moduleResolution": "node",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"esModuleInterop": true,
"skipLibCheck": true,

View File

@ -31,7 +31,7 @@ export default defineConfig(async (merge) => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { vitePostCopySizePlugin } = require('../scripts/post-copy-size-plugin')
const baseConfig: UserConfigExport = {
const baseConfig: UserConfigExport<'vite' | 'webpack5'> = {
projectName: 'nomadro-tt',
date: '2026-3-30',
designWidth: 750,
@ -79,7 +79,7 @@ export default defineConfig(async (merge) => {
alias: {
'@': path.resolve(__dirname, '..', 'src'),
},
modifyWebpackChain(chain) {
modifyWebpackChain(chain: { plugin(name: string): { use(plugin: unknown, args?: unknown[]): unknown } }) {
if (useVite) return
// eslint-disable-next-line @typescript-eslint/no-var-requires
const CopyWebpackPlugin = require('copy-webpack-plugin')

View File

@ -25,7 +25,7 @@ export default defineAppConfig({
},
},
/** 抖音官方:app.json usePrivacyCheck(见隐私协议开发指南) */
usePrivacyCheck: true,
...{ usePrivacyCheck: true },
/** 兼容旧字段 */
__usePrivacyCheck__: true,
window: {

View File

@ -74,14 +74,16 @@ export function H5Txt({
className,
id,
children,
style,
}: {
className?: string
id?: string
children?: ReactNode
style?: CSSProperties
}) {
if (isH5) return <span id={id} className={className}>{children}</span>
if (isH5) return <span id={id} className={className} style={style}>{children}</span>
return (
<Text id={id} className={className}>
<Text id={id} className={className} style={style}>
{children}
</Text>
)

View File

@ -30,7 +30,7 @@
"id": "nomadcna",
"title": "nomadcna",
"subtitle": "国内数字游民社区",
"href": "https://nomadro.com/social",
"href": "https://nomadro.com/hub",
"icon": "/icons/nomadcna.webp"
}
]

File diff suppressed because one or more lines are too long

View File

@ -26,6 +26,8 @@ export type Destination = {
climate?: string
nomads_count?: string
highlights?: string[]
map_x?: number
map_y?: number
}
export type Meetup = {

View File

@ -12,6 +12,8 @@ export type ChapterMeta = {
id: string
title: string
order: number
emoji?: string
unlocked?: boolean
}
export type BookDetail = {
@ -47,6 +49,7 @@ export type ReadPayload = {
price_label?: string
offer_name?: string
updated_at?: number
progress?: { chapter_id: string; percent: number }
access?: AccessSnapshot
}

View File

@ -94,7 +94,13 @@ export default defineConfig(async (merge) => {
alias: {
'@': h5Src,
},
modifyWebpackChain(chain) {
modifyWebpackChain(chain: {
resolve: {
modules: { prepend(path: string): unknown }
alias: { set(key: string, value: string): unknown }
}
plugin(name: string): { use(plugin: unknown, args?: unknown[]): unknown }
}) {
const weappNm = path.resolve(__dirname, '..', 'node_modules')
const webpack = require('webpack')
chain.resolve.modules.prepend(weappNm)

View File

@ -7,7 +7,7 @@
"xhs_imgs": 120,
"xhs_budget_kb": 2867,
"xhs_used_kb": 1012,
"seconds": 3.4,
"seconds": 1.2,
"limits": {
"douyin": "main≤4MB sub≤2MB total≤16MB",
"xhs": "offline pack ≤10MB & ≤200 files; no CDN"

View File

@ -460,6 +460,8 @@ def write_xhs(chapters: list[dict], title: str) -> None:
"author": "异度世界",
"coverEmoji": "🚀",
"description": "配图按小红书小工具包体积上限精选固化(禁 CDN)。",
# 小红书小工具试读章数;赞赏解锁全书(§3.18 rewardAuthor)
"free_chapters": 3,
"tags": soft_sanitize_audit_deep(["数字游民", "云手机", "无人直播", "自动化"]),
"chapters": [
{

View File

@ -177,6 +177,24 @@ test('configuration polling pauses in background and never overlaps slow meta re
stop()
})
test('copy and page configuration updates notify subscribers without a version bump', async () => {
let config = { ...seed, copy: { navContent: 'old' }, pages: { book: true } }
const { api } = harness('services/remoteConfig.ts', {
request: async () => ({ statusCode: 200, data: { config } }),
}, seedImport)
const updates = []
const unsubscribe = api.subscribeRemoteConfig(result => updates.push(result.config))
await api.loadRemoteConfig(true)
config = { ...config, copy: { navContent: 'new' } }
await api.loadRemoteConfig(true)
config = { ...config, pages: { book: false } }
await api.loadRemoteConfig(true)
unsubscribe()
assert.equal(updates.length, 3)
assert.equal(updates[1].copy.navContent, 'new')
assert.equal(updates[2].pages.book, false)
})
test('rapid taps open one page; home resets the stack', async () => {
const gate = deferred()
let navigations = 0

View File

@ -21,7 +21,7 @@ test('reads fail over and subsequent writes use the successful origin', async ()
await api.socialApi.listMessages('general')
await api.socialApi.sendMessage('general', 'Name', 'Hello', 'key')
assert.equal(urls.length, 3)
assert.ok(urls[2].startsWith('https://api.nomadro.cn/'))
assert.equal(new URL(urls[2]).origin, new URL(urls[1]).origin)
})
test('uncertain message writes never replay across origins', async () => {
let count = 0

View File

@ -1,16 +1,17 @@
{
"extends": "../h5/tsconfig.json",
"compilerOptions": {
"target": "ES2017",
"module": "commonjs",
"module": "esnext",
"jsx": "react-jsx",
"strict": true,
"moduleResolution": "node",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"esModuleInterop": true,
"skipLibCheck": true,
"baseUrl": ".",
"paths": { "@/*": ["src/*"] },
"paths": { "@/*": ["../h5/src/*"] },
"types": ["@tarojs/taro"]
},
"include": ["src", "types", "config"]
"include": ["../h5/src", "types", "config"]
}

File diff suppressed because one or more lines are too long

View File

@ -39,6 +39,7 @@
<button type="button" class="home-xhs-btn" id="home-checkin">打卡发笔记</button>
<button type="button" class="home-xhs-btn" id="home-journal">写日记</button>
<button type="button" class="home-xhs-btn" id="home-works">我的作品</button>
<button type="button" class="home-xhs-btn home-xhs-reward is-hidden" id="home-reward">赞赏解锁</button>
</div>
<p class="home-time" id="home-time"></p>
</div>
@ -125,6 +126,7 @@
<p class="rs-cap" id="storage-cap">本地缓存 · 检测中</p>
<p class="rs-section">小红书</p>
<div class="rs-actions">
<button type="button" class="rs-action is-hidden" id="btn-reward">赞赏解锁全书</button>
<button type="button" class="rs-action" id="btn-checkin">阅读打卡发笔记</button>
<button type="button" class="rs-action" id="btn-selfie">自拍打卡发笔记</button>
<button type="button" class="rs-action" id="btn-photo-note">配图发笔记</button>

View File

@ -736,6 +736,61 @@ button {
color: var(--r-text);
}
.paywall {
margin: 28px 0 40px;
padding: 22px 14px 18px;
text-align: center;
border-top: 1px dashed var(--r-border);
background: linear-gradient(180deg, transparent, rgba(245, 158, 11, 0.08));
border-radius: 0 0 16px 16px;
}
.paywall-emoji {
display: block;
font-size: 30px;
line-height: 1;
}
.paywall-title {
display: block;
margin-top: 8px;
font-size: 20px;
font-weight: 700;
color: var(--r-text);
}
.paywall-desc {
display: block;
margin: 6px auto 0;
max-width: 16em;
font-size: 13px;
line-height: 1.45;
color: var(--r-muted);
}
.paywall-btn {
margin-top: 16px;
min-height: 44px;
min-width: 160px;
background: linear-gradient(135deg, #f59e0b, #d97706);
}
.paywall-hint {
display: block;
margin-top: 10px;
font-size: 12px;
color: var(--r-muted);
}
.drawer-item.locked .drawer-name {
opacity: 0.72;
}
.home-xhs-reward {
border-color: rgba(245, 158, 11, 0.45);
color: #f59e0b;
}
.md-body {
font-size: 16px;
line-height: 1.7;

View File

@ -11,16 +11,25 @@ ROOT = Path(__file__).resolve().parents[1]
MINI = ROOT.parent
SRC = ROOT / "tool"
OUT = ROOT / "release-book"
PACK = MINI / "scripts" / "pack-hackrobot-book.py"
PACK_CANDIDATES = (
MINI / "weapp" / "scripts" / "pack-hackrobot-book.py",
MINI / "scripts" / "pack-hackrobot-book.py",
)
def main() -> int:
check_call([sys.executable, str(ROOT / "scripts" / "sync_data.py")])
sync = ROOT / "scripts" / "sync_data.py"
if sync.is_file():
try:
check_call([sys.executable, str(sync)])
except Exception as e:
print(f"WARN sync_data failed, continue with local book seed: {e}", file=sys.stderr)
# export 会写回旧册;必须再用 hackrobot 覆盖 book-data + portal.book
if PACK.is_file():
check_call([sys.executable, str(PACK)])
pack = next((p for p in PACK_CANDIDATES if p.is_file()), None)
if pack:
check_call([sys.executable, str(pack)])
else:
print(f"WARN missing {PACK}", file=sys.stderr)
print(f"WARN missing pack-hackrobot-book.py under {PACK_CANDIDATES}", file=sys.stderr)
if OUT.exists():
shutil.rmtree(OUT, ignore_errors=True)
@ -70,6 +79,14 @@ def main() -> int:
if "低成本工作室" not in app_js or "数字游民:自动化杠杆副业" not in app_js:
print("FATAL release-book missing hackrobot chapters", file=sys.stderr)
return 1
if "rewardAuthor" not in app_js or "free_chapters" not in app_js:
print("FATAL release-book missing tip/trial unlock hooks", file=sys.stderr)
return 1
css = (OUT / "styles.css").read_text(encoding="utf-8", errors="ignore")
html = (OUT / "index.html").read_text(encoding="utf-8", errors="ignore")
if ".paywall" not in css or 'id="btn-reward"' not in html:
print("FATAL release-book missing paywall UI", file=sys.stderr)
return 1
print(f"assembled {OUT}")
for p in sorted(OUT.iterdir()):

View File

@ -8,14 +8,19 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
MINI = ROOT.parent
SCRIPT = MINI / "scripts" / "export-xhs-offline.mjs"
# SoT 在 xhs/scripts;兼容旧路径 miniprogram/scripts
CANDIDATES = (
ROOT / "scripts" / "export-xhs-offline.mjs",
MINI / "scripts" / "export-xhs-offline.mjs",
)
def main() -> int:
if not SCRIPT.is_file():
print(f"missing {SCRIPT}", file=sys.stderr)
script = next((p for p in CANDIDATES if p.is_file()), None)
if not script:
print(f"missing export-xhs-offline.mjs under {CANDIDATES}", file=sys.stderr)
return 1
return subprocess.call(["node", str(SCRIPT)], cwd=str(MINI))
return subprocess.call(["node", str(script)], cwd=str(MINI))
if __name__ == "__main__":

View File

@ -1,601 +1,4 @@
/* book-app runtime — BOOK_DATA from book/book-data.js */
(function () {
return 0;
});
}
function setLocalData(key, data, encrypt) {
var serialized;
try {
serialized = JSON.stringify(data);
} catch (e) {
return Promise.resolve(false);
}
if (typeof serialized !== "string") return Promise.resolve(false);
var useEncrypt = !!encrypt;
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
isClientVersionAtLeast(buildVersion, STORAGE_MIN) &&
mt &&
typeof mt.setStorage === "function"
) {
var payload = { key: key, data: serialized };
if (useEncrypt) payload.encrypt = true;
return Promise.resolve(mt.setStorage(payload))
.then(function () {
return true;
})
.catch(function () {
return writeBrowser(key, serialized);
});
}
return writeBrowser(key, serialized);
});
}
function writeBrowser(key, serialized) {
try {
global.localStorage.setItem(key, serialized);
return true;
} catch (e) {
return false;
}
}
function getLocalData(key, fallback, encrypt) {
var useEncrypt = !!encrypt;
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
isClientVersionAtLeast(buildVersion, STORAGE_MIN) &&
mt &&
typeof mt.getStorage === "function"
) {
var payload = { key: key };
if (useEncrypt) payload.encrypt = true;
return Promise.resolve(mt.getStorage(payload))
.then(function (res) {
var raw = res && res.data;
if (raw != null && raw !== "") {
try {
return JSON.parse(raw);
} catch (e) {
return fallback;
}
}
// Retry without encrypt (migration), then browser
if (useEncrypt) {
return Promise.resolve(mt.getStorage({ key: key }))
.then(function (res2) {
var raw2 = res2 && res2.data;
if (raw2 != null && raw2 !== "") {
try {
var parsed = JSON.parse(raw2);
return setLocalData(key, parsed, true).then(function () {
return parsed;
});
} catch (e2) {
return readBrowser(key, fallback);
}
}
return readBrowser(key, fallback);
})
.catch(function () {
return readBrowser(key, fallback);
});
}
var fromBrowser = readBrowser(key, null);
if (fromBrowser == null) return fallback;
return writeNative(mt, key, JSON.stringify(fromBrowser), false).then(
function () {
return fromBrowser;
},
function () {
return fromBrowser;
}
);
})
.catch(function () {
return readBrowser(key, fallback);
});
}
return readBrowser(key, fallback);
});
}
function writeNative(mt, key, serialized, encrypt) {
if (!mt || typeof mt.setStorage !== "function") {
return Promise.resolve(false);
}
var payload = { key: key, data: serialized };
if (encrypt) payload.encrypt = true;
return Promise.resolve(mt.setStorage(payload)).then(
function () {
return true;
},
function () {
return false;
}
);
}
function readBrowser(key, fallback) {
try {
var raw = global.localStorage.getItem(key);
if (raw == null || raw === "") return fallback;
return JSON.parse(raw);
} catch (e) {
return fallback;
}
}
function removeLocalData(key) {
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
isClientVersionAtLeast(buildVersion, STORAGE_MIN) &&
mt &&
typeof mt.removeStorage === "function"
) {
return Promise.resolve(mt.removeStorage({ key: key }))
.then(function () {
removeBrowser(key);
return true;
})
.catch(function () {
return removeBrowser(key);
});
}
return removeBrowser(key);
});
}
function clearLocalData() {
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
isClientVersionAtLeast(buildVersion, STORAGE_MIN) &&
mt &&
typeof mt.clearStorage === "function"
) {
return Promise.resolve(mt.clearStorage())
.then(function () {
clearBrowser();
return true;
})
.catch(function () {
return clearBrowser();
});
}
return clearBrowser();
});
}
function removeBrowser(key) {
try {
global.localStorage.removeItem(key);
return true;
} catch (e) {
return false;
}
}
function clearBrowser() {
try {
global.localStorage.clear();
return true;
} catch (e) {
return false;
}
}
function getLaunchOptions() {
var xhs = global.xhs;
if (xhs && xhs.launchOptions) {
return Promise.resolve(xhs.launchOptions);
}
var mt = getMiniTool();
if (!mt || typeof mt.getLaunchOptions !== "function") {
return Promise.resolve(null);
}
return Promise.resolve(mt.getLaunchOptions()).catch(function () {
return null;
});
}
/** Read miniToolSnapshotInfo from launch options (comment re-entry, §3.9). */
function readSnapshotInfo(launchOptions) {
if (!launchOptions) return null;
var raw =
launchOptions.miniToolSnapshotInfo ||
(launchOptions.query && launchOptions.query.miniToolSnapshotInfo) ||
(launchOptions.referrerInfo &&
launchOptions.referrerInfo.miniToolSnapshotInfo) ||
(launchOptions.extraData && launchOptions.extraData.miniToolSnapshotInfo);
if (!raw) return null;
if (typeof raw === "object") return raw;
try {
return JSON.parse(raw);
} catch (e) {
return null;
}
}
function callApi(name, options) {
var mt = getMiniTool();
if (!mt || typeof mt[name] !== "function") {
return Promise.reject({ errMsg: name + ":fail not available" });
}
return Promise.resolve(mt[name](options || {}));
}
function writeTempFile(dataUrl) {
return callApi("writeTempFile", { data: dataUrl }).then(function (res) {
return (res && res.filePath) || dataUrl;
});
}
function saveImageToPhotosAlbum(filePath) {
return callApi("saveImageToPhotosAlbum", { filePath: filePath });
}
function postNote(opts) {
return callApi("postNote", opts);
}
function canPostComment(buildVersion) {
var mt = getMiniTool();
return (
isClientVersionAtLeast(buildVersion, COMMENT_MIN) &&
mt &&
typeof mt.interactionOpenApi === "function"
);
}
function postComment(payload, saveToAlbum) {
return callApi("interactionOpenApi", {
payload: payload,
saveToAlbum: saveToAlbum !== false
});
}
function getStorageInfo() {
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
!isClientVersionAtLeast(buildVersion, STORAGE_MIN) ||
!mt ||
typeof mt.getStorageInfo !== "function"
) {
return null;
}
return Promise.resolve(mt.getStorageInfo()).catch(function () {
return null;
});
});
}
function canUseFileSystem(buildVersion) {
var mt = getMiniTool();
return (
isClientVersionAtLeast(buildVersion, FILE_MIN) &&
mt &&
typeof mt.writeFile === "function" &&
typeof mt.readFile === "function"
);
}
function getUserDataPath() {
return getLaunchOptions().then(function (opts) {
var env = opts && opts.miniToolEnv;
return (env && env.userDataPath) || "";
});
}
function ensureDir(dirPath) {
var mt = getMiniTool();
if (!mt || typeof mt.mkdir !== "function") {
return Promise.resolve(false);
}
return Promise.resolve(mt.mkdir({ dirPath: dirPath, recursive: true }))
.then(function () {
return true;
})
.catch(function () {
return false;
});
}
function writeUtf8File(relativePath, data) {
return getBuildVersion().then(function (bv) {
if (!canUseFileSystem(bv)) {
return Promise.reject({ errMsg: "writeFile:fail version" });
}
return getUserDataPath().then(function (root) {
if (!root) return Promise.reject({ errMsg: "writeFile:fail no path" });
var rel = String(relativePath || "").replace(/^\/+/, "");
var parts = rel.split("/");
var dir =
parts.length > 1 ? root + "/" + parts.slice(0, -1).join("/") : root;
var filePath = root + "/" + rel;
return ensureDir(dir).then(function () {
return callApi("writeFile", {
filePath: filePath,
data: typeof data === "string" ? data : JSON.stringify(data),
encoding: "utf8"
}).then(function () {
return filePath;
});
});
});
});
}
function appendUtf8File(relativePath, data) {
return getBuildVersion().then(function (bv) {
if (!canUseFileSystem(bv)) {
return Promise.reject({ errMsg: "appendFile:fail version" });
}
var mt = getMiniTool();
if (!mt || typeof mt.appendFile !== "function") {
// Fallback: read + write
return readUtf8File(relativePath).then(function (prev) {
return writeUtf8File(
relativePath,
(prev || "") + (typeof data === "string" ? data : String(data))
);
});
}
return getUserDataPath().then(function (root) {
if (!root) return Promise.reject({ errMsg: "appendFile:fail no path" });
var rel = String(relativePath || "").replace(/^\/+/, "");
var parts = rel.split("/");
var dir =
parts.length > 1 ? root + "/" + parts.slice(0, -1).join("/") : root;
var filePath = root + "/" + rel;
return ensureDir(dir).then(function () {
return callApi("appendFile", {
filePath: filePath,
data: typeof data === "string" ? data : String(data),
encoding: "utf8"
}).then(function () {
return filePath;
});
});
});
});
}
function postVideoNote(opts) {
var videoRes = { video_url: opts.videoPath };
if (opts.coverPath) videoRes.cover_url = opts.coverPath;
return callApi("postNote", {
title: opts.title,
content: opts.content,
pageType: "video_publish",
mediaInfo: {
video_resources: videoRes
}
});
}
function readUtf8File(relativePath) {
return getBuildVersion().then(function (bv) {
if (!canUseFileSystem(bv)) {
return Promise.resolve(null);
}
return getUserDataPath().then(function (root) {
if (!root) return null;
var filePath = root + "/" + String(relativePath || "").replace(/^\/+/, "");
return callApi("readFile", { filePath: filePath, encoding: "utf8" })
.then(function (res) {
return res && res.data != null ? res.data : null;
})
.catch(function () {
return null;
});
});
});
}
/** Write dataURL to temp, then optionally persist via saveFile (9.49+). */
function persistImage(dataUrl, relativePath) {
return writeTempFile(dataUrl).then(function (tempPath) {
return getBuildVersion().then(function (bv) {
var mt = getMiniTool();
if (
!relativePath ||
!isClientVersionAtLeast(bv, FILE_MIN) ||
!mt ||
typeof mt.saveFile !== "function"
) {
return tempPath;
}
return getUserDataPath().then(function (root) {
if (!root) return tempPath;
var dest = root + "/" + String(relativePath).replace(/^\/+/, "");
var dir = dest.replace(/\/[^/]+$/, "");
return ensureDir(dir).then(function () {
return callApi("saveFile", {
tempFilePath: tempPath,
filePath: dest
})
.then(function (res) {
return (res && res.savedFilePath) || dest || tempPath;
})
.catch(function () {
return tempPath;
});
});
});
});
});
}
function getFileStorageInfo() {
return getBuildVersion().then(function (bv) {
var mt = getMiniTool();
if (
!isClientVersionAtLeast(bv, FILE_MIN) ||
!mt ||
typeof mt.getFileStorageInfo !== "function"
) {
return null;
}
return Promise.resolve(mt.getFileStorageInfo()).catch(function () {
return null;
});
});
}
function unlinkFile(relativeOrAbsPath) {
return getBuildVersion().then(function (bv) {
var mt = getMiniTool();
if (
!isClientVersionAtLeast(bv, FILE_MIN) ||
!mt ||
typeof mt.unlink !== "function"
) {
return false;
}
var path = String(relativeOrAbsPath || "");
if (!path) return false;
var p = Promise.resolve(path);
if (path.indexOf("/") !== 0 && path.indexOf("usr") !== 0) {
p = getUserDataPath().then(function (root) {
return root ? root + "/" + path.replace(/^\/+/, "") : path;
});
}
return p.then(function (filePath) {
return callApi("unlink", { filePath: filePath })
.then(function () {
return true;
})
.catch(function () {
return false;
});
});
});
}
function readDirList(relativeDir) {
return getBuildVersion().then(function (bv) {
var mt = getMiniTool();
if (
!isClientVersionAtLeast(bv, FILE_MIN) ||
!mt ||
typeof mt.readDir !== "function"
) {
return [];
}
return getUserDataPath().then(function (root) {
if (!root) return [];
var dirPath =
root +
(relativeDir
? "/" + String(relativeDir).replace(/^\/+|\/+$/g, "")
: "");
return callApi("readDir", { dirPath: dirPath })
.then(function (res) {
var files = (res && res.files) || [];
return files.map(function (f) {
if (typeof f === "string") {
return { name: f, path: dirPath + "/" + f };
}
var name = f.name || f.fileName || String(f);
return {
name: name,
path: f.path || f.filePath || dirPath + "/" + name,
isDir: !!(f.isDir || f.isDirectory)
};
});
})
.catch(function () {
return [];
});
});
});
}
function cleanupShareDir() {
return readDirList("share").then(function (files) {
var chain = Promise.resolve(0);
for (var i = 0; i < files.length; i++) {
(function (file) {
if (file.isDir) return;
chain = chain.then(function (n) {
return callApi("unlink", { filePath: file.path })
.then(function () {
return n + 1;
})
.catch(function () {
return n;
});
});
})(files[i]);
}
return chain;
});
}
/** Convert <input type=file> File / Blob to data URL (offline, no network). */
function blobToDataUrl(blob) {
return new Promise(function (resolve, reject) {
if (!blob) {
reject({ errMsg: "blobToDataUrl:fail empty" });
return;
}
try {
var reader = new FileReader();
reader.onload = function () {
resolve(reader.result);
};
reader.onerror = function () {
reject({ errMsg: "blobToDataUrl:fail read" });
};
reader.readAsDataURL(blob);
} catch (e) {
reject({ errMsg: "blobToDataUrl:fail " + (e && e.message) });
}
});
}
global.XhsBridge = {
getBuildVersion: getBuildVersion,
getClientVersion: getClientVersion,
isClientVersionAtLeast: isClientVersionAtLeast,
setLocalData: setLocalData,
getLocalData: getLocalData,
removeLocalData: removeLocalData,
clearLocalData: clearLocalData,
getStorageInfo: getStorageInfo,
getFileStorageInfo: getFileStorageInfo,
getLaunchOptions: getLaunchOptions,
readSnapshotInfo: readSnapshotInfo,
writeTempFile: writeTempFile,
saveImageToPhotosAlbum: saveImageToPhotosAlbum,
postNote: postNote,
canPostComment: canPostComment,
postComment: postComment,
canUseFileSystem: canUseFileSystem,
getUserDataPath: getUserDataPath,
writeUtf8File: writeUtf8File,
appendUtf8File: appendUtf8File,
readUtf8File: readUtf8File,
persistImage: persistImage,
unlinkFile: unlinkFile,
readDirList: readDirList,
cleanupShareDir: cleanupShareDir,
blobToDataUrl: blobToDataUrl,
postVideoNote: postVideoNote,
getMiniTool: getMiniTool,
STORAGE_MIN: STORAGE_MIN,
COMMENT_MIN: COMMENT_MIN,
FILE_MIN: FILE_MIN
};
})(window);
/* book-app runtime — BOOK_DATA from book/book-data.js */
(function () {
"use strict";
@ -608,8 +11,11 @@
var JOURNAL_KEY = "yidu_journal";
var TIME_KEY = "yidu_read_time";
var WORKS_KEY = "yidu_works";
var UNLOCK_KEY = "yidu_book_unlock";
var NOTES_FILE = "notes/clips.json";
var JOURNAL_FILE = "notes/journal.json";
/** 试读章数兜底;BOOK_DATA.free_chapters / unlock_percent 可覆盖 */
var DEFAULT_FREE_CHAPTERS = 3;
var Bridge = window.XhsBridge;
var FONT_SIZES = [
{ label: "小", value: 15 },
@ -660,7 +66,10 @@
jumpLockUntil: 0,
chromeHidden: false,
camStream: null,
camShot: null
camShot: null,
unlocked: false,
rewarding: false,
closeRetentionOn: false
};
var el = {};
@ -1143,6 +552,128 @@
return null;
}
function freeChapterCount() {
var book = state.book || {};
var chapters = book.chapters || [];
var total = chapters.length || 1;
var n = Number(book.free_chapters);
if (isFinite(n) && n >= 1) {
return Math.min(total, Math.max(1, Math.floor(n)));
}
var pct = Number(book.unlock_percent);
if (isFinite(pct) && pct > 0 && pct < 100) {
return Math.min(total, Math.max(1, Math.floor((total * pct) / 100)));
}
return Math.min(total, DEFAULT_FREE_CHAPTERS);
}
/** 赞赏可用才门控;旧客户端 / 浏览器保证全书可读 */
function canGateByReward() {
return !!(Bridge && typeof Bridge.canRewardAuthor === "function" && Bridge.canRewardAuthor(state.buildVersion));
}
function hasFullAccess() {
if (!canGateByReward()) return true;
return !!state.unlocked;
}
function isChapterLocked(idx) {
if (hasFullAccess()) return false;
return idx >= freeChapterCount();
}
function loadUnlock() {
var bookId = state.book && state.book.id;
return Bridge.getLocalData(UNLOCK_KEY, null, true).then(function (raw) {
if (!raw || typeof raw !== "object") return false;
if (raw.bookId && bookId && raw.bookId !== bookId) return false;
return !!raw.unlocked;
});
}
function saveUnlock(unlocked) {
state.unlocked = !!unlocked;
return Bridge.setLocalData(
UNLOCK_KEY,
{
bookId: state.book && state.book.id,
unlocked: !!unlocked,
at: Date.now()
},
true
);
}
function syncCloseRetention() {
var want = canGateByReward() && !state.unlocked;
if (want === state.closeRetentionOn) {
return Promise.resolve(want);
}
state.closeRetentionOn = want;
if (!Bridge || typeof Bridge.setCloseRetentionEnabled !== "function") {
return Promise.resolve(false);
}
return Bridge.setCloseRetentionEnabled(want).catch(function () {
return false;
});
}
function buildPaywallHtml() {
var freeN = freeChapterCount();
var total = ((state.book && state.book.chapters) || []).length;
var lockedN = Math.max(0, total - freeN);
var tipOk = canGateByReward();
return (
'<div class="paywall" id="book-paywall">' +
'<span class="paywall-emoji">☕</span>' +
'<span class="paywall-title">试读结束</span>' +
'<span class="paywall-desc">已开放前 ' +
freeN +
" 章 · 余下 " +
lockedN +
" 章需赞赏解锁</span>" +
(tipOk
? '<button type="button" class="fin-btn paywall-btn" data-unlock="reward">赞赏解锁全书</button>' +
'<span class="paywall-hint">任意金额即可 · 关闭时也可顺手支持作者</span>'
: '<span class="paywall-hint">请升级小红书至 9.53.3+ 后赞赏解锁</span>') +
"</div>"
);
}
function requestUnlock() {
if (state.rewarding) return;
if (!canGateByReward()) {
alert("当前环境暂不支持赞赏,请升级小红书后重试");
return;
}
var already = !!state.unlocked;
state.rewarding = true;
Bridge.rewardAuthor()
.then(function () {
if (already) {
state.rewarding = false;
alert("感谢再次支持");
return null;
}
return saveUnlock(true).then(function () {
state.rewarding = false;
return syncCloseRetention();
});
})
.then(function (didUnlock) {
if (already || didUnlock === null) return;
alert("感谢支持,全书已解锁");
renderReader(true);
syncActionLabels();
})
.catch(function (err) {
state.rewarding = false;
var msg = String((err && err.errMsg) || "");
if (/cancel|取消|fail user/i.test(msg)) return;
alert("赞赏未完成,可稍后再试");
});
}
function escapeText(s) {
return String(s)
.replace(/&/g, "&amp;")
@ -1205,7 +736,14 @@
}
} else {
if (el.btnStart) el.btnStart.textContent = "开始阅读";
if (el.homeHint) el.homeHint.textContent = "点一下,直接进入正文";
if (el.homeHint) {
if (canGateByReward() && !state.unlocked) {
el.homeHint.textContent =
"免费试读前 " + freeChapterCount() + " 章 · 赞赏解锁全书";
} else {
el.homeHint.textContent = "点一下,直接进入正文";
}
}
}
updateHomeTimeLabel();
showView("home");
@ -1371,20 +909,26 @@
var active = i === state.activeChapter ? " active" : "";
var emoji = CHAPTER_EMOJIS[i % CHAPTER_EMOJIS.length];
var starred = isBookmarked(ch.id) ? " ★" : "";
var locked = isChapterLocked(i);
var lockMark = locked ? " 🔒" : "";
html.push(
'<button type="button" class="drawer-item' +
active +
(locked ? " locked" : "") +
'" data-ch="' +
ch.id +
'" data-idx="' +
i +
'"><span class="drawer-idx">' +
'"' +
(locked ? ' data-locked="1"' : "") +
'><span class="drawer-idx">' +
pad2(i + 1) +
'</span><span class="drawer-body"><span class="drawer-name">' +
emoji +
" " +
escapeText(ch.title) +
starred +
lockMark +
"</span></span></button>"
);
}
@ -1570,6 +1114,27 @@
opts = opts || {};
var chapters = (state.book && state.book.chapters) || [];
if (idx < 0 || idx >= chapters.length) return;
if (isChapterLocked(idx)) {
var wall = $("book-paywall");
if (wall) {
state.jumpLockUntil = Date.now() + (opts.lockMs || 520);
state.activeChapter = Math.max(0, freeChapterCount() - 1);
var wr = wall.getBoundingClientRect();
var wy =
(window.pageYOffset || document.documentElement.scrollTop || 0) +
wr.top -
topbarOffset();
scrollToY(Math.max(0, wy));
if (opts.update !== false) {
setTimeout(function () {
updateProgressUI();
}, 60);
}
} else if (!opts.silent) {
requestUnlock();
}
return;
}
var ch = chapters[idx];
var target = $("ch-" + ch.id);
if (!target) return;
@ -1708,15 +1273,20 @@
remainingMinutes() +
'</span><span class="stat-l">余下</span></div>' +
"</div>" +
'<span class="hero-tip">点左右翻页 · 点中间显隐顶栏</span>' +
'<span class="hero-tip">' +
(canGateByReward() && !state.unlocked
? "试读前 " + freeChapterCount() + " 章 · 点左右翻页"
: "点左右翻页 · 点中间显隐顶栏") +
"</span>" +
"</div>"
);
for (var i = 0; i < chapters.length; i++) {
var visibleEnd = hasFullAccess() ? chapters.length : freeChapterCount();
for (var i = 0; i < visibleEnd; i++) {
var ch = chapters[i];
var mins = chapterMinutes(ch.content);
var emoji = CHAPTER_EMOJIS[i % CHAPTER_EMOJIS.length];
var next = chapters[i + 1];
var next = i + 1 < visibleEnd ? chapters[i + 1] : null;
var nextEmoji = CHAPTER_EMOJIS[(i + 1) % CHAPTER_EMOJIS.length];
html.push('<section class="chapter-block" id="ch-' + ch.id + '" data-idx="' + i + '">');
if (i > 0) {
@ -1768,6 +1338,9 @@
html.push("</section>");
}
if (!hasFullAccess()) {
html.push(buildPaywallHtml());
} else {
html.push(
'<div class="fin" id="book-fin">' +
'<span class="fin-emoji">✨</span>' +
@ -1779,6 +1352,7 @@
'<button type="button" class="fin-btn ghost" data-fin="home">返回封面</button>' +
"</div></div>"
);
}
if (el.paper) el.paper.innerHTML = html.join("");
renderToc("");
@ -1790,6 +1364,11 @@
idx = state.progress.chapterIndex;
}
if (idx < 0) idx = 0;
if (isChapterLocked(idx)) {
idx = Math.max(0, freeChapterCount() - 1);
jumpToChapter(idx, { lockMs: 600 });
return;
}
state.activeChapter = idx;
var pct = Number(state.progress.scrollPercent) || 0;
if (pct > 2) {
@ -1813,11 +1392,15 @@
typeof progress.chapterIndex === "number"
? progress.chapterIndex
: findChapterIndex(progress.chapterId);
if (idx >= 0) state.activeChapter = idx;
if (idx >= 0) {
if (isChapterLocked(idx)) idx = Math.max(0, freeChapterCount() - 1);
state.activeChapter = idx;
}
}
renderReader(true);
refreshPrefSegs();
syncActionLabels();
syncCloseRetention();
startReadTimer();
});
}
@ -1841,6 +1424,14 @@
var showComment = Bridge.canPostComment(state.buildVersion);
if (el.btnComment) setHidden(el.btnComment, !showComment);
if (el.btnCommentText) setHidden(el.btnCommentText, !showComment);
var showReward = canGateByReward();
if (el.btnReward) {
setHidden(el.btnReward, !showReward);
el.btnReward.textContent = state.unlocked ? "已解锁 · 再赞赏" : "赞赏解锁全书";
}
if (el.btnRewardHome) {
setHidden(el.btnRewardHome, !showReward || state.unlocked);
}
}
function chapterExcerpt(ch, maxLen) {
@ -2953,7 +2544,9 @@
el.homeCheckin = $("home-checkin");
el.homeJournal = $("home-journal");
el.homeWorks = $("home-works");
el.btnRewardHome = $("home-reward");
el.btnStart = $("btn-start");
el.btnReward = $("btn-reward");
el.btnToc = $("btn-toc");
el.btnTocTitle = $("btn-toc-title");
el.btnSettings = $("btn-settings");
@ -3106,6 +2699,10 @@
});
on(el.btnClearData, "click", clearLocalData);
on(el.btnBackHome, "click", goHome);
on(el.btnReward, "click", requestUnlock);
on(el.btnRewardHome, "click", function () {
requestUnlock();
});
on(el.tabChapters, "click", function () {
setDrawerTab("chapters");
});
@ -3177,6 +2774,10 @@
goHome();
return;
}
if (node.getAttribute && node.getAttribute("data-unlock") === "reward") {
requestUnlock();
return;
}
if (node.classList && node.classList.contains("next-peek")) {
var idx = Number(node.getAttribute("data-next-idx") || 0);
jumpToChapter(idx);
@ -3237,7 +2838,9 @@
node.tagName === "BUTTON" ||
node.tagName === "A" ||
(node.classList &&
(node.classList.contains("next-peek") || node.classList.contains("fin-btn")))
(node.classList.contains("next-peek") ||
node.classList.contains("fin-btn") ||
node.classList.contains("paywall-btn")))
) {
return;
}
@ -3274,6 +2877,7 @@
? snap.chapterIndex
: findChapterIndex(snap.chapterId);
if (idx < 0) idx = 0;
if (isChapterLocked(idx)) idx = Math.max(0, freeChapterCount() - 1);
state.activeChapter = idx;
var pct = Number(snap.scrollPercent) || 0;
getProgress(state.book.id).then(function (progress) {
@ -3331,19 +2935,23 @@
loadStreak(),
loadReadTime(),
loadWorks(),
loadUnlock(),
Bridge.getLaunchOptions()
]);
})
.then(function (tuple) {
state.prefs = tuple[0] || copyObj(DEFAULT_PREFS);
state.unlocked = !!tuple[7];
bind();
refreshStorageCap();
var snap = Bridge.readSnapshotInfo(tuple[7]);
syncCloseRetention();
var snap = Bridge.readSnapshotInfo(tuple[8]);
if (snap && applySnapshot(snap)) {
startReadTimer();
return;
}
renderHome();
syncActionLabels();
})
.catch(function (err) {
showBootError("启动错误: " + (err && err.message ? err.message : String(err)));

View File

@ -736,6 +736,61 @@ button {
color: var(--r-text);
}
.paywall {
margin: 28px 0 40px;
padding: 22px 14px 18px;
text-align: center;
border-top: 1px dashed var(--r-border);
background: linear-gradient(180deg, transparent, rgba(245, 158, 11, 0.08));
border-radius: 0 0 16px 16px;
}
.paywall-emoji {
display: block;
font-size: 30px;
line-height: 1;
}
.paywall-title {
display: block;
margin-top: 8px;
font-size: 20px;
font-weight: 700;
color: var(--r-text);
}
.paywall-desc {
display: block;
margin: 6px auto 0;
max-width: 16em;
font-size: 13px;
line-height: 1.45;
color: var(--r-muted);
}
.paywall-btn {
margin-top: 16px;
min-height: 44px;
min-width: 160px;
background: linear-gradient(135deg, #f59e0b, #d97706);
}
.paywall-hint {
display: block;
margin-top: 10px;
font-size: 12px;
color: var(--r-muted);
}
.drawer-item.locked .drawer-name {
opacity: 0.72;
}
.home-xhs-reward {
border-color: rgba(245, 158, 11, 0.45);
color: #f59e0b;
}
.md-body {
font-size: 16px;
line-height: 1.7;

View File

@ -39,6 +39,7 @@
<button type="button" class="home-xhs-btn" id="home-checkin">打卡发笔记</button>
<button type="button" class="home-xhs-btn" id="home-journal">写日记</button>
<button type="button" class="home-xhs-btn" id="home-works">我的作品</button>
<button type="button" class="home-xhs-btn home-xhs-reward is-hidden" id="home-reward">赞赏解锁</button>
</div>
<p class="home-time" id="home-time"></p>
</div>
@ -125,6 +126,7 @@
<p class="rs-cap" id="storage-cap">本地缓存 · 检测中</p>
<p class="rs-section">小红书</p>
<div class="rs-actions">
<button type="button" class="rs-action is-hidden" id="btn-reward">赞赏解锁全书</button>
<button type="button" class="rs-action" id="btn-checkin">阅读打卡发笔记</button>
<button type="button" class="rs-action" id="btn-selfie">自拍打卡发笔记</button>
<button type="button" class="rs-action" id="btn-photo-note">配图发笔记</button>

File diff suppressed because one or more lines are too long

View File

@ -8,6 +8,8 @@
var STORAGE_MIN = 9460;
var COMMENT_MIN = 9490;
var FILE_MIN = 9490;
/** §3.18 / §3.19 赞赏 & 挽留:客户端 9.53.3+ → 9533 */
var REWARD_MIN = 9533;
function readBuildVersion(launchOptions) {
var env = launchOptions && launchOptions.miniToolEnv;
@ -302,6 +304,50 @@
});
}
function canRewardAuthor(buildVersion) {
var mt = getMiniTool();
return (
isClientVersionAtLeast(buildVersion, REWARD_MIN) &&
mt &&
typeof mt.rewardAuthor === "function"
);
}
/** §3.18 — 成功仅表示赞赏流程结束,不含金额;取消/失败走 reject */
function rewardAuthor() {
return getBuildVersion().then(function (bv) {
if (!canRewardAuthor(bv)) {
return Promise.reject({ errMsg: "rewardAuthor:fail not available" });
}
return callApi("rewardAuthor");
});
}
/**
* §3.19 — 关闭容器时是否拉起赞赏挽留;默认 false,仅当前容器有效。
* 低于 9.53.3 时静默跳过,保证核心可读。
*/
function setCloseRetentionEnabled(enabled) {
var on = !!enabled;
return getBuildVersion().then(function (bv) {
var mt = getMiniTool();
if (
!isClientVersionAtLeast(bv, REWARD_MIN) ||
!mt ||
typeof mt.setCloseRetentionEnabled !== "function"
) {
return false;
}
return callApi("setCloseRetentionEnabled", { enabled: on })
.then(function () {
return true;
})
.catch(function () {
return false;
});
});
}
function getStorageInfo() {
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
@ -620,6 +666,9 @@
postNote: postNote,
canPostComment: canPostComment,
postComment: postComment,
canRewardAuthor: canRewardAuthor,
rewardAuthor: rewardAuthor,
setCloseRetentionEnabled: setCloseRetentionEnabled,
canUseFileSystem: canUseFileSystem,
getUserDataPath: getUserDataPath,
writeUtf8File: writeUtf8File,
@ -634,6 +683,7 @@
getMiniTool: getMiniTool,
STORAGE_MIN: STORAGE_MIN,
COMMENT_MIN: COMMENT_MIN,
FILE_MIN: FILE_MIN
FILE_MIN: FILE_MIN,
REWARD_MIN: REWARD_MIN
};
})(window);

File diff suppressed because one or more lines are too long

View File

@ -18,27 +18,43 @@
"tabLabel": "小册"
},
"community": {
"enabled": true,
"enabled": false,
"title": "旅居社群",
"tabLabel": "社群"
"tabLabel": "社群",
"note": "默认隐藏;后台可开"
},
"social": {
"enabled": true,
"title": "游民社区",
"tabLabel": "社区",
"note": "门户 /social · 可拆独立域"
"note": "国际 /social · 勿与中文 Hub 混用"
},
"hub": {
"enabled": true,
"title": "游民社区",
"tabLabel": "社区",
"note": "中文门户 /portal → /hub/home"
},
"hubBlog": {
"enabled": false,
"title": "Hub Blog",
"tabLabel": "Hub Blog",
"note": "/hub/blog"
},
"destinations": {
"enabled": true,
"title": "目的地"
"enabled": false,
"title": "目的地",
"note": "默认隐藏"
},
"meetups": {
"enabled": true,
"title": "活动"
"enabled": false,
"title": "活动",
"note": "默认隐藏"
},
"vip": {
"enabled": true,
"title": "会员中心"
"enabled": false,
"title": "会员中心",
"note": "deep link only"
},
"game": {
"enabled": false,

View File

@ -52,3 +52,12 @@ packages/sdk/tools.json
| GET | `/api/public/v1/nav/links` | listNavLinks |
Social 读接口优先反代 `SOCIAL_API_URL`,失败回落本地种子(离线兜底)。
## SDK / MCP 请求行为
SDK 默认请求超时为 15 秒,可通过 `createNomadroClient({ timeoutMs })` 调整;MCP 同为 15 秒。
网络失败、超时和 HTTP 错误均不自动重放写请求。成功响应必须是 JSON 对象,HTML、`null`、数组等异常响应会抛出错误。
SDK HTTP 错误保留 `status` 和 `data`,便于调用方区分权限、参数和上游故障。
`callTool` 直接读取 `packages/sdk/tools.json`,支持解构后调用。
本地回归:`pnpm test:platform`。测试使用模拟请求,不连接生产服务。

View File

@ -47,6 +47,8 @@ const aliases = {
};
const nextConfig: NextConfig = {
// Allow an isolated local audit without replacing another dev/build output.
distDir: process.env.NOMADRO_NEXT_DIST_DIR || ".next",
poweredByHeader: false,
compress: true,
experimental: {

View File

@ -32,6 +32,9 @@
"start": "next start",
"lint": "eslint",
"typecheck": "tsc --noEmit",
"test:platform": "node --test tests/platform.test.cjs",
"typecheck:all": "pnpm typecheck && pnpm --filter @nomadro/admin exec tsc --noEmit && pnpm --filter @nomadro/admin-com exec tsc --noEmit && pnpm --filter @nomadro/miniprogram-h5 exec tsc --noEmit && pnpm --filter @nomadro/miniprogram-weapp exec tsc --noEmit && pnpm --filter @nomadro/miniprogram-tt exec tsc --noEmit && pnpm --dir apps/hackrobot/vip exec tsc --noEmit",
"test:local": "pnpm test:platform && pnpm --filter @nomadro/miniprogram-weapp test:runtime && pnpm --filter @nomadro/miniprogram-weapp test:social && python -m pytest apps/api/tests -q && python scripts/test_hub_boundaries.py && node scripts/test-hub-config.cjs && python scripts/lane_guard.py",
"guard:lanes": "python scripts/lane_guard.py",
"guard:lanes:update": "python scripts/lane_guard.py --update-baseline",
"clean": "node scripts/clean-artifacts.mjs",
@ -88,17 +91,17 @@
"markdown-it": "^15.0.3",
"marked": "^17.0.4",
"nanoid": "^6.0.2",
"next": "16.1.6",
"next": "16.4.6",
"next-themes": "^0.4.6",
"photoswipe": "^5.4.4",
"pocketbase": "^0.26.8",
"posthog-js": "^1.447.3",
"prop-types": "^15.8.1",
"qrcode.react": "^4.2.0",
"react": "19.2.3",
"react": "19.2.9",
"react-beautiful-dnd": "^13.1.1",
"react-datepicker": "^9.1.0",
"react-dom": "19.2.3",
"react-dom": "19.2.9",
"react-dropzone": "^20.1.4",
"react-hot-keys": "^3.0.0",
"react-hot-toast": "^2.6.1",
@ -135,15 +138,21 @@
"@types/react-dom": "^19",
"@types/three": "^0.183.1",
"eslint": "^9",
"eslint-config-next": "16.1.6",
"eslint-config-next": "16.4.6",
"tailwindcss": "^4",
"typescript": "^5"
},
"packageManager": "pnpm@10.25.0+sha1.2cfb3ab644446565c127f58165cc76368c9c920b",
"engines": {
"node": ">=18"
"node": ">=20.9.0"
},
"pnpm": {
"overrides": {
"seroval@<1.6.10": "1.6.10",
"@remix-run/router@<1.23.3": "1.23.3",
"markdown-it@>=14.0.0 <14.3.3": "14.3.3",
"linkify-it@>=5.0.0 <5.0.2": "5.0.2"
},
"onlyBuiltDependencies": [
"@parcel/watcher",
"@swc/core",

View File

@ -38,7 +38,7 @@ function fillPath(template, args) {
});
}
async function callTool(name, args = {}) {
export async function callTool(name, args = {}, doFetch = fetch) {
const tool = TOOLS.find((t) => t.name === name);
if (!tool) throw new Error(`unknown tool ${name}`);
const pathParams = [...tool.path.matchAll(/\{(\w+)\}/g)].map((m) => m[1]);
@ -63,11 +63,16 @@ async function callTool(name, args = {}) {
for (const p of pathParams) delete payload[p];
body = JSON.stringify(payload);
}
const res = await fetch(url, { method: tool.method, headers, body });
const data = await res.json().catch(() => ({}));
const res = await doFetch(url, {
method: tool.method, headers, body, signal: AbortSignal.timeout(15_000),
});
const payload = await res.json().catch(() => undefined);
const data = payload && typeof payload === "object" && !Array.isArray(payload)
? payload : undefined;
if (!res.ok) {
throw new Error(data.detail || data.error || `HTTP ${res.status}`);
throw new Error(data?.detail || data?.error || `HTTP ${res.status}`);
}
if (!data) throw new Error(`Invalid JSON object response (HTTP ${res.status})`);
return data;
}

View File

@ -68,7 +68,7 @@ export function resolvePayProvider(input: ResolvePayInput = {}): {
const region: PayRegion =
input.region && input.region !== "auto"
? input.region
: input.audience === "intl" || input.isChinaUser === false
: (input.audience ? input.audience === "intl" : input.isChinaUser === false)
? "overseas"
: "cn";

View File

@ -14,6 +14,8 @@ export type NomadroClientOptions = {
/** Social guest id for write endpoints */
guestId?: string;
fetch?: typeof fetch;
/** Maximum duration of a request in milliseconds (default 15 seconds). */
timeoutMs?: number;
};
export type JsonMap = Record<string, unknown>;
@ -42,6 +44,10 @@ export function createNomadroClient(opts: NomadroClientOptions = {}) {
"https://nomadro.com"
).replace(/\/$/, "");
const doFetch = opts.fetch || fetch;
const timeoutMs = opts.timeoutMs ?? 15_000;
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
throw new Error("timeoutMs must be a positive finite number");
}
async function request(
method: "GET" | "POST",
@ -67,16 +73,20 @@ export function createNomadroClient(opts: NomadroClientOptions = {}) {
headers,
body: body ? JSON.stringify(body) : undefined,
cache: "no-store",
signal: AbortSignal.timeout(timeoutMs),
});
const data = (await res.json().catch(() => ({}))) as JsonMap;
const payload: unknown = await res.json().catch(() => undefined);
const data = payload && typeof payload === "object" && !Array.isArray(payload)
? payload as JsonMap : undefined;
if (!res.ok) {
const err = new Error(
String(data.detail || data.error || `HTTP ${res.status}`),
String(data?.detail || data?.error || `HTTP ${res.status}`),
) as Error & { status?: number; data?: JsonMap };
err.status = res.status;
err.data = data;
throw err;
}
if (!data) throw new Error(`Invalid JSON object response (HTTP ${res.status})`);
return data;
}
@ -129,36 +139,14 @@ export function createNomadroClient(opts: NomadroClientOptions = {}) {
/** Invoke any tool by name (MCP-friendly). */
async callTool(name: NomadroToolName, args: JsonMap = {}) {
switch (name) {
case "health":
return this.health();
case "getMeta":
return this.getMeta();
case "getConfig":
return this.getConfig();
case "listMapCities":
return this.listMapCities(args as never);
case "searchCities":
return this.searchCities(args as never);
case "listMeetups":
return this.listMeetups(args as never);
case "openMeetup":
return this.openMeetup(args as never);
case "listGigs":
return this.listGigs(args as never);
case "applyGig":
return this.applyGig(args as never);
case "joinSocial":
return this.joinSocial(args as never);
case "checkVip":
return this.checkVip(args as never);
case "listNavLinks":
return this.listNavLinks(args as never);
case "listSocialRoutes":
return this.listSocialRoutes();
default:
throw new Error(`unknown tool ${name}`);
}
const tool = NOMADRO_TOOLS.find((item) => item.name === name);
if (!tool) throw new Error(`unknown tool ${name}`);
const path = fillPath(tool.path, args);
const payload = { ...args };
for (const match of tool.path.matchAll(/\{(\w+)\}/g)) delete payload[match[1]];
return tool.method === "GET"
? request("GET", path, payload)
: request("POST", path, undefined, payload);
},
};
}

3180
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 775 B

After

Width:  |  Height:  |  Size: 30 KiB

View File

@ -20,11 +20,22 @@ ADMIN = '/www/wwwroot/admin.nomadro.com'
API_FILES = [
'routers/ops_admin.py', 'routers/public_config.py', 'routers/weapp_switches_admin.py',
'routers/social_ugc_admin.py', 'routers/google_admin.py', 'routers/social_blog_admin.py',
'routers/hub_ugc_admin.py', 'routers/hub_locale_geo_admin.py', 'routers/hub_blog_admin.py',
'services/weapp_switches.py', 'services/config_live.py', 'services/google_link.py',
'services/google_oauth.py', 'services/social_blog_ops.py',
'services/hub_ugc.py', 'services/hub_experience.py', 'services/hub_locale_geo.py',
'services/hub_blog_ops.py', 'services/hub_ops.py', 'services/hub_join_config.py',
'services/ntfy.py', 'services/track.py', 'services/social_ugc.py',
]
SOCIAL_FILES = ['pb_data.py', 'store.py', 'face_check.py', 'routers/api.py', 's3_upload.py']
# Full hub_svc tree for nomadro-hub + nomadmini-api (/api/admin/hub needs config/security_denylist/…)
HUB_FILES = [
'pb_data.py', 'store.py', 'face_check.py', 'config.py', 's3_upload.py', 'community_board.py',
'security_denylist.py', 'realtime.py', 'live.py', 'remote_flags.py', 'trial_gate.py',
'onboarding.py', 'notify_bridge.py', 'im.py', 'contract.py',
'geo_pb.py', 'geo_cities.py', 'geo_store.py', 'geo_h3.py', 'photon.py',
'__init__.py', 'routers/__init__.py', 'routers/api.py', 'routers/geo.py',
]
SOURCE_FILES = [
'next.config.ts', 'src/proxy.ts', 'src/lib/service-proxy.ts', 'src/lib/admin-auth.ts',
'src/lib/ntfy.ts', 'src/lib/ntfy-rich.ts', 'src/lib/feedback-identity.ts',
@ -104,6 +115,16 @@ def main():
archive.addfile(entry, io.BytesIO(blob))
for relative in SOCIAL_FILES:
archive.add(ROOT / 'apps/api/services/social_svc' / relative, arcname='social/' + relative)
for relative in HUB_FILES:
path = ROOT / 'apps/api/services/hub_svc' / relative
if path.is_file():
archive.add(path, arcname='hub/' + relative)
hub_main = ROOT / 'apps/api/hub_main.py'
if hub_main.is_file():
archive.add(hub_main, arcname='hub_main.py')
schemas = ROOT / 'apps/api/services/nomadro_pb/schemas.py'
if schemas.is_file():
archive.add(schemas, arcname='nomadro_pb/schemas.py')
digest = hashlib.sha256(package.read_bytes()).hexdigest()
print('release', RELEASE, 'build', build_id, 'packageMB', round(package.stat().st_size / 1024**2, 1))
sftp = client.open_sftp()
@ -114,6 +135,7 @@ def main():
[f'/opt/nomadmini/backend/app/{name}' for name in API_FILES]
+ [f'{PORTAL}/apps/api/services/social_svc/{name}' for name in SOCIAL_FILES]
+ [f'/opt/nomadmini/backend/social_svc/{name}' for name in SOCIAL_FILES]
+ [f'{PORTAL}/apps/api/services/hub_svc/{name}' for name in HUB_FILES]
)
target_args = ' '.join(targets)
try:
@ -121,7 +143,11 @@ def main():
echo '{digest} /tmp/nomadro-upgrade-{RELEASE}.tgz' | sha256sum -c -
mkdir -p {STAGE} {BACKUP}
tar -xzf /tmp/nomadro-upgrade-{RELEASE}.tgz -C {STAGE}
tar -czf {BACKUP}/backend.tgz {target_args}
EXISTING=""
for f in {target_args}; do
if [ -e "$f" ]; then EXISTING="$EXISTING $f"; fi
done
if [ -n "$EXISTING" ]; then tar -czf {BACKUP}/backend.tgz $EXISTING; else tar -czf {BACKUP}/backend.tgz --files-from /dev/null; fi
cp -a {ADMIN} {BACKUP}/admin
cp /etc/nginx/sites-available/admin.nomadro.com.conf {BACKUP}/admin-nginx.conf
cp {PORTAL}/data/remote-config.json {BACKUP}/remote-config.json
@ -135,17 +161,67 @@ test -f {STAGE}/portal/.next/BUILD_ID
run(client, f'cp {STAGE}/social/{relative} {PORTAL}/apps/api/services/social_svc/{relative}')
# admin.nomadro.com → :8010 imports /opt/nomadmini/backend/social_svc (not portal tree)
run(client, f'mkdir -p /opt/nomadmini/backend/social_svc/$(dirname {relative}) && cp {STAGE}/social/{relative} /opt/nomadmini/backend/social_svc/{relative}')
for relative in HUB_FILES:
run(client, f'mkdir -p {PORTAL}/apps/api/services/hub_svc/$(dirname {relative}) && cp {STAGE}/hub/{relative} {PORTAL}/apps/api/services/hub_svc/{relative}')
# admin.nomadro.com → :8010 also needs hub_svc for /api/admin/hub/*
run(client, f'mkdir -p /opt/nomadmini/backend/hub_svc/$(dirname {relative}) && cp {STAGE}/hub/{relative} /opt/nomadmini/backend/hub_svc/{relative}')
run(client, f'test -f {STAGE}/hub_main.py && cp {STAGE}/hub_main.py {PORTAL}/apps/api/hub_main.py || true')
run(client, f'test -f {STAGE}/nomadro_pb/schemas.py && cp {STAGE}/nomadro_pb/schemas.py {PORTAL}/apps/api/services/nomadro_pb/schemas.py || true')
run(client, f'test -f {STAGE}/nomadro_pb/schemas.py && mkdir -p /opt/nomadmini/backend/nomadro_pb && cp {STAGE}/nomadro_pb/schemas.py /opt/nomadmini/backend/nomadro_pb/schemas.py || true')
# Source parity for the legacy API tree and repository service tree.
for relative in API_FILES:
source = ROOT / 'apps/api/services/ebook_svc' / relative
if not source.is_file():
print('skip missing api source', relative)
continue
destination = f'{PORTAL}/apps/api/services/ebook_svc/{relative}'
sftp = client.open_sftp()
try: sftp.put(str(source), destination)
finally: sftp.close()
# Ensure production main.py mounts hub admin routers (file-level API copy alone is not enough)
run(client, r'''set -eu
python3 - <<'PY'
from pathlib import Path
p = Path('/opt/nomadmini/backend/app/main.py')
text = p.read_text(encoding='utf-8')
if 'include_router(hub_ugc_admin.router)' in text:
print('main.py hub routers ok')
else:
needle = 'app.include_router(social_ugc_admin.router)\n'
if needle not in text:
raise SystemExit('main.py missing social_ugc anchor')
imports = (
'from app.routers import hub_ugc_admin # noqa: E402\n'
'from app.routers import hub_locale_geo_admin # noqa: E402\n'
'from app.routers import hub_blog_admin # noqa: E402\n'
)
includes = (
'app.include_router(hub_ugc_admin.router)\n'
'app.include_router(hub_locale_geo_admin.router)\n'
'app.include_router(hub_blog_admin.router)\n'
)
if 'hub_ugc_admin' not in text:
text = text.replace(
'from app.routers import social_ugc_admin # noqa: E402\n',
'from app.routers import social_ugc_admin # noqa: E402\n' + imports,
1,
)
text = text.replace(needle, needle + includes, 1)
p.write_text(text, encoding='utf-8')
print('main.py hub routers patched')
PY
mkdir -p /etc/systemd/system/nomadmini-api.service.d
cat >/etc/systemd/system/nomadmini-api.service.d/hub-path.conf <<'EOF'
[Service]
Environment=PYTHONPATH=/opt/nomadmini/backend
Environment=HUB_INTERNAL_URL=http://127.0.0.1:8025
EOF
systemctl daemon-reload
''')
run(client, '''set -eu
cd /opt/nomadmini/backend
.venv/bin/python -c 'from app.routers import ops_admin,public_config,weapp_switches_admin; print("API imports OK")'
systemctl restart nomadmini-api nomadro-social
.venv/bin/python -c 'from app.routers import ops_admin,public_config,weapp_switches_admin,hub_ugc_admin; print("API imports OK", hub_ugc_admin.router.prefix)'
systemctl restart nomadmini-api nomadro-social nomadro-hub
''')
run(client, f'''set -eu
cd {PORTAL}
@ -162,13 +238,15 @@ done
curl --fail --silent --max-time 10 http://127.0.0.1:4003/api/health >/dev/null
curl --fail --silent --max-time 15 https://nomadro.com/ >/dev/null
curl --fail --silent --max-time 15 https://nomadro.com/social/chat >/dev/null
curl --fail --silent --max-time 15 https://nomadro.com/hub/home >/dev/null
curl --fail --silent --max-time 15 https://nomadro.com/notifications/settings >/dev/null
curl --fail --silent --max-time 10 http://127.0.0.1:8010/health >/dev/null
curl --fail --silent --max-time 10 http://127.0.0.1:8020/health >/dev/null
curl --fail --silent --max-time 10 http://127.0.0.1:8025/health >/dev/null
cp -a {STAGE}/admin/assets/. {ADMIN}/assets/
cp {STAGE}/admin/index.html {ADMIN}/index.html.next
mv {ADMIN}/index.html.next {ADMIN}/index.html
systemctl is-active nomadro nomadmini-api nomadro-social nginx
systemctl is-active nomadro nomadmini-api nomadro-social nomadro-hub nginx
''')
report = {'release': RELEASE, 'buildId': build_id, 'backup': BACKUP, 'stage': STAGE, 'sha256': digest, 'deployed': True}
(ROOT / 'artifacts/platform-upgrade/deployment.json').write_text(json.dumps(report, indent=2), encoding='utf-8')

View File

@ -5,41 +5,25 @@ export const runtime = "nodejs";
export const dynamic = "force-dynamic";
/**
* Admin list of join leads — prefer local portal store (works without hub_svc deploy).
* Falls through to upstream admin API when local empty and upstream available.
* Read Hub leads from the authenticated Hub API; never use the Social portal file.
*/
export async function GET(req: NextRequest) {
if (!(await requireAdminSession())) {
const auth = req.headers.get("authorization") || "";
if (!auth.startsWith("Bearer ") && !(await requireAdminSession())) {
return NextResponse.json({ ok: false, error: 'unauthorized' }, { status: 401, headers: { 'Cache-Control': 'no-store' } });
}
const qs = req.nextUrl.searchParams.toString();
const origin = req.nextUrl.origin;
try {
const local = await fetch(
`${origin}/api/portal/join-leads${qs ? `?${qs}` : ""}`,
{ headers: { cookie: req.headers.get('cookie') || '' }, cache: "no-store", signal: AbortSignal.timeout(5000) },
);
if (local.ok) {
const data = (await local.json()) as {
ok?: boolean;
total?: number;
items?: unknown[];
};
if (Array.isArray(data.items) && (data.items.length > 0 || data.total === 0)) {
return NextResponse.json(data);
}
}
} catch {
/* try upstream */
}
const upstream = (
process.env.ADMIN_API_URL ||
process.env.API_URL ||
""
"https://api.nomadro.com"
).replace(/\/$/, "");
if (upstream) {
try {
if (new URL(upstream).origin === req.nextUrl.origin) {
return NextResponse.json({ ok: false, error: "Hub 管理 API 上游不能指向门户自身" }, { status: 503 });
}
const cookie = req.headers.get("cookie") || "";
const auth = req.headers.get("authorization") || "";
const res = await fetch(
@ -68,10 +52,10 @@ export async function GET(req: NextRequest) {
items: [],
error: e instanceof Error ? e.message : "upstream fail",
},
{ status: 200 },
{ status: 503 },
);
}
}
return NextResponse.json({ ok: true, total: 0, items: [] });
return NextResponse.json({ ok: false, error: "Hub 管理 API 未配置" }, { status: 503 });
}

View File

@ -458,7 +458,13 @@ h2{color:#1e293b;margin:0 0 8px;font-size:1.5rem;}
successWrap.classList.add("show");
var dest=returnUrl||"/";
var joinDest=/[?&]join=1(?:&|$)/.test(dest)||(function(){try{return localStorage.getItem("social-join-pending-profile")==="1"||sessionStorage.getItem("social-join-pending-profile")==="1"||document.cookie.indexOf("nomadro_social_join=1")>=0;}catch(e){return false;}})();
if(joinDest){
var hubDest=false;
try{hubDest=new URL(dest,window.location.origin).pathname==="/hub/paid";}catch(e){}
if(hubDest){
var hubReturn=new URL(dest,window.location.origin);
hubReturn.searchParams.set("order_id",orderId);
dest=hubReturn.toString();
}else if(joinDest){
try{localStorage.setItem("social-join-pending-profile","1");sessionStorage.setItem("social-join-pending-profile","1");localStorage.setItem("social-join-paid","1");}catch(e){}
dest="/paid?join=1&paid=1";
}

View File

@ -1,5 +1,7 @@
import { NextRequest } from "next/server";
import { listBlogPosts } from "@hub/lib/blog/catalog";
import { publishedHubBlog } from "@hub/lib/blog/published";
export const dynamic = "force-dynamic";
import {
assertPublicKey,
jsonOk,
@ -14,10 +16,8 @@ export async function OPTIONS(req: NextRequest) {
export async function GET(req: NextRequest) {
const denied = assertPublicKey(req);
if (denied) return denied;
const locale = (req.nextUrl.searchParams.get("locale") || "en").trim();
const items = listBlogPosts({
locale: locale === "all" ? "all" : locale === "zh" ? "zh" : "en",
}).map((p) => ({
const { posts, enabled } = await publishedHubBlog();
const items = posts.map((p) => ({
slug: p.slug,
title: p.title,
description: p.description,
@ -31,6 +31,7 @@ export async function GET(req: NextRequest) {
}));
return jsonOk(req, {
ok: true,
enabled,
total: items.length,
items,
pagePath: "/hub/blog",

View File

@ -1,10 +1,10 @@
import { proxyHub } from "@hub/lib/publicApi";
import { NextRequest } from "next/server";
import { HUB_CITIES } from "@hub/lib/cities";
import {
assertPublicKey,
jsonOk,
optionsOk,
proxySocial,
} from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) {
@ -16,7 +16,7 @@ export async function GET(req: NextRequest) {
if (denied) return denied;
const sp = req.nextUrl.searchParams;
const qs = sp.toString();
const remote = await proxySocial(`/map/cities${qs ? `?${qs}` : ""}`);
const remote = await proxyHub(`/map/cities${qs ? `?${qs}` : ""}`);
if (remote.ok) {
return jsonOk(req, { ok: true, source: "hub_api", ...(remote.data as object) });
}

View File

@ -1,10 +1,10 @@
import { proxyHub } from "@hub/lib/publicApi";
import { NextRequest } from "next/server";
import { HUB_CITIES } from "@hub/lib/cities";
import {
assertPublicKey,
jsonOk,
optionsOk,
proxySocial,
} from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) {
@ -21,7 +21,7 @@ export async function GET(req: NextRequest) {
if (!q) {
return jsonOk(req, { ok: true, items: [], source: "empty_q" });
}
const remote = await proxySocial(
const remote = await proxyHub(
`/cities/search?q=${encodeURIComponent(q)}&limit=${limit}&lang=${encodeURIComponent(lang)}`,
);
if (remote.ok) {

View File

@ -1,11 +1,11 @@
import { proxyHub } from "@hub/lib/publicApi";
import { NextRequest } from "next/server";
import { PUBLIC_GIGS } from "~/lib/public-api/catalog";
import { hubPublicCatalog } from "@hub/lib/publicApi";
import {
assertPublicKey,
jsonErr,
jsonOk,
optionsOk,
proxySocial,
} from "~/lib/public-api/http";
export async function OPTIONS(req: NextRequest) {
@ -19,15 +19,16 @@ export async function POST(
const denied = assertPublicKey(req);
if (denied) return denied;
const { gigId } = await ctx.params;
const gig = PUBLIC_GIGS.find((g) => g.id === gigId);
const { gigs } = await hubPublicCatalog();
const gig = gigs.find((g) => g.id === gigId);
if (!gig) return jsonErr(req, 404, "gig not found");
const body = (await req.json().catch(() => ({}))) as {
name?: string;
contact?: string;
note?: string;
};
const name = (body.name || "").trim();
const contact = (body.contact || "").trim();
const name = typeof body?.name === "string" ? body.name.trim() : "";
const contact = typeof body?.contact === "string" ? body.contact.trim() : "";
if (!name || !contact) {
return jsonErr(req, 400, "name and contact required", {
pagePath: "/hub/team",
@ -35,15 +36,15 @@ export async function POST(
});
}
const guest =
req.headers.get("x-social-hub-hub-guest-id") ||
req.headers.get("x-hub-guest-id") ||
`public-${Buffer.from(contact).toString("base64url").slice(0, 24)}`;
const remote = await proxySocial(`/gigs/${encodeURIComponent(gigId)}/apply`, {
const remote = await proxyHub(`/gigs/${encodeURIComponent(gigId)}/apply`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Hub-Guest-Id": guest,
},
body: JSON.stringify({ name, contact, note: body.note || "" }),
body: JSON.stringify({ name, contact, note: typeof body.note === "string" ? body.note : "" }),
});
if (remote.ok) {
return jsonOk(req, {
@ -55,16 +56,7 @@ export async function POST(
linkText: "查看招聘",
});
}
return jsonOk(req, {
ok: true,
status: "queued_local",
source: "fallback",
gigId,
name,
contact,
note: body.note || "",
pagePath: "/hub/team",
linkText: "打开申请页重试",
detail: "upstream apply unavailable; return handoff",
return jsonErr(req, remote.status || 503, "申请尚未提交,请稍后重试", {
pagePath: "/hub/team", linkText: "返回申请页", status: "not_submitted",
});
}

View File

@ -1,5 +1,5 @@
import { NextRequest } from "next/server";
import { PUBLIC_GIGS } from "~/lib/public-api/catalog";
import { hubPublicCatalog } from "@hub/lib/publicApi";
import {
assertPublicKey,
jsonOk,
@ -17,7 +17,7 @@ export async function GET(req: NextRequest) {
const keyword = (req.nextUrl.searchParams.get("keyword") || "")
.trim()
.toLowerCase();
let gigs = [...PUBLIC_GIGS];
let { gigs } = await hubPublicCatalog();
if (kind && kind !== "all") {
gigs = gigs.filter((g) => g.kind === kind);
}

View File

@ -1,5 +1,5 @@
import { NextRequest } from "next/server";
import { PUBLIC_JOIN } from "~/lib/public-api/catalog";
import { PUBLIC_HUB_JOIN } from "@hub/lib/publicApi";
import {
assertPublicKey,
jsonOk,
@ -16,9 +16,9 @@ export async function GET(req: NextRequest) {
const email = req.nextUrl.searchParams.get("email") || "";
return jsonOk(req, {
ok: true,
...PUBLIC_JOIN,
...PUBLIC_HUB_JOIN,
email: email || null,
isMember: false,
note: "Paid social join is isolated from VIP (__vip__). Prefer handoff to pagePath.",
note: "Hub 中文社区独立加入流程,请前往 pagePath 完成。",
});
}

View File

@ -1,5 +1,5 @@
import { NextRequest } from "next/server";
import { PUBLIC_MEETUPS } from "~/lib/public-api/catalog";
import { hubPublicCatalog } from "@hub/lib/publicApi";
import {
assertPublicKey,
jsonErr,
@ -18,7 +18,8 @@ export async function GET(
const denied = assertPublicKey(req);
if (denied) return denied;
const { meetupId } = await ctx.params;
const room = PUBLIC_MEETUPS.find((r) => r.id === meetupId);
const { meetups } = await hubPublicCatalog();
const room = meetups.find((r) => r.id === meetupId);
if (!room) return jsonErr(req, 404, "meetup not found");
const nick = req.nextUrl.searchParams.get("nick") || "游民";
return jsonOk(req, {

View File

@ -1,5 +1,5 @@
import { NextRequest } from "next/server";
import { PUBLIC_MEETUPS } from "~/lib/public-api/catalog";
import { hubPublicCatalog } from "@hub/lib/publicApi";
import {
assertPublicKey,
jsonOk,
@ -16,7 +16,7 @@ export async function GET(req: NextRequest) {
const keyword = (req.nextUrl.searchParams.get("keyword") || "")
.trim()
.toLowerCase();
let rooms = [...PUBLIC_MEETUPS];
let { meetups: rooms } = await hubPublicCatalog();
if (keyword) {
rooms = rooms.filter(
(r) =>

View File

@ -1,5 +1,8 @@
import { NextRequest } from "next/server";
import { HUB_SECTIONS } from "@hub/lib/catalog";
import { hubPath } from "@hub/lib/hubPath";
import { isHubNavEnabled } from "@hub/lib/navFlags";
import { readRemoteConfigFile } from "~/lib/remote-config-store";
import {
assertPublicKey,
jsonOk,
@ -13,9 +16,15 @@ export async function OPTIONS(req: NextRequest) {
export async function GET(req: NextRequest) {
const denied = assertPublicKey(req);
if (denied) return denied;
const config = await readRemoteConfigFile();
return jsonOk(req, {
ok: true,
base: "/hub",
sections: HUB_SECTIONS,
sections: HUB_SECTIONS.map(section => ({
...section,
features: section.features
.filter(feature => isHubNavEnabled(config.copy.hubExperience?.navigation, feature.href))
.map(feature => ({ ...feature, href: hubPath(feature.href) })),
})).filter(section => section.features.length),
});
}

View File

@ -6,6 +6,7 @@ import { getLocale } from "@ebook/lib/i18n/server";
import { BookRoutesProvider } from "@ebook/components/BookRoutes";
import { ModuleBoundary } from "~/components/module-boundary";
import "@ebook/app/globals.css";
import "@ebook/app/cover-hero.css";
export default async function BookLayout({
children,

View File

@ -1,7 +1,11 @@
@import "tailwindcss";
/* Scan portal sources only; build outputs and audit artifacts are not classes. */
@import "tailwindcss" source("../");
@source "../../packages";
:root,
.dark {
/* Chinese text remains readable offline without a Google Fonts download. */
--font-noto-sc: "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
--background: #0a0e17;
--foreground: #f1f5f9;
--hub-accent-1: #ff6b6b;

View File

@ -634,6 +634,7 @@ html.light .hub-navbar.scrolled,
min-height: 100svh;
gap: 0.65rem;
padding-top: calc(var(--hub-nav-height) + 0.65rem);
padding-inline: max(1rem, env(safe-area-inset-left), env(safe-area-inset-right));
}
.hub-hero-title {
@ -648,26 +649,36 @@ html.light .hub-navbar.scrolled,
animation-duration: 7s;
}
.hub-portal-grid {
/* 三大模块:H5 恢复横向三卡(与原版一致) */
.hub-portal-grid,
.hub-portal-grid--row,
.hub-portal-grid--2x2 {
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
max-width: none;
}
.hub-portal-card {
padding: 14px 10px;
gap: 10px;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
min-height: 88px;
padding: 10px 8px;
text-align: center;
}
.hub-portal-ico {
width: 32px;
height: 32px;
font-size: 0.95rem;
width: 34px;
height: 34px;
font-size: 1.05rem;
border-radius: 10px;
}
.hub-portal-name {
font-size: 0.78rem;
letter-spacing: -0.03em;
font-size: 0.86rem;
letter-spacing: -0.02em;
white-space: nowrap;
}
.hub-fc-1 {
@ -687,16 +698,13 @@ html.light .hub-navbar.scrolled,
}
@media (max-width: 380px) {
.hub-portal-grid {
gap: 6px;
}
.hub-portal-card {
padding: 12px 6px;
padding: 12px 14px;
min-height: 48px;
}
.hub-portal-name {
font-size: 0.7rem;
font-size: 0.92rem;
}
}

View File

@ -1,10 +1,12 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import BlogPostClient from "@hub/components/blog/BlogPostClient";
import { getBlogPost, listBlogPosts, listBlogSlugs } from "@hub/lib/blog/catalog";
import { getBlogPost, listBlogSlugs } from "@hub/lib/blog/catalog";
import { resolveBlogAdSense } from "@hub/lib/blog/adsense";
import { blogPostingJsonLd } from "@hub/lib/blog/jsonld";
import { readRemoteConfigFile } from "~/lib/remote-config-store";
import { publishedHubBlog } from "@hub/lib/blog/published";
export const dynamic = "force-dynamic";
type Props = { params: Promise<{ slug: string }> };
@ -14,7 +16,8 @@ export async function generateStaticParams() {
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const post = getBlogPost(slug);
const publication = await publishedHubBlog();
const post = publication.posts.some((p) => p.slug === slug) ? getBlogPost(slug) : null;
if (!post) return { title: "Not found" };
const url = `https://nomadro.com/hub/blog/${post.slug}`;
return {
@ -43,15 +46,16 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
export default async function HubBlogPostPage({ params }: Props) {
const { slug } = await params;
const post = getBlogPost(slug);
const publication = await publishedHubBlog();
const post = publication.posts.some((p) => p.slug === slug) ? getBlogPost(slug) : null;
if (!post) notFound();
const related = listBlogPosts({ locale: post.locale })
const related = publication.posts
.filter((p) => p.slug !== post.slug)
.filter((p) => p.tags.some((t) => post.tags.includes(t)))
.slice(0, 3);
const config = await readRemoteConfigFile().catch(() => null);
const config = publication.config;
const adsense = resolveBlogAdSense(config);
const jsonLd = blogPostingJsonLd(post);
@ -59,7 +63,7 @@ export default async function HubBlogPostPage({ params }: Props) {
<>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c") }}
/>
<BlogPostClient post={post} related={related} adsense={adsense} />
</>

View File

@ -3,16 +3,19 @@ import Link from "next/link";
import SiteShell from "@hub/components/SiteShell";
import { HubFooter } from "@hub/components/HubNavigation";
import { hubPath } from "@hub/lib/hubPath";
import HubInformationPage from "@hub/components/HubInformationPage";
import { isHubCnOnly } from "@hub/lib/hubCnLock";
export const metadata: Metadata = {
title: "About the Nomad Blog | Nomadro",
title: "关于游民社区 | Nomadro Hub",
description:
"Who publishes Nomadro’s nomad blog, what we write about, and how advertising may appear after approval.",
"面向中文用户的独立游民社区,认识伙伴、远程工作、同城见面与共创。",
alternates: { canonical: "https://nomadro.com/hub/blog/about" },
robots: { index: true, follow: true },
};
export default function HubBlogAboutPage() {
if (isHubCnOnly()) return <HubInformationPage />;
return (
<SiteShell title="About" editorial>
<article className="sblog-page sblog-article">

View File

@ -1,7 +1,7 @@
/** Blog suspense — spinner only, no intermediate page. */
export default function BlogLoading() {
return (
<div className="social-loader" role="status" aria-busy="true" aria-label="Loading">
<div className="social-loader" role="status" aria-busy="true" aria-label="正在加载文章">
<span className="social-loader-ring" aria-hidden="true" />
</div>
);

View File

@ -1,17 +1,20 @@
import type { Metadata } from "next";
import BlogListClient from "@hub/components/blog/BlogListClient";
import { listBlogPosts } from "@hub/lib/blog/catalog";
import { publishedHubBlog } from "@hub/lib/blog/published";
import { notFound } from "next/navigation";
export const dynamic = "force-dynamic";
import { blogListJsonLd } from "@hub/lib/blog/jsonld";
export const metadata: Metadata = {
title: "Nomad Blog | Nomadro",
title: "游民手记 | Nomadro Hub",
description:
"English field notes for digital nomads: cities, cafés, remote work, budgets, and meeting people on the road.",
"面向中文游民的城市生活、远程办公与社区见面手记。",
alternates: { canonical: "https://nomadro.com/hub/blog" },
openGraph: {
title: "Nomad Blog | Nomadro",
title: "游民手记 | Nomadro Hub",
description:
"Practical guides for remote work and slow travel. Content-first — ads off until AdSense approval.",
"从远程办公到同城见面,分享实用的游民生活经验。",
url: "https://nomadro.com/hub/blog",
type: "website",
siteName: "Nomadro",
@ -19,17 +22,18 @@ export const metadata: Metadata = {
robots: { index: true, follow: true },
};
export default function HubBlogPage() {
const posts = listBlogPosts({ locale: "en", adsenseReadyOnly: false });
export default async function HubBlogPage() {
const { posts, enabled, heroLead } = await publishedHubBlog();
if (!enabled) notFound();
const jsonLd = blogListJsonLd(posts);
return (
<>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, "\\u003c") }}
/>
<BlogListClient posts={posts} />
<BlogListClient posts={posts} heroLead={heroLead} />
</>
);
}

View File

@ -1,18 +1,22 @@
import { listBlogPosts } from "@hub/lib/blog/catalog";
import { publishedHubBlog } from "@hub/lib/blog/published";
export const dynamic = "force-dynamic";
const cdata = (s: string) => s.replace(/\]\]>/g, "]]]]><![CDATA[>");
const SITE = "https://nomadro.com";
export async function GET() {
const posts = listBlogPosts({ locale: "en" });
const { posts, enabled } = await publishedHubBlog();
if (!enabled) return new Response(null, { status: 404 });
const items = posts
.map(
(p) => `
<item>
<title><![CDATA[${p.title}]]></title>
<title><![CDATA[${cdata(p.title)}]]></title>
<link>${SITE}/hub/blog/${p.slug}</link>
<guid>${SITE}/hub/blog/${p.slug}</guid>
<pubDate>${new Date(p.date).toUTCString()}</pubDate>
<description><![CDATA[${p.description}]]></description>
<description><![CDATA[${cdata(p.description)}]]></description>
</item>`,
)
.join("");
@ -20,10 +24,10 @@ export async function GET() {
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Nomadro Nomad Blog</title>
<title>Nomadro Hub 游民手记</title>
<link>${SITE}/hub/blog</link>
<description>English field notes for digital nomads</description>
<language>en-us</language>
<description>面向中文游民的远程办公与社区生活手记</description>
<language>zh-CN</language>
${items}
</channel>
</rss>`;
@ -31,7 +35,7 @@ export async function GET() {
return new Response(xml, {
headers: {
"Content-Type": "application/rss+xml; charset=utf-8",
"Cache-Control": "public, max-age=3600",
"Cache-Control": "no-store",
},
});
}

View File

@ -1,4 +1,4 @@
import CoffeeBookPage from "@coffee/components/CoffeeBookPage";
import CoffeeBookPage from "@hub/coffee/components/CoffeeBookPage";
export default async function Page({
params,
@ -6,5 +6,5 @@ export default async function Page({
params: Promise<{ username: string; slug: string }>;
}) {
const { username, slug } = await params;
return <CoffeeBookPage username={username} slug={slug} />;
return <CoffeeBookPage key={`${username}/${slug}`} username={username} slug={slug} />;
}

View File

@ -1,4 +1,4 @@
import CoffeeHostPage from "@coffee/components/CoffeeHostPage";
import CoffeeHostPage from "@hub/coffee/components/CoffeeHostPage";
export default async function Page({
params,
@ -6,5 +6,5 @@ export default async function Page({
params: Promise<{ username: string }>;
}) {
const { username } = await params;
return <CoffeeHostPage username={username} />;
return <CoffeeHostPage key={username} username={username} />;
}

View File

@ -1,4 +1,4 @@
import CoffeeBookingDetail from "@coffee/components/CoffeeBookingDetail";
import CoffeeBookingDetail from "@hub/coffee/components/CoffeeBookingDetail";
export default async function Page({
params,

View File

@ -1,4 +1,4 @@
import CoffeeManagePage from "@coffee/components/CoffeeManagePage";
import CoffeeManagePage from "@hub/coffee/components/CoffeeManagePage";
export default function Page() {
return <CoffeeManagePage />;

View File

@ -1,4 +1,4 @@
import CoffeeLanding from "@coffee/components/CoffeeLanding";
import CoffeeLanding from "@hub/coffee/components/CoffeeLanding";
export default function Page() {
return <CoffeeLanding />;

View File

@ -7,6 +7,7 @@ import "@hub/app/theme2.css";
import "@hub/app/theme3.css";
import "@hub/app/theme4.css";
import "@hub/app/home.css";
import "@hub/app/cn-join.css";
import "@hub/app/experience.css";
import "@hub/app/interaction.css";
import "@hub/app/studio.css";
@ -21,7 +22,7 @@ import HubExperience from "@hub/components/HubExperience";
export const metadata = {
title: "Nomadro Hub · 游民社区",
description: "游民社区:聊天群、约会、语音厅、同城见面、招聘共创",
description: "换一座城市,不必重新孤独。加群,找到同频的人。",
};
export default function HubLayout({

View File

@ -1,7 +1,7 @@
/** Route suspense — spinner only, no intermediate page. */
export default function HubLoading() {
return (
<div className="social-loader" role="status" aria-busy="true" aria-label="Loading">
<div className="social-loader" role="status" aria-busy="true" aria-label="正在加载社区">
<span className="social-loader-ring" aria-hidden="true" />
</div>
);

View File

@ -3,17 +3,20 @@ import Link from "next/link";
import SiteShell from "@hub/components/SiteShell";
import { HubFooter } from "@hub/components/HubNavigation";
import { hubPath } from "@hub/lib/hubPath";
import HubInformationPage from "@hub/components/HubInformationPage";
import { isHubCnOnly } from "@hub/lib/hubCnLock";
export const metadata: Metadata = {
title: "Privacy | Nomadro Social",
title: "隐私说明 | Nomadro Hub",
description:
"How Nomadro handles data on /hub, cookies, analytics, and advertising (including Google AdSense when enabled).",
"了解 Nomadro Hub 中文社区的数据处理、本机存储与隐私选择。",
alternates: { canonical: "https://nomadro.com/hub/privacy" },
robots: { index: true, follow: true },
};
/** AdSense reviewers look for a clear Privacy Policy with ads/cookies disclosure */
export default function HubPrivacyPage() {
if (isHubCnOnly()) return <HubInformationPage privacy />;
return (
<SiteShell title="Privacy" editorial>
<article className="sblog-page sblog-article">

View File

@ -1,11 +1,13 @@
import type { MetadataRoute } from "next";
import { listBlogPosts } from "@hub/lib/blog/catalog";
import { publishedHubBlog } from "@hub/lib/blog/published";
export const dynamic = "force-dynamic";
import { getPublicSiteUrl } from "~/lib/google/site";
const SITE = getPublicSiteUrl();
export default function sitemap(): MetadataRoute.Sitemap {
const posts = listBlogPosts({ locale: "all" });
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const { posts, enabled } = await publishedHubBlog();
const staticRoutes: MetadataRoute.Sitemap = [
{
url: `${SITE}/hub/blog`,
@ -32,5 +34,5 @@ export default function sitemap(): MetadataRoute.Sitemap {
changeFrequency: "monthly" as const,
priority: 0.7,
}));
return [...staticRoutes, ...postRoutes];
return [...staticRoutes.filter((route) => enabled || !route.url.includes("/blog")), ...postRoutes];
}

View File

@ -1,6 +1,9 @@
import type { ReactNode } from "react";
import WorkAccessGate from "@work/components/WorkAccessGate";
import HubReservedModule from "@hub/components/HubReservedModule";
import { isHubCnOnly } from "@hub/lib/hubCnLock";
export default function WorkLayout({ children }: { children: ReactNode }) {
if (isHubCnOnly()) return <HubReservedModule kind="work" />;
return <WorkAccessGate>{children}</WorkAccessGate>;
}

View File

@ -3,7 +3,6 @@ import "./hub.css";
import { type Metadata, type Viewport } from "next";
import { Suspense } from "react";
import { Noto_Sans_SC } from "next/font/google";
import { outfit } from "~/lib/fonts";
import { LocaleProvider } from "~/components/locale-provider";
import {
@ -118,20 +117,13 @@ export const metadata: Metadata = {
},
};
const notoSansSC = Noto_Sans_SC({
subsets: ["latin"],
weight: ["300", "400", "500", "700"],
variable: "--font-noto-sc",
display: "swap",
});
export default function RootLayout({
children,
}: Readonly<{ children: React.ReactNode }>) {
return (
<html
lang="zh-CN"
className={`${outfit.variable} ${notoSansSC.variable} dark`}
className={`${outfit.variable} dark`}
suppressHydrationWarning
>
<head>

View File

@ -1,5 +1,10 @@
import "@navmini/styles/global.css";
export default function NavLayout({ children }: { children: React.ReactNode }) {
return <div className="navmini-root">{children}</div>;
/* 默认日间;客户端 App 按 navmini-theme 覆盖。勿写 html — 门户强制 dark */
return (
<div className="navmini-root" data-theme="light">
{children}
</div>
);
}

View File

@ -1,7 +1,7 @@
"use client";
import Link from "next/link";
import type { ReactNode } from "react";
import { hardNavClick } from "~/lib/hard-nav";
import { useRemoteConfig } from "~/lib/use-remote-config";
import type { NomadroRemoteConfig } from "~/lib/remote-config";
@ -46,8 +46,9 @@ export function ModuleGate({
<p style={{ margin: 0, color: "#94a3b8", maxWidth: 320, lineHeight: 1.5 }}>
该内容暂未开放,稍后再来看看吧。
</p>
<Link
href="/"
<a
href="/portal"
onClick={hardNavClick("/portal")}
style={{
marginTop: 8,
color: "#0a0e17",
@ -62,7 +63,7 @@ export function ModuleGate({
}}
>
返回首页
</Link>
</a>
</div>
);
}

Some files were not shown because too many files have changed in this diff Show More