diff --git a/.cursor/rules/audience-cn-intl.mdc b/.cursor/rules/audience-cn-intl.mdc
new file mode 100644
index 0000000..b1001a2
--- /dev/null
+++ b/.cursor/rules/audience-cn-intl.mdc
@@ -0,0 +1,48 @@
+---
+description: 中文/国际受众模块化 — 支付登录关注文案VIP埋点等全进模块
+alwaysApply: true
+---
+
+# 受众模块化(强制)
+
+## SoT
+
+`src/modules/audience/`
+
+| 路径 | 职责 |
+|------|------|
+| `detect.ts` | 微信 UA + is-china-user 识别 |
+| `cn/` | 中文用户:支付/登录/关注/文案/VIP/埋点/社群 |
+| `intl/` | 国际用户(.com 默认):同上全套 |
+| `resolve.ts` | `resolveAudienceBundle()` 合并远程 `audience.*` |
+| `index.ts` | **唯一公共面** |
+
+## 产品姿态
+
+- **intl**:`.com` 默认(英语为主 + 多语言 UI)
+- **cn**:必须特殊对待(微信内置 / is-china-user 命中)
+
+## 开发铁律
+
+```ts
+import { resolveAudienceBundle, useAudienceModule } from "~/modules/audience"
+const { module, lane, profile } = resolveAudienceBundle()
+// module.pay / .login / .follow / .copy / .vip / .track / .social
+```
+
+**禁止**在页面散落 `if (isChina)` / `if (locale === "zh")` 决定支付网关、登录方式、关注渠道、VIP CTA。
+
+新增能力(支付、登录、关注、文案、VIP、埋点、社群、小册 PDF/加密货币、运营位…)→ **同时改 `cn/` 与 `intl/`**,再经 `AudienceModule` 类型约束。
+
+小册变现:`module.ebook.showPdfBuy` / `showCryptoSupport` — **仅 intl**;中文用户禁止展示 Download Edition / Buy Now $29 / Coffee·Lunch·Sponsor。
+
+## 后台
+
+登录后全屏选模块 → `/cn/*` | `/intl/*`(`admin.nomadro.com`)。
+
+## 识别
+
+1. 微信 / 企业微信内置 → cn
+2. `is-china-user` → cn
+3. 否则 → intl
+勿用 UI locale 反推受众轨。
diff --git a/.cursor/rules/com-first-deploy.mdc b/.cursor/rules/com-first-deploy.mdc
new file mode 100644
index 0000000..05b72b7
--- /dev/null
+++ b/.cursor/rules/com-first-deploy.mdc
@@ -0,0 +1,41 @@
+---
+description: .com 美国机为开发发版核心;.cn 独立同步;Taro→三端小程序链路
+alwaysApply: true
+---
+
+# 核心机与发版顺序(强制)
+
+## 一句话
+
+**本仓开发与默认发版核心是 `nomadro.com`(美国 VPS),不是 `.cn`。**
+
+## 双站关系
+
+| 站 | 机 | 角色 |
+|---|---|---|
+| **`.com`** | 美国 VPS(如 `108.174.50.68`) | **主开发 / 默认部署目标** |
+| **`.cn`** | 中国机 `82.157.112.245` | 独立生产;**仅在 .com 中文轨测稳后**再同步 |
+
+- `.com` 内分 **中文用户 / 国际用户**(`src/modules/audience/{cn,intl}`,`resolveAudienceBundle()`)。
+- `.com` 中文用户体验测好 → 再同步到 `.cn` 与中国服务器。
+- **`.com` 中文轨与 `.cn` 服务器彼此独立**(库、配置、进程、发版互不顶替)。禁止「只发 82 就当 .com 已上线」。
+- 用户说「部署上线」且未点名域名 → **默认发 `.com` / 美国机**;发 `.cn` 必须明确说 `.cn` / 中国机 / 82。
+
+## 产品复制链(中国三端)
+
+```
+.com(Next · 受众 cn/intl)
+ └─ 中文轨测稳 → 同步 .cn(Next · 中国机,独立)
+ └─ Taro H5(apps/miniprogram/h5)对齐 .cn 体验
+ └─ Taro 多端编译 → 微信 / 抖音 / 小红书
+```
+
+- **微信小程序**是中国核心;抖音、小红书跟 Taro H5 SoT。
+- 小程序 **禁止 web-view** 承载业务(见 `no-webview-content.mdc`)。
+- `.com` 树 `apps/com/*` **无小程序**;小程序只走 `apps/miniprogram/*`。
+
+## 反模式
+
+- 默认 `deploy_*_82.py` / 只冒烟 `nomadro.cn` 却对用户说「已上线」
+- 把 `.cn` 当主站、把 `.com` 当镜像
+- 用 UI locale 代替受众轨;或假定 `.com` 中文与 `.cn` 共享同一后端
diff --git a/.cursor/rules/payments-i18n.mdc b/.cursor/rules/payments-i18n.mdc
index 34bd654..2a00876 100644
--- a/.cursor/rules/payments-i18n.mdc
+++ b/.cursor/rules/payments-i18n.mdc
@@ -16,7 +16,9 @@ alwaysApply: true
统一经 FastAPI(`apps/api`)写 PocketBase;前端勿直连商户密钥。
-## 多语言
+## 多语言与受众
-- 默认中文 / 英语;扩展日语、越南语、泰语等小语种
-- 门户已有 `lib/i18n` + `is-china-user`;垂直应用逐步对齐,勿再造冲突 locale 键
+- **`.com`**:国际(英语为主)默认;中文用户特殊对待(见 `audience-cn-intl.mdc`)
+- UI 语言:中文 / 英语;扩展日语、越南语、泰语等小语种
+- 支付分流跟 **`detectAudience().isChina`**(含微信内置),**不要**跟 UI locale
+- 门户:`lib/i18n` + `lib/audience` + `is-china-user`;垂直应用对齐,勿再造冲突 locale 键
diff --git a/.cursor/skills/nomadro-platform/SKILL.md b/.cursor/skills/nomadro-platform/SKILL.md
new file mode 100644
index 0000000..f38bf6c
--- /dev/null
+++ b/.cursor/skills/nomadro-platform/SKILL.md
@@ -0,0 +1,63 @@
+---
+name: nomadro-platform
+description: >-
+ Use Nomadro public API / SDK / MCP tools for nomadro.com (US primary).
+ Health, remote-config, social map/meetups/gigs/join, VIP check, nav links.
+ Prefer MCP tools or GET https://nomadro.com/api/public/v1/* .
+---
+
+# Nomadro Platform
+
+## Deploy truth
+
+- **Core**: `https://nomadro.com` (US). Default for agents and SDK `baseUrl`.
+- **China mirror**: `https://nomadro.cn` — independent; sync only after `.com` cn-audience is stable.
+- Audience lanes: `cn` | `intl` via `src/modules/audience`.
+
+## Surfaces (same tool list)
+
+| Surface | Entry |
+|---|---|
+| Docs UI | `https://nomadro.com/developers` (Scalar) |
+| OpenAPI | `GET /api/public/v1/openapi.json` |
+| Tools | `GET /api/public/v1/tools` |
+| SDK | `@nomadro/sdk` → `createNomadroClient({ baseUrl })` |
+| MCP | `pnpm mcp` / `node packages/mcp/src/cli.mjs` |
+| WeChat skill | `apps/miniprogram/weapp/ai-pkg/socialSkill` |
+
+Tool SoT: `packages/sdk/tools.json`
+
+## When to call which tool
+
+- Platform probe → `health` / `getMeta` / `getConfig`
+- Map / cities → `listMapCities` / `searchCities` → handoff `/social/map`
+- Video rooms → `listMeetups` / `openMeetup` (no web-view in miniprograms)
+- Gigs → `listGigs` / `applyGig` (name+contact required)
+- Paid community join (not VIP) → `joinSocial` → `/social/join`
+- VIP membership → `checkVip` with email
+- Nav catalog → `listNavLinks`
+
+## MCP config (Cursor)
+
+```json
+{
+ "mcpServers": {
+ "nomadro": {
+ "command": "node",
+ "args": ["packages/mcp/src/cli.mjs"],
+ "env": {
+ "NOMADRO_PUBLIC_ORIGIN": "https://nomadro.com"
+ }
+ }
+ }
+}
+```
+
+Optional: `NOMADRO_PUBLIC_API_KEY`, `NOMADRO_SOCIAL_GUEST_ID`.
+
+## Constraints
+
+1. Do not treat `.cn` as the default ship target.
+2. Social join ≠ VIP (`__social_join__` vs `__vip__`).
+3. Miniprogram content must stay native (no business web-view).
+4. Prefer returning `pagePath` handoffs so users complete pay/forms in UI.
diff --git a/.gitignore b/.gitignore
index 991c312..bc6c5c3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -42,6 +42,14 @@ node_modules/
# remote-config 本地备份(写入时自动生成)
/data/backups/
+/data/notify/
+/data/work/
+/data/coffee/
+
+# secondary-dev upstream clones (reference only)
+/apps/work/upstream/
+/apps/notify/upstream/
+/apps/coffee/upstream/
# debug
npm-debug.log*
diff --git a/AGENTS.md b/AGENTS.md
index 4d53c2c..8217ae5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -10,6 +10,8 @@ Follow `.cursor/rules/*.mdc`。
|---|---|
| Next portal(.com 主 / .cn 同步) | `src/app` + `src/modules` |
| 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/二级域 |
| Taro H5 SoT | `apps/miniprogram/h5`(weapp 共用 `../h5/src`) |
| Unified API | `apps/api` |
| Admin SPA (.cn) | `apps/admin` → `admin.nomadro.cn`(微信 / 抖音) |
diff --git a/README.md b/README.md
index 7118e02..6c259df 100644
--- a/README.md
+++ b/README.md
@@ -7,12 +7,14 @@
```
src/ Next.js 门户 .cn(app 路由壳 + modules 业务)
apps/miniprogram/ Taro:h5 SoT · weapp · tt · xhs(仅 .cn 备案线)
-apps/api/ 统一 FastAPI(ebook + community + pay + social + work)
+apps/api/ 统一 FastAPI(ebook + community + pay + social + work + notify)
apps/admin/ admin.nomadro.cn 管理 SPA(微信 / 抖音)
apps/com/ .com 源码隔离树(美国 VPS · 无小程序)→ admin.nomadro.com
apps/work/ 远程工作参考 upstream / overlay(Planka · Etherpad;产品 UI 不跑 iframe)
+apps/notify/ 通知参考 upstream(Novu;产品 UI 不跑 iframe)
+apps/coffee/ 咖啡聊预约参考 upstream(Cal.com;产品 UI 不跑 iframe)
packages/ @nomadro/pay · pb · sdk
-data/ 远程配置等运行时数据(含 social.db · work.sqlite3)
+data/ 远程配置等运行时数据(含 social.db · work/notify/coffee.sqlite3)
scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
```
@@ -23,6 +25,8 @@ scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
| 旅居社群 | `/community` | `src/modules/community`(Lounge / Ergo / MiroTalk;**勿改名**) |
| 游民社区 | `/social` | `src/modules/social` · API `/api/social/v1` · SQLite · Centrifugo 实时 · 视觉默认 T1 |
| **远程工作** | `/social/work` | `src/modules/work` · FastAPI `work_svc` `/api/work/v1`(看板 + 文档) |
+| **通知** | `/notifications` · `/social/notify` | `src/modules/notify` · FastAPI `notify_svc` `/api/notify/v1`(收件箱 + 工作流) |
+| **咖啡聊预约** | `/social/coffeechat` | `src/modules/coffee` · FastAPI `coffee_svc` `/api/coffee/v1`(Cal.com 域:日程/时段/预约) |
| VIP | `/vip` | `src/modules/vip`(微信小程序原生页,见下) |
| 后台 .cn | admin.nomadro.cn | `apps/admin`(`/wechat` · `/douyin`) |
| 后台 .com | admin.nomadro.com | `apps/com/admin`(**仅 Web**;美国 VPS) |
@@ -30,6 +34,69 @@ scripts/ 本地开发 / 清理(dev-api · clean-artifacts)
`.cn` 后台平台:`/wechat/*` 微信 · `/douyin/*` 抖音。抖音加群弹窗集成在 **`/douyin/modules`**。`.com` 未备案,**无**小程序后台。
+## 技术栈(Next 门户 + FastAPI)
+
+### 前端(`src/` · Next.js)
+
+| 层 | 技术 |
+|---|---|
+| 框架 | Next.js 16(App Router)· React 19 · TypeScript · pnpm workspace |
+| 样式 | Tailwind CSS 4 · Sass · 模块 CSS |
+| 主题 | `next-themes`(日/夜防闪烁) |
+| 动效 / 图标 | Framer Motion · animate.css · Lucide |
+| 地图 | MapLibre GL · h3-js |
+| 实时 | Centrifuge(对接 Centrifugo)· socket.io-client |
+| Markdown / 编辑 | react-markdown · marked · markdown-it · Gravity UI Markdown · Diplodoc · highlight.js |
+| DnD / 组件库 | `@hello-pangea/dnd` · Ant Design · Gravity UI · Semantic UI React |
+| 3D | three.js |
+| i18n / 受众 | i18next · `is-china-user` · `src/modules/audience/{cn,intl}` |
+| 其它 | PocketBase JS SDK · QR · PhotoSwipe · `@nomadro/{pay,pb,sdk}` |
+
+业务垂直在 `src/modules/{nav,ebook,community,social,work,notify,vip,audience}`;`src/app` 只挂路由。同源 API 经 Next Route Handler 反代到 FastAPI(如 `/api/work/v1`、`/api/notify/v1`)。
+
+### 后端(`apps/api` · FastAPI)
+
+| 层 | 技术 |
+|---|---|
+| 运行时 | FastAPI · Uvicorn |
+| 服务 | `ebook_svc` · `community_svc` · `pay_svc` · `social_svc` · `work_svc` · `notify_svc` · `coffee_svc` |
+| 独立进程 | `social_main :8020` · `work_main :8021` · `notify_main :8023` · `coffee_main :8024`(主 API 另有统一入口) |
+| 数据 | PocketBase(账号/订单等)· SQLite(social / work / notify / coffee) |
+| 对象存储 | SeaweedFS S3(`s3.nomadro.com`;社群 / 加入头像共用 `S3_*`) |
+| 支付 | 海外 Creem / NOWPayments;国内 zpay · xpay/xorpay;密钥只走 API |
+
+### 周边同仓
+
+| 端 | 技术 |
+|---|---|
+| 小程序 | Taro 4 + React(H5 SoT → 微信 / 抖音 / 小红书);**禁止 web-view 承载业务** |
+| 管理后台 | Vite SPA(`apps/admin` · `apps/com/admin`) |
+| 运维常见 | Nginx / Caddy · Docker · Umami · Uptime-Kuma · ntfy · SeaweedFS / MinIO |
+
+## 开源对照(域模型二次开发)
+
+原则:**读开源域模型后自研进 Nomadro**,同域原生页;**禁止** iframe / 二级域硬嵌官方 UI。上游仅对照:`pnpm work:fetch` · `pnpm notify:fetch`。
+
+| 开源项目 | 用途 | Nomadro 落点 |
+|---|---|---|
+| [Planka](https://github.com/plankanban/planka) | 看板域模型 | `/social/work/boards` · `work_svc` |
+| [Etherpad](https://github.com/ether/etherpad) | 协作文档 / 修订 | `/social/work/pads` · `work_svc` |
+| [Novu](https://github.com/novuhq/novu) | 通知工作流 / Inbox | `/social/notify` · `/notifications` · `notify_svc` |
+| [Cal.com](https://github.com/calcom/cal.com) | 预约 / 日程 / 时段 | `/social/coffeechat` · `coffee_svc` |
+| MiroTalk | 视频厅(白标同域) | 社群活动直播 / join |
+| Centrifugo | 实时推送 | Social 聊天 WebSocket |
+| PocketBase | BaaS / 鉴权与业务库 | `@nomadro/pb` · 支付写库 |
+| Taro | 多端小程序 | `apps/miniprogram/*` |
+| MapLibre | 地图 | `/social/map` 等 |
+| three.js | 3D | 门户 / H5(游戏模块冷冻) |
+| Umami | 分析 | 运维 |
+| Uptime-Kuma | 可用性监控 | 运维 |
+| ntfy | 运维通知 | 运维 |
+| SeaweedFS / MinIO | 对象存储(头像 / 社群媒体 → `s3.nomadro.com`) | `social_svc` · `community_svc` |
+| Caddy | 反代(可选) | 运维 |
+
+细节:[`apps/work/README.md`](apps/work/README.md) · [`apps/notify/README.md`](apps/notify/README.md)。
+
### 微信后台(admin.nomadro.cn/wechat)
侧栏分组:**总览** · **内容** · **运营** · **数据与发布**。系统字体;侧栏菜单区单独滚动、底栏固定。
@@ -95,6 +162,8 @@ pnpm dev:tt # 抖音小程序
pnpm dev:admin # 管理后台 :5173
pnpm dev:api # FastAPI(需先建 apps/api/.venv)
pnpm dev:work-api # 远程工作 work_svc :8021(看板 / 文档)
+pnpm dev:notify-api # 通知 notify_svc :8023(收件箱 / 工作流)
+pnpm dev:coffee-api # 咖啡聊 coffee_svc :8024(预约 / 时段)
pnpm build:portal
pnpm build:admin
@@ -130,6 +199,8 @@ pnpm dev:api
与旅居社群 `/community` **完全独立**:门户 `src/modules/social` + `src/app/social`;后端 `social_svc`(前缀 `/api/social/v1`,库文件 `data/social/social.db` 或 `SOCIAL_DB_PATH`);`SOCIAL_ENABLED=false` 或挂载失败不影响 ebook / community / pay。门户首页主入口为「游民社区」;旅居社群仍保留。增量部署见 [`deploy/social/README.md`](deploy/social/README.md)。
+**加入流程(`/social/join`)**:支付成功 → `?step=profile` 完善资料(PC 双栏 + 实时名片;H5 全宽)→ 完成。本地 `joinFlow` 标记;开发可跳过支付。**头像**:`POST /api/social/v1/upload` → 美国机 SeaweedFS(`s3.nomadro.com`,与 community 共用 `S3_*`);失败落本地 `/api/social/v1/files/avatar/*`。资料草稿挂载后再读 localStorage,避免 SSR hydration 不一致。
+
**地理发现**:`/social/map`、`/social/places`;内部 API `GET /api/social/v1/map/cities`。对外标准面:`/api/public/v1`(OpenAPI / SDK / MCP / Skill,见 [`docs/public-api.md`](docs/public-api.md))。**默认发版 `.com`(美国机)**;`.cn` 独立同步。
### 远程工作(`/social/work`)
@@ -149,7 +220,40 @@ pnpm dev # http://localhost:3000/social/work
数据:`data/work/work.sqlite3`(或 `WORK_DATA_DIR`)。参考 upstream:`pnpm work:fetch`(仅对照,产品不跑 Docker Planka UI)。细节见 [`apps/work/README.md`](apps/work/README.md)。
-| 层 | 线上(82) | 说明 |
+### 通知(`/notifications` · `/social/notify`)
+
+读 **Novu** 域模型后自研。用户向收件箱与编排控制台分离;同域原生页,**禁止** iframe。
+
+| 能力 | 路由 | 说明 |
+|------|------|------|
+| 全部通知 | `/social/notifications`(根路径 `/notifications` 重定向) | 分类:社交 / 搭子 / 项目 / 系统;点击跳转;全部/单条已读;删除 |
+| 偏好设置 | `/social/notifications/settings` | 免打扰 · 邮件订阅 · 浏览器推送授权 |
+| 顶部铃铛 | SiteShell | 未读角标,轮询 `/api/notify/v1/inbox/unread` |
+| 编排控制台 | `/social/notify` | 工作流 / 订阅者 / 主题 / 活动(Novu 二次开发) |
+
+```bash
+pnpm dev:notify-api # :8023 · NOTIFY_API_URL → /api/notify/v1
+pnpm notify:fetch # 可选对照源码
+pnpm dev # http://localhost:3000/notifications
+```
+
+数据:`data/notify/notify.sqlite3`。细节见 [`apps/notify/README.md`](apps/notify/README.md)。
+
+### 咖啡聊预约(`/social/coffeechat`)
+
+读 **Cal.com** 域模型后自研:Host · EventType · Schedule/Availability · Slots · Booking。同域原生页;咖啡馆点位仍见 `/social/places?tab=cafes`。
+
+```bash
+pnpm dev:coffee-api # :8024 · COFFEE_API_URL → /api/coffee/v1
+pnpm coffee:fetch # 可选对照源码
+pnpm dev # http://localhost:3000/social/coffeechat
+```
+
+数据:`data/coffee/coffee.sqlite3`。细节见 [`apps/coffee/README.md`](apps/coffee/README.md)。
+
+**`.com`(美国机,默认发版)**:`python deploy/work/deploy_us.py` → 门户 `nomadro` `:4003` + `nomadro-work` `:8021`;nginx `^~ /api/work/` **直连** work_svc(勿经 Next,避免 `Connection: upgrade` 导致 503)。冒烟:`https://nomadro.com/social/work` · `/api/work/v1/boards`。
+
+| 层 | 线上(82 · `.cn`) | 说明 |
|---|---|---|
| 门户 | `nomadro.service` `:4003` | `/social/*`;前端发版须**本地确认后再上线** |
| Social API | `nomadro-social.service` `:8020` | `apps/api/social_main.py`;nginx `/api/social/` |
@@ -223,6 +327,8 @@ pnpm dev # http://localhost:3000/social/work
| 管理后台 | 开关 / Social / 社群数据 / Books CRUD;`admin.nomadro.cn` |
| API | `config_live` 推送;admin CRUD;sqlite 加固;已部署 `api.nomadro.cn` |
| 禁令 | 全端无业务 web-view;WXSS 禁裸 `*`(sanitize) |
+| 加入资料 | `/social/join`:支付 → profile 双栏名片 · 头像 `POST /upload` → SeaweedFS `s3.nomadro.com` |
+| 同域自研 | `/social/work` · `/social/notify` · `/notifications` · `/social/coffeechat`(禁 iframe) |
提审上传:
diff --git a/apps/admin/README.md b/apps/admin/README.md
index c5e0173..087eb8b 100644
--- a/apps/admin/README.md
+++ b/apps/admin/README.md
@@ -2,6 +2,8 @@
Vite + React SPA。业务 API 经同源反代到 **`nomadmini-api`** / `apps/api`。
+> **`.com` Web 后台已源码隔离**:见 [`apps/com`](../com) → `admin.nomadro.com`(美国 VPS,无微信/抖音)。勿把小程序能力做到 `.com` 树,也勿把 `.com` 合回本包。
+
## 本地
```bash
diff --git a/apps/admin/deploy/deploy.py b/apps/admin/deploy/deploy.py
index 4af2356..54d2188 100644
--- a/apps/admin/deploy/deploy.py
+++ b/apps/admin/deploy/deploy.py
@@ -120,8 +120,8 @@ WX_APP_KEY=CBi5tdkkSWuvkDvWJNnSjrGmeYE3xlsg
WX_SANDBOX_APP_KEY=0wB3HV3sfKVTEgomZ6BIbgsN8Mlbv5Bn
WX_PAY_ENV=0
JWT_SECRET=nomadro-jwt-prod-2026
-ADMIN_USERNAME=admin
-ADMIN_PASSWORD=Xiao4669805
+ADMIN_USERNAME=hackrobot
+ADMIN_PASSWORD=Xiao4669805@
PB_URL=http://127.0.0.1:8090
PB_ADMIN_EMAIL=admin@nomadro.cn
PB_ADMIN_PASSWORD=Xiao4669805
diff --git a/apps/admin/src/pages/Login.tsx b/apps/admin/src/pages/Login.tsx
index 22f4138..5181829 100644
--- a/apps/admin/src/pages/Login.tsx
+++ b/apps/admin/src/pages/Login.tsx
@@ -4,7 +4,7 @@ import { api, setToken } from '../api'
export default function Login() {
const nav = useNavigate()
- const [username, setUsername] = useState('admin')
+ const [username, setUsername] = useState('hackrobot')
const [password, setPassword] = useState('')
const [err, setErr] = useState('')
const [loading, setLoading] = useState(false)
diff --git a/apps/admin/src/pages/Vip.tsx b/apps/admin/src/pages/Vip.tsx
index 58ab8a8..f83885b 100644
--- a/apps/admin/src/pages/Vip.tsx
+++ b/apps/admin/src/pages/Vip.tsx
@@ -125,7 +125,7 @@ const empty: VipCfg = {
gameEnabled: false,
joinGroupAction: 'popup',
vipWebBridgeEnabled: false,
- vipPriceFen: 29800,
+ vipPriceFen: 8800,
vipProductId: 'tiktok',
vipCta: '立即加入',
vipOfferKey: 'tiktok',
diff --git a/apps/api/coffee_main.py b/apps/api/coffee_main.py
new file mode 100644
index 0000000..c5e1ce5
--- /dev/null
+++ b/apps/api/coffee_main.py
@@ -0,0 +1,42 @@
+"""Nomadro coffeechat booking API — Cal.com-domain secondary-dev."""
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+from fastapi import FastAPI
+from fastapi.middleware.cors import CORSMiddleware
+
+ROOT = Path(__file__).resolve().parent
+SERVICES = ROOT / "services"
+sys.path.insert(0, str(ROOT))
+sys.path.insert(0, str(SERVICES))
+
+from coffee_svc.config import COFFEE_ENABLED # noqa: E402
+from coffee_svc.routers import router as coffee_router # noqa: E402
+from coffee_svc.store import init_db # noqa: E402
+
+app = FastAPI(title="nomadro-coffee", docs_url="/docs", redoc_url=None)
+
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=["*"],
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+
+@app.on_event("startup")
+def _startup() -> None:
+ if COFFEE_ENABLED:
+ init_db()
+
+
+if COFFEE_ENABLED:
+ app.include_router(coffee_router, prefix="/api/coffee/v1")
+
+
+@app.get("/health")
+def health():
+ return {"ok": True, "service": "nomadro-coffee", "coffee": bool(COFFEE_ENABLED)}
diff --git a/apps/api/notify_main.py b/apps/api/notify_main.py
new file mode 100644
index 0000000..9237811
--- /dev/null
+++ b/apps/api/notify_main.py
@@ -0,0 +1,42 @@
+"""Nomadro notify API — Novu-domain workflows + inbox (secondary-dev)."""
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+from fastapi import FastAPI
+from fastapi.middleware.cors import CORSMiddleware
+
+ROOT = Path(__file__).resolve().parent
+SERVICES = ROOT / "services"
+sys.path.insert(0, str(ROOT))
+sys.path.insert(0, str(SERVICES))
+
+from notify_svc.config import NOTIFY_ENABLED # noqa: E402
+from notify_svc.routers import router as notify_router # noqa: E402
+from notify_svc.store import init_db # noqa: E402
+
+app = FastAPI(title="nomadro-notify", docs_url="/docs", redoc_url=None)
+
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=["*"],
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+
+@app.on_event("startup")
+def _startup() -> None:
+ if NOTIFY_ENABLED:
+ init_db()
+
+
+if NOTIFY_ENABLED:
+ app.include_router(notify_router, prefix="/api/notify/v1")
+
+
+@app.get("/health")
+def health():
+ return {"ok": True, "service": "nomadro-notify", "notify": bool(NOTIFY_ENABLED)}
diff --git a/apps/api/requirements.txt b/apps/api/requirements.txt
index b45bb74..64a29e2 100644
--- a/apps/api/requirements.txt
+++ b/apps/api/requirements.txt
@@ -16,6 +16,7 @@ email-validator==2.2.0
boto3==1.35.99
sqlalchemy
pocketbase
+h3
requests
minio
opencv-python-headless
diff --git a/apps/api/services/coffee_svc/__init__.py b/apps/api/services/coffee_svc/__init__.py
new file mode 100644
index 0000000..7190938
--- /dev/null
+++ b/apps/api/services/coffee_svc/__init__.py
@@ -0,0 +1 @@
+"""Nomadro coffeechat booking — Cal.com-domain secondary-dev."""
diff --git a/apps/api/services/coffee_svc/config.py b/apps/api/services/coffee_svc/config.py
new file mode 100644
index 0000000..4500031
--- /dev/null
+++ b/apps/api/services/coffee_svc/config.py
@@ -0,0 +1,21 @@
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+COFFEE_ENABLED = os.getenv("COFFEE_ENABLED", "1").strip().lower() not in {
+ "0",
+ "false",
+ "no",
+ "off",
+}
+
+DATA_DIR = Path(os.getenv("COFFEE_DATA_DIR", "/var/lib/nomadro/coffee"))
+if not DATA_DIR.exists():
+ DATA_DIR = (
+ Path(os.getenv("COFFEE_DATA_DIR_LOCAL", "")).resolve()
+ if os.getenv("COFFEE_DATA_DIR_LOCAL")
+ else Path.cwd() / "data" / "coffee"
+ )
+
+DB_PATH = DATA_DIR / "coffee.sqlite3"
diff --git a/apps/api/services/coffee_svc/routers/__init__.py b/apps/api/services/coffee_svc/routers/__init__.py
new file mode 100644
index 0000000..502d465
--- /dev/null
+++ b/apps/api/services/coffee_svc/routers/__init__.py
@@ -0,0 +1,3 @@
+from .api import router
+
+__all__ = ["router"]
diff --git a/apps/api/services/coffee_svc/routers/api.py b/apps/api/services/coffee_svc/routers/api.py
new file mode 100644
index 0000000..7bc8215
--- /dev/null
+++ b/apps/api/services/coffee_svc/routers/api.py
@@ -0,0 +1,142 @@
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Query
+from pydantic import BaseModel, Field
+
+from coffee_svc import store
+
+router = APIRouter(tags=["coffee"])
+
+
+class SchedulePatch(BaseModel):
+ availability: list[dict[str, Any]] | None = None
+ timezone: str | None = None
+ name: str | None = None
+
+
+class EventTypeIn(BaseModel):
+ slug: str = Field(min_length=1, max_length=80)
+ title: str = Field(min_length=1, max_length=200)
+ description: str = ""
+ length_minutes: int = Field(default=30, ge=5, le=480)
+ slot_interval: int = Field(default=15, ge=5, le=60)
+ locations: list[dict[str, Any]] = Field(default_factory=list)
+ active: bool = True
+ buffer_before: int = 0
+ buffer_after: int = 0
+
+
+class BookingIn(BaseModel):
+ username: str = Field(min_length=1, max_length=80)
+ event_slug: str = Field(min_length=1, max_length=80)
+ start: str = Field(min_length=1, max_length=40)
+ attendee_name: str = Field(min_length=1, max_length=120)
+ attendee_email: str | None = None
+ attendee_device: str | None = None
+ location: str | None = None
+ notes: str = ""
+
+
+@router.get("/health")
+def health():
+ return {"ok": True, "service": "nomadro-coffee", "inspiredBy": ["cal.com"]}
+
+
+@router.get("/hosts")
+def hosts():
+ return {"ok": True, "hosts": store.list_hosts()}
+
+
+@router.get("/hosts/{username}")
+def host(username: str):
+ h = store.get_host(username)
+ if not h:
+ raise HTTPException(404, "host_not_found")
+ return {"ok": True, "host": h}
+
+
+@router.get("/hosts/{username}/schedule")
+def schedule(username: str):
+ s = store.get_schedule(username)
+ if not s:
+ raise HTTPException(404, "schedule_not_found")
+ return {"ok": True, "schedule": s}
+
+
+@router.patch("/hosts/{username}/schedule")
+def patch_schedule(username: str, body: SchedulePatch):
+ try:
+ s = store.update_schedule(
+ username,
+ availability=body.availability,
+ timezone_name=body.timezone,
+ name=body.name,
+ )
+ except ValueError as e:
+ raise HTTPException(400, str(e)) from e
+ return {"ok": True, "schedule": s}
+
+
+@router.get("/hosts/{username}/event-types/{slug}")
+def event_type(username: str, slug: str):
+ e = store.get_event_type(username, slug)
+ if not e:
+ raise HTTPException(404, "event_type_not_found")
+ return {"ok": True, "event_type": e}
+
+
+@router.post("/hosts/{username}/event-types")
+def create_event_type(username: str, body: EventTypeIn):
+ try:
+ e = store.upsert_event_type(username, body.model_dump())
+ except ValueError as e:
+ raise HTTPException(400, str(e)) from e
+ return {"ok": True, "event_type": e}
+
+
+@router.get("/hosts/{username}/event-types/{slug}/slots")
+def slots(
+ username: str,
+ slug: str,
+ day: str = Query(..., description="YYYY-MM-DD in host local timezone"),
+):
+ try:
+ return store.available_slots(username, slug, day)
+ except ValueError as e:
+ raise HTTPException(400, str(e)) from e
+
+
+@router.get("/bookings")
+def bookings(
+ host: str | None = Query(default=None),
+ status: str | None = Query(default=None),
+):
+ return {"ok": True, "bookings": store.list_bookings(host_username=host, status=status)}
+
+
+@router.get("/bookings/{booking_id}")
+def booking(booking_id: str):
+ b = store.get_booking(booking_id)
+ if not b:
+ raise HTTPException(404, "booking_not_found")
+ return {"ok": True, "booking": b}
+
+
+@router.post("/bookings")
+def book(body: BookingIn):
+ try:
+ b = store.create_booking(body.model_dump())
+ except ValueError as e:
+ code = 409 if str(e) == "slot_unavailable" else 400
+ raise HTTPException(code, str(e)) from e
+ return {"ok": True, "booking": b}
+
+
+@router.post("/bookings/{booking_id}/cancel")
+def cancel(booking_id: str):
+ b = store.cancel_booking(booking_id)
+ if not b:
+ raise HTTPException(404, "booking_not_found")
+ return {"ok": True, "booking": b}
diff --git a/apps/api/services/coffee_svc/store.py b/apps/api/services/coffee_svc/store.py
new file mode 100644
index 0000000..e53128c
--- /dev/null
+++ b/apps/api/services/coffee_svc/store.py
@@ -0,0 +1,719 @@
+"""
+SQLite store — domain shaped after Cal.com
+(User/Host · EventType · Schedule · Availability · Booking · Attendee · Slot).
+Secondary-dev reimplementation for Nomadro coffeechat (not upstream Cal runtime).
+"""
+from __future__ import annotations
+
+import json
+import sqlite3
+import time
+import uuid
+from datetime import date, datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any
+from zoneinfo import ZoneInfo
+
+from .config import DATA_DIR, DB_PATH
+
+try:
+ from ebook_svc.core.sqlite_util import connect as _connect
+except Exception: # pragma: no cover
+
+ def _connect(path: str | Path, *, timeout: float = 30.0) -> sqlite3.Connection:
+ p = Path(path)
+ p.parent.mkdir(parents=True, exist_ok=True)
+ c = sqlite3.connect(str(p), timeout=timeout)
+ c.row_factory = sqlite3.Row
+ c.execute("PRAGMA journal_mode=WAL")
+ return c
+
+
+WEEKDAYS = ("sun", "mon", "tue", "wed", "thu", "fri", "sat")
+# Cal.com uses 0=Sunday … Python weekday() is 0=Monday — map carefully
+PY_TO_CAL = {0: "mon", 1: "tue", 2: "wed", 3: "thu", 4: "fri", 5: "sat", 6: "sun"}
+
+
+def _now() -> str:
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+
+
+def _id(prefix: str) -> str:
+ return f"{prefix}_{uuid.uuid4().hex[:10]}"
+
+
+def _conn() -> sqlite3.Connection:
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
+ return _connect(DB_PATH)
+
+
+def _json(v: Any) -> str:
+ return json.dumps(v, ensure_ascii=False)
+
+
+def _parse(s: str | None, default: Any = None) -> Any:
+ if not s:
+ return default if default is not None else {}
+ try:
+ return json.loads(s)
+ except Exception:
+ return default if default is not None else {}
+
+
+def init_db() -> None:
+ with _conn() as c:
+ c.executescript(
+ """
+ CREATE TABLE IF NOT EXISTS hosts (
+ id TEXT PRIMARY KEY,
+ username TEXT NOT NULL UNIQUE,
+ name TEXT NOT NULL,
+ bio TEXT NOT NULL DEFAULT '',
+ avatar TEXT,
+ timezone TEXT NOT NULL DEFAULT 'Asia/Shanghai',
+ city TEXT NOT NULL DEFAULT '',
+ created_at TEXT NOT NULL
+ );
+ CREATE TABLE IF NOT EXISTS schedules (
+ id TEXT PRIMARY KEY,
+ host_id TEXT NOT NULL,
+ name TEXT NOT NULL DEFAULT 'Working hours',
+ timezone TEXT NOT NULL DEFAULT 'Asia/Shanghai',
+ availability_json TEXT NOT NULL DEFAULT '[]',
+ created_at TEXT NOT NULL,
+ FOREIGN KEY(host_id) REFERENCES hosts(id)
+ );
+ CREATE TABLE IF NOT EXISTS event_types (
+ id TEXT PRIMARY KEY,
+ host_id TEXT NOT NULL,
+ schedule_id TEXT NOT NULL,
+ slug TEXT NOT NULL,
+ title TEXT NOT NULL,
+ description TEXT NOT NULL DEFAULT '',
+ length_minutes INTEGER NOT NULL DEFAULT 30,
+ slot_interval INTEGER NOT NULL DEFAULT 15,
+ buffer_before INTEGER NOT NULL DEFAULT 0,
+ buffer_after INTEGER NOT NULL DEFAULT 0,
+ locations_json TEXT NOT NULL DEFAULT '[]',
+ active INTEGER NOT NULL DEFAULT 1,
+ created_at TEXT NOT NULL,
+ UNIQUE(host_id, slug),
+ FOREIGN KEY(host_id) REFERENCES hosts(id),
+ FOREIGN KEY(schedule_id) REFERENCES schedules(id)
+ );
+ CREATE TABLE IF NOT EXISTS bookings (
+ id TEXT PRIMARY KEY,
+ uid TEXT NOT NULL UNIQUE,
+ event_type_id TEXT NOT NULL,
+ host_id TEXT NOT NULL,
+ title TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'accepted',
+ start_utc TEXT NOT NULL,
+ end_utc TEXT NOT NULL,
+ location TEXT NOT NULL DEFAULT '',
+ notes TEXT NOT NULL DEFAULT '',
+ attendee_name TEXT NOT NULL,
+ attendee_email TEXT,
+ attendee_device TEXT,
+ created_at TEXT NOT NULL,
+ cancelled_at TEXT,
+ FOREIGN KEY(event_type_id) REFERENCES event_types(id),
+ FOREIGN KEY(host_id) REFERENCES hosts(id)
+ );
+ CREATE INDEX IF NOT EXISTS idx_bookings_host_start
+ ON bookings(host_id, start_utc);
+ """
+ )
+ _seed(c)
+
+
+def _default_availability() -> list[dict[str, Any]]:
+ """Cal.com-style weekly windows (local schedule timezone)."""
+ windows = [{"days": ["mon", "tue", "wed", "thu", "fri"], "startTime": 600, "endTime": 720}]
+ # 10:00–12:00 and 14:00–18:00 as minutes from midnight
+ windows.append(
+ {"days": ["mon", "tue", "wed", "thu", "fri"], "startTime": 840, "endTime": 1080}
+ )
+ windows.append({"days": ["sat"], "startTime": 660, "endTime": 900})
+ return windows
+
+
+def _seed(c: sqlite3.Connection) -> None:
+ if c.execute("SELECT 1 FROM hosts LIMIT 1").fetchone():
+ return
+ now = _now()
+ hosts = [
+ ("host_alice", "alice", "Alice Chen", "成都远程 · 爱咖啡闲聊产品与出海", "Chengdu", "Asia/Shanghai"),
+ ("host_bob", "bob", "Bob Rivera", "EN/ZH · coffee or video walkthrough", "Chiang Mai", "Asia/Bangkok"),
+ ("host_guest", "guest", "Guest Nomad", "演示主持人 · 可约 30 分钟咖啡聊", "Shenzhen", "Asia/Shanghai"),
+ ]
+ for hid, user, name, bio, city, tz in hosts:
+ c.execute(
+ """INSERT INTO hosts(id,username,name,bio,avatar,timezone,city,created_at)
+ VALUES(?,?,?,?,?,?,?,?)""",
+ (hid, user, name, bio, None, tz, city, now),
+ )
+ sid = f"sch_{user}"
+ c.execute(
+ """INSERT INTO schedules(id,host_id,name,timezone,availability_json,created_at)
+ VALUES(?,?,?,?,?,?)""",
+ (sid, hid, "Working hours", tz, _json(_default_availability()), now),
+ )
+ events = [
+ (
+ f"et_{user}_coffee",
+ "coffee-30",
+ "☕ 咖啡聊 30′",
+ "同城咖啡馆或语音闲聊,认识一下就好。",
+ 30,
+ [
+ {"type": "inPerson", "label": "咖啡馆(见面后定)"},
+ {"type": "link", "label": "语音/视频", "link": "/social/meetup"},
+ ],
+ ),
+ (
+ f"et_{user}_video",
+ "video-45",
+ "📹 视频深聊 45′",
+ "产品 / 副业 / 旅居经验,线上视频。",
+ 45,
+ [{"type": "link", "label": "Nomadro 视频厅", "link": "/social/meetup"}],
+ ),
+ ]
+ for eid, slug, title, desc, length, locs in events:
+ c.execute(
+ """INSERT INTO event_types(
+ id,host_id,schedule_id,slug,title,description,length_minutes,
+ slot_interval,buffer_before,buffer_after,locations_json,active,created_at
+ ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""",
+ (
+ eid,
+ hid,
+ sid,
+ slug,
+ title,
+ desc,
+ length,
+ 15,
+ 0,
+ 0,
+ _json(locs),
+ 1,
+ now,
+ ),
+ )
+
+ # sample booking tomorrow 10:00 Asia/Shanghai for alice coffee
+ tz = ZoneInfo("Asia/Shanghai")
+ tomorrow = datetime.now(tz).date() + timedelta(days=1)
+ start_local = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 10, 0, tzinfo=tz)
+ end_local = start_local + timedelta(minutes=30)
+ c.execute(
+ """INSERT INTO bookings(
+ id,uid,event_type_id,host_id,title,status,start_utc,end_utc,location,notes,
+ attendee_name,attendee_email,attendee_device,created_at,cancelled_at
+ ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
+ (
+ _id("bk"),
+ _id("uid"),
+ "et_alice_coffee",
+ "host_alice",
+ "☕ 咖啡聊 30′",
+ "accepted",
+ start_local.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ end_local.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "咖啡馆(见面后定)",
+ "种子预约",
+ "Demo Attendee",
+ "demo@nomadro.com",
+ None,
+ now,
+ None,
+ ),
+ )
+
+
+# —— hosts / event types ——
+
+
+def list_hosts() -> list[dict[str, Any]]:
+ with _conn() as c:
+ rows = c.execute("SELECT * FROM hosts ORDER BY username").fetchall()
+ out = []
+ for r in rows:
+ n = c.execute(
+ "SELECT COUNT(*) AS n FROM event_types WHERE host_id=? AND active=1",
+ (r["id"],),
+ ).fetchone()["n"]
+ out.append(_host_out(dict(r), event_count=n))
+ return out
+
+
+def get_host(username: str) -> dict[str, Any] | None:
+ with _conn() as c:
+ r = c.execute(
+ "SELECT * FROM hosts WHERE username=? OR id=?",
+ (username, username),
+ ).fetchone()
+ if not r:
+ return None
+ events = [
+ _event_out(dict(e))
+ for e in c.execute(
+ "SELECT * FROM event_types WHERE host_id=? AND active=1 ORDER BY length_minutes",
+ (r["id"],),
+ ).fetchall()
+ ]
+ h = _host_out(dict(r), event_count=len(events))
+ h["event_types"] = events
+ return h
+
+
+def _host_out(r: dict[str, Any], *, event_count: int = 0) -> dict[str, Any]:
+ return {
+ "id": r["id"],
+ "username": r["username"],
+ "name": r["name"],
+ "bio": r.get("bio") or "",
+ "avatar": r.get("avatar"),
+ "timezone": r.get("timezone") or "Asia/Shanghai",
+ "city": r.get("city") or "",
+ "event_count": event_count,
+ "created_at": r.get("created_at"),
+ }
+
+
+def get_event_type(username: str, slug: str) -> dict[str, Any] | None:
+ with _conn() as c:
+ h = c.execute(
+ "SELECT * FROM hosts WHERE username=? OR id=?",
+ (username, username),
+ ).fetchone()
+ if not h:
+ return None
+ e = c.execute(
+ "SELECT * FROM event_types WHERE host_id=? AND slug=?",
+ (h["id"], slug),
+ ).fetchone()
+ if not e:
+ return None
+ out = _event_out(dict(e))
+ out["host"] = _host_out(dict(h))
+ sch = c.execute(
+ "SELECT * FROM schedules WHERE id=?", (e["schedule_id"],)
+ ).fetchone()
+ if sch:
+ out["schedule"] = _schedule_out(dict(sch))
+ return out
+
+
+def _event_out(r: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "id": r["id"],
+ "host_id": r["host_id"],
+ "schedule_id": r["schedule_id"],
+ "slug": r["slug"],
+ "title": r["title"],
+ "description": r.get("description") or "",
+ "length_minutes": int(r["length_minutes"]),
+ "slot_interval": int(r.get("slot_interval") or 15),
+ "buffer_before": int(r.get("buffer_before") or 0),
+ "buffer_after": int(r.get("buffer_after") or 0),
+ "locations": _parse(r.get("locations_json"), []),
+ "active": bool(r.get("active")),
+ "created_at": r.get("created_at"),
+ }
+
+
+def _schedule_out(r: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "id": r["id"],
+ "host_id": r["host_id"],
+ "name": r["name"],
+ "timezone": r["timezone"],
+ "availability": _parse(r.get("availability_json"), []),
+ "created_at": r["created_at"],
+ }
+
+
+def get_schedule(host_username: str) -> dict[str, Any] | None:
+ with _conn() as c:
+ h = c.execute(
+ "SELECT * FROM hosts WHERE username=? OR id=?",
+ (host_username, host_username),
+ ).fetchone()
+ if not h:
+ return None
+ s = c.execute(
+ "SELECT * FROM schedules WHERE host_id=? ORDER BY created_at LIMIT 1",
+ (h["id"],),
+ ).fetchone()
+ return _schedule_out(dict(s)) if s else None
+
+
+def update_schedule(
+ host_username: str,
+ *,
+ availability: list[dict[str, Any]] | None = None,
+ timezone_name: str | None = None,
+ name: str | None = None,
+) -> dict[str, Any]:
+ with _conn() as c:
+ h = c.execute(
+ "SELECT * FROM hosts WHERE username=? OR id=?",
+ (host_username, host_username),
+ ).fetchone()
+ if not h:
+ raise ValueError("host_not_found")
+ s = c.execute(
+ "SELECT * FROM schedules WHERE host_id=? ORDER BY created_at LIMIT 1",
+ (h["id"],),
+ ).fetchone()
+ if not s:
+ raise ValueError("schedule_not_found")
+ avail = (
+ _json(availability)
+ if availability is not None
+ else s["availability_json"]
+ )
+ tz = timezone_name or s["timezone"]
+ nm = name or s["name"]
+ c.execute(
+ "UPDATE schedules SET availability_json=?, timezone=?, name=? WHERE id=?",
+ (avail, tz, nm, s["id"]),
+ )
+ if timezone_name:
+ c.execute(
+ "UPDATE hosts SET timezone=? WHERE id=?",
+ (timezone_name, h["id"]),
+ )
+ row = c.execute("SELECT * FROM schedules WHERE id=?", (s["id"],)).fetchone()
+ return _schedule_out(dict(row))
+
+
+def upsert_event_type(
+ host_username: str,
+ data: dict[str, Any],
+) -> dict[str, Any]:
+ slug = (data.get("slug") or "").strip()
+ title = (data.get("title") or "").strip()
+ if not slug or not title:
+ raise ValueError("slug_and_title_required")
+ with _conn() as c:
+ h = c.execute(
+ "SELECT * FROM hosts WHERE username=? OR id=?",
+ (host_username, host_username),
+ ).fetchone()
+ if not h:
+ raise ValueError("host_not_found")
+ sch = c.execute(
+ "SELECT id FROM schedules WHERE host_id=? LIMIT 1",
+ (h["id"],),
+ ).fetchone()
+ if not sch:
+ raise ValueError("schedule_not_found")
+ existing = c.execute(
+ "SELECT * FROM event_types WHERE host_id=? AND slug=?",
+ (h["id"], slug),
+ ).fetchone()
+ length = int(data.get("length_minutes") or 30)
+ interval = int(data.get("slot_interval") or 15)
+ locs = data.get("locations") or [
+ {"type": "inPerson", "label": "咖啡馆(见面后定)"}
+ ]
+ now = _now()
+ if existing:
+ c.execute(
+ """UPDATE event_types SET title=?,description=?,length_minutes=?,
+ slot_interval=?,locations_json=?,active=? WHERE id=?""",
+ (
+ title,
+ data.get("description") or "",
+ length,
+ interval,
+ _json(locs),
+ 1 if data.get("active", True) else 0,
+ existing["id"],
+ ),
+ )
+ eid = existing["id"]
+ else:
+ eid = _id("et")
+ c.execute(
+ """INSERT INTO event_types(
+ id,host_id,schedule_id,slug,title,description,length_minutes,
+ slot_interval,buffer_before,buffer_after,locations_json,active,created_at
+ ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""",
+ (
+ eid,
+ h["id"],
+ sch["id"],
+ slug,
+ title,
+ data.get("description") or "",
+ length,
+ interval,
+ int(data.get("buffer_before") or 0),
+ int(data.get("buffer_after") or 0),
+ _json(locs),
+ 1,
+ now,
+ ),
+ )
+ row = c.execute("SELECT * FROM event_types WHERE id=?", (eid,)).fetchone()
+ return _event_out(dict(row))
+
+
+# —— slots (Cal.com getSchedule / availableSlots parity) ——
+
+
+def _parse_utc(s: str) -> datetime:
+ if s.endswith("Z"):
+ s = s[:-1] + "+00:00"
+ return datetime.fromisoformat(s).astimezone(timezone.utc)
+
+
+def available_slots(
+ username: str,
+ event_slug: str,
+ day: str,
+) -> dict[str, Any]:
+ """Return bookable UTC slots for a local calendar day (YYYY-MM-DD)."""
+ et = get_event_type(username, event_slug)
+ if not et or not et.get("active"):
+ raise ValueError("event_type_not_found")
+ host = et["host"]
+ sch = et.get("schedule") or {}
+ tz_name = sch.get("timezone") or host.get("timezone") or "Asia/Shanghai"
+ try:
+ tz = ZoneInfo(tz_name)
+ except Exception:
+ tz = ZoneInfo("Asia/Shanghai")
+ tz_name = "Asia/Shanghai"
+
+ try:
+ day_d = date.fromisoformat(day)
+ except ValueError as e:
+ raise ValueError("invalid_day") from e
+
+ length = int(et["length_minutes"])
+ interval = int(et.get("slot_interval") or 15)
+ buf_before = int(et.get("buffer_before") or 0)
+ buf_after = int(et.get("buffer_after") or 0)
+ cal_day = PY_TO_CAL[day_d.weekday()]
+ windows = [
+ w
+ for w in (sch.get("availability") or [])
+ if cal_day in (w.get("days") or [])
+ ]
+ if not windows:
+ return {
+ "ok": True,
+ "day": day,
+ "timezone": tz_name,
+ "slots": [],
+ "event_type": {"slug": et["slug"], "length_minutes": length},
+ }
+
+ # busy from accepted bookings that day (host local)
+ day_start = datetime(day_d.year, day_d.month, day_d.day, 0, 0, tzinfo=tz)
+ day_end = day_start + timedelta(days=1)
+ with _conn() as c:
+ busy_rows = c.execute(
+ """SELECT start_utc,end_utc FROM bookings
+ WHERE host_id=? AND status='accepted'
+ AND start_utc < ? AND end_utc > ?""",
+ (
+ host["id"],
+ day_end.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ day_start.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ ),
+ ).fetchall()
+ busy = [(_parse_utc(b["start_utc"]), _parse_utc(b["end_utc"])) for b in busy_rows]
+
+ now_utc = datetime.now(timezone.utc)
+ slots: list[dict[str, str]] = []
+ for w in windows:
+ start_m = int(w.get("startTime") or 0)
+ end_m = int(w.get("endTime") or 0)
+ cursor = day_start + timedelta(minutes=start_m)
+ window_end = day_start + timedelta(minutes=end_m)
+ while cursor + timedelta(minutes=length) <= window_end:
+ slot_start = cursor
+ slot_end = cursor + timedelta(minutes=length)
+ slot_start_utc = slot_start.astimezone(timezone.utc)
+ slot_end_utc = slot_end.astimezone(timezone.utc)
+ # past
+ if slot_start_utc <= now_utc + timedelta(minutes=5):
+ cursor += timedelta(minutes=interval)
+ continue
+ # overlap busy with buffers
+ blocked = False
+ for b0, b1 in busy:
+ a0 = slot_start_utc - timedelta(minutes=buf_before)
+ a1 = slot_end_utc + timedelta(minutes=buf_after)
+ if a0 < b1 and a1 > b0:
+ blocked = True
+ break
+ if not blocked:
+ slots.append(
+ {
+ "start": slot_start_utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "end": slot_end_utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "local": slot_start.strftime("%H:%M"),
+ }
+ )
+ cursor += timedelta(minutes=interval)
+
+ return {
+ "ok": True,
+ "day": day,
+ "timezone": tz_name,
+ "slots": slots,
+ "event_type": {
+ "slug": et["slug"],
+ "title": et["title"],
+ "length_minutes": length,
+ },
+ "host": {"username": host["username"], "name": host["name"]},
+ }
+
+
+# —— bookings ——
+
+
+def create_booking(data: dict[str, Any]) -> dict[str, Any]:
+ username = (data.get("username") or "").strip()
+ slug = (data.get("event_slug") or data.get("slug") or "").strip()
+ start = (data.get("start") or "").strip()
+ attendee_name = (data.get("attendee_name") or "").strip()
+ if not username or not slug or not start or not attendee_name:
+ raise ValueError("username_slug_start_attendee_required")
+
+ et = get_event_type(username, slug)
+ if not et or not et.get("active"):
+ raise ValueError("event_type_not_found")
+
+ start_utc = _parse_utc(start if "T" in start else start + "Z")
+ end_utc = start_utc + timedelta(minutes=int(et["length_minutes"]))
+ day = start_utc.astimezone(
+ ZoneInfo(et["host"].get("timezone") or "Asia/Shanghai")
+ ).date().isoformat()
+
+ # re-validate slot still free
+ avail = available_slots(username, slug, day)
+ ok_starts = {s["start"] for s in avail["slots"]}
+ start_key = start_utc.strftime("%Y-%m-%dT%H:%M:%SZ")
+ if start_key not in ok_starts:
+ raise ValueError("slot_unavailable")
+
+ locs = et.get("locations") or []
+ loc_label = data.get("location") or (
+ locs[0].get("label") if locs else "Coffeechat"
+ )
+ now = _now()
+ bid = _id("bk")
+ uid = _id("uid")
+ with _conn() as c:
+ c.execute(
+ """INSERT INTO bookings(
+ id,uid,event_type_id,host_id,title,status,start_utc,end_utc,location,notes,
+ attendee_name,attendee_email,attendee_device,created_at,cancelled_at
+ ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
+ (
+ bid,
+ uid,
+ et["id"],
+ et["host"]["id"],
+ et["title"],
+ "accepted",
+ start_key,
+ end_utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ loc_label,
+ data.get("notes") or "",
+ attendee_name,
+ data.get("attendee_email"),
+ data.get("attendee_device"),
+ now,
+ None,
+ ),
+ )
+ return get_booking(bid) # type: ignore[return-value]
+
+
+def get_booking(booking_id: str) -> dict[str, Any] | None:
+ with _conn() as c:
+ r = c.execute(
+ "SELECT * FROM bookings WHERE id=? OR uid=?",
+ (booking_id, booking_id),
+ ).fetchone()
+ if not r:
+ return None
+ h = c.execute("SELECT username,name,city FROM hosts WHERE id=?", (r["host_id"],)).fetchone()
+ return _booking_out(dict(r), host=dict(h) if h else None)
+
+
+def list_bookings(
+ *,
+ host_username: str | None = None,
+ status: str | None = None,
+) -> list[dict[str, Any]]:
+ with _conn() as c:
+ q = "SELECT b.* FROM bookings b"
+ args: list[Any] = []
+ if host_username:
+ q += " JOIN hosts h ON h.id=b.host_id WHERE (h.username=? OR h.id=?)"
+ args.extend([host_username, host_username])
+ else:
+ q += " WHERE 1=1"
+ if status:
+ q += " AND b.status=?"
+ args.append(status)
+ q += " ORDER BY b.start_utc DESC LIMIT 100"
+ rows = c.execute(q, args).fetchall()
+ out = []
+ for r in rows:
+ h = c.execute(
+ "SELECT username,name,city FROM hosts WHERE id=?",
+ (r["host_id"],),
+ ).fetchone()
+ out.append(_booking_out(dict(r), host=dict(h) if h else None))
+ return out
+
+
+def cancel_booking(booking_id: str) -> dict[str, Any] | None:
+ with _conn() as c:
+ r = c.execute(
+ "SELECT id FROM bookings WHERE id=? OR uid=?",
+ (booking_id, booking_id),
+ ).fetchone()
+ if not r:
+ return None
+ c.execute(
+ "UPDATE bookings SET status='cancelled', cancelled_at=? WHERE id=?",
+ (_now(), r["id"]),
+ )
+ return get_booking(r["id"])
+
+
+def _booking_out(r: dict[str, Any], host: dict[str, Any] | None = None) -> dict[str, Any]:
+ return {
+ "id": r["id"],
+ "uid": r["uid"],
+ "event_type_id": r["event_type_id"],
+ "host_id": r["host_id"],
+ "host": host,
+ "title": r["title"],
+ "status": r["status"],
+ "start": r["start_utc"],
+ "end": r["end_utc"],
+ "location": r.get("location") or "",
+ "notes": r.get("notes") or "",
+ "attendee": {
+ "name": r["attendee_name"],
+ "email": r.get("attendee_email"),
+ "device": r.get("attendee_device"),
+ },
+ "created_at": r["created_at"],
+ "cancelled_at": r.get("cancelled_at"),
+ }
diff --git a/apps/api/services/ebook_svc/config.py b/apps/api/services/ebook_svc/config.py
index d42f21d..e8c0781 100644
--- a/apps/api/services/ebook_svc/config.py
+++ b/apps/api/services/ebook_svc/config.py
@@ -33,8 +33,8 @@ class Settings(BaseSettings):
# JWT / Admin
jwt_secret: str = "nomadro-jwt-local-dev-2026"
- admin_username: str = "admin"
- admin_password: str = "Xiao4669805"
+ admin_username: str = "hackrobot"
+ admin_password: str = "Xiao4669805@"
# PocketBase
pb_url: str = "http://127.0.0.1:8090"
diff --git a/apps/api/services/ebook_svc/domains/books/products.py b/apps/api/services/ebook_svc/domains/books/products.py
index dd0f7a6..8aee5f6 100644
--- a/apps/api/services/ebook_svc/domains/books/products.py
+++ b/apps/api/services/ebook_svc/domains/books/products.py
@@ -26,11 +26,11 @@ PRODUCT_OFFERS: list[dict[str, Any]] = [
"label": "tiktok",
"name": "tiktok",
"product_id": "tiktok",
- "price_fen": 29800,
+ "price_fen": 8800,
"unlock_percent": 30,
"free": False,
"image": "props/tiktok.png",
- "remark": "已发布 · ¥298",
+ "remark": "已发布 · ¥88",
},
{
"key": "youtube",
diff --git a/apps/api/services/ebook_svc/main.py b/apps/api/services/ebook_svc/main.py
index 174f076..32ac833 100644
--- a/apps/api/services/ebook_svc/main.py
+++ b/apps/api/services/ebook_svc/main.py
@@ -91,6 +91,12 @@ app.include_router(weapp_switches_admin.router)
app.include_router(social_ops_admin.router)
app.include_router(social_ugc_admin.router)
app.include_router(community_admin.router)
+# 运营:ntfy 状态 / 试推(admin.nomadro.com)
+from ebook_svc.routers import ops_admin # noqa: E402
+from ebook_svc.routers import audience_admin # noqa: E402
+
+app.include_router(ops_admin.router)
+app.include_router(audience_admin.router)
# 公开远程配置(抖音真机:dyapi/api 合法域名 + 有效证书)
app.include_router(public_config.router)
diff --git a/apps/api/services/ebook_svc/routers/audience_admin.py b/apps/api/services/ebook_svc/routers/audience_admin.py
new file mode 100644
index 0000000..f024831
--- /dev/null
+++ b/apps/api/services/ebook_svc/routers/audience_admin.py
@@ -0,0 +1,38 @@
+"""受众分轨 — admin.nomadro.com/audience(中文用户 / 国际)。"""
+from __future__ import annotations
+
+from typing import Any, Literal
+
+from fastapi import APIRouter, Depends
+from pydantic import BaseModel
+
+from ebook_svc.core.security import require_admin
+from ebook_svc.services.audience_config import read_audience_config, write_audience_config
+
+router = APIRouter(prefix="/api/admin/audience", tags=["audience-admin"])
+
+
+class LaneIn(BaseModel):
+ payEnabled: bool | None = None
+ socialFollow: bool | None = None
+ followChannel: Literal["wechat", "x", "none"] | None = None
+ vipCta: str | None = None
+ homeLead: str | None = None
+ note: str | None = None
+
+
+class AudienceBody(BaseModel):
+ defaultLane: Literal["cn", "intl"] | None = None
+ cn: LaneIn | None = None
+ intl: LaneIn | None = None
+
+
+@router.get("")
+async def get_audience(_: str = Depends(require_admin)) -> dict[str, Any]:
+ return read_audience_config()
+
+
+@router.put("")
+async def put_audience(body: AudienceBody, _: str = Depends(require_admin)) -> dict[str, Any]:
+ patch = body.model_dump(exclude_none=True)
+ return write_audience_config(patch)
diff --git a/apps/api/services/ebook_svc/routers/ops_admin.py b/apps/api/services/ebook_svc/routers/ops_admin.py
new file mode 100644
index 0000000..14a9ba3
--- /dev/null
+++ b/apps/api/services/ebook_svc/routers/ops_admin.py
@@ -0,0 +1,46 @@
+"""运营:ntfy 状态 / 试推 — admin.nomadro.com 与 .cn 共用。"""
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends
+from pydantic import BaseModel, Field
+
+from ebook_svc.config import settings
+from ebook_svc.core.security import require_admin
+from ebook_svc.services import ntfy as ntfy_svc
+
+router = APIRouter(prefix="/api/admin/ops", tags=["ops-admin"])
+
+
+class NtfyTestBody(BaseModel):
+ title: str = Field(default="[WebAdmin] 试推", max_length=80)
+ message: str = Field(default="admin.nomadro.com 通知通路正常", max_length=500)
+ priority: int = Field(default=3, ge=1, le=5)
+ tags: str | None = Field(default="white_check_mark,globe_with_meridians")
+
+
+@router.get("/ntfy")
+async def ntfy_status(_: str = Depends(require_admin)) -> dict:
+ base = (settings.ntfy_base_url or "").rstrip("/")
+ topic = (settings.ntfy_topic or "").strip().strip("/")
+ return {
+ "enabled": bool(settings.ntfy_enabled),
+ "baseUrl": base,
+ "topic": topic,
+ "hasToken": bool((settings.ntfy_token or "").strip()),
+ "publicHint": "https://ntfy.nomadro.cn/" + topic if topic else "",
+ }
+
+
+@router.post("/ntfy/test")
+async def ntfy_test(body: NtfyTestBody, _: str = Depends(require_admin)) -> dict:
+ ok = await ntfy_svc.notify(
+ body.message,
+ title=body.title[:80],
+ tags=body.tags,
+ priority=body.priority,
+ )
+ return {
+ "ok": ok,
+ "enabled": bool(settings.ntfy_enabled),
+ "topic": (settings.ntfy_topic or "").strip(),
+ }
diff --git a/apps/api/services/ebook_svc/services/audience_config.py b/apps/api/services/ebook_svc/services/audience_config.py
new file mode 100644
index 0000000..0268454
--- /dev/null
+++ b/apps/api/services/ebook_svc/services/audience_config.py
@@ -0,0 +1,128 @@
+"""受众分轨 remote-config.audience — .com 国际优先,中文用户特殊对待。"""
+from __future__ import annotations
+
+import json
+from copy import deepcopy
+from datetime import datetime, timezone
+from typing import Any
+
+from ebook_svc.services.tt_platform_config import resolve_config_file
+
+DEFAULT_CN: dict[str, Any] = {
+ "payEnabled": True,
+ "socialFollow": True,
+ "followChannel": "wechat",
+ "vipCta": "立即加入 · ¥88",
+ "homeLead": "",
+ "note": "中文用户特殊线:微信内置 / is-china-user;支付走 zpay/xpay",
+}
+
+DEFAULT_INTL: dict[str, Any] = {
+ "payEnabled": True,
+ "socialFollow": True,
+ "followChannel": "x",
+ "vipCta": "Join VIP",
+ "homeLead": "",
+ "note": ".com 默认国际线(英语为主);Creem / NOWPayments",
+}
+
+DEFAULT_AUDIENCE: dict[str, Any] = {
+ "defaultLane": "intl",
+ "cn": deepcopy(DEFAULT_CN),
+ "intl": deepcopy(DEFAULT_INTL),
+}
+
+
+def _read_raw() -> dict[str, Any]:
+ path = resolve_config_file()
+ if not path.is_file():
+ return {}
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ return raw if isinstance(raw, dict) else {}
+ except Exception:
+ return {}
+
+
+def _write_raw(out: dict[str, Any]) -> None:
+ path = resolve_config_file()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ out["updatedAt"] = datetime.now(timezone.utc).isoformat()
+ try:
+ out["version"] = int(out.get("version") or 1) + 1
+ except Exception:
+ out["version"] = 2
+ if path.is_file():
+ bak = path.with_suffix(path.suffix + f".bak-{out['updatedAt'].replace(':', '-')}")
+ try:
+ bak.write_text(path.read_text(encoding="utf-8"), encoding="utf-8")
+ except Exception:
+ pass
+ path.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ try:
+ from ebook_svc.services.config_live import notify_config_written
+
+ notify_config_written(out)
+ except Exception:
+ pass
+
+
+def _norm_lane(raw: Any, fallback: dict[str, Any]) -> dict[str, Any]:
+ m = raw if isinstance(raw, dict) else {}
+ out = deepcopy(fallback)
+ if "payEnabled" in m:
+ out["payEnabled"] = bool(m["payEnabled"])
+ if "socialFollow" in m:
+ out["socialFollow"] = bool(m["socialFollow"])
+ ch = m.get("followChannel")
+ if ch in ("wechat", "x", "none"):
+ out["followChannel"] = ch
+ if "vipCta" in m and m["vipCta"] is not None:
+ out["vipCta"] = str(m["vipCta"])
+ if "homeLead" in m and m["homeLead"] is not None:
+ out["homeLead"] = str(m["homeLead"])
+ if "note" in m and m["note"] is not None:
+ out["note"] = str(m["note"])
+ return out
+
+
+def read_audience_config() -> dict[str, Any]:
+ raw = _read_raw()
+ a = raw.get("audience") if isinstance(raw.get("audience"), dict) else {}
+ lane = a.get("defaultLane")
+ default_lane = lane if lane in ("cn", "intl") else "intl"
+ return {
+ "ok": True,
+ "defaultLane": default_lane,
+ "cn": _norm_lane(a.get("cn"), DEFAULT_CN),
+ "intl": _norm_lane(a.get("intl"), DEFAULT_INTL),
+ "detection": {
+ "lib": "is-china-user",
+ "wechatUa": "micromessenger",
+ "repo": "https://github.com/yArna/isChinaUser",
+ "note": ".com 国际优先;微信内置或 is-china-user 命中 → cn 特殊线",
+ },
+ "version": raw.get("version"),
+ "updatedAt": raw.get("updatedAt"),
+ "configPath": str(resolve_config_file()),
+ }
+
+
+def write_audience_config(patch: dict[str, Any]) -> dict[str, Any]:
+ raw = _read_raw()
+ out: dict[str, Any] = dict(raw) if raw else {"version": 2}
+ cur = out.get("audience") if isinstance(out.get("audience"), dict) else {}
+ audience = {
+ "defaultLane": cur.get("defaultLane") or "intl",
+ "cn": _norm_lane(cur.get("cn"), DEFAULT_CN),
+ "intl": _norm_lane(cur.get("intl"), DEFAULT_INTL),
+ }
+ if patch.get("defaultLane") in ("cn", "intl"):
+ audience["defaultLane"] = patch["defaultLane"]
+ if isinstance(patch.get("cn"), dict):
+ audience["cn"] = _norm_lane(patch["cn"], audience["cn"])
+ if isinstance(patch.get("intl"), dict):
+ audience["intl"] = _norm_lane(patch["intl"], audience["intl"])
+ out["audience"] = audience
+ _write_raw(out)
+ return read_audience_config()
diff --git a/apps/api/services/ebook_svc/services/track.py b/apps/api/services/ebook_svc/services/track.py
index ca6ef27..91fa931 100644
--- a/apps/api/services/ebook_svc/services/track.py
+++ b/apps/api/services/ebook_svc/services/track.py
@@ -98,6 +98,13 @@ CLIENT_LABEL = {
"h5": "H5",
"miniapp": "小程序",
"api": "API",
+ "web": "Web",
+ "web_com": "nomadro.com",
+ "web_cn": "nomadro.cn",
+ "web_intl": "Web·intl",
+ "web_cn_tag": "Web·cn",
+ "vip_web": "VIP Web",
+ "web_local": "localhost",
"wx_push": "微信推送",
}
@@ -105,8 +112,22 @@ CLIENT_NTFY_TAGS = {
"tt": "tiktok",
"weapp": "wechat",
"h5": "globe_with_meridians",
+ "web": "globe_with_meridians",
+ "web_com": "globe_with_meridians",
+ "web_cn": "globe_with_meridians",
+ "web_intl": "globe_with_meridians",
+ "web_local": "globe_with_meridians",
+ "vip_web": "globe_with_meridians",
}
+# 门户 Web 由 Next /api/track 负责 ntfy;此处只入库,避免双推 + page_view 刷屏
+_WEB_STORE_ONLY_PREFIXES = ("web", "vip_web")
+
+
+def _web_store_only(client: str | None) -> bool:
+ c = (client or "").strip().lower()
+ return any(c == p or c.startswith(f"{p}_") for p in _WEB_STORE_ONLY_PREFIXES)
+
def _short_openid(openid: str | None) -> str:
if not openid:
@@ -213,7 +234,7 @@ async def ingest_events(
except Exception:
logger.exception("track save failed")
- if name in NTFY_ALWAYS:
+ if name in NTFY_ALWAYS and not _web_store_only(client_key):
ntfy_title = _title(name, client=client_key)
if name == "wx_push" and ev.get("label"):
ntfy_title = f"[{_channel_label(client_key)}] {ev['label']}"[:80]
diff --git a/apps/api/services/ebook_svc/services/vip_config.py b/apps/api/services/ebook_svc/services/vip_config.py
index 7beb48a..709471e 100644
--- a/apps/api/services/ebook_svc/services/vip_config.py
+++ b/apps/api/services/ebook_svc/services/vip_config.py
@@ -22,7 +22,7 @@ DEFAULT_VIP = {
"gameEnabled": False,
# VIP 跳转默认关 → 加群仍弹窗(现网);后台可开 vip
"joinGroupAction": "popup",
- "vipPriceFen": 29800,
+ "vipPriceFen": 8800,
"vipProductId": "tiktok",
# CTA 不含价格;价格由方案卡片/后台展示
"vipCta": "立即加入",
diff --git a/apps/api/services/ebook_svc/services/weapp_switches.py b/apps/api/services/ebook_svc/services/weapp_switches.py
index a3c06b3..81819aa 100644
--- a/apps/api/services/ebook_svc/services/weapp_switches.py
+++ b/apps/api/services/ebook_svc/services/weapp_switches.py
@@ -196,6 +196,11 @@ def write_weapp_switches(patch: dict[str, Any]) -> dict[str, Any]:
base = _norm_mod(modules.get(key), DEFAULT_MODULES[key])
modules[key] = _norm_mod(val, base)
+ # 防止补丁写入后兄弟模块丢失 / 首页入口被清空:始终补齐 MODULE_KEYS
+ for key in MODULE_KEYS:
+ modules[key] = _norm_mod(modules.get(key), DEFAULT_MODULES[key])
+ modules["game"] = {**DEFAULT_MODULES["game"], "enabled": False}
+
if isinstance(patch.get("flags"), dict):
fp = patch["flags"]
if "payEnabled" in fp:
diff --git a/apps/api/services/notify_svc/__init__.py b/apps/api/services/notify_svc/__init__.py
new file mode 100644
index 0000000..5b86fc5
--- /dev/null
+++ b/apps/api/services/notify_svc/__init__.py
@@ -0,0 +1 @@
+"""Nomadro notify — Novu-domain secondary-dev (workflows · subscribers · inbox)."""
diff --git a/apps/api/services/notify_svc/config.py b/apps/api/services/notify_svc/config.py
new file mode 100644
index 0000000..5035385
--- /dev/null
+++ b/apps/api/services/notify_svc/config.py
@@ -0,0 +1,21 @@
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+NOTIFY_ENABLED = os.getenv("NOTIFY_ENABLED", "1").strip().lower() not in {
+ "0",
+ "false",
+ "no",
+ "off",
+}
+
+DATA_DIR = Path(os.getenv("NOTIFY_DATA_DIR", "/var/lib/nomadro/notify"))
+if not DATA_DIR.exists():
+ DATA_DIR = (
+ Path(os.getenv("NOTIFY_DATA_DIR_LOCAL", "")).resolve()
+ if os.getenv("NOTIFY_DATA_DIR_LOCAL")
+ else Path.cwd() / "data" / "notify"
+ )
+
+DB_PATH = DATA_DIR / "notify.sqlite3"
diff --git a/apps/api/services/notify_svc/routers/__init__.py b/apps/api/services/notify_svc/routers/__init__.py
new file mode 100644
index 0000000..502d465
--- /dev/null
+++ b/apps/api/services/notify_svc/routers/__init__.py
@@ -0,0 +1,3 @@
+from .api import router
+
+__all__ = ["router"]
diff --git a/apps/api/services/notify_svc/routers/api.py b/apps/api/services/notify_svc/routers/api.py
new file mode 100644
index 0000000..8ef869d
--- /dev/null
+++ b/apps/api/services/notify_svc/routers/api.py
@@ -0,0 +1,295 @@
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Query
+from pydantic import BaseModel, Field
+
+from notify_svc import store
+
+router = APIRouter(tags=["notify"])
+
+
+class SubscriberIn(BaseModel):
+ subscriber_id: str = Field(min_length=1, max_length=120)
+ email: str | None = None
+ phone: str | None = None
+ first_name: str | None = None
+ last_name: str | None = None
+ avatar: str | None = None
+ locale: str | None = "zh"
+ data: dict[str, Any] | None = None
+
+
+class TopicIn(BaseModel):
+ key: str = Field(min_length=1, max_length=80)
+ name: str = Field(default="", max_length=200)
+
+
+class TopicMemberIn(BaseModel):
+ subscriber_id: str = Field(min_length=1, max_length=120)
+
+
+class StepIn(BaseModel):
+ id: str | None = None
+ type: str = "in_app"
+ name: str = ""
+ position: float | None = None
+ active: bool = True
+ template: dict[str, Any] = Field(default_factory=dict)
+ filters: list[Any] = Field(default_factory=list)
+
+
+class WorkflowIn(BaseModel):
+ workflow_id: str = Field(min_length=1, max_length=120)
+ name: str = Field(min_length=1, max_length=200)
+ description: str = ""
+ tags: list[str] = Field(default_factory=list)
+ steps: list[StepIn] = Field(default_factory=list)
+
+
+class WorkflowPatch(BaseModel):
+ name: str | None = None
+ description: str | None = None
+ active: bool | None = None
+ tags: list[str] | None = None
+ steps: list[StepIn] | None = None
+
+
+class TriggerIn(BaseModel):
+ workflow_id: str = Field(min_length=1, max_length=120)
+ subscriber_id: str | None = None
+ topic_key: str | None = None
+ payload: dict[str, Any] = Field(default_factory=dict)
+
+
+class PrefsIn(BaseModel):
+ channels: dict[str, Any] = Field(default_factory=dict)
+
+
+class MessagePatch(BaseModel):
+ read: bool | None = None
+ archived: bool | None = None
+ deleted: bool | None = None
+
+
+class ReadAllIn(BaseModel):
+ subscriber_id: str = "guest"
+ category: str | None = None
+
+
+@router.get("/health")
+def health():
+ return {"ok": True, "service": "nomadro-notify", "inspiredBy": ["novu"]}
+
+
+@router.get("/subscribers")
+def subscribers():
+ return {"ok": True, "subscribers": store.list_subscribers()}
+
+
+@router.get("/subscribers/{subscriber_id}")
+def subscriber(subscriber_id: str):
+ s = store.get_subscriber(subscriber_id)
+ if not s:
+ raise HTTPException(404, "subscriber_not_found")
+ return {"ok": True, "subscriber": s}
+
+
+@router.post("/subscribers")
+def create_subscriber(body: SubscriberIn):
+ try:
+ s = store.upsert_subscriber(body.model_dump())
+ except ValueError as e:
+ raise HTTPException(400, str(e)) from e
+ return {"ok": True, "subscriber": s}
+
+
+@router.put("/subscribers/{subscriber_id}")
+def update_subscriber(subscriber_id: str, body: SubscriberIn):
+ data = body.model_dump()
+ data["subscriber_id"] = subscriber_id
+ try:
+ s = store.upsert_subscriber(data)
+ except ValueError as e:
+ raise HTTPException(400, str(e)) from e
+ return {"ok": True, "subscriber": s}
+
+
+@router.delete("/subscribers/{subscriber_id}")
+def remove_subscriber(subscriber_id: str):
+ if not store.delete_subscriber(subscriber_id):
+ raise HTTPException(404, "subscriber_not_found")
+ return {"ok": True}
+
+
+@router.get("/subscribers/{subscriber_id}/preferences")
+def get_prefs(subscriber_id: str):
+ p = store.get_preferences(subscriber_id)
+ if not p:
+ raise HTTPException(404, "subscriber_not_found")
+ return {"ok": True, "preferences": p}
+
+
+@router.put("/subscribers/{subscriber_id}/preferences")
+def put_prefs(subscriber_id: str, body: PrefsIn):
+ try:
+ p = store.set_preferences(subscriber_id, body.channels)
+ except ValueError as e:
+ raise HTTPException(404, str(e)) from e
+ return {"ok": True, "preferences": p}
+
+
+@router.get("/topics")
+def topics():
+ return {"ok": True, "topics": store.list_topics()}
+
+
+@router.post("/topics")
+def create_topic(body: TopicIn):
+ try:
+ t = store.create_topic(body.key, body.name)
+ except ValueError as e:
+ raise HTTPException(400, str(e)) from e
+ return {"ok": True, "topic": t}
+
+
+@router.post("/topics/{topic_key}/subscribers")
+def topic_add(topic_key: str, body: TopicMemberIn):
+ try:
+ t = store.add_topic_subscriber(topic_key, body.subscriber_id)
+ except ValueError as e:
+ raise HTTPException(400, str(e)) from e
+ return {"ok": True, "topic": t}
+
+
+@router.delete("/topics/{topic_key}/subscribers/{subscriber_id}")
+def topic_remove(topic_key: str, subscriber_id: str):
+ if not store.remove_topic_subscriber(topic_key, subscriber_id):
+ raise HTTPException(404, "not_found")
+ return {"ok": True}
+
+
+@router.get("/workflows")
+def workflows():
+ return {"ok": True, "workflows": store.list_workflows()}
+
+
+@router.get("/workflows/{workflow_id}")
+def workflow(workflow_id: str):
+ w = store.get_workflow(workflow_id)
+ if not w:
+ raise HTTPException(404, "workflow_not_found")
+ return {"ok": True, "workflow": w}
+
+
+@router.post("/workflows")
+def create_workflow(body: WorkflowIn):
+ try:
+ w = store.create_workflow(
+ body.workflow_id,
+ body.name,
+ body.description,
+ [s.model_dump() for s in body.steps] if body.steps else None,
+ body.tags,
+ )
+ except ValueError as e:
+ raise HTTPException(400, str(e)) from e
+ return {"ok": True, "workflow": w}
+
+
+@router.patch("/workflows/{workflow_id}")
+def patch_workflow(workflow_id: str, body: WorkflowPatch):
+ patch = body.model_dump(exclude_unset=True)
+ if "steps" in patch and patch["steps"] is not None:
+ patch["steps"] = [s if isinstance(s, dict) else s for s in patch["steps"]]
+ w = store.update_workflow(workflow_id, patch)
+ if not w:
+ raise HTTPException(404, "workflow_not_found")
+ return {"ok": True, "workflow": w}
+
+
+@router.delete("/workflows/{workflow_id}")
+def remove_workflow(workflow_id: str):
+ if not store.delete_workflow(workflow_id):
+ raise HTTPException(404, "workflow_not_found")
+ return {"ok": True}
+
+
+@router.post("/events/trigger")
+def trigger(body: TriggerIn):
+ try:
+ result = store.trigger_event(
+ workflow_id=body.workflow_id,
+ subscriber_id=body.subscriber_id,
+ topic_key=body.topic_key,
+ payload=body.payload,
+ )
+ except ValueError as e:
+ raise HTTPException(400, str(e)) from e
+ return {"ok": True, **result}
+
+
+@router.get("/inbox")
+def inbox(
+ subscriber_id: str = Query(default="guest"),
+ include_archived: bool = False,
+ category: str | None = Query(default=None),
+):
+ return {
+ "ok": True,
+ "subscriber_id": subscriber_id,
+ "unread": store.unread_count(subscriber_id),
+ "unread_by_category": store.unread_by_category(subscriber_id),
+ "messages": store.list_inbox(
+ subscriber_id,
+ include_archived=include_archived,
+ category=category,
+ ),
+ }
+
+
+@router.get("/inbox/unread")
+def inbox_unread(subscriber_id: str = Query(default="guest")):
+ return {
+ "ok": True,
+ "subscriber_id": subscriber_id,
+ "unread": store.unread_count(subscriber_id),
+ "unread_by_category": store.unread_by_category(subscriber_id),
+ }
+
+
+@router.post("/inbox/read-all")
+def inbox_read_all(body: ReadAllIn):
+ n = store.mark_all_read(body.subscriber_id, body.category)
+ return {
+ "ok": True,
+ "updated": n,
+ "unread": store.unread_count(body.subscriber_id),
+ "unread_by_category": store.unread_by_category(body.subscriber_id),
+ }
+
+
+@router.patch("/inbox/{message_id}")
+def patch_inbox(message_id: str, body: MessagePatch):
+ m = store.patch_message(message_id, body.model_dump(exclude_unset=True))
+ if not m:
+ raise HTTPException(404, "message_not_found")
+ return {"ok": True, "message": m}
+
+
+@router.delete("/inbox/{message_id}")
+def delete_inbox(message_id: str):
+ if not store.delete_message(message_id):
+ raise HTTPException(404, "message_not_found")
+ return {"ok": True}
+
+
+@router.get("/activity")
+def activity(limit: int = Query(default=50, ge=1, le=200)):
+ return {"ok": True, "activity": store.list_activity(limit)}
+
+
+@router.get("/integrations")
+def integrations():
+ return {"ok": True, "integrations": store.list_integrations()}
diff --git a/apps/api/services/notify_svc/store.py b/apps/api/services/notify_svc/store.py
new file mode 100644
index 0000000..f34a0a7
--- /dev/null
+++ b/apps/api/services/notify_svc/store.py
@@ -0,0 +1,1312 @@
+"""
+SQLite store — domain shaped after Novu
+(Organization/Environment · Subscriber · Topic · Workflow · Event · Notification · Message).
+Secondary-dev reimplementation for Nomadro (not upstream runtime / Docker Novu).
+"""
+from __future__ import annotations
+
+import json
+import sqlite3
+import time
+import uuid
+from pathlib import Path
+from typing import Any
+
+from .config import DATA_DIR, DB_PATH
+
+try:
+ from ebook_svc.core.sqlite_util import connect as _connect
+except Exception: # pragma: no cover
+
+ def _connect(path: str | Path, *, timeout: float = 30.0) -> sqlite3.Connection:
+ p = Path(path)
+ p.parent.mkdir(parents=True, exist_ok=True)
+ c = sqlite3.connect(str(p), timeout=timeout)
+ c.row_factory = sqlite3.Row
+ c.execute("PRAGMA journal_mode=WAL")
+ return c
+
+
+CHANNEL_STEPS = {"in_app", "email", "sms", "push", "chat"}
+ACTION_STEPS = {"delay", "digest", "throttle"}
+ALL_STEPS = CHANNEL_STEPS | ACTION_STEPS
+CATEGORIES = ("social", "buddy", "project", "system")
+
+
+def _default_prefs() -> dict[str, Any]:
+ return {
+ "in_app": True,
+ "email": True,
+ "sms": False,
+ "push": True,
+ "chat": False,
+ "dnd": False,
+ "email_subscribe": True,
+ "browser_push": False,
+ "push_permission": "default",
+ }
+
+
+def _ensure_column(c: sqlite3.Connection, table: str, column: str, decl: str) -> None:
+ cols = {r[1] for r in c.execute(f"PRAGMA table_info({table})").fetchall()}
+ if column not in cols:
+ c.execute(f"ALTER TABLE {table} ADD COLUMN {column} {decl}")
+
+
+def _now() -> str:
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+
+
+def _id(prefix: str) -> str:
+ return f"{prefix}_{uuid.uuid4().hex[:10]}"
+
+
+def _conn() -> sqlite3.Connection:
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
+ return _connect(DB_PATH)
+
+
+def _row(r: sqlite3.Row | None) -> dict[str, Any] | None:
+ if r is None:
+ return None
+ return dict(r)
+
+
+def _json(v: Any) -> str:
+ return json.dumps(v, ensure_ascii=False)
+
+
+def _parse(s: str | None, default: Any = None) -> Any:
+ if not s:
+ return default if default is not None else {}
+ try:
+ return json.loads(s)
+ except Exception:
+ return default if default is not None else {}
+
+
+def init_db() -> None:
+ with _conn() as c:
+ c.executescript(
+ """
+ CREATE TABLE IF NOT EXISTS environments (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ slug TEXT NOT NULL UNIQUE,
+ created_at TEXT NOT NULL
+ );
+ CREATE TABLE IF NOT EXISTS subscribers (
+ id TEXT PRIMARY KEY,
+ env_id TEXT NOT NULL,
+ subscriber_id TEXT NOT NULL,
+ email TEXT,
+ phone TEXT,
+ first_name TEXT,
+ last_name TEXT,
+ avatar TEXT,
+ locale TEXT DEFAULT 'zh',
+ data_json TEXT NOT NULL DEFAULT '{}',
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ UNIQUE(env_id, subscriber_id),
+ FOREIGN KEY(env_id) REFERENCES environments(id)
+ );
+ CREATE TABLE IF NOT EXISTS topics (
+ id TEXT PRIMARY KEY,
+ env_id TEXT NOT NULL,
+ key TEXT NOT NULL,
+ name TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ UNIQUE(env_id, key),
+ FOREIGN KEY(env_id) REFERENCES environments(id)
+ );
+ CREATE TABLE IF NOT EXISTS topic_subscribers (
+ topic_id TEXT NOT NULL,
+ subscriber_pk TEXT NOT NULL,
+ PRIMARY KEY(topic_id, subscriber_pk),
+ FOREIGN KEY(topic_id) REFERENCES topics(id),
+ FOREIGN KEY(subscriber_pk) REFERENCES subscribers(id)
+ );
+ CREATE TABLE IF NOT EXISTS workflows (
+ id TEXT PRIMARY KEY,
+ env_id TEXT NOT NULL,
+ workflow_id TEXT NOT NULL,
+ name TEXT NOT NULL,
+ description TEXT NOT NULL DEFAULT '',
+ active INTEGER NOT NULL DEFAULT 1,
+ tags_json TEXT NOT NULL DEFAULT '[]',
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ UNIQUE(env_id, workflow_id),
+ FOREIGN KEY(env_id) REFERENCES environments(id)
+ );
+ CREATE TABLE IF NOT EXISTS workflow_steps (
+ id TEXT PRIMARY KEY,
+ workflow_pk TEXT NOT NULL,
+ type TEXT NOT NULL,
+ name TEXT NOT NULL DEFAULT '',
+ position REAL NOT NULL DEFAULT 0,
+ active INTEGER NOT NULL DEFAULT 1,
+ template_json TEXT NOT NULL DEFAULT '{}',
+ filters_json TEXT NOT NULL DEFAULT '[]',
+ FOREIGN KEY(workflow_pk) REFERENCES workflows(id)
+ );
+ CREATE TABLE IF NOT EXISTS integrations (
+ id TEXT PRIMARY KEY,
+ env_id TEXT NOT NULL,
+ channel TEXT NOT NULL,
+ provider TEXT NOT NULL,
+ active INTEGER NOT NULL DEFAULT 0,
+ credentials_json TEXT NOT NULL DEFAULT '{}',
+ created_at TEXT NOT NULL,
+ FOREIGN KEY(env_id) REFERENCES environments(id)
+ );
+ CREATE TABLE IF NOT EXISTS events (
+ id TEXT PRIMARY KEY,
+ env_id TEXT NOT NULL,
+ transaction_id TEXT NOT NULL,
+ workflow_pk TEXT NOT NULL,
+ payload_json TEXT NOT NULL DEFAULT '{}',
+ created_at TEXT NOT NULL,
+ FOREIGN KEY(env_id) REFERENCES environments(id),
+ FOREIGN KEY(workflow_pk) REFERENCES workflows(id)
+ );
+ CREATE TABLE IF NOT EXISTS notifications (
+ id TEXT PRIMARY KEY,
+ event_id TEXT NOT NULL,
+ subscriber_pk TEXT NOT NULL,
+ workflow_pk TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'completed',
+ created_at TEXT NOT NULL,
+ FOREIGN KEY(event_id) REFERENCES events(id),
+ FOREIGN KEY(subscriber_pk) REFERENCES subscribers(id),
+ FOREIGN KEY(workflow_pk) REFERENCES workflows(id)
+ );
+ CREATE TABLE IF NOT EXISTS jobs (
+ id TEXT PRIMARY KEY,
+ notification_id TEXT NOT NULL,
+ step_id TEXT NOT NULL,
+ channel TEXT NOT NULL,
+ status TEXT NOT NULL,
+ detail_json TEXT NOT NULL DEFAULT '{}',
+ created_at TEXT NOT NULL,
+ FOREIGN KEY(notification_id) REFERENCES notifications(id)
+ );
+ CREATE TABLE IF NOT EXISTS messages (
+ id TEXT PRIMARY KEY,
+ notification_id TEXT,
+ subscriber_pk TEXT NOT NULL,
+ channel TEXT NOT NULL DEFAULT 'in_app',
+ subject TEXT NOT NULL DEFAULT '',
+ body TEXT NOT NULL DEFAULT '',
+ cta_label TEXT,
+ cta_url TEXT,
+ payload_json TEXT NOT NULL DEFAULT '{}',
+ read INTEGER NOT NULL DEFAULT 0,
+ archived INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL,
+ FOREIGN KEY(subscriber_pk) REFERENCES subscribers(id)
+ );
+ CREATE TABLE IF NOT EXISTS preferences (
+ subscriber_pk TEXT PRIMARY KEY,
+ channels_json TEXT NOT NULL DEFAULT '{}',
+ updated_at TEXT NOT NULL,
+ FOREIGN KEY(subscriber_pk) REFERENCES subscribers(id)
+ );
+ """
+ )
+ _ensure_column(c, "messages", "category", "TEXT NOT NULL DEFAULT 'system'")
+ _ensure_column(c, "messages", "deleted", "INTEGER NOT NULL DEFAULT 0")
+ _seed(c)
+ _ensure_demo_feed(c)
+
+
+def _seed(c: sqlite3.Connection) -> None:
+ if c.execute("SELECT 1 FROM environments LIMIT 1").fetchone():
+ return
+ now = _now()
+ env = "env_prod"
+ c.execute(
+ "INSERT INTO environments(id,name,slug,created_at) VALUES(?,?,?,?)",
+ (env, "Production", "production", now),
+ )
+
+ subs = [
+ ("sub_guest", "guest", "guest@nomadro.com", None, "Guest", "Nomad", "zh"),
+ ("sub_alice", "alice", "alice@nomadro.com", "+8613800000001", "Alice", "Chen", "zh"),
+ ("sub_bob", "bob", "bob@nomadro.com", None, "Bob", "Rivera", "en"),
+ ]
+ for pk, sid, email, phone, fn, ln, loc in subs:
+ c.execute(
+ """INSERT INTO subscribers(
+ id,env_id,subscriber_id,email,phone,first_name,last_name,avatar,locale,data_json,created_at,updated_at
+ ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""",
+ (pk, env, sid, email, phone, fn, ln, None, loc, _json({"plan": "free"}), now, now),
+ )
+ c.execute(
+ "INSERT INTO preferences(subscriber_pk,channels_json,updated_at) VALUES(?,?,?)",
+ (pk, _json(_default_prefs()), now),
+ )
+
+ topic = "topic_nomads"
+ c.execute(
+ "INSERT INTO topics(id,env_id,key,name,created_at) VALUES(?,?,?,?,?)",
+ (topic, env, "nomads", "Nomadro Nomads", now),
+ )
+ for pk in ("sub_guest", "sub_alice", "sub_bob"):
+ c.execute(
+ "INSERT INTO topic_subscribers(topic_id,subscriber_pk) VALUES(?,?)",
+ (topic, pk),
+ )
+
+ wf_welcome = "wf_welcome"
+ c.execute(
+ """INSERT INTO workflows(id,env_id,workflow_id,name,description,active,tags_json,created_at,updated_at)
+ VALUES(?,?,?,?,?,?,?,?,?)""",
+ (
+ wf_welcome,
+ env,
+ "welcome-onboarding",
+ "Welcome onboarding",
+ "In-app welcome + email stub when a nomad joins",
+ 1,
+ _json(["onboarding", "product"]),
+ now,
+ now,
+ ),
+ )
+ steps_welcome = [
+ (
+ _id("step"),
+ "in_app",
+ "In-app welcome",
+ 0,
+ {
+ "subject": "欢迎加入 Nomadro",
+ "body": "嗨 {{firstName}}——打开收件箱,开始远程一起做事。",
+ "ctaLabel": "打开工作台",
+ "ctaUrl": "/social/work",
+ },
+ ),
+ (
+ _id("step"),
+ "email",
+ "Welcome email",
+ 1,
+ {
+ "subject": "Welcome to Nomadro, {{firstName}}",
+ "body": "Your remote stack is ready: work · social · notify.",
+ },
+ ),
+ ]
+ for sid, typ, name, pos, tpl in steps_welcome:
+ c.execute(
+ """INSERT INTO workflow_steps(id,workflow_pk,type,name,position,active,template_json,filters_json)
+ VALUES(?,?,?,?,?,?,?,?)""",
+ (sid, wf_welcome, typ, name, pos, 1, _json(tpl), "[]"),
+ )
+
+ wf_meetup = "wf_meetup"
+ c.execute(
+ """INSERT INTO workflows(id,env_id,workflow_id,name,description,active,tags_json,created_at,updated_at)
+ VALUES(?,?,?,?,?,?,?,?,?)""",
+ (
+ wf_meetup,
+ env,
+ "meetup-reminder",
+ "Meetup reminder",
+ "Delay stub then in-app reminder for city meetups",
+ 1,
+ _json(["meetup", "social"]),
+ now,
+ now,
+ ),
+ )
+ steps_meetup = [
+ (
+ _id("step"),
+ "delay",
+ "Wait window",
+ 0,
+ {"amount": 15, "unit": "minutes"},
+ ),
+ (
+ _id("step"),
+ "in_app",
+ "Meetup ping",
+ 1,
+ {
+ "subject": "活动提醒 · {{city}}",
+ "body": "{{title}} 快开始了,别迟到。",
+ "ctaLabel": "查看活动",
+ "ctaUrl": "/social/meetup",
+ },
+ ),
+ (
+ _id("step"),
+ "push",
+ "Push stub",
+ 2,
+ {"title": "{{title}}", "body": "Starts soon in {{city}}"},
+ ),
+ ]
+ for sid, typ, name, pos, tpl in steps_meetup:
+ c.execute(
+ """INSERT INTO workflow_steps(id,workflow_pk,type,name,position,active,template_json,filters_json)
+ VALUES(?,?,?,?,?,?,?,?)""",
+ (sid, wf_meetup, typ, name, pos, 1, _json(tpl), "[]"),
+ )
+
+ for channel, provider, active in (
+ ("in_app", "nomadro-inbox", 1),
+ ("email", "smtp-stub", 0),
+ ("sms", "twilio-stub", 0),
+ ("push", "web-push-stub", 0),
+ ("chat", "slack-stub", 0),
+ ):
+ c.execute(
+ """INSERT INTO integrations(id,env_id,channel,provider,active,credentials_json,created_at)
+ VALUES(?,?,?,?,?,?,?)""",
+ (_id("int"), env, channel, provider, active, "{}", now),
+ )
+
+ # seed one inbox message for guest
+ nid = _id("ntf")
+ eid = _id("evt")
+ c.execute(
+ """INSERT INTO events(id,env_id,transaction_id,workflow_pk,payload_json,created_at)
+ VALUES(?,?,?,?,?,?)""",
+ (eid, env, _id("tx"), wf_welcome, _json({"source": "seed"}), now),
+ )
+ c.execute(
+ """INSERT INTO notifications(id,event_id,subscriber_pk,workflow_pk,status,created_at)
+ VALUES(?,?,?,?,?,?)""",
+ (nid, eid, "sub_guest", wf_welcome, "completed", now),
+ )
+ c.execute(
+ """INSERT INTO messages(
+ id,notification_id,subscriber_pk,channel,subject,body,cta_label,cta_url,payload_json,read,archived,category,deleted,created_at
+ ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
+ (
+ _id("msg"),
+ nid,
+ "sub_guest",
+ "in_app",
+ "欢迎加入 Nomadro",
+ "嗨 Guest——打开收件箱,开始远程一起做事。",
+ "打开工作台",
+ "/social/work",
+ _json({"seed": True}),
+ 0,
+ 0,
+ "system",
+ 0,
+ now,
+ ),
+ )
+
+
+def _ensure_demo_feed(c: sqlite3.Connection) -> None:
+ """Fill guest inbox with categorized samples (idempotent by subject tag)."""
+ guest = c.execute(
+ "SELECT id FROM subscribers WHERE subscriber_id='guest'"
+ ).fetchone()
+ if not guest:
+ return
+ pk = guest["id"]
+ now = _now()
+ samples = [
+ (
+ "social",
+ "Alice 想认识你",
+ "在成都 · 看看对方介绍,决定要不要聊聊。",
+ "查看资料",
+ "/social/people",
+ ),
+ (
+ "buddy",
+ "有人找搭子:出海小工具",
+ "兼职 / 一起做点事 · 匹配你的技能标签。",
+ "去看看",
+ "/social/team",
+ ),
+ (
+ "project",
+ "看板有新动态",
+ "Sprint board · 卡片「部署 Notify」已更新。",
+ "打开看板",
+ "/social/work/boards",
+ ),
+ (
+ "system",
+ "安全提醒:确认登录设备",
+ "若非本人操作,请立刻修改密码并联系支持。",
+ "账号设置",
+ "/social/roster",
+ ),
+ ]
+ for cat, subject, body, cta, url in samples:
+ exists = c.execute(
+ "SELECT 1 FROM messages WHERE subscriber_pk=? AND subject=? LIMIT 1",
+ (pk, subject),
+ ).fetchone()
+ if exists:
+ continue
+ c.execute(
+ """INSERT INTO messages(
+ id,notification_id,subscriber_pk,channel,subject,body,cta_label,cta_url,
+ payload_json,read,archived,category,deleted,created_at
+ ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
+ (
+ _id("msg"),
+ None,
+ pk,
+ "in_app",
+ subject,
+ body,
+ cta,
+ url,
+ _json({"demo": True, "category": cat}),
+ 0,
+ 0,
+ cat,
+ 0,
+ now,
+ ),
+ )
+
+
+def default_env_id(c: sqlite3.Connection | None = None) -> str:
+ own = c is None
+ if own:
+ c = _conn()
+ assert c is not None
+ row = c.execute("SELECT id FROM environments ORDER BY created_at LIMIT 1").fetchone()
+ if own:
+ c.close()
+ if not row:
+ raise RuntimeError("no_environment")
+ return str(row["id"])
+
+
+# —— subscribers ——
+
+
+def list_subscribers() -> list[dict[str, Any]]:
+ with _conn() as c:
+ rows = c.execute(
+ "SELECT * FROM subscribers ORDER BY created_at DESC"
+ ).fetchall()
+ return [_subscriber_out(dict(r)) for r in rows]
+
+
+def get_subscriber(subscriber_id: str) -> dict[str, Any] | None:
+ with _conn() as c:
+ r = c.execute(
+ "SELECT * FROM subscribers WHERE subscriber_id=? OR id=?",
+ (subscriber_id, subscriber_id),
+ ).fetchone()
+ return _subscriber_out(dict(r)) if r else None
+
+
+def upsert_subscriber(data: dict[str, Any]) -> dict[str, Any]:
+ sid = (data.get("subscriber_id") or "").strip()
+ if not sid:
+ raise ValueError("subscriber_id_required")
+ now = _now()
+ with _conn() as c:
+ env = default_env_id(c)
+ existing = c.execute(
+ "SELECT id FROM subscribers WHERE env_id=? AND subscriber_id=?",
+ (env, sid),
+ ).fetchone()
+ payload = {
+ "email": data.get("email"),
+ "phone": data.get("phone"),
+ "first_name": data.get("first_name") or data.get("firstName"),
+ "last_name": data.get("last_name") or data.get("lastName"),
+ "avatar": data.get("avatar"),
+ "locale": data.get("locale") or "zh",
+ "data_json": _json(data.get("data") or {}),
+ }
+ if existing:
+ pk = existing["id"]
+ c.execute(
+ """UPDATE subscribers SET email=?,phone=?,first_name=?,last_name=?,avatar=?,locale=?,data_json=?,updated_at=?
+ WHERE id=?""",
+ (
+ payload["email"],
+ payload["phone"],
+ payload["first_name"],
+ payload["last_name"],
+ payload["avatar"],
+ payload["locale"],
+ payload["data_json"],
+ now,
+ pk,
+ ),
+ )
+ else:
+ pk = _id("sub")
+ c.execute(
+ """INSERT INTO subscribers(
+ id,env_id,subscriber_id,email,phone,first_name,last_name,avatar,locale,data_json,created_at,updated_at
+ ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""",
+ (
+ pk,
+ env,
+ sid,
+ payload["email"],
+ payload["phone"],
+ payload["first_name"],
+ payload["last_name"],
+ payload["avatar"],
+ payload["locale"],
+ payload["data_json"],
+ now,
+ now,
+ ),
+ )
+ c.execute(
+ "INSERT INTO preferences(subscriber_pk,channels_json,updated_at) VALUES(?,?,?)",
+ (pk, _json(_default_prefs()), now),
+ )
+ row = c.execute("SELECT * FROM subscribers WHERE id=?", (pk,)).fetchone()
+ return _subscriber_out(dict(row))
+
+
+def delete_subscriber(subscriber_id: str) -> bool:
+ with _conn() as c:
+ r = c.execute(
+ "SELECT id FROM subscribers WHERE subscriber_id=? OR id=?",
+ (subscriber_id, subscriber_id),
+ ).fetchone()
+ if not r:
+ return False
+ pk = r["id"]
+ c.execute("DELETE FROM topic_subscribers WHERE subscriber_pk=?", (pk,))
+ c.execute("DELETE FROM preferences WHERE subscriber_pk=?", (pk,))
+ c.execute("DELETE FROM messages WHERE subscriber_pk=?", (pk,))
+ c.execute("DELETE FROM subscribers WHERE id=?", (pk,))
+ return True
+
+
+def _subscriber_out(r: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "id": r["id"],
+ "subscriber_id": r["subscriber_id"],
+ "email": r.get("email"),
+ "phone": r.get("phone"),
+ "first_name": r.get("first_name"),
+ "last_name": r.get("last_name"),
+ "avatar": r.get("avatar"),
+ "locale": r.get("locale") or "zh",
+ "data": _parse(r.get("data_json"), {}),
+ "created_at": r.get("created_at"),
+ "updated_at": r.get("updated_at"),
+ }
+
+
+# —— topics ——
+
+
+def list_topics() -> list[dict[str, Any]]:
+ with _conn() as c:
+ rows = c.execute("SELECT * FROM topics ORDER BY created_at DESC").fetchall()
+ out = []
+ for r in rows:
+ d = dict(r)
+ count = c.execute(
+ "SELECT COUNT(*) AS n FROM topic_subscribers WHERE topic_id=?",
+ (d["id"],),
+ ).fetchone()["n"]
+ members = c.execute(
+ """SELECT s.subscriber_id FROM topic_subscribers ts
+ JOIN subscribers s ON s.id=ts.subscriber_pk
+ WHERE ts.topic_id=? ORDER BY s.subscriber_id""",
+ (d["id"],),
+ ).fetchall()
+ out.append(
+ {
+ "id": d["id"],
+ "key": d["key"],
+ "name": d["name"],
+ "subscriber_count": count,
+ "subscribers": [m["subscriber_id"] for m in members],
+ "created_at": d["created_at"],
+ }
+ )
+ return out
+
+
+def create_topic(key: str, name: str) -> dict[str, Any]:
+ key = key.strip()
+ name = name.strip() or key
+ if not key:
+ raise ValueError("key_required")
+ now = _now()
+ with _conn() as c:
+ env = default_env_id(c)
+ pk = _id("topic")
+ try:
+ c.execute(
+ "INSERT INTO topics(id,env_id,key,name,created_at) VALUES(?,?,?,?,?)",
+ (pk, env, key, name, now),
+ )
+ except sqlite3.IntegrityError as e:
+ raise ValueError("topic_exists") from e
+ return {
+ "id": pk,
+ "key": key,
+ "name": name,
+ "subscriber_count": 0,
+ "subscribers": [],
+ "created_at": now,
+ }
+
+
+def add_topic_subscriber(topic_key: str, subscriber_id: str) -> dict[str, Any]:
+ with _conn() as c:
+ t = c.execute(
+ "SELECT * FROM topics WHERE key=? OR id=?",
+ (topic_key, topic_key),
+ ).fetchone()
+ s = c.execute(
+ "SELECT * FROM subscribers WHERE subscriber_id=? OR id=?",
+ (subscriber_id, subscriber_id),
+ ).fetchone()
+ if not t or not s:
+ raise ValueError("not_found")
+ c.execute(
+ "INSERT OR IGNORE INTO topic_subscribers(topic_id,subscriber_pk) VALUES(?,?)",
+ (t["id"], s["id"]),
+ )
+ topics = [x for x in list_topics() if x["id"] == t["id"] or x["key"] == t["key"]]
+ return topics[0]
+
+
+def remove_topic_subscriber(topic_key: str, subscriber_id: str) -> bool:
+ with _conn() as c:
+ t = c.execute(
+ "SELECT id FROM topics WHERE key=? OR id=?",
+ (topic_key, topic_key),
+ ).fetchone()
+ s = c.execute(
+ "SELECT id FROM subscribers WHERE subscriber_id=? OR id=?",
+ (subscriber_id, subscriber_id),
+ ).fetchone()
+ if not t or not s:
+ return False
+ c.execute(
+ "DELETE FROM topic_subscribers WHERE topic_id=? AND subscriber_pk=?",
+ (t["id"], s["id"]),
+ )
+ return True
+
+
+# —— workflows ——
+
+
+def _workflow_out(c: sqlite3.Connection, r: sqlite3.Row) -> dict[str, Any]:
+ d = dict(r)
+ steps = c.execute(
+ """SELECT * FROM workflow_steps WHERE workflow_pk=? ORDER BY position ASC""",
+ (d["id"],),
+ ).fetchall()
+ return {
+ "id": d["id"],
+ "workflow_id": d["workflow_id"],
+ "name": d["name"],
+ "description": d.get("description") or "",
+ "active": bool(d.get("active")),
+ "tags": _parse(d.get("tags_json"), []),
+ "created_at": d["created_at"],
+ "updated_at": d["updated_at"],
+ "steps": [
+ {
+ "id": s["id"],
+ "type": s["type"],
+ "name": s["name"],
+ "position": s["position"],
+ "active": bool(s["active"]),
+ "template": _parse(s["template_json"], {}),
+ "filters": _parse(s["filters_json"], []),
+ }
+ for s in steps
+ ],
+ }
+
+
+def list_workflows() -> list[dict[str, Any]]:
+ with _conn() as c:
+ rows = c.execute("SELECT * FROM workflows ORDER BY updated_at DESC").fetchall()
+ return [_workflow_out(c, r) for r in rows]
+
+
+def get_workflow(workflow_id: str) -> dict[str, Any] | None:
+ with _conn() as c:
+ r = c.execute(
+ "SELECT * FROM workflows WHERE workflow_id=? OR id=?",
+ (workflow_id, workflow_id),
+ ).fetchone()
+ return _workflow_out(c, r) if r else None
+
+
+def create_workflow(
+ workflow_id: str,
+ name: str,
+ description: str = "",
+ steps: list[dict[str, Any]] | None = None,
+ tags: list[str] | None = None,
+) -> dict[str, Any]:
+ workflow_id = workflow_id.strip()
+ name = name.strip()
+ if not workflow_id or not name:
+ raise ValueError("workflow_id_and_name_required")
+ now = _now()
+ with _conn() as c:
+ env = default_env_id(c)
+ pk = _id("wf")
+ try:
+ c.execute(
+ """INSERT INTO workflows(id,env_id,workflow_id,name,description,active,tags_json,created_at,updated_at)
+ VALUES(?,?,?,?,?,?,?,?,?)""",
+ (pk, env, workflow_id, name, description, 1, _json(tags or []), now, now),
+ )
+ except sqlite3.IntegrityError as e:
+ raise ValueError("workflow_exists") from e
+ for i, step in enumerate(steps or [{"type": "in_app", "name": "In-app", "template": {}}]):
+ typ = step.get("type") or "in_app"
+ if typ not in ALL_STEPS:
+ typ = "in_app"
+ c.execute(
+ """INSERT INTO workflow_steps(id,workflow_pk,type,name,position,active,template_json,filters_json)
+ VALUES(?,?,?,?,?,?,?,?)""",
+ (
+ _id("step"),
+ pk,
+ typ,
+ step.get("name") or typ,
+ float(step.get("position", i)),
+ 1 if step.get("active", True) else 0,
+ _json(step.get("template") or {}),
+ _json(step.get("filters") or []),
+ ),
+ )
+ r = c.execute("SELECT * FROM workflows WHERE id=?", (pk,)).fetchone()
+ return _workflow_out(c, r)
+
+
+def update_workflow(workflow_id: str, patch: dict[str, Any]) -> dict[str, Any] | None:
+ with _conn() as c:
+ r = c.execute(
+ "SELECT * FROM workflows WHERE workflow_id=? OR id=?",
+ (workflow_id, workflow_id),
+ ).fetchone()
+ if not r:
+ return None
+ pk = r["id"]
+ now = _now()
+ name = patch.get("name", r["name"])
+ description = patch.get("description", r["description"])
+ active = r["active"] if patch.get("active") is None else (1 if patch["active"] else 0)
+ tags = patch.get("tags")
+ tags_json = _json(tags) if tags is not None else r["tags_json"]
+ c.execute(
+ """UPDATE workflows SET name=?,description=?,active=?,tags_json=?,updated_at=? WHERE id=?""",
+ (name, description, active, tags_json, now, pk),
+ )
+ if "steps" in patch and isinstance(patch["steps"], list):
+ c.execute("DELETE FROM workflow_steps WHERE workflow_pk=?", (pk,))
+ for i, step in enumerate(patch["steps"]):
+ typ = step.get("type") or "in_app"
+ if typ not in ALL_STEPS:
+ typ = "in_app"
+ c.execute(
+ """INSERT INTO workflow_steps(id,workflow_pk,type,name,position,active,template_json,filters_json)
+ VALUES(?,?,?,?,?,?,?,?)""",
+ (
+ step.get("id") or _id("step"),
+ pk,
+ typ,
+ step.get("name") or typ,
+ float(step.get("position", i)),
+ 1 if step.get("active", True) else 0,
+ _json(step.get("template") or {}),
+ _json(step.get("filters") or []),
+ ),
+ )
+ row = c.execute("SELECT * FROM workflows WHERE id=?", (pk,)).fetchone()
+ return _workflow_out(c, row)
+
+
+def delete_workflow(workflow_id: str) -> bool:
+ with _conn() as c:
+ r = c.execute(
+ "SELECT id FROM workflows WHERE workflow_id=? OR id=?",
+ (workflow_id, workflow_id),
+ ).fetchone()
+ if not r:
+ return False
+ c.execute("DELETE FROM workflow_steps WHERE workflow_pk=?", (r["id"],))
+ c.execute("DELETE FROM workflows WHERE id=?", (r["id"],))
+ return True
+
+
+# —— preferences / integrations / inbox ——
+
+
+def _merge_prefs(raw: dict[str, Any] | None) -> dict[str, Any]:
+ out = _default_prefs()
+ if raw:
+ out.update(raw)
+ return out
+
+
+def get_preferences(subscriber_id: str) -> dict[str, Any] | None:
+ with _conn() as c:
+ s = c.execute(
+ "SELECT id,subscriber_id FROM subscribers WHERE subscriber_id=? OR id=?",
+ (subscriber_id, subscriber_id),
+ ).fetchone()
+ if not s:
+ return None
+ p = c.execute(
+ "SELECT * FROM preferences WHERE subscriber_pk=?", (s["id"],)
+ ).fetchone()
+ prefs = _merge_prefs(_parse(p["channels_json"], {}) if p else {})
+ return {
+ "subscriber_id": s["subscriber_id"],
+ "channels": prefs,
+ "dnd": bool(prefs.get("dnd")),
+ "email_subscribe": bool(prefs.get("email_subscribe")),
+ "browser_push": bool(prefs.get("browser_push")),
+ "push_permission": prefs.get("push_permission") or "default",
+ "updated_at": p["updated_at"] if p else None,
+ }
+
+
+def set_preferences(subscriber_id: str, channels: dict[str, Any]) -> dict[str, Any]:
+ with _conn() as c:
+ s = c.execute(
+ "SELECT id,subscriber_id FROM subscribers WHERE subscriber_id=? OR id=?",
+ (subscriber_id, subscriber_id),
+ ).fetchone()
+ if not s:
+ raise ValueError("subscriber_not_found")
+ now = _now()
+ existing = c.execute(
+ "SELECT channels_json FROM preferences WHERE subscriber_pk=?",
+ (s["id"],),
+ ).fetchone()
+ merged = _merge_prefs(_parse(existing["channels_json"], {}) if existing else {})
+ merged.update(channels or {})
+ c.execute(
+ """INSERT INTO preferences(subscriber_pk,channels_json,updated_at) VALUES(?,?,?)
+ ON CONFLICT(subscriber_pk) DO UPDATE SET channels_json=excluded.channels_json,updated_at=excluded.updated_at""",
+ (s["id"], _json(merged), now),
+ )
+ return get_preferences(subscriber_id) # type: ignore[return-value]
+
+
+def list_integrations() -> list[dict[str, Any]]:
+ with _conn() as c:
+ rows = c.execute(
+ "SELECT id,channel,provider,active,created_at FROM integrations ORDER BY channel"
+ ).fetchall()
+ return [
+ {
+ "id": r["id"],
+ "channel": r["channel"],
+ "provider": r["provider"],
+ "active": bool(r["active"]),
+ "created_at": r["created_at"],
+ }
+ for r in rows
+ ]
+
+
+def list_inbox(
+ subscriber_id: str,
+ *,
+ include_archived: bool = False,
+ category: str | None = None,
+ include_deleted: bool = False,
+) -> list[dict[str, Any]]:
+ with _conn() as c:
+ s = c.execute(
+ "SELECT id FROM subscribers WHERE subscriber_id=? OR id=?",
+ (subscriber_id, subscriber_id),
+ ).fetchone()
+ if not s:
+ return []
+ q = "SELECT * FROM messages WHERE subscriber_pk=? AND channel='in_app'"
+ args: list[Any] = [s["id"]]
+ if not include_deleted:
+ q += " AND COALESCE(deleted,0)=0"
+ if not include_archived:
+ q += " AND archived=0"
+ if category and category in CATEGORIES:
+ q += " AND category=?"
+ args.append(category)
+ q += " ORDER BY created_at DESC"
+ rows = c.execute(q, args).fetchall()
+ return [_message_out(dict(r)) for r in rows]
+
+
+def patch_message(message_id: str, patch: dict[str, Any]) -> dict[str, Any] | None:
+ with _conn() as c:
+ r = c.execute("SELECT * FROM messages WHERE id=?", (message_id,)).fetchone()
+ if not r:
+ return None
+ read = r["read"] if patch.get("read") is None else (1 if patch["read"] else 0)
+ archived = (
+ r["archived"] if patch.get("archived") is None else (1 if patch["archived"] else 0)
+ )
+ deleted = r["deleted"] if patch.get("deleted") is None else (1 if patch["deleted"] else 0)
+ c.execute(
+ "UPDATE messages SET read=?, archived=?, deleted=? WHERE id=?",
+ (read, archived, deleted, message_id),
+ )
+ row = c.execute("SELECT * FROM messages WHERE id=?", (message_id,)).fetchone()
+ return _message_out(dict(row))
+
+
+def delete_message(message_id: str) -> bool:
+ m = patch_message(message_id, {"deleted": True})
+ return m is not None
+
+
+def mark_all_read(subscriber_id: str, category: str | None = None) -> int:
+ with _conn() as c:
+ s = c.execute(
+ "SELECT id FROM subscribers WHERE subscriber_id=? OR id=?",
+ (subscriber_id, subscriber_id),
+ ).fetchone()
+ if not s:
+ return 0
+ q = (
+ "UPDATE messages SET read=1 WHERE subscriber_pk=? AND channel='in_app' "
+ "AND COALESCE(deleted,0)=0 AND read=0"
+ )
+ args: list[Any] = [s["id"]]
+ if category and category in CATEGORIES:
+ q += " AND category=?"
+ args.append(category)
+ cur = c.execute(q, args)
+ return int(cur.rowcount or 0)
+
+
+def unread_count(subscriber_id: str, category: str | None = None) -> int:
+ with _conn() as c:
+ s = c.execute(
+ "SELECT id FROM subscribers WHERE subscriber_id=? OR id=?",
+ (subscriber_id, subscriber_id),
+ ).fetchone()
+ if not s:
+ return 0
+ q = (
+ "SELECT COUNT(*) AS n FROM messages WHERE subscriber_pk=? AND channel='in_app' "
+ "AND read=0 AND archived=0 AND COALESCE(deleted,0)=0"
+ )
+ args: list[Any] = [s["id"]]
+ if category and category in CATEGORIES:
+ q += " AND category=?"
+ args.append(category)
+ return int(c.execute(q, args).fetchone()["n"])
+
+
+def unread_by_category(subscriber_id: str) -> dict[str, int]:
+ return {cat: unread_count(subscriber_id, cat) for cat in CATEGORIES}
+
+
+def _message_out(r: dict[str, Any]) -> dict[str, Any]:
+ cat = r.get("category") or "system"
+ if cat not in CATEGORIES:
+ cat = "system"
+ href = r.get("cta_url") or ""
+ return {
+ "id": r["id"],
+ "notification_id": r.get("notification_id"),
+ "channel": r.get("channel") or "in_app",
+ "category": cat,
+ "subject": r.get("subject") or "",
+ "body": r.get("body") or "",
+ "cta_label": r.get("cta_label"),
+ "cta_url": href,
+ "href": href,
+ "payload": _parse(r.get("payload_json"), {}),
+ "read": bool(r.get("read")),
+ "archived": bool(r.get("archived")),
+ "deleted": bool(r.get("deleted")),
+ "created_at": r.get("created_at"),
+ }
+
+
+def list_activity(limit: int = 50) -> list[dict[str, Any]]:
+ with _conn() as c:
+ rows = c.execute(
+ """SELECT n.id,n.status,n.created_at,n.event_id,
+ s.subscriber_id,w.workflow_id,w.name AS workflow_name,
+ e.transaction_id,e.payload_json
+ FROM notifications n
+ JOIN subscribers s ON s.id=n.subscriber_pk
+ JOIN workflows w ON w.id=n.workflow_pk
+ JOIN events e ON e.id=n.event_id
+ ORDER BY n.created_at DESC LIMIT ?""",
+ (limit,),
+ ).fetchall()
+ out = []
+ for r in rows:
+ jobs = c.execute(
+ "SELECT channel,status,detail_json,created_at FROM jobs WHERE notification_id=? ORDER BY created_at",
+ (r["id"],),
+ ).fetchall()
+ out.append(
+ {
+ "id": r["id"],
+ "status": r["status"],
+ "created_at": r["created_at"],
+ "subscriber_id": r["subscriber_id"],
+ "workflow_id": r["workflow_id"],
+ "workflow_name": r["workflow_name"],
+ "transaction_id": r["transaction_id"],
+ "payload": _parse(r["payload_json"], {}),
+ "jobs": [
+ {
+ "channel": j["channel"],
+ "status": j["status"],
+ "detail": _parse(j["detail_json"], {}),
+ "created_at": j["created_at"],
+ }
+ for j in jobs
+ ],
+ }
+ )
+ return out
+
+
+def _render(tpl: str, ctx: dict[str, Any]) -> str:
+ out = tpl or ""
+ for k, v in ctx.items():
+ out = out.replace("{{" + k + "}}", str(v if v is not None else ""))
+ return out
+
+
+def trigger_event(
+ *,
+ workflow_id: str,
+ subscriber_id: str | None = None,
+ topic_key: str | None = None,
+ payload: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ payload = payload or {}
+ with _conn() as c:
+ env = default_env_id(c)
+ wf = c.execute(
+ "SELECT * FROM workflows WHERE workflow_id=? OR id=?",
+ (workflow_id, workflow_id),
+ ).fetchone()
+ if not wf:
+ raise ValueError("workflow_not_found")
+ if not wf["active"]:
+ raise ValueError("workflow_inactive")
+
+ targets: list[sqlite3.Row] = []
+ if topic_key:
+ t = c.execute(
+ "SELECT id FROM topics WHERE key=? OR id=?",
+ (topic_key, topic_key),
+ ).fetchone()
+ if not t:
+ raise ValueError("topic_not_found")
+ targets = list(
+ c.execute(
+ """SELECT s.* FROM topic_subscribers ts
+ JOIN subscribers s ON s.id=ts.subscriber_pk
+ WHERE ts.topic_id=?""",
+ (t["id"],),
+ ).fetchall()
+ )
+ elif subscriber_id:
+ s = c.execute(
+ "SELECT * FROM subscribers WHERE subscriber_id=? OR id=?",
+ (subscriber_id, subscriber_id),
+ ).fetchone()
+ if not s:
+ raise ValueError("subscriber_not_found")
+ targets = [s]
+ else:
+ raise ValueError("subscriber_or_topic_required")
+
+ steps = c.execute(
+ "SELECT * FROM workflow_steps WHERE workflow_pk=? AND active=1 ORDER BY position",
+ (wf["id"],),
+ ).fetchall()
+
+ now = _now()
+ tx = _id("tx")
+ eid = _id("evt")
+ c.execute(
+ """INSERT INTO events(id,env_id,transaction_id,workflow_pk,payload_json,created_at)
+ VALUES(?,?,?,?,?,?)""",
+ (eid, env, tx, wf["id"], _json(payload), now),
+ )
+
+ notifications: list[dict[str, Any]] = []
+ for sub in targets:
+ prefs_row = c.execute(
+ "SELECT channels_json FROM preferences WHERE subscriber_pk=?",
+ (sub["id"],),
+ ).fetchone()
+ prefs = _parse(prefs_row["channels_json"], {}) if prefs_row else {}
+ ctx = {
+ "firstName": sub["first_name"] or sub["subscriber_id"],
+ "lastName": sub["last_name"] or "",
+ "email": sub["email"] or "",
+ "subscriberId": sub["subscriber_id"],
+ **{k: v for k, v in payload.items() if isinstance(v, (str, int, float))},
+ }
+ nid = _id("ntf")
+ c.execute(
+ """INSERT INTO notifications(id,event_id,subscriber_pk,workflow_pk,status,created_at)
+ VALUES(?,?,?,?,?,?)""",
+ (nid, eid, sub["id"], wf["id"], "completed", now),
+ )
+ job_outs = []
+ for step in steps:
+ typ = step["type"]
+ tpl = _parse(step["template_json"], {})
+ if typ in ACTION_STEPS:
+ status = "skipped_recorded"
+ detail = {"reason": f"{typ}_stub", "template": tpl}
+ c.execute(
+ """INSERT INTO jobs(id,notification_id,step_id,channel,status,detail_json,created_at)
+ VALUES(?,?,?,?,?,?,?)""",
+ (_id("job"), nid, step["id"], typ, status, _json(detail), now),
+ )
+ job_outs.append({"channel": typ, "status": status})
+ continue
+
+ # channel preference gate
+ if prefs.get(typ) is False:
+ status = "skipped_preference"
+ c.execute(
+ """INSERT INTO jobs(id,notification_id,step_id,channel,status,detail_json,created_at)
+ VALUES(?,?,?,?,?,?,?)""",
+ (
+ _id("job"),
+ nid,
+ step["id"],
+ typ,
+ status,
+ _json({"reason": "preference_off"}),
+ now,
+ ),
+ )
+ job_outs.append({"channel": typ, "status": status})
+ continue
+
+ # DND: mute external channels; inbox still receives in_app
+ if prefs.get("dnd") and typ != "in_app":
+ status = "skipped_dnd"
+ c.execute(
+ """INSERT INTO jobs(id,notification_id,step_id,channel,status,detail_json,created_at)
+ VALUES(?,?,?,?,?,?,?)""",
+ (
+ _id("job"),
+ nid,
+ step["id"],
+ typ,
+ status,
+ _json({"reason": "dnd"}),
+ now,
+ ),
+ )
+ job_outs.append({"channel": typ, "status": status})
+ continue
+
+ if typ == "email" and prefs.get("email_subscribe") is False:
+ status = "skipped_preference"
+ c.execute(
+ """INSERT INTO jobs(id,notification_id,step_id,channel,status,detail_json,created_at)
+ VALUES(?,?,?,?,?,?,?)""",
+ (
+ _id("job"),
+ nid,
+ step["id"],
+ typ,
+ status,
+ _json({"reason": "email_subscribe_off"}),
+ now,
+ ),
+ )
+ job_outs.append({"channel": typ, "status": status})
+ continue
+
+ if typ == "in_app":
+ subject = _render(tpl.get("subject") or tpl.get("title") or "", ctx)
+ body = _render(tpl.get("body") or tpl.get("content") or "", ctx)
+ cat = (
+ tpl.get("category")
+ or payload.get("category")
+ or "system"
+ )
+ if cat not in CATEGORIES:
+ cat = "system"
+ mid = _id("msg")
+ c.execute(
+ """INSERT INTO messages(
+ id,notification_id,subscriber_pk,channel,subject,body,cta_label,cta_url,
+ payload_json,read,archived,category,deleted,created_at
+ ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
+ (
+ mid,
+ nid,
+ sub["id"],
+ "in_app",
+ subject,
+ body,
+ tpl.get("ctaLabel") or tpl.get("cta_label"),
+ tpl.get("ctaUrl") or tpl.get("cta_url"),
+ _json(payload),
+ 0,
+ 0,
+ cat,
+ 0,
+ now,
+ ),
+ )
+ status = "delivered"
+ detail = {"message_id": mid, "category": cat}
+ else:
+ # external channels: record intent only (stub providers)
+ status = "queued_stub"
+ detail = {
+ "provider": f"{typ}-stub",
+ "rendered": {
+ "subject": _render(tpl.get("subject") or tpl.get("title") or "", ctx),
+ "body": _render(tpl.get("body") or "", ctx),
+ },
+ }
+ c.execute(
+ """INSERT INTO jobs(id,notification_id,step_id,channel,status,detail_json,created_at)
+ VALUES(?,?,?,?,?,?,?)""",
+ (_id("job"), nid, step["id"], typ, status, _json(detail), now),
+ )
+ job_outs.append({"channel": typ, "status": status})
+
+ notifications.append(
+ {
+ "id": nid,
+ "subscriber_id": sub["subscriber_id"],
+ "jobs": job_outs,
+ }
+ )
+
+ return {
+ "transaction_id": tx,
+ "event_id": eid,
+ "workflow_id": wf["workflow_id"],
+ "notifications": notifications,
+ }
diff --git a/apps/api/services/pay_svc/payment/factory.py b/apps/api/services/pay_svc/payment/factory.py
index 920503b..695ccbe 100644
--- a/apps/api/services/pay_svc/payment/factory.py
+++ b/apps/api/services/pay_svc/payment/factory.py
@@ -62,6 +62,21 @@ def reset_provider():
_provider_instance = None
+def _overseas_provider(preferred: str | None = None) -> PaymentProvider:
+ """海外:显式 nowpayments 优先;否则 Creem → 加密货币 NOWPayments 回退。"""
+ pref = (preferred or "").strip().lower()
+ if pref == "nowpayments":
+ return get_payment_provider_by_name("nowpayments")
+ if pref == "creem":
+ if (CREEM_API_KEY or "").strip():
+ return get_payment_provider_by_name("creem")
+ # Creem 未配密钥时自动改走加密支付
+ return get_payment_provider_by_name("nowpayments")
+ if (CREEM_API_KEY or "").strip():
+ return get_payment_provider_by_name("creem")
+ return get_payment_provider_by_name("nowpayments")
+
+
def resolve_provider(
device: str | None = None,
req_provider: str | None = None,
@@ -70,18 +85,20 @@ def resolve_provider(
) -> PaymentProvider:
"""
根据区域 + 设备解析支付渠道:
- - region=overseas → creem(可用 nowpayments 显式覆盖)
+ - region=overseas → creem(无密钥则 nowpayments;可显式 nowpayments)
- 微信内(device=wechat 或 UA 含 MicroMessenger) → xorpay
- PC/手机浏览器 → zpay
- 显式传入的 provider 优先。
+ 显式传入的 provider 优先(海外缺 Creem 密钥时回退加密货币)。
"""
req = (req_provider or "").strip().lower()
- if req in _CN_NAMES or req in _OVERSEAS_NAMES:
+ if req in _OVERSEAS_NAMES:
+ return _overseas_provider(req)
+ if req in _CN_NAMES:
return get_payment_provider_by_name(req)
reg = (region or "").strip().lower()
if reg in ("overseas", "intl", "global"):
- return get_payment_provider_by_name("creem")
+ return _overseas_provider(None)
dev = (device or "pc").lower()
if dev == "wechat":
diff --git a/apps/api/services/pay_svc/payment/zpay.py b/apps/api/services/pay_svc/payment/zpay.py
index 39b35d4..65b318d 100644
--- a/apps/api/services/pay_svc/payment/zpay.py
+++ b/apps/api/services/pay_svc/payment/zpay.py
@@ -2,11 +2,15 @@
ZPAY 支付渠道实现
文档: https://z-pay.cn/doc.html
支持:页面跳转支付、API 接口支付、异步通知验签
+
+美国 VPS 常被 zpayz.cn CDN 掐断 POST;优先 z-pay.cn / api.z-pay.cn。
+可用环境变量覆盖:ZPAY_MAPI_URL / ZPAY_SUBMIT_URL / ZPAY_API_BASE
"""
import hashlib
import json
import logging
-from typing import Any, Dict, Optional
+import os
+from typing import Any, Dict, List, Optional
import requests
@@ -14,6 +18,23 @@ from .base import PaymentProvider
logger = logging.getLogger(__name__)
+# 多域名:海外机优先通的排前面;国内机三个一般都能用
+_DEFAULT_MAPI_URLS = (
+ "https://z-pay.cn/mapi.php",
+ "https://api.z-pay.cn/mapi.php",
+ "https://zpayz.cn/mapi.php",
+)
+_DEFAULT_SUBMIT_URLS = (
+ "https://z-pay.cn/submit.php",
+ "https://api.z-pay.cn/submit.php",
+ "https://zpayz.cn/submit.php",
+)
+_DEFAULT_API_BASES = (
+ "https://z-pay.cn",
+ "https://api.z-pay.cn",
+ "https://zpayz.cn",
+)
+
def _is_internal_ip(ip: Optional[str]) -> bool:
"""判断是否为内网 IP,ZPAY 可能拒收导致 Ubuntu 部署失败"""
@@ -27,16 +48,29 @@ def _is_internal_ip(ip: Optional[str]) -> bool:
return False
+def _split_urls(raw: str | None, defaults: tuple[str, ...]) -> List[str]:
+ if raw and raw.strip():
+ return [u.strip() for u in raw.split(",") if u.strip()]
+ return list(defaults)
+
+
class ZPayProvider(PaymentProvider):
"""ZPAY 支付(易支付兼容接口)"""
- # API 地址
- SUBMIT_URL = "https://zpayz.cn/submit.php" # 页面跳转
- MAPI_URL = "https://zpayz.cn/mapi.php" # API 接口
-
def __init__(self, pid: str, key: str):
self.pid = pid
self.key = key
+ self.mapi_urls = _split_urls(os.getenv("ZPAY_MAPI_URL"), _DEFAULT_MAPI_URLS)
+ self.submit_urls = _split_urls(os.getenv("ZPAY_SUBMIT_URL"), _DEFAULT_SUBMIT_URLS)
+ self.api_bases = _split_urls(os.getenv("ZPAY_API_BASE"), _DEFAULT_API_BASES)
+
+ @property
+ def SUBMIT_URL(self) -> str:
+ return self.submit_urls[0]
+
+ @property
+ def MAPI_URL(self) -> str:
+ return self.mapi_urls[0]
@property
def name(self) -> str:
@@ -141,71 +175,73 @@ class ZPayProvider(PaymentProvider):
params["sign_type"] = "MD5"
params["sign"] = self._md5_sign(params)
- try:
- resp = requests.post(self.MAPI_URL, data=params, timeout=15)
- except requests.exceptions.SSLError as e:
- logger.error("ZPAY SSL 错误(Ubuntu 可能 CA 证书不全): %s", e, exc_info=True)
- return {
- "status": "error",
- "provider": self.name,
- "msg": f"连接 zpayz.cn SSL 失败: {e}。Ubuntu 请安装 ca-certificates: apt install ca-certificates",
- }
- except requests.RequestException as e:
- logger.error("ZPAY 连接失败: %s", e, exc_info=True)
- return {
- "status": "error",
- "provider": self.name,
- "msg": f"连接 zpayz.cn 失败: {e}。请检查服务器网络、防火墙或 DNS。",
- }
-
- try:
- result = resp.json()
- except Exception:
- result = {}
- # ZPAY 可能返回二次编码的 JSON(body 为 JSON 字符串),需再次解析
- if isinstance(result, str):
+ last_err = ""
+ resp = None
+ result: Dict[str, Any] = {}
+ for mapi_url in self.mapi_urls:
try:
- result = json.loads(result)
+ resp = requests.post(mapi_url, data=params, timeout=15)
+ except requests.exceptions.SSLError as e:
+ last_err = f"SSL 失败 ({mapi_url}): {e}"
+ logger.warning("ZPAY SSL: %s", last_err)
+ continue
+ except requests.RequestException as e:
+ last_err = f"连接失败 ({mapi_url}): {e}"
+ logger.warning("ZPAY 连接: %s", last_err)
+ continue
+
+ try:
+ result = resp.json()
except Exception:
result = {}
- if not isinstance(result, dict):
- result = {}
- # 部分环境下 ZPAY 将成功数据放在 msg 中(msg 为 JSON 字符串)
- msg_val = result.get("msg")
- if isinstance(msg_val, str) and msg_val.strip().startswith("{"):
+ # ZPAY 可能返回二次编码的 JSON(body 为 JSON 字符串),需再次解析
+ if isinstance(result, str):
+ try:
+ result = json.loads(result)
+ except Exception:
+ result = {}
+ if not isinstance(result, dict):
+ result = {}
+ # 部分环境下 ZPAY 将成功数据放在 msg 中(msg 为 JSON 字符串)
+ msg_val = result.get("msg")
+ if isinstance(msg_val, str) and msg_val.strip().startswith("{"):
+ try:
+ inner = json.loads(msg_val)
+ if isinstance(inner, dict) and int(float(inner.get("code", 0))) == 1:
+ result = inner
+ except Exception:
+ pass
try:
- inner = json.loads(msg_val)
- if isinstance(inner, dict) and int(float(inner.get("code", 0))) == 1:
- result = inner
- except Exception:
- pass
- try:
- code = int(float(result.get("code", 0)))
- except (TypeError, ValueError):
- code = 0
- if code == 1:
- return {
- "status": "ok",
- "provider": self.name,
- "payurl": result.get("payurl"),
- "payurl2": result.get("payurl2"), # 微信 H5,手机浏览器打开可唤醒微信
- "qrcode": result.get("qrcode"),
- "img": result.get("img"),
- "O_id": result.get("O_id"),
- "trade_no": result.get("trade_no"),
- }
- err_msg = result.get("msg", resp.text)
- logger.error(
- "ZPAY create_order_api 失败 status=%s code=%s msg=%s resp_text=%s",
- resp.status_code,
- code,
- err_msg,
- resp.text[:500] if resp.text else "",
- )
+ code = int(float(result.get("code", 0)))
+ except (TypeError, ValueError):
+ code = 0
+ if code == 1:
+ logger.info("ZPAY mapi ok via %s", mapi_url)
+ return {
+ "status": "ok",
+ "provider": self.name,
+ "payurl": result.get("payurl"),
+ "payurl2": result.get("payurl2"), # 微信 H5,手机浏览器打开可唤醒微信
+ "qrcode": result.get("qrcode"),
+ "img": result.get("img"),
+ "O_id": result.get("O_id"),
+ "trade_no": result.get("trade_no"),
+ "mapi_url": mapi_url,
+ }
+ last_err = str(result.get("msg") or (resp.text if resp is not None else "") or "unknown")
+ logger.warning(
+ "ZPAY mapi 业务失败 url=%s status=%s code=%s msg=%s",
+ mapi_url,
+ getattr(resp, "status_code", None),
+ code,
+ last_err[:300],
+ )
+
+ logger.error("ZPAY create_order_api 全部域名失败: %s", last_err)
return {
"status": "error",
"provider": self.name,
- "msg": err_msg,
+ "msg": last_err or "ZPAY mapi 不可用",
}
def verify_notify(self, data: Dict[str, Any]) -> bool:
@@ -229,22 +265,28 @@ class ZPayProvider(PaymentProvider):
def query_order_status(self, out_trade_no: str, timeout: int = 15) -> Dict[str, Any]:
"""查询 ZPAY 订单支付状态(供 nomadvip/digital/cnomadcna/nomadlms 共用)"""
- url = f"https://zpayz.cn/api.php?act=order&pid={self.pid}&key={self.key}&out_trade_no={out_trade_no}"
- try:
- resp = requests.get(url, timeout=timeout)
- result = resp.json() if resp.ok else {}
- except Exception as e:
- return {"paid": False, "error": str(e)}
- try:
- code = result.get("code", 0)
- code = int(code) if isinstance(code, (int, float)) or str(code).isdigit() else 0
- except (ValueError, TypeError):
- code = 0
- if code != 1:
- return {"paid": False, "msg": result.get("msg", "查询失败")}
- try:
- status = int(result.get("status", 0))
- except (ValueError, TypeError):
- status = 0
- money = result.get("money") or result.get("pay_price") or ""
- return {"paid": status == 1, "status": status, "pay_price": str(money) if money else ""}
+ last_err = ""
+ result: Dict[str, Any] = {}
+ for base in self.api_bases:
+ url = f"{base.rstrip('/')}/api.php?act=order&pid={self.pid}&key={self.key}&out_trade_no={out_trade_no}"
+ try:
+ resp = requests.get(url, timeout=timeout)
+ result = resp.json() if resp.ok else {}
+ except Exception as e:
+ last_err = str(e)
+ continue
+ try:
+ code = result.get("code", 0)
+ code = int(code) if isinstance(code, (int, float)) or str(code).isdigit() else 0
+ except (ValueError, TypeError):
+ code = 0
+ if code != 1:
+ last_err = str(result.get("msg", "查询失败"))
+ continue
+ try:
+ status = int(result.get("status", 0))
+ except (ValueError, TypeError):
+ status = 0
+ money = result.get("money") or result.get("pay_price") or ""
+ return {"paid": status == 1, "status": status, "pay_price": str(money) if money else ""}
+ return {"paid": False, "error": last_err or "查询失败"}
diff --git a/apps/api/services/pay_svc/routers/nomadvip.py b/apps/api/services/pay_svc/routers/nomadvip.py
index 1502c4c..749f33a 100644
--- a/apps/api/services/pay_svc/routers/nomadvip.py
+++ b/apps/api/services/pay_svc/routers/nomadvip.py
@@ -124,6 +124,16 @@ async def nomadvip_payh5(item: dict, request: Request):
}
name = type_map.get(pay_type, "VIP会员充值")
notify_url = _get_notify_path(provider.name)
+ # 海外金额:fen→美元展示数值(与前端 intl 定价一致,先按元数值当 USD)
+ overseas_extra = None
+ if provider.name in ("creem", "nowpayments"):
+ overseas_extra = {
+ "amount_cents": max(100, int(round(float(total_fee_yuan) * 100))),
+ "currency": "USD",
+ "price_amount": float(total_fee_yuan),
+ "price_currency": "usd",
+ "product_name": name,
+ }
result = provider.create_order(
order_id=order_id,
name=name,
@@ -132,7 +142,31 @@ async def nomadvip_payh5(item: dict, request: Request):
notify_url=notify_url,
return_url=item.get("return_url"),
client_ip=item.get("client_ip"),
+ extra=overseas_extra,
)
+ # Creem 未配置时回退加密货币 NOWPayments
+ if (
+ provider.name == "creem"
+ and result.get("ok") is False
+ and "CREEM_API_KEY" in str(result.get("error") or "")
+ ):
+ provider = get_payment_provider_by_name("nowpayments")
+ notify_url = _get_notify_path(provider.name)
+ result = provider.create_order(
+ order_id=order_id,
+ name=name,
+ total_fee_yuan=total_fee_yuan,
+ pay_type=channel,
+ notify_url=notify_url,
+ return_url=item.get("return_url"),
+ client_ip=item.get("client_ip"),
+ extra=overseas_extra,
+ )
+ logging.warning(
+ "[payjsapi] payh5 creem missing key → fallback nowpayments order_id=%s ok=%s",
+ order_id,
+ result.get("ok"),
+ )
logging.info(
"[payjsapi] payh5 created order_id=%s provider=%s notify_url=%s return_url=%s",
order_id,
@@ -154,9 +188,15 @@ async def nomadvip_payh5(item: dict, request: Request):
redirect_url = result.get("redirect_url") or result.get("pay_url") or ""
if provider.name in ("creem", "nowpayments"):
if result.get("ok") is False:
+ err = result.get("error") or "overseas pay failed"
+ if "not configured" in str(err).lower():
+ err = (
+ f"{err}. Configure CREEM_API_KEY and/or NOWPAYMENTS_API_KEY "
+ "on US pay_svc (.com overseas)."
+ )
return {
"status": "error",
- "error": result.get("error") or "overseas pay failed",
+ "error": err,
"provider": provider.name,
}
return {
diff --git a/apps/api/services/social_svc/__init__.py b/apps/api/services/social_svc/__init__.py
index b5ee826..bb2b4eb 100644
--- a/apps/api/services/social_svc/__init__.py
+++ b/apps/api/services/social_svc/__init__.py
@@ -1 +1,4 @@
-"""游民社区独立后端 — 与 community/ebook/pay 数据完全隔离。"""
+"""游民社区独立后端 — 与 community/ebook/pay 数据完全隔离。
+
+IM 协议见 ``contract.py``:服务端无 UI 假设;Web / 微信小程序任意换皮。
+"""
diff --git a/apps/api/services/social_svc/config.py b/apps/api/services/social_svc/config.py
index 192716a..207005d 100644
--- a/apps/api/services/social_svc/config.py
+++ b/apps/api/services/social_svc/config.py
@@ -8,6 +8,10 @@ _ROOT = Path(__file__).resolve().parents[4] # nomadro/
_DEFAULT_DB = _ROOT / "data" / "social" / "social.db"
SOCIAL_DB_PATH = Path(os.getenv("SOCIAL_DB_PATH", str(_DEFAULT_DB))).resolve()
+SOCIAL_UPLOAD_DIR = Path(
+ os.getenv("SOCIAL_UPLOAD_DIR", str(SOCIAL_DB_PATH.parent / "uploads"))
+).resolve()
+SOCIAL_UPLOAD_MAX_BYTES = int(os.getenv("SOCIAL_UPLOAD_MAX_BYTES", str(25 * 1024 * 1024)))
SOCIAL_ENABLED = os.getenv("SOCIAL_ENABLED", "true").lower() in {"1", "true", "yes", "on"}
# Centrifugo(实时层;缺省关,部署后用环境变量打开)
@@ -36,3 +40,34 @@ LIVE_STREAM_SECRET = os.getenv(
)
LIVE_MAX_PEERS = int(os.getenv("LIVE_MAX_PEERS", "6"))
LIVE_PEER_TTL_SEC = int(os.getenv("LIVE_PEER_TTL_SEC", "45"))
+
+# Geo discovery (MapLibre / Photon / H3 + PocketBase trips)
+PHOTON_BASE_URL = os.getenv(
+ "PHOTON_BASE_URL",
+ "https://photon.komoot.io",
+).rstrip("/")
+PHOTON_TIMEOUT_SEC = float(os.getenv("PHOTON_TIMEOUT_SEC", "6"))
+H3_CITY_RES = int(os.getenv("H3_CITY_RES", "4"))
+H3_NEAR_RES = int(os.getenv("H3_NEAR_RES", "7"))
+# PocketBase for social_trips (same env family as pay_svc)
+_pb_internal = os.getenv("PB_INTERNAL_URL") or os.getenv("POCKETBASE_INTERNAL_URL")
+_pb_explicit = os.getenv("PB_URL") or os.getenv("POCKETBASE_URL")
+if _pb_internal:
+ PB_URL = _pb_internal.rstrip("/")
+elif _pb_explicit:
+ PB_URL = _pb_explicit.rstrip("/")
+else:
+ PB_URL = "http://127.0.0.1:8090"
+PB_ADMIN_EMAIL = (
+ os.getenv("PB_ADMIN_EMAIL") or os.getenv("POCKETBASE_EMAIL") or ""
+)
+PB_ADMIN_PASSWORD = (
+ os.getenv("PB_ADMIN_PASSWORD") or os.getenv("POCKETBASE_PASSWORD") or ""
+)
+SOCIAL_TRIPS_COLLECTION = os.getenv("SOCIAL_TRIPS_COLLECTION", "social_trips")
+SOCIAL_GEO_USE_PB = os.getenv("SOCIAL_GEO_USE_PB", "true").lower() in {
+ "1",
+ "true",
+ "yes",
+ "on",
+}
diff --git a/apps/api/services/social_svc/contract.py b/apps/api/services/social_svc/contract.py
new file mode 100644
index 0000000..60a568a
--- /dev/null
+++ b/apps/api/services/social_svc/contract.py
@@ -0,0 +1,67 @@
+"""Nomadro Social IM — server contract (UI-agnostic).
+
+Frontends (Web / 微信小程序 / future apps) MUST treat this as the only SoT.
+No UI assumptions: display names, layouts, emoji pickers live entirely in clients.
+
+Transport
+---------
+- REST: ``/api/social/v1/*``
+- Realtime: Centrifugo channel ``social:{channelId}``
+- Auth peer: header ``X-Social-Guest-Id`` (or ``?guest=``)
+
+HTTP (chat core)
+----------------
+GET /health
+GET /realtime/token?channel_id=
+GET /channels/{id}/desc
+GET /channels/{id}/messages?since=&before=&limit=&q=
+POST /channels/{id}/messages body: {author, text?, clientId?, replyTo?, attachments?, mentions?}
+PATCH /channels/{id}/messages/{msgId} body: {text} # edit
+POST /channels/{id}/messages/{msgId}/recall
+POST /channels/{id}/messages/{msgId}/react body: {emoji}
+POST /channels/{id}/messages/{msgId}/pin body: {pinned?}
+POST /channels/{id}/messages/{msgId}/report body: {reason?}
+POST /channels/{id}/presence body: {nick?} # soft online heartbeat
+POST /channels/{id}/notes body: {what: recv|read|kp, seq?}
+POST /channels/{id}/upload multipart file → attachment descriptor
+GET /files/{fileId} stream uploaded bytes
+
+Centrifugo publications (JSON)
+------------------------------
+{"type":"chat.message","message":{…full message…}}
+{"type":"chat.note","what":"recv|read|kp","seq":N,"guestId":"...","at":"..."}
+
+Message fields
+--------------
+- ``seq``: monotonic int per channel (Tinode-inspired sync cursor)
+- ``clientId``: client idempotency key (optional but recommended)
+- ``replyTo``: {id, author, text, seq?}
+- ``attachments``: [{id, kind, url, name, mime, size}]
+- ``reactions``: {emoji: [guestId, …]}
+- ``mentions``: [name, …]
+- ``editedAt`` / ``recalled`` / ``pinned``
+"""
+from __future__ import annotations
+
+IM_PROTOCOL = "nomadro.im.v1"
+IM_FEATURES = (
+ "seq",
+ "clientId",
+ "since",
+ "before",
+ "note.recv",
+ "note.read",
+ "note.kp",
+ "centrifugo",
+ "replyTo",
+ "attachments",
+ "upload",
+ "recall",
+ "react",
+ "edit",
+ "pin",
+ "search",
+ "mentions",
+ "report",
+ "presence",
+)
diff --git a/apps/api/services/social_svc/geo_cities.py b/apps/api/services/social_svc/geo_cities.py
new file mode 100644
index 0000000..cfc9fa8
--- /dev/null
+++ b/apps/api/services/social_svc/geo_cities.py
@@ -0,0 +1,229 @@
+"""Seed cities with approximate lat/lng for map aggregation (no personal GPS)."""
+from __future__ import annotations
+
+from typing import Any
+
+# Offline seed mirrored by src/modules/social/lib/cities.ts
+SEED_CITIES: list[dict[str, Any]] = [
+ {
+ "id": "dali",
+ "name": "大理",
+ "country": "中国",
+ "emoji": "🏔️",
+ "vibe": "苍山洱海 · 慢生活",
+ "members": 520,
+ "meetupCount": 12,
+ "costHint": "¥3,000/月起",
+ "wifiMbps": 50,
+ "tags": ["热门", "便宜", "山城"],
+ "hot": True,
+ "lat": 25.6065,
+ "lng": 100.2679,
+ },
+ {
+ "id": "chengdu",
+ "name": "成都",
+ "country": "中国",
+ "emoji": "🌶️",
+ "vibe": "天府之国 · 美食慢节奏",
+ "members": 680,
+ "meetupCount": 18,
+ "costHint": "¥4,500/月起",
+ "wifiMbps": 80,
+ "tags": ["热门", "美食", "宜居"],
+ "hot": True,
+ "lat": 30.5728,
+ "lng": 104.0668,
+ },
+ {
+ "id": "hangzhou",
+ "name": "杭州",
+ "country": "中国",
+ "emoji": "🏞️",
+ "vibe": "西湖 · 互联网重镇",
+ "members": 560,
+ "meetupCount": 14,
+ "costHint": "¥6,000/月起",
+ "wifiMbps": 100,
+ "tags": ["热门", "高速网络"],
+ "hot": True,
+ "lat": 30.2741,
+ "lng": 120.1551,
+ },
+ {
+ "id": "kunming",
+ "name": "昆明",
+ "country": "中国",
+ "emoji": "🌸",
+ "vibe": "四季如春 · 通往东南亚",
+ "members": 380,
+ "meetupCount": 8,
+ "costHint": "¥3,500/月起",
+ "wifiMbps": 55,
+ "tags": ["温暖", "便宜"],
+ "hot": False,
+ "lat": 25.0389,
+ "lng": 102.7183,
+ },
+ {
+ "id": "shenzhen",
+ "name": "深圳",
+ "country": "中国",
+ "emoji": "🚀",
+ "vibe": "科技创新 · 创业友好",
+ "members": 850,
+ "meetupCount": 22,
+ "costHint": "¥8,000/月起",
+ "wifiMbps": 120,
+ "tags": ["热门", "高速网络", "一线城市"],
+ "hot": True,
+ "lat": 22.5431,
+ "lng": 114.0579,
+ },
+ {
+ "id": "xiamen",
+ "name": "厦门",
+ "country": "中国",
+ "emoji": "🏝️",
+ "vibe": "海滨花园 · 鼓浪屿",
+ "members": 320,
+ "meetupCount": 7,
+ "costHint": "¥5,500/月起",
+ "wifiMbps": 70,
+ "tags": ["海滨", "温暖"],
+ "hot": False,
+ "lat": 24.4798,
+ "lng": 118.0894,
+ },
+ {
+ "id": "shanghai",
+ "name": "上海",
+ "country": "中国",
+ "emoji": "🌆",
+ "vibe": "国际大都市 · 文化交汇",
+ "members": 1200,
+ "meetupCount": 28,
+ "costHint": "¥10,000/月起",
+ "wifiMbps": 110,
+ "tags": ["一线城市", "热门"],
+ "hot": True,
+ "lat": 31.2304,
+ "lng": 121.4737,
+ },
+ {
+ "id": "lijiang",
+ "name": "丽江",
+ "country": "中国",
+ "emoji": "🏯",
+ "vibe": "玉龙雪山 · 古城慢旅",
+ "members": 280,
+ "meetupCount": 5,
+ "costHint": "¥3,200/月起",
+ "wifiMbps": 45,
+ "tags": ["便宜", "山城"],
+ "hot": False,
+ "lat": 26.8721,
+ "lng": 100.2299,
+ },
+ {
+ "id": "chiangmai",
+ "name": "清迈",
+ "country": "泰国",
+ "emoji": "🌿",
+ "vibe": "Nimman · 游民大本营",
+ "members": 940,
+ "meetupCount": 36,
+ "costHint": "฿18,000/月起",
+ "wifiMbps": 90,
+ "tags": ["热门", "友好社区", "高速网络"],
+ "hot": True,
+ "lat": 18.7883,
+ "lng": 98.9853,
+ },
+ {
+ "id": "bali",
+ "name": "巴厘岛",
+ "country": "印尼",
+ "emoji": "🌴",
+ "vibe": "Canggu · 冲浪与 cowork",
+ "members": 720,
+ "meetupCount": 24,
+ "costHint": "Rp8jt/月起",
+ "wifiMbps": 60,
+ "tags": ["海滨", "温暖", "热门"],
+ "hot": True,
+ "lat": -8.6478,
+ "lng": 115.1385,
+ },
+ {
+ "id": "lisbon",
+ "name": "里斯本",
+ "country": "葡萄牙",
+ "emoji": "🌊",
+ "vibe": "阳光海岸 · 欧洲时区",
+ "members": 610,
+ "meetupCount": 16,
+ "costHint": "€1,200/月起",
+ "wifiMbps": 100,
+ "tags": ["海滨", "友好社区"],
+ "hot": False,
+ "lat": 38.7223,
+ "lng": -9.1393,
+ },
+ {
+ "id": "penang",
+ "name": "槟城",
+ "country": "马来西亚",
+ "emoji": "🍜",
+ "vibe": "美食 · 海风开放工位",
+ "members": 260,
+ "meetupCount": 6,
+ "costHint": "RM2,800/月起",
+ "wifiMbps": 100,
+ "tags": ["美食", "便宜"],
+ "hot": False,
+ "lat": 5.4141,
+ "lng": 100.3288,
+ },
+]
+
+_BY_ID = {c["id"]: c for c in SEED_CITIES}
+_BY_NAME = {c["name"]: c for c in SEED_CITIES}
+
+
+def list_seed_cities() -> list[dict[str, Any]]:
+ return [dict(c) for c in SEED_CITIES]
+
+
+def get_seed_city(city_id: str) -> dict[str, Any] | None:
+ c = _BY_ID.get((city_id or "").strip())
+ return dict(c) if c else None
+
+
+def resolve_city_id(city: str, city_id: str | None = None) -> str | None:
+ if city_id and city_id in _BY_ID:
+ return city_id
+ name = (city or "").split("·")[0].strip()
+ hit = _BY_NAME.get(name)
+ return hit["id"] if hit else None
+
+
+def city_public(c: dict[str, Any], *, extras: dict[str, Any] | None = None) -> dict[str, Any]:
+ out = {
+ "id": c["id"],
+ "name": c["name"],
+ "country": c["country"],
+ "emoji": c.get("emoji", ""),
+ "vibe": c.get("vibe", ""),
+ "lat": c["lat"],
+ "lng": c["lng"],
+ "memberCount": int(c.get("members") or 0),
+ "meetupCount": int(c.get("meetupCount") or 0),
+ "costHint": c.get("costHint", ""),
+ "wifiMbps": c.get("wifiMbps"),
+ "tags": list(c.get("tags") or []),
+ "hot": bool(c.get("hot")),
+ }
+ if extras:
+ out.update(extras)
+ return out
diff --git a/apps/api/services/social_svc/geo_h3.py b/apps/api/services/social_svc/geo_h3.py
new file mode 100644
index 0000000..35e0c9a
--- /dev/null
+++ b/apps/api/services/social_svc/geo_h3.py
@@ -0,0 +1,25 @@
+"""H3 cell helpers — soft-dep on `h3` package; rounded fallback otherwise."""
+from __future__ import annotations
+
+from .config import H3_CITY_RES, H3_NEAR_RES
+
+try:
+ import h3 # type: ignore
+
+ def latlng_to_cell(lat: float, lng: float, res: int | None = None) -> str:
+ r = H3_CITY_RES if res is None else res
+ return str(h3.latlng_to_cell(float(lat), float(lng), int(r)))
+
+ def near_cell(lat: float, lng: float) -> str:
+ return latlng_to_cell(lat, lng, H3_NEAR_RES)
+
+except Exception: # pragma: no cover
+
+ def latlng_to_cell(lat: float, lng: float, res: int | None = None) -> str:
+ r = H3_CITY_RES if res is None else res
+ # Coarse grid fallback (~res 4–5 order of magnitude)
+ step = 0.5 if r <= 4 else 0.2 if r <= 5 else 0.05
+ return f"g{r}:{round(float(lat) / step) * step:.4f}:{round(float(lng) / step) * step:.4f}"
+
+ def near_cell(lat: float, lng: float) -> str:
+ return latlng_to_cell(lat, lng, H3_NEAR_RES)
diff --git a/apps/api/services/social_svc/geo_pb.py b/apps/api/services/social_svc/geo_pb.py
new file mode 100644
index 0000000..d49a6c2
--- /dev/null
+++ b/apps/api/services/social_svc/geo_pb.py
@@ -0,0 +1,330 @@
+"""PocketBase `social_trips` — primary SoT when admin credentials work."""
+from __future__ import annotations
+
+import logging
+import time
+from typing import Any
+
+import httpx
+
+from .config import (
+ PB_ADMIN_EMAIL,
+ PB_ADMIN_PASSWORD,
+ PB_URL,
+ SOCIAL_GEO_USE_PB,
+ SOCIAL_TRIPS_COLLECTION,
+)
+
+log = logging.getLogger("social_svc.geo_pb")
+
+_token: str | None = None
+_token_at = 0.0
+_ensured = False
+
+
+def pb_enabled() -> bool:
+ return bool(
+ SOCIAL_GEO_USE_PB
+ and PB_URL
+ and PB_ADMIN_EMAIL
+ and PB_ADMIN_PASSWORD
+ )
+
+
+def _now() -> str:
+ return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
+
+
+def _auth_token() -> str | None:
+ global _token, _token_at
+ if not pb_enabled():
+ return None
+ if _token and (time.time() - _token_at) < 300:
+ return _token
+ base = PB_URL.rstrip("/")
+ try:
+ with httpx.Client(timeout=8.0) as client:
+ # PB 0.22+ superusers; fall back to legacy admins
+ for path in (
+ "/api/collections/_superusers/auth-with-password",
+ "/api/admins/auth-with-password",
+ ):
+ r = client.post(
+ f"{base}{path}",
+ json={"identity": PB_ADMIN_EMAIL, "password": PB_ADMIN_PASSWORD},
+ )
+ if r.status_code < 400:
+ data = r.json()
+ tok = data.get("token")
+ if tok:
+ _token = str(tok)
+ _token_at = time.time()
+ return _token
+ except Exception as exc: # pragma: no cover
+ log.warning("pb auth failed: %s", exc)
+ return None
+
+
+def _headers() -> dict[str, str] | None:
+ tok = _auth_token()
+ if not tok:
+ return None
+ return {"Authorization": tok}
+
+
+def ensure_collection() -> bool:
+ """Best-effort create `social_trips` collection if missing."""
+ global _ensured
+ if _ensured:
+ return True
+ headers = _headers()
+ if not headers:
+ return False
+ base = PB_URL.rstrip("/")
+ name = SOCIAL_TRIPS_COLLECTION
+ try:
+ with httpx.Client(timeout=12.0) as client:
+ chk = client.get(f"{base}/api/collections/{name}", headers=headers)
+ if chk.status_code == 200:
+ _ensured = True
+ return True
+ body = {
+ "name": name,
+ "type": "base",
+ "listRule": "",
+ "viewRule": "",
+ "createRule": "",
+ "updateRule": "",
+ "deleteRule": "",
+ "fields": [
+ {"name": "guest_id", "type": "text", "required": True},
+ {"name": "city_id", "type": "text", "required": False},
+ {"name": "city", "type": "text", "required": True},
+ {"name": "country", "type": "text", "required": False},
+ {"name": "lat", "type": "number", "required": False},
+ {"name": "lng", "type": "number", "required": False},
+ {"name": "h3_cell", "type": "text", "required": False},
+ {"name": "arrival_date", "type": "text", "required": False},
+ {"name": "departure_date", "type": "text", "required": False},
+ {
+ "name": "visibility",
+ "type": "select",
+ "required": True,
+ "maxSelect": 1,
+ "values": ["public", "friends", "private"],
+ },
+ {
+ "name": "status",
+ "type": "select",
+ "required": True,
+ "maxSelect": 1,
+ "values": ["here", "planned", "past"],
+ },
+ {"name": "updated_at", "type": "text", "required": True},
+ ],
+ "indexes": [
+ "CREATE INDEX idx_social_trips_guest ON social_trips (guest_id)",
+ "CREATE INDEX idx_social_trips_city ON social_trips (city_id)",
+ ],
+ }
+ # PocketBase 0.22+ uses `fields`; older used `schema`
+ created = client.post(
+ f"{base}/api/collections",
+ headers=headers,
+ json=body,
+ )
+ if created.status_code >= 400:
+ body_legacy = {
+ "name": name,
+ "type": "base",
+ "listRule": None,
+ "viewRule": None,
+ "createRule": None,
+ "updateRule": None,
+ "deleteRule": None,
+ "schema": [
+ {"name": "guest_id", "type": "text", "required": True},
+ {"name": "city_id", "type": "text", "required": False},
+ {"name": "city", "type": "text", "required": True},
+ {"name": "country", "type": "text", "required": False},
+ {"name": "lat", "type": "number", "required": False},
+ {"name": "lng", "type": "number", "required": False},
+ {"name": "h3_cell", "type": "text", "required": False},
+ {"name": "arrival_date", "type": "text", "required": False},
+ {"name": "departure_date", "type": "text", "required": False},
+ {
+ "name": "visibility",
+ "type": "select",
+ "required": True,
+ "options": {"maxSelect": 1, "values": ["public", "friends", "private"]},
+ },
+ {
+ "name": "status",
+ "type": "select",
+ "required": True,
+ "options": {"maxSelect": 1, "values": ["here", "planned", "past"]},
+ },
+ {"name": "updated_at", "type": "text", "required": True},
+ ],
+ }
+ created = client.post(
+ f"{base}/api/collections",
+ headers=headers,
+ json=body_legacy,
+ )
+ if created.status_code < 400:
+ _ensured = True
+ log.info("created PocketBase collection %s", name)
+ return True
+ log.warning("pb create collection failed: %s %s", created.status_code, created.text[:200])
+ except Exception as exc: # pragma: no cover
+ log.warning("pb ensure_collection: %s", exc)
+ return False
+
+
+def _rec_to_trip(rec: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "id": rec.get("id") or "",
+ "guest_id": rec.get("guest_id") or "",
+ "city_id": rec.get("city_id") or "",
+ "city": rec.get("city") or "",
+ "country": rec.get("country") or "",
+ "lat": rec.get("lat"),
+ "lng": rec.get("lng"),
+ "h3_cell": rec.get("h3_cell") or "",
+ "arrival_date": rec.get("arrival_date") or "",
+ "departure_date": rec.get("departure_date") or "",
+ "visibility": rec.get("visibility") or "public",
+ "status": rec.get("status") or "planned",
+ "updated_at": rec.get("updated_at") or "",
+ }
+
+
+def list_trips(
+ *,
+ guest_id: str | None = None,
+ city_id: str | None = None,
+ visibility: str | None = "public",
+ status: str | None = None,
+ limit: int = 200,
+) -> list[dict[str, Any]] | None:
+ """Return trips from PB, or None if PB unavailable (caller falls back to SQLite)."""
+ headers = _headers()
+ if not headers:
+ return None
+ ensure_collection()
+ filters: list[str] = []
+ if guest_id:
+ filters.append(f'guest_id="{guest_id}"')
+ if city_id:
+ filters.append(f'city_id="{city_id}"')
+ if visibility:
+ filters.append(f'visibility="{visibility}"')
+ if status:
+ filters.append(f'status="{status}"')
+ params: dict[str, Any] = {
+ "page": 1,
+ "perPage": max(1, min(limit, 500)),
+ "sort": "-updated_at",
+ }
+ if filters:
+ params["filter"] = " && ".join(filters)
+ base = PB_URL.rstrip("/")
+ col = SOCIAL_TRIPS_COLLECTION
+ try:
+ with httpx.Client(timeout=10.0) as client:
+ r = client.get(
+ f"{base}/api/collections/{col}/records",
+ headers=headers,
+ params=params,
+ )
+ if r.status_code >= 400:
+ return None
+ items = r.json().get("items") or []
+ return [_rec_to_trip(x) for x in items if isinstance(x, dict)]
+ except Exception as exc: # pragma: no cover
+ log.warning("pb list_trips: %s", exc)
+ return None
+
+
+def upsert_trip(trip: dict[str, Any]) -> dict[str, Any] | None:
+ headers = _headers()
+ if not headers:
+ return None
+ ensure_collection()
+ base = PB_URL.rstrip("/")
+ col = SOCIAL_TRIPS_COLLECTION
+ payload = {
+ "guest_id": trip["guest_id"],
+ "city_id": trip.get("city_id") or "",
+ "city": trip["city"],
+ "country": trip.get("country") or "",
+ "lat": trip.get("lat"),
+ "lng": trip.get("lng"),
+ "h3_cell": trip.get("h3_cell") or "",
+ "arrival_date": trip.get("arrival_date") or "",
+ "departure_date": trip.get("departure_date") or "",
+ "visibility": trip.get("visibility") or "public",
+ "status": trip.get("status") or "planned",
+ "updated_at": trip.get("updated_at") or _now(),
+ }
+ tid = trip.get("id") or ""
+ try:
+ with httpx.Client(timeout=10.0) as client:
+ if tid:
+ 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",
+ headers=headers,
+ json=payload,
+ )
+ if r.status_code >= 400:
+ log.warning("pb upsert_trip failed: %s", r.text[:200])
+ return None
+ return _rec_to_trip(r.json())
+ except Exception as exc: # pragma: no cover
+ log.warning("pb upsert_trip: %s", exc)
+ return None
+
+
+def delete_trip(trip_id: str, guest_id: str) -> bool | None:
+ """True deleted, False not found/forbidden, None PB down."""
+ headers = _headers()
+ if not headers:
+ return None
+ ensure_collection()
+ base = PB_URL.rstrip("/")
+ col = SOCIAL_TRIPS_COLLECTION
+ try:
+ with httpx.Client(timeout=8.0) as client:
+ get = client.get(
+ f"{base}/api/collections/{col}/records/{trip_id}",
+ headers=headers,
+ )
+ if get.status_code == 404:
+ return False
+ if get.status_code >= 400:
+ return None
+ rec = get.json()
+ if (rec.get("guest_id") or "") != guest_id:
+ return False
+ d = client.delete(
+ f"{base}/api/collections/{col}/records/{trip_id}",
+ headers=headers,
+ )
+ return d.status_code < 400
+ except Exception as exc: # pragma: no cover
+ log.warning("pb delete_trip: %s", exc)
+ return None
diff --git a/apps/api/services/social_svc/geo_store.py b/apps/api/services/social_svc/geo_store.py
new file mode 100644
index 0000000..ccba3a3
--- /dev/null
+++ b/apps/api/services/social_svc/geo_store.py
@@ -0,0 +1,382 @@
+"""Trips store: SQLite always; PocketBase preferred SoT when reachable."""
+from __future__ import annotations
+
+import time
+import uuid
+from datetime import date
+from typing import Any
+
+from . import geo_pb
+from .geo_cities import (
+ city_public,
+ get_seed_city,
+ list_seed_cities,
+ resolve_city_id,
+)
+from .geo_h3 import latlng_to_cell
+from .store import db
+
+
+def _uid() -> str:
+ return f"trip_{uuid.uuid4().hex[:12]}"
+
+
+def _now() -> str:
+ return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
+
+
+def ensure_trips_schema() -> None:
+ with db() as conn:
+ conn.executescript(
+ """
+ CREATE TABLE IF NOT EXISTS trips (
+ id TEXT PRIMARY KEY,
+ guest_id TEXT NOT NULL,
+ city_id TEXT,
+ city TEXT NOT NULL,
+ country TEXT,
+ lat REAL,
+ lng REAL,
+ h3_cell TEXT,
+ arrival_date TEXT,
+ departure_date TEXT,
+ visibility TEXT NOT NULL DEFAULT 'public',
+ status TEXT NOT NULL DEFAULT 'planned',
+ updated_at TEXT NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS idx_trips_guest ON trips(guest_id);
+ CREATE INDEX IF NOT EXISTS idx_trips_city ON trips(city_id);
+ CREATE INDEX IF NOT EXISTS idx_trips_vis ON trips(visibility, status);
+ """
+ )
+
+
+def _row_trip(r: Any) -> dict[str, Any]:
+ return {
+ "id": r["id"],
+ "guest_id": r["guest_id"],
+ "city_id": r["city_id"] or "",
+ "city": r["city"],
+ "country": r["country"] or "",
+ "lat": r["lat"],
+ "lng": r["lng"],
+ "h3_cell": r["h3_cell"] or "",
+ "arrival_date": r["arrival_date"] or "",
+ "departure_date": r["departure_date"] or "",
+ "visibility": r["visibility"] or "public",
+ "status": r["status"] or "planned",
+ "updated_at": r["updated_at"],
+ }
+
+
+def list_trips_sqlite(
+ *,
+ guest_id: str | None = None,
+ city_id: str | None = None,
+ visibility: str | None = None,
+ status: str | None = None,
+ limit: int = 200,
+) -> list[dict[str, Any]]:
+ ensure_trips_schema()
+ clauses: list[str] = []
+ args: list[Any] = []
+ if guest_id:
+ clauses.append("guest_id = ?")
+ args.append(guest_id)
+ if city_id:
+ clauses.append("city_id = ?")
+ args.append(city_id)
+ if visibility:
+ clauses.append("visibility = ?")
+ args.append(visibility)
+ if status:
+ clauses.append("status = ?")
+ args.append(status)
+ where = (" WHERE " + " AND ".join(clauses)) if clauses else ""
+ sql = f"SELECT * FROM trips{where} ORDER BY updated_at DESC LIMIT ?"
+ args.append(max(1, min(limit, 500)))
+ with db() as conn:
+ rows = conn.execute(sql, args).fetchall()
+ return [_row_trip(r) for r in rows]
+
+
+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)
+
+
+def save_trip_sqlite(trip: dict[str, Any]) -> dict[str, Any]:
+ ensure_trips_schema()
+ with db() as conn:
+ conn.execute(
+ """
+ INSERT INTO trips (
+ id, guest_id, city_id, city, country, lat, lng, h3_cell,
+ arrival_date, departure_date, visibility, status, updated_at
+ ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
+ ON CONFLICT(id) DO UPDATE SET
+ city_id=excluded.city_id,
+ city=excluded.city,
+ country=excluded.country,
+ lat=excluded.lat,
+ lng=excluded.lng,
+ h3_cell=excluded.h3_cell,
+ arrival_date=excluded.arrival_date,
+ departure_date=excluded.departure_date,
+ visibility=excluded.visibility,
+ status=excluded.status,
+ updated_at=excluded.updated_at
+ """,
+ (
+ trip["id"],
+ trip["guest_id"],
+ trip.get("city_id") or "",
+ trip["city"],
+ trip.get("country") or "",
+ trip.get("lat"),
+ trip.get("lng"),
+ trip.get("h3_cell") or "",
+ trip.get("arrival_date") or "",
+ trip.get("departure_date") or "",
+ trip.get("visibility") or "public",
+ trip.get("status") or "planned",
+ trip.get("updated_at") or _now(),
+ ),
+ )
+ return trip
+
+
+def create_trip(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
+ city = (payload.get("city") or "").strip()
+ if not city:
+ raise ValueError("city required")
+ city_id = (payload.get("city_id") or "").strip() or resolve_city_id(city) or ""
+ seed = get_seed_city(city_id) if city_id else None
+ lat = payload.get("lat")
+ lng = payload.get("lng")
+ if lat is None and seed:
+ lat = seed["lat"]
+ if lng is None and seed:
+ lng = seed["lng"]
+ country = (payload.get("country") or "").strip() or (seed or {}).get("country") or ""
+ h3_cell = ""
+ if lat is not None and lng is not None:
+ h3_cell = latlng_to_cell(float(lat), float(lng))
+ trip = {
+ "id": _uid(),
+ "guest_id": guest_id,
+ "city_id": city_id,
+ "city": city,
+ "country": country,
+ "lat": float(lat) if lat is not None else None,
+ "lng": float(lng) if lng is not None else None,
+ "h3_cell": h3_cell,
+ "arrival_date": (payload.get("arrival_date") or "").strip()[:10],
+ "departure_date": (payload.get("departure_date") or "").strip()[:10],
+ "visibility": (payload.get("visibility") or "public").strip() or "public",
+ "status": (payload.get("status") or "planned").strip() or "planned",
+ "updated_at": _now(),
+ }
+ if trip["visibility"] not in {"public", "friends", "private"}:
+ trip["visibility"] = "public"
+ 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
+
+
+def update_trip(guest_id: str, trip_id: str, payload: dict[str, Any]) -> dict[str, Any] | None:
+ existing = None
+ for t in list_trips(guest_id=guest_id, visibility=None, limit=500):
+ 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()
+ city_id = (payload.get("city_id") if "city_id" in payload else existing.get("city_id")) or ""
+ city_id = str(city_id).strip() or resolve_city_id(city) or ""
+ seed = get_seed_city(city_id) if city_id else None
+ lat = payload.get("lat", existing.get("lat"))
+ lng = payload.get("lng", existing.get("lng"))
+ if lat is None and seed:
+ lat = seed["lat"]
+ if lng is None and seed:
+ lng = seed["lng"]
+ trip = {
+ **existing,
+ "city": city,
+ "city_id": city_id,
+ "country": (payload.get("country") if "country" in payload else existing.get("country"))
+ or (seed or {}).get("country")
+ or "",
+ "lat": float(lat) if lat is not None else None,
+ "lng": float(lng) if lng is not None else None,
+ "arrival_date": (
+ payload.get("arrival_date")
+ if "arrival_date" in payload
+ else existing.get("arrival_date")
+ )
+ or "",
+ "departure_date": (
+ payload.get("departure_date")
+ if "departure_date" in payload
+ else existing.get("departure_date")
+ )
+ or "",
+ "visibility": (
+ payload.get("visibility")
+ if "visibility" in payload
+ else existing.get("visibility")
+ )
+ or "public",
+ "status": (payload.get("status") if "status" in payload else existing.get("status"))
+ or "planned",
+ "updated_at": _now(),
+ }
+ 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
+
+
+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
+
+
+def map_cities() -> list[dict[str, Any]]:
+ """City aggregation for map — seed counts + live trip overlays (no personal coords)."""
+ trips = list_trips(visibility="public", limit=500)
+ live_by_city: dict[str, dict[str, int]] = {}
+ for t in trips:
+ cid = t.get("city_id") or resolve_city_id(t.get("city") or "") or ""
+ if not cid:
+ continue
+ bucket = live_by_city.setdefault(cid, {"here": 0, "planned": 0})
+ st = t.get("status") or "planned"
+ if st == "here":
+ bucket["here"] += 1
+ elif st == "planned":
+ bucket["planned"] += 1
+ out = []
+ for c in list_seed_cities():
+ live = live_by_city.get(c["id"], {})
+ extras = {
+ "arrivingSoon": int(live.get("planned") or 0),
+ "currentlyHere": int(live.get("here") or 0),
+ "h3": latlng_to_cell(c["lat"], c["lng"]),
+ # bump seed memberCount with live presence signal (display only)
+ "memberCount": int(c.get("members") or 0) + int(live.get("here") or 0),
+ }
+ out.append(city_public(c, extras=extras))
+ return out
+
+
+def city_detail(city_id: str) -> dict[str, Any] | None:
+ seed = get_seed_city(city_id)
+ if not seed:
+ return None
+ trips = list_trips(city_id=city_id, visibility="public", limit=200)
+ here = [t for t in trips if t.get("status") == "here"]
+ planned = [t for t in trips if t.get("status") == "planned"]
+ base = city_public(
+ seed,
+ extras={
+ "currentlyHere": len(here),
+ "arrivingSoon": len(planned),
+ "h3": latlng_to_cell(seed["lat"], seed["lng"]),
+ "memberCount": int(seed.get("members") or 0) + len(here),
+ },
+ )
+ base["recentArrivals"] = [
+ {
+ "guestId": t["guest_id"][:8] + "…",
+ "city": t["city"],
+ "status": t["status"],
+ "arrival_date": t.get("arrival_date") or "",
+ "departure_date": t.get("departure_date") or "",
+ }
+ for t in (here + planned)[:12]
+ ]
+ return base
+
+
+def _parse_ymd(s: str) -> date | None:
+ s = (s or "").strip()[:10]
+ if len(s) < 10:
+ return None
+ try:
+ return date.fromisoformat(s)
+ except ValueError:
+ return None
+
+
+def travel_overlaps(guest_id: str) -> list[dict[str, Any]]:
+ mine = list_trips(guest_id=guest_id, visibility=None, limit=100)
+ mine = [t for t in mine if t.get("visibility") != "private"]
+ others = [
+ t
+ for t in list_trips(visibility="public", limit=500)
+ if t.get("guest_id") != guest_id
+ ]
+ out: list[dict[str, Any]] = []
+ for a in mine:
+ a0, a1 = _parse_ymd(a.get("arrival_date") or ""), _parse_ymd(a.get("departure_date") or "")
+ if not a0 or not a1 or a1 < a0:
+ continue
+ for b in others:
+ if (a.get("city_id") and b.get("city_id") and a["city_id"] != b["city_id"]) or (
+ not a.get("city_id")
+ and (a.get("city") or "").split("·")[0].strip()
+ != (b.get("city") or "").split("·")[0].strip()
+ ):
+ continue
+ b0, b1 = _parse_ymd(b.get("arrival_date") or ""), _parse_ymd(
+ b.get("departure_date") or ""
+ )
+ if not b0 or not b1 or b1 < b0:
+ continue
+ start = max(a0, b0)
+ end = min(a1, b1)
+ if end < start:
+ continue
+ days = (end - start).days + 1
+ out.append(
+ {
+ "city": a.get("city") or b.get("city"),
+ "cityId": a.get("city_id") or b.get("city_id") or "",
+ "overlapDays": days,
+ "from": start.isoformat(),
+ "to": end.isoformat(),
+ "otherGuest": (b.get("guest_id") or "")[:8] + "…",
+ "myTripId": a["id"],
+ "theirStatus": b.get("status") or "",
+ }
+ )
+ out.sort(key=lambda x: (-int(x["overlapDays"]), x["from"]))
+ return out[:50]
diff --git a/apps/api/services/social_svc/im.py b/apps/api/services/social_svc/im.py
new file mode 100644
index 0000000..1c67c17
--- /dev/null
+++ b/apps/api/services/social_svc/im.py
@@ -0,0 +1,45 @@
+"""Tinode-inspired IM primitives on Nomadro social stack.
+
+Borrowed ideas (not code) from tinode/chat:
+- per-topic monotonic ``seq`` for sync / unread / pagination
+- clientId idempotent publish
+- note.recv / note.read watermarks
+- lightweight rate limit before fan-out
+
+Transport stays Centrifugo; persistence stays SQLite (isolated social.db).
+"""
+from __future__ import annotations
+
+import time
+from collections import defaultdict, deque
+from threading import Lock
+from typing import Any
+
+# guest -> timestamps of recent posts (process-local; fine for single social worker)
+_RATE: dict[str, deque[float]] = defaultdict(deque)
+_RATE_LOCK = Lock()
+_RATE_WINDOW_SEC = 60.0
+_RATE_MAX = 30 # msgs / window / guest
+
+
+def check_rate(guest_id: str) -> None:
+ """Raise ValueError if guest exceeds send rate."""
+ now = time.time()
+ key = (guest_id or "").strip() or "_"
+ with _RATE_LOCK:
+ q = _RATE[key]
+ while q and now - q[0] > _RATE_WINDOW_SEC:
+ q.popleft()
+ if len(q) >= _RATE_MAX:
+ raise ValueError("发送过快,请稍后再试")
+ q.append(now)
+
+
+def note_event(what: str, seq: int, guest_id: str) -> dict[str, Any]:
+ return {
+ "type": "chat.note",
+ "what": what, # recv | read | kp
+ "seq": int(seq),
+ "guestId": guest_id,
+ "at": time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()),
+ }
diff --git a/apps/api/services/social_svc/photon.py b/apps/api/services/social_svc/photon.py
new file mode 100644
index 0000000..b4dd9b6
--- /dev/null
+++ b/apps/api/services/social_svc/photon.py
@@ -0,0 +1,73 @@
+"""Server-side Photon geocoder proxy (no browser CORS / key leakage)."""
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+import httpx
+
+from .config import PHOTON_BASE_URL, PHOTON_TIMEOUT_SEC
+
+log = logging.getLogger("social_svc.photon")
+
+
+def _norm_feature(f: dict[str, Any]) -> dict[str, Any] | None:
+ props = f.get("properties") or {}
+ geom = f.get("geometry") or {}
+ coords = geom.get("coordinates") or []
+ if len(coords) < 2:
+ return None
+ lng, lat = float(coords[0]), float(coords[1])
+ name = (
+ props.get("name")
+ or props.get("city")
+ or props.get("town")
+ or props.get("village")
+ or props.get("county")
+ or ""
+ ).strip()
+ if not name:
+ return None
+ country = (props.get("country") or "").strip()
+ state = (props.get("state") or props.get("county") or "").strip()
+ osm_id = props.get("osm_id")
+ osm_type = props.get("osm_type") or ""
+ cid = f"photon:{osm_type}{osm_id}" if osm_id is not None else f"photon:{lat:.4f},{lng:.4f}"
+ return {
+ "id": cid,
+ "name": name,
+ "country": country,
+ "state": state,
+ "lat": lat,
+ "lng": lng,
+ "osmKey": props.get("osm_key"),
+ "osmValue": props.get("osm_value"),
+ "source": "photon",
+ }
+
+
+async def search_cities(q: str, *, limit: int = 8, lang: str = "zh") -> list[dict[str, Any]]:
+ query = (q or "").strip()
+ if len(query) < 2:
+ return []
+ base = (PHOTON_BASE_URL or "").rstrip("/")
+ if not base:
+ return []
+ url = f"{base}/api/"
+ params = {"q": query, "limit": max(1, min(limit, 20)), "lang": lang or "zh"}
+ try:
+ async with httpx.AsyncClient(timeout=PHOTON_TIMEOUT_SEC) as client:
+ res = await client.get(url, params=params)
+ res.raise_for_status()
+ data = res.json()
+ except Exception as exc: # pragma: no cover
+ log.warning("photon search failed: %s", exc)
+ return []
+ out: list[dict[str, Any]] = []
+ for f in data.get("features") or []:
+ if not isinstance(f, dict):
+ continue
+ n = _norm_feature(f)
+ if n:
+ out.append(n)
+ return out
diff --git a/apps/api/services/social_svc/realtime.py b/apps/api/services/social_svc/realtime.py
index af54d6c..8b7da43 100644
--- a/apps/api/services/social_svc/realtime.py
+++ b/apps/api/services/social_svc/realtime.py
@@ -77,5 +77,18 @@ async def publish_chat_message(channel_id: str, message: dict[str, Any]) -> bool
return await _publish(channel_id, {"type": "chat.message", "message": message})
+async def publish_chat_note(
+ channel_id: str,
+ *,
+ what: str,
+ seq: int,
+ guest_id: str,
+) -> bool:
+ """Tinode-like {note}: recv / read / kp (typing)."""
+ from social_svc.im import note_event
+
+ return await _publish(channel_id, note_event(what, seq, guest_id))
+
+
async def publish_live_event(channel_id: str, event: str, payload: dict[str, Any]) -> bool:
return await _publish(channel_id, {"type": f"live.{event}", **payload})
diff --git a/apps/api/services/social_svc/routers/__init__.py b/apps/api/services/social_svc/routers/__init__.py
index 502d465..1ee3a07 100644
--- a/apps/api/services/social_svc/routers/__init__.py
+++ b/apps/api/services/social_svc/routers/__init__.py
@@ -1,3 +1,10 @@
-from .api import router
+from fastapi import APIRouter
+
+from .api import router as _api
+from .geo import router as _geo
+
+router = APIRouter()
+router.include_router(_api)
+router.include_router(_geo)
__all__ = ["router"]
diff --git a/apps/api/services/social_svc/routers/api.py b/apps/api/services/social_svc/routers/api.py
index 9c499d3..cb8e0d8 100644
--- a/apps/api/services/social_svc/routers/api.py
+++ b/apps/api/services/social_svc/routers/api.py
@@ -1,15 +1,20 @@
"""游民社区 API — 前缀 /api/social/v1,与 /api/v1 社群隔离。"""
from __future__ import annotations
-from fastapi import APIRouter, Header, HTTPException, Query
+from pathlib import Path
+from typing import Any
+
+from fastapi import APIRouter, File, Form, Header, HTTPException, Query, UploadFile
+from fastapi.responses import FileResponse
from pydantic import BaseModel, Field
from starlette.concurrency import run_in_threadpool
from social_svc import live, store
-from social_svc.config import SOCIAL_ENABLED
+from social_svc.config import SOCIAL_ENABLED, SOCIAL_UPLOAD_MAX_BYTES
from social_svc.realtime import (
issue_connection_token,
publish_chat_message,
+ publish_chat_note,
publish_live_event,
)
@@ -26,10 +31,55 @@ def _guest(
return gid
+class ReplyToIn(BaseModel):
+ id: str = Field(min_length=1, max_length=80)
+ author: str = Field(default="游民", max_length=48)
+ text: str = Field(default="", max_length=240)
+ seq: int | None = Field(default=None, ge=0)
+
+
+class AttachmentIn(BaseModel):
+ id: str = Field(default="", max_length=80)
+ kind: str = Field(default="file", max_length=16)
+ url: str = Field(min_length=1, max_length=800)
+ name: str = Field(default="file", max_length=160)
+ mime: str = Field(default="application/octet-stream", max_length=120)
+ size: int = Field(default=0, ge=0, le=50 * 1024 * 1024)
+
+
class MessageIn(BaseModel):
author: str = Field(default="游民", max_length=48)
- text: str = Field(min_length=1, max_length=2000)
+ text: str = Field(default="", max_length=2000)
clientId: str | None = Field(default=None, min_length=1, max_length=80)
+ replyTo: ReplyToIn | None = None
+ attachments: list[AttachmentIn] = Field(default_factory=list)
+ mentions: list[str] = Field(default_factory=list)
+
+
+class EditMessageIn(BaseModel):
+ text: str = Field(min_length=1, max_length=2000)
+
+
+class ReactIn(BaseModel):
+ emoji: str = Field(min_length=1, max_length=16)
+
+
+class PinIn(BaseModel):
+ pinned: bool = True
+
+
+class ReportIn(BaseModel):
+ reason: str = Field(default="", max_length=240)
+
+
+class PresenceIn(BaseModel):
+ nick: str = Field(default="游民", max_length=48)
+
+
+class NoteIn(BaseModel):
+ """Tinode {note}: recv / read / kp (typing keepalive)."""
+ what: str = Field(min_length=2, max_length=8)
+ seq: int = Field(default=0, ge=0)
class ReviewIn(BaseModel):
@@ -47,6 +97,15 @@ class RosterIn(BaseModel):
linktree: str = Field(default="", max_length=240)
skills: str = Field(default="", max_length=200)
bio: str = Field(default="", max_length=2000)
+ avatar: str = Field(default="", max_length=500)
+ # extra join fields accepted but not all persisted as columns
+ gender: str = Field(default="", max_length=16)
+ relationship: str = Field(default="", max_length=32)
+ education: str = Field(default="", max_length=32)
+ graduation: str = Field(default="", max_length=32)
+ wechat: str = Field(default="", max_length=64)
+ intents: str = Field(default="", max_length=240)
+ updatedAt: str = Field(default="", max_length=40)
class FeedbackIn(BaseModel):
@@ -68,8 +127,12 @@ async def social_health():
return {"ok": False, "module": "social", "enabled": False}
h = store.health()
from social_svc.config import CENTRIFUGO_ENABLED
+ from social_svc.contract import IM_FEATURES, IM_PROTOCOL
h["centrifugo"] = bool(CENTRIFUGO_ENABLED)
+ h["imProtocol"] = IM_PROTOCOL
+ h["imFeatures"] = list(IM_FEATURES)
+ h["uiAgnostic"] = True
return h
@@ -83,10 +146,42 @@ async def realtime_token(
return issue_connection_token(peer, channel_id)
+@router.get("/channels/{channel_id}/desc")
+def get_channel_desc(
+ channel_id: str,
+ x_social_guest_id: str | None = Header(default=None),
+ guest: str | None = Query(default=None),
+):
+ """Tinode-like topic desc: seq + recv/read/unread for current peer."""
+ peer = None
+ try:
+ peer = _guest(x_social_guest_id, guest)
+ except HTTPException:
+ peer = None
+ return store.channel_desc(channel_id, peer)
+
+
@router.get("/channels/{channel_id}/messages")
-def get_messages(channel_id: str, limit: int = 100):
+def get_messages(
+ channel_id: str,
+ limit: int = 100,
+ since: int | None = Query(default=None, ge=0),
+ before: int | None = Query(default=None, ge=0),
+ q: str | None = Query(default=None, max_length=80),
+):
store.init_db()
- return {"items": store.list_messages(channel_id, limit)}
+ items = store.list_messages(
+ channel_id, limit, since=since, before=before, q=q
+ )
+ desc = store.channel_desc(channel_id)
+ return {"items": items, "seq": desc["seq"]}
+
+
+async def _publish_msg(channel_id: str, saved: dict[str, Any]) -> None:
+ try:
+ await publish_chat_message(channel_id, saved)
+ except Exception:
+ pass
@router.post("/channels/{channel_id}/messages")
@@ -97,18 +192,311 @@ async def post_message(
guest: str | None = Query(default=None),
):
peer = _guest(x_social_guest_id, guest)
- if not body.text.strip():
- raise HTTPException(status_code=400, detail="empty text")
+ if not body.text.strip() and not body.attachments:
+ raise HTTPException(status_code=400, detail="empty message")
+
def persist():
store.init_db()
- return store.add_message(channel_id, body.author, body.text, peer, body.clientId)
+ return store.add_message(
+ channel_id,
+ body.author,
+ body.text,
+ peer,
+ body.clientId,
+ reply_to=body.replyTo.model_dump() if body.replyTo else None,
+ attachments=[a.model_dump() for a in body.attachments],
+ mentions=body.mentions,
+ )
+
try:
saved = await run_in_threadpool(persist)
except ValueError as exc:
- raise HTTPException(status_code=409, detail=str(exc)) from exc
- # 实时推送失败不影响落库成功
+ detail = str(exc)
+ if "过快" in detail:
+ code = 429
+ elif "empty" in detail:
+ code = 400
+ else:
+ code = 409
+ raise HTTPException(status_code=code, detail=detail) from exc
+ await _publish_msg(channel_id, saved)
+ return saved
+
+
+@router.patch("/channels/{channel_id}/messages/{msg_id}")
+async def patch_message(
+ channel_id: str,
+ msg_id: str,
+ body: EditMessageIn,
+ x_social_guest_id: str | None = Header(default=None),
+ guest: str | None = Query(default=None),
+):
+ peer = _guest(x_social_guest_id, guest)
+
+ def persist():
+ store.init_db()
+ return store.edit_message(channel_id, msg_id, peer, body.text)
+
try:
- await publish_chat_message(channel_id, saved)
+ saved = await run_in_threadpool(persist)
+ except ValueError as exc:
+ detail = str(exc)
+ code = 403 if "not your" in detail else 404 if "not found" in detail else 400
+ raise HTTPException(status_code=code, detail=detail) from exc
+ await _publish_msg(channel_id, saved)
+ return saved
+
+
+@router.post("/channels/{channel_id}/messages/{msg_id}/recall")
+async def recall_message(
+ channel_id: str,
+ msg_id: str,
+ x_social_guest_id: str | None = Header(default=None),
+ guest: str | None = Query(default=None),
+):
+ peer = _guest(x_social_guest_id, guest)
+
+ def persist():
+ store.init_db()
+ return store.recall_message(channel_id, msg_id, peer)
+
+ try:
+ saved = await run_in_threadpool(persist)
+ except ValueError as exc:
+ detail = str(exc)
+ code = 403 if "not your" in detail else 404 if "not found" in detail else 400
+ raise HTTPException(status_code=code, detail=detail) from exc
+ await _publish_msg(channel_id, saved)
+ return saved
+
+
+@router.post("/channels/{channel_id}/messages/{msg_id}/react")
+async def react_message(
+ channel_id: str,
+ msg_id: str,
+ body: ReactIn,
+ x_social_guest_id: str | None = Header(default=None),
+ guest: str | None = Query(default=None),
+):
+ peer = _guest(x_social_guest_id, guest)
+
+ def persist():
+ store.init_db()
+ return store.react_message(channel_id, msg_id, peer, body.emoji)
+
+ try:
+ saved = await run_in_threadpool(persist)
+ except ValueError as exc:
+ detail = str(exc)
+ code = 404 if "not found" in detail else 400
+ raise HTTPException(status_code=code, detail=detail) from exc
+ await _publish_msg(channel_id, saved)
+ return saved
+
+
+@router.post("/channels/{channel_id}/messages/{msg_id}/pin")
+async def pin_message(
+ channel_id: str,
+ msg_id: str,
+ body: PinIn,
+ x_social_guest_id: str | None = Header(default=None),
+ guest: str | None = Query(default=None),
+):
+ peer = _guest(x_social_guest_id, guest)
+
+ def persist():
+ store.init_db()
+ return store.pin_message(channel_id, msg_id, peer, body.pinned)
+
+ try:
+ saved = await run_in_threadpool(persist)
+ except ValueError as exc:
+ detail = str(exc)
+ code = 404 if "not found" in detail else 400
+ raise HTTPException(status_code=code, detail=detail) from exc
+ await _publish_msg(channel_id, saved)
+ return saved
+
+
+@router.post("/channels/{channel_id}/messages/{msg_id}/report")
+async def report_message(
+ channel_id: str,
+ msg_id: str,
+ body: ReportIn,
+ x_social_guest_id: str | None = Header(default=None),
+ guest: str | None = Query(default=None),
+):
+ peer = _guest(x_social_guest_id, guest)
+
+ def persist():
+ store.init_db()
+ return store.report_message(channel_id, msg_id, peer, body.reason)
+
+ try:
+ return await run_in_threadpool(persist)
+ except ValueError as exc:
+ detail = str(exc)
+ code = 404 if "not found" in detail else 400
+ raise HTTPException(status_code=code, detail=detail) from exc
+
+
+@router.post("/channels/{channel_id}/presence")
+async def post_presence(
+ channel_id: str,
+ body: PresenceIn,
+ x_social_guest_id: str | None = Header(default=None),
+ guest: str | None = Query(default=None),
+):
+ peer = _guest(x_social_guest_id, guest)
+ return store.touch_presence(channel_id, peer, body.nick)
+
+
+@router.post("/upload")
+async def upload_media(
+ file: UploadFile = File(...),
+ purpose: str = Form(default="avatar"),
+ x_social_guest_id: str | None = Header(default=None),
+ guest: str | None = Query(default=None),
+):
+ """Guest-friendly image upload → SeaweedFS S3 (fallback local)."""
+ peer = _guest(x_social_guest_id, guest)
+ ctype = (file.content_type or "").lower()
+ if not ctype.startswith("image/"):
+ raise HTTPException(status_code=400, detail="仅支持图片")
+ raw = await file.read()
+ if not raw:
+ raise HTTPException(status_code=400, detail="空文件")
+ max_avatar = min(SOCIAL_UPLOAD_MAX_BYTES, 8 * 1024 * 1024)
+
+ def persist():
+ from social_svc.s3_upload import upload_bytes
+
+ return upload_bytes(
+ raw,
+ filename=file.filename or "avatar.jpg",
+ content_type=file.content_type or "image/jpeg",
+ purpose=(purpose or "avatar")[:40],
+ guest_id=peer,
+ max_size=max_avatar,
+ )
+
+ try:
+ result = await run_in_threadpool(persist)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ except Exception as exc:
+ raise HTTPException(status_code=503, detail=f"上传失败: {exc}") from exc
+
+ return {
+ "ok": True,
+ "success": True,
+ "url": result.url,
+ "object_key": result.object_key,
+ "size": result.size,
+ "content_type": result.content_type,
+ "storage": result.storage,
+ }
+
+
+@router.get("/files/avatar/{name}")
+def get_local_avatar(name: str):
+ """Serve locally-fallback avatar files when S3 is unavailable."""
+ from social_svc.config import SOCIAL_UPLOAD_DIR
+
+ safe = Path(name).name
+ if safe != name or ".." in name:
+ raise HTTPException(status_code=400, detail="非法文件名")
+ path = SOCIAL_UPLOAD_DIR / "avatars" / safe
+ if not path.is_file():
+ raise HTTPException(status_code=404, detail="not found")
+ return FileResponse(path)
+
+
+@router.post("/channels/{channel_id}/upload")
+async def upload_file(
+ channel_id: str,
+ file: UploadFile = File(...),
+ kind: str = Form(default="file"),
+ x_social_guest_id: str | None = Header(default=None),
+ guest: str | None = Query(default=None),
+):
+ peer = _guest(x_social_guest_id, guest)
+ raw = await file.read()
+ if not raw:
+ raise HTTPException(status_code=400, detail="empty file")
+ if len(raw) > SOCIAL_UPLOAD_MAX_BYTES:
+ raise HTTPException(status_code=413, detail="file too large")
+ mime = file.content_type or "application/octet-stream"
+ guessed = kind
+ if guessed == "file":
+ if mime.startswith("image/"):
+ guessed = "image"
+ elif mime.startswith("video/"):
+ guessed = "video"
+ elif mime.startswith("audio/"):
+ guessed = "audio"
+
+ def persist():
+ store.init_db()
+ return store.save_upload(
+ channel_id,
+ peer,
+ kind=guessed,
+ name=file.filename or "file",
+ mime=mime,
+ data=raw,
+ )
+
+ try:
+ return await run_in_threadpool(persist)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
+@router.get("/files/{file_id}")
+def get_file(file_id: str):
+ store.init_db()
+ meta = store.get_file(file_id)
+ if not meta:
+ raise HTTPException(status_code=404, detail="file not found")
+ path = Path(meta["path"])
+ if not path.is_file():
+ raise HTTPException(status_code=404, detail="file missing")
+ return FileResponse(
+ path,
+ media_type=meta["mime"],
+ filename=meta["name"],
+ )
+
+
+@router.post("/channels/{channel_id}/notes")
+async def post_note(
+ channel_id: str,
+ body: NoteIn,
+ x_social_guest_id: str | None = Header(default=None),
+ guest: str | None = Query(default=None),
+):
+ """Tinode {note}: recv/read persist; kp (typing) is fan-out only."""
+ peer = _guest(x_social_guest_id, guest)
+ what = body.what.strip().lower()
+ if what == "kp":
+ try:
+ await publish_chat_note(channel_id, what="kp", seq=0, guest_id=peer)
+ except Exception:
+ pass
+ return {"ok": True, "what": "kp"}
+ if what not in {"recv", "read"}:
+ raise HTTPException(status_code=400, detail="what must be recv|read|kp")
+ try:
+ saved = await run_in_threadpool(
+ lambda: store.set_note(channel_id, peer, what, body.seq)
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ try:
+ await publish_chat_note(
+ channel_id, what=what, seq=saved["seq"], guest_id=peer
+ )
except Exception:
pass
return saved
diff --git a/apps/api/services/social_svc/routers/geo.py b/apps/api/services/social_svc/routers/geo.py
new file mode 100644
index 0000000..a85483c
--- /dev/null
+++ b/apps/api/services/social_svc/routers/geo.py
@@ -0,0 +1,230 @@
+"""Geo discovery API — map cities, Photon search, trips, overlaps."""
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import APIRouter, Header, HTTPException, Query
+from pydantic import BaseModel, Field
+from starlette.concurrency import run_in_threadpool
+
+from social_svc import geo_store, photon
+from social_svc.config import SOCIAL_ENABLED
+from social_svc.geo_cities import list_seed_cities, city_public
+
+router = APIRouter(tags=["social-geo"])
+
+
+def _guest(
+ x_social_guest_id: str | None,
+ guest_q: str | None = None,
+) -> str:
+ gid = (x_social_guest_id or guest_q or "").strip()
+ if not gid or len(gid) > 80:
+ raise HTTPException(status_code=400, detail="missing X-Social-Guest-Id")
+ return gid
+
+
+class TripIn(BaseModel):
+ city: str = Field(min_length=1, max_length=80)
+ city_id: str = Field(default="", max_length=64)
+ country: str = Field(default="", max_length=64)
+ lat: float | None = None
+ lng: float | None = None
+ arrival_date: str = Field(default="", max_length=10)
+ departure_date: str = Field(default="", max_length=10)
+ visibility: str = Field(default="public", max_length=16)
+ status: str = Field(default="planned", max_length=16)
+
+
+class TripPatch(BaseModel):
+ city: str | None = Field(default=None, max_length=80)
+ city_id: str | None = Field(default=None, max_length=64)
+ country: str | None = Field(default=None, max_length=64)
+ lat: float | None = None
+ lng: float | None = None
+ arrival_date: str | None = Field(default=None, max_length=10)
+ departure_date: str | None = Field(default=None, max_length=10)
+ visibility: str | None = Field(default=None, max_length=16)
+ status: str | None = Field(default=None, max_length=16)
+
+
+@router.get("/map/cities")
+async def map_cities(
+ west: float | None = None,
+ south: float | None = None,
+ east: float | None = None,
+ north: float | None = None,
+):
+ if not SOCIAL_ENABLED:
+ raise HTTPException(status_code=503, detail="social disabled")
+ items = await run_in_threadpool(geo_store.map_cities)
+ if None not in (west, south, east, north):
+ items = [
+ c
+ for c in items
+ if west <= float(c["lng"]) <= east and south <= float(c["lat"]) <= north # type: ignore[operator]
+ ]
+ return {"items": items, "source": "seed+trips"}
+
+
+@router.get("/cities/search")
+async def cities_search(
+ q: str = Query(default="", max_length=80),
+ limit: int = Query(default=8, ge=1, le=20),
+ lang: str = Query(default="zh", max_length=8),
+):
+ if not SOCIAL_ENABLED:
+ raise HTTPException(status_code=503, detail="social disabled")
+ query = (q or "").strip().lower()
+ seed_hits = []
+ if query:
+ for c in list_seed_cities():
+ hay = f"{c['name']} {c['country']} {' '.join(c.get('tags') or [])}".lower()
+ if query in hay:
+ seed_hits.append(city_public(c, extras={"source": "seed"}))
+ photon_hits = await photon.search_cities(q, limit=limit, lang=lang)
+ # Prefer seed ids when names collide
+ seed_names = {c["name"] for c in seed_hits}
+ merged = list(seed_hits)
+ for p in photon_hits:
+ if p["name"] in seed_names:
+ continue
+ merged.append(p)
+ return {"items": merged[:limit], "q": q}
+
+
+@router.get("/cities/{city_id}")
+async def city_detail(city_id: str):
+ if not SOCIAL_ENABLED:
+ raise HTTPException(status_code=503, detail="social disabled")
+ item = await run_in_threadpool(geo_store.city_detail, city_id)
+ if not item:
+ raise HTTPException(status_code=404, detail="city not found")
+ return {"item": item}
+
+
+@router.get("/people")
+async def people_geo(
+ city: str = Query(default="", max_length=80),
+ cityId: str = Query(default="", max_length=64),
+ status: str = Query(default="", max_length=16),
+ profession: str = Query(default="", max_length=80),
+ interest: str = Query(default="", max_length=80),
+ language: str = Query(default="", max_length=40),
+ currentlyHere: bool = Query(default=False),
+ arrivingSoon: bool = Query(default=False),
+ limit: int = Query(default=40, ge=1, le=100),
+):
+ """Public trip-backed presence filter (no lat/lng). Seed roster still lives client-side."""
+ if not SOCIAL_ENABLED:
+ raise HTTPException(status_code=503, detail="social disabled")
+
+ def _run() -> list[dict[str, Any]]:
+ vis = "public"
+ st = None
+ if currentlyHere:
+ st = "here"
+ elif arrivingSoon:
+ st = "planned"
+ elif status in {"here", "planned", "past"}:
+ st = status
+ trips = geo_store.list_trips(
+ city_id=cityId or None,
+ visibility=vis,
+ status=st,
+ limit=limit * 3,
+ )
+ out: list[dict[str, Any]] = []
+ for t in trips:
+ if city and city.lower() not in (t.get("city") or "").lower():
+ continue
+ # profession/interest/language reserved for roster join later
+ _ = (profession, interest, language)
+ out.append(
+ {
+ "guestId": (t.get("guest_id") or "")[:10],
+ "city": t.get("city"),
+ "cityId": t.get("city_id") or "",
+ "status": t.get("status"),
+ "arrival_date": t.get("arrival_date") or "",
+ "departure_date": t.get("departure_date") or "",
+ "h3Res": t.get("h3_cell") or "",
+ }
+ )
+ if len(out) >= limit:
+ break
+ return out
+
+ items = await run_in_threadpool(_run)
+ return {"items": items}
+
+
+@router.get("/travel-overlaps")
+async def travel_overlaps(
+ x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
+ guest_id: str | None = Query(default=None),
+):
+ if not SOCIAL_ENABLED:
+ raise HTTPException(status_code=503, detail="social disabled")
+ gid = _guest(x_social_guest_id, guest_id)
+ items = await run_in_threadpool(geo_store.travel_overlaps, gid)
+ return {"items": items}
+
+
+@router.get("/trips")
+async def list_my_trips(
+ x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
+ guest_id: str | None = Query(default=None),
+):
+ if not SOCIAL_ENABLED:
+ raise HTTPException(status_code=503, detail="social disabled")
+ gid = _guest(x_social_guest_id, guest_id)
+ items = await run_in_threadpool(
+ lambda: geo_store.list_trips(guest_id=gid, visibility=None, limit=100)
+ )
+ return {"items": items}
+
+
+@router.post("/trips")
+async def create_trip(
+ body: TripIn,
+ x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
+):
+ if not SOCIAL_ENABLED:
+ raise HTTPException(status_code=503, detail="social disabled")
+ gid = _guest(x_social_guest_id)
+ try:
+ item = await run_in_threadpool(geo_store.create_trip, gid, body.model_dump())
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return {"item": item}
+
+
+@router.patch("/trips/{trip_id}")
+async def patch_trip(
+ trip_id: str,
+ body: TripPatch,
+ x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
+):
+ if not SOCIAL_ENABLED:
+ raise HTTPException(status_code=503, detail="social disabled")
+ gid = _guest(x_social_guest_id)
+ payload = {k: v for k, v in body.model_dump().items() if v is not None}
+ item = await run_in_threadpool(geo_store.update_trip, gid, trip_id, payload)
+ if not item:
+ raise HTTPException(status_code=404, detail="trip not found")
+ return {"item": item}
+
+
+@router.delete("/trips/{trip_id}")
+async def remove_trip(
+ trip_id: str,
+ x_social_guest_id: str | None = Header(default=None, alias="X-Social-Guest-Id"),
+):
+ if not SOCIAL_ENABLED:
+ raise HTTPException(status_code=503, detail="social disabled")
+ gid = _guest(x_social_guest_id)
+ ok = await run_in_threadpool(geo_store.delete_trip, gid, trip_id)
+ if not ok:
+ raise HTTPException(status_code=404, detail="trip not found")
+ return {"ok": True}
diff --git a/apps/api/services/social_svc/s3_upload.py b/apps/api/services/social_svc/s3_upload.py
new file mode 100644
index 0000000..b470f6f
--- /dev/null
+++ b/apps/api/services/social_svc/s3_upload.py
@@ -0,0 +1,133 @@
+"""Avatar / media upload via SeaweedFS S3 (s3.nomadro.com), with local fallback."""
+from __future__ import annotations
+
+import mimetypes
+import os
+import uuid
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from urllib.parse import quote
+
+from social_svc.config import SOCIAL_UPLOAD_DIR
+
+
+@dataclass
+class UploadResult:
+ url: str
+ object_key: str
+ size: int
+ content_type: str
+ storage: str # "s3" | "local"
+
+
+def _env(name: str, *alts: str, default: str = "") -> str:
+ for key in (name, *alts):
+ val = (os.getenv(key) or "").strip()
+ if val:
+ return val
+ return default
+
+
+def s3_enabled() -> bool:
+ """Same SeaweedFS defaults as community_svc (s3.nomadro.com → :8333)."""
+ if _env("S3_ENABLED", default="true").lower() not in {"1", "true", "yes", "on"}:
+ return False
+ # Access key defaults to nomadweb (US SeaweedFS); secret must come from env on prod.
+ return bool(
+ _env("S3_ACCESS_KEY", "S3_ACCESS_KEY_ID", default="nomadweb")
+ and _env("S3_SECRET_KEY", "S3_SECRET_ACCESS_KEY")
+ )
+
+
+def _client():
+ import boto3
+ from botocore.client import Config
+
+ return boto3.client(
+ "s3",
+ endpoint_url=_env("S3_ENDPOINT", default="http://127.0.0.1:8333").rstrip("/"),
+ aws_access_key_id=_env(
+ "S3_ACCESS_KEY", "S3_ACCESS_KEY_ID", default="nomadweb"
+ ),
+ aws_secret_access_key=_env("S3_SECRET_KEY", "S3_SECRET_ACCESS_KEY"),
+ region_name=_env("S3_REGION", default="us-east-1"),
+ config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
+ )
+
+
+def _object_key(filename: str, purpose: str, guest_id: str) -> str:
+ suffix = Path(filename or "upload.bin").suffix.lower() or ".jpg"
+ if suffix not in {".jpg", ".jpeg", ".png", ".webp", ".gif"}:
+ suffix = ".jpg"
+ day = datetime.now(timezone.utc).strftime("%Y/%m/%d")
+ prefix = (os.getenv("S3_UPLOAD_PREFIX") or "social").strip("/")
+ purpose_part = (purpose or "avatar").replace("/", "-")[:40]
+ guest = "".join(c for c in guest_id if c.isalnum() or c in "_-")[:32] or "guest"
+ return f"{prefix}/{purpose_part}/{day}/{guest}_{uuid.uuid4().hex}{suffix}"
+
+
+def public_url_for_key(key: str) -> str:
+ base = _env(
+ "S3_PUBLIC_URL", default="https://s3.nomadro.com"
+ ).rstrip("/")
+ bucket = _env("S3_BUCKET", default="nomadweb").strip("/")
+ return f"{base}/{bucket}/{quote(key, safe='/')}"
+
+
+def upload_bytes(
+ data: bytes,
+ *,
+ filename: str,
+ content_type: str,
+ purpose: str,
+ guest_id: str,
+ max_size: int,
+) -> UploadResult:
+ if not data:
+ raise ValueError("empty file")
+ if len(data) > max_size:
+ raise ValueError(f"file too large (max {max_size // 1024 // 1024}MB)")
+
+ ctype = content_type or mimetypes.guess_type(filename or "")[0] or "image/jpeg"
+ if not ctype.startswith("image/"):
+ raise ValueError("only images allowed")
+
+ key = _object_key(filename, purpose, guest_id)
+
+ if s3_enabled():
+ bucket = _env("S3_BUCKET", default="nomadweb")
+ client = _client()
+ try:
+ try:
+ client.put_object(
+ Bucket=bucket,
+ Key=key,
+ Body=data,
+ ContentType=ctype,
+ ACL="public-read",
+ )
+ except Exception:
+ client.put_object(Bucket=bucket, Key=key, Body=data, ContentType=ctype)
+ return UploadResult(
+ url=public_url_for_key(key),
+ object_key=key,
+ size=len(data),
+ content_type=ctype,
+ storage="s3",
+ )
+ except Exception:
+ # Fall through to local if SeaweedFS is briefly unreachable
+ pass
+
+ # Local fallback (dev / S3 off / S3 error)
+ path = SOCIAL_UPLOAD_DIR / "avatars" / Path(key).name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(data)
+ return UploadResult(
+ url=f"/api/social/v1/files/avatar/{path.name}",
+ object_key=str(path),
+ size=len(data),
+ content_type=ctype,
+ storage="local",
+ )
diff --git a/apps/api/services/social_svc/store.py b/apps/api/services/social_svc/store.py
index b5597f3..b5532eb 100644
--- a/apps/api/services/social_svc/store.py
+++ b/apps/api/services/social_svc/store.py
@@ -10,7 +10,7 @@ from contextlib import contextmanager
from pathlib import Path
from typing import Any, Iterator
-from .config import SOCIAL_DB_PATH
+from .config import SOCIAL_DB_PATH, SOCIAL_UPLOAD_DIR, SOCIAL_UPLOAD_MAX_BYTES
try:
from ebook_svc.core.sqlite_util import connect as _connect
@@ -60,6 +60,20 @@ def init_db() -> None:
);
CREATE INDEX IF NOT EXISTS idx_messages_channel ON messages(channel_id, created_at);
+ CREATE TABLE IF NOT EXISTS channel_meta (
+ channel_id TEXT PRIMARY KEY,
+ next_seq INTEGER NOT NULL DEFAULT 1
+ );
+
+ CREATE TABLE IF NOT EXISTS channel_read (
+ guest_id TEXT NOT NULL,
+ channel_id TEXT NOT NULL,
+ recv_seq INTEGER NOT NULL DEFAULT 0,
+ read_seq INTEGER NOT NULL DEFAULT 0,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (guest_id, channel_id)
+ );
+
CREATE TABLE IF NOT EXISTS cafe_reviews (
id TEXT PRIMARY KEY,
cafe_id TEXT NOT NULL,
@@ -81,6 +95,7 @@ def init_db() -> None:
linktree TEXT,
skills TEXT,
bio TEXT,
+ avatar TEXT,
updated_at TEXT NOT NULL
);
@@ -102,61 +117,681 @@ def init_db() -> None:
guest_id TEXT NOT NULL,
created_at TEXT NOT NULL
);
+
+ CREATE TABLE IF NOT EXISTS trips (
+ id TEXT PRIMARY KEY,
+ guest_id TEXT NOT NULL,
+ city_id TEXT,
+ city TEXT NOT NULL,
+ country TEXT,
+ lat REAL,
+ lng REAL,
+ h3_cell TEXT,
+ arrival_date TEXT,
+ departure_date TEXT,
+ visibility TEXT NOT NULL DEFAULT 'public',
+ status TEXT NOT NULL DEFAULT 'planned',
+ updated_at TEXT NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS idx_trips_guest ON trips(guest_id);
+ CREATE INDEX IF NOT EXISTS idx_trips_city ON trips(city_id);
+ CREATE INDEX IF NOT EXISTS idx_trips_vis ON trips(visibility, status);
"""
)
+ # migrate older DBs missing seq / client_id / meta
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(messages)").fetchall()}
+ if "seq" not in cols:
+ conn.execute("ALTER TABLE messages ADD COLUMN seq INTEGER")
+ if "client_id" not in cols:
+ conn.execute("ALTER TABLE messages ADD COLUMN client_id TEXT")
+ if "meta" not in cols:
+ conn.execute("ALTER TABLE messages ADD COLUMN meta TEXT")
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_messages_channel_seq ON messages(channel_id, seq)"
+ )
+ roster_cols = {r[1] for r in conn.execute("PRAGMA table_info(roster)").fetchall()}
+ if "avatar" not in roster_cols:
+ conn.execute("ALTER TABLE roster ADD COLUMN avatar TEXT")
+ conn.executescript(
+ """
+ CREATE TABLE IF NOT EXISTS files (
+ id TEXT PRIMARY KEY,
+ channel_id TEXT NOT NULL,
+ guest_id TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ name TEXT NOT NULL,
+ mime TEXT NOT NULL,
+ size INTEGER NOT NULL,
+ path TEXT NOT NULL,
+ created_at TEXT NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS idx_files_channel ON files(channel_id, created_at);
+ """
+ )
+ _backfill_seq(conn)
+ try:
+ from . import geo_pb
+
+ geo_pb.ensure_collection()
+ except Exception:
+ pass
-def list_messages(channel_id: str, limit: int = 100) -> list[dict[str, Any]]:
- with db() as conn:
+def _parse_meta(raw: str | None) -> dict[str, Any]:
+ if not raw:
+ return {}
+ try:
+ data = json.loads(raw)
+ return data if isinstance(data, dict) else {}
+ except Exception:
+ return {}
+
+
+def _dump_meta(meta: dict[str, Any] | None) -> str:
+ return json.dumps(meta or {}, ensure_ascii=False, separators=(",", ":"))
+
+
+_MSG_COLS = "id, channel_id, author, text, guest_id, created_at, seq, client_id, meta"
+
+
+def _backfill_seq(conn: sqlite3.Connection) -> None:
+ """Assign monotonic seq to legacy rows (Tinode-style topic seq)."""
+ channels = conn.execute(
+ "SELECT DISTINCT channel_id FROM messages WHERE seq IS NULL OR seq = 0"
+ ).fetchall()
+ for ch in channels:
+ cid = ch["channel_id"]
rows = conn.execute(
"""
- SELECT id, channel_id, author, text, guest_id, created_at
+ SELECT id FROM messages
+ WHERE channel_id = ? AND (seq IS NULL OR seq = 0)
+ ORDER BY created_at ASC, rowid ASC
+ """,
+ (cid,),
+ ).fetchall()
+ if not rows:
+ continue
+ meta = conn.execute(
+ "SELECT next_seq FROM channel_meta WHERE channel_id = ?", (cid,)
+ ).fetchone()
+ start = int(meta["next_seq"]) if meta else 1
+ for i, r in enumerate(rows):
+ conn.execute("UPDATE messages SET seq = ? WHERE id = ?", (start + i, r["id"]))
+ nxt = start + len(rows)
+ if meta:
+ cur = int(meta["next_seq"] or 1)
+ if nxt > cur:
+ conn.execute(
+ "UPDATE channel_meta SET next_seq = ? WHERE channel_id = ?",
+ (nxt, cid),
+ )
+ else:
+ conn.execute(
+ "INSERT INTO channel_meta(channel_id, next_seq) VALUES (?, ?)",
+ (cid, nxt),
+ )
+
+
+def _row_message(r: sqlite3.Row) -> dict[str, Any]:
+ item: dict[str, Any] = {
+ "id": r["id"],
+ "channelId": r["channel_id"],
+ "author": r["author"],
+ "text": r["text"],
+ "guestId": r["guest_id"],
+ "at": r["created_at"],
+ "seq": int(r["seq"] or 0),
+ }
+ try:
+ cid = r["client_id"]
+ except (IndexError, KeyError):
+ cid = None
+ if cid:
+ item["clientId"] = cid
+ try:
+ meta_raw = r["meta"]
+ except (IndexError, KeyError):
+ meta_raw = None
+ meta = _parse_meta(meta_raw)
+ # Element-like fields flattened for clients
+ if meta.get("replyTo"):
+ item["replyTo"] = meta["replyTo"]
+ if meta.get("attachments"):
+ item["attachments"] = meta["attachments"]
+ if meta.get("reactions"):
+ item["reactions"] = meta["reactions"]
+ if meta.get("mentions"):
+ item["mentions"] = meta["mentions"]
+ if meta.get("editedAt"):
+ item["editedAt"] = meta["editedAt"]
+ if meta.get("recalled"):
+ item["recalled"] = True
+ item["text"] = ""
+ if meta.get("pinned"):
+ item["pinned"] = True
+ if meta.get("pinnedAt"):
+ item["pinnedAt"] = meta["pinnedAt"]
+ if meta.get("reported"):
+ item["reported"] = True
+ return item
+
+
+def _get_message(conn: sqlite3.Connection, msg_id: str) -> sqlite3.Row | None:
+ return conn.execute(
+ f"SELECT {_MSG_COLS} FROM messages WHERE id = ?", (msg_id,)
+ ).fetchone()
+
+
+def _get_message_row(conn: sqlite3.Connection, msg_id: str) -> sqlite3.Row | None:
+ return _get_message(conn, msg_id)
+
+
+def channel_desc(channel_id: str, guest_id: str | None = None) -> dict[str, Any]:
+ """Tinode-like topic desc: latest seq + caller's recv/read watermarks."""
+ init_db()
+ with db() as conn:
+ meta = conn.execute(
+ "SELECT next_seq FROM channel_meta WHERE channel_id = ?", (channel_id,)
+ ).fetchone()
+ if meta:
+ seq = max(0, int(meta["next_seq"]) - 1)
+ else:
+ row = conn.execute(
+ "SELECT MAX(seq) AS m FROM messages WHERE channel_id = ?", (channel_id,)
+ ).fetchone()
+ seq = int(row["m"] or 0)
+ recv = read = 0
+ if guest_id:
+ mark = conn.execute(
+ """
+ SELECT recv_seq, read_seq FROM channel_read
+ WHERE guest_id = ? AND channel_id = ?
+ """,
+ (guest_id, channel_id),
+ ).fetchone()
+ if mark:
+ recv = int(mark["recv_seq"] or 0)
+ read = int(mark["read_seq"] or 0)
+ peers = online_peers(channel_id)
+ return {
+ "channelId": channel_id,
+ "seq": seq,
+ "recv": recv,
+ "read": read,
+ "unread": max(0, seq - read),
+ "online": len(peers),
+ "peers": peers,
+ }
+
+
+def list_messages(
+ channel_id: str,
+ limit: int = 100,
+ *,
+ since: int | None = None,
+ before: int | None = None,
+ q: str | None = None,
+) -> list[dict[str, Any]]:
+ """History with Tinode-style seq cursors (since exclusive, before exclusive)."""
+ lim = max(1, min(int(limit or 100), 500))
+ needle = (q or "").strip()[:80]
+ with db() as conn:
+ if needle:
+ like = f"%{needle}%"
+ rows = conn.execute(
+ f"""
+ SELECT {_MSG_COLS}
+ FROM messages
+ WHERE channel_id = ?
+ AND COALESCE(json_extract(meta, '$.recalled'), 0) = 0
+ AND (text LIKE ? OR author LIKE ?)
+ ORDER BY COALESCE(seq, 0) DESC, rowid DESC
+ LIMIT ?
+ """,
+ (channel_id, like, like, lim),
+ ).fetchall()
+ return [_row_message(r) for r in reversed(rows)]
+ if since is not None and since > 0:
+ rows = conn.execute(
+ f"""
+ SELECT {_MSG_COLS}
+ FROM messages
+ WHERE channel_id = ? AND seq IS NOT NULL AND seq > ?
+ ORDER BY seq ASC
+ LIMIT ?
+ """,
+ (channel_id, since, lim),
+ ).fetchall()
+ return [_row_message(r) for r in rows]
+ if before is not None and before > 0:
+ rows = conn.execute(
+ f"""
+ SELECT {_MSG_COLS}
+ FROM messages
+ WHERE channel_id = ? AND seq IS NOT NULL AND seq < ?
+ ORDER BY seq DESC
+ LIMIT ?
+ """,
+ (channel_id, before, lim),
+ ).fetchall()
+ return [_row_message(r) for r in reversed(rows)]
+ rows = conn.execute(
+ f"""
+ SELECT {_MSG_COLS}
FROM messages
WHERE channel_id = ?
- ORDER BY created_at DESC, rowid DESC
+ ORDER BY COALESCE(seq, 0) DESC, rowid DESC
LIMIT ?
""",
- (channel_id, max(1, min(limit, 500))),
+ (channel_id, lim),
).fetchall()
- return [
- {
- "id": r["id"],
- "channelId": r["channel_id"],
- "author": r["author"],
- "text": r["text"],
- "guestId": r["guest_id"],
- "at": r["created_at"],
- }
- for r in reversed(rows)
+ return [_row_message(r) for r in reversed(rows)]
+
+
+def _normalize_reply(reply_to: dict[str, Any] | None) -> dict[str, Any] | None:
+ if not reply_to or not isinstance(reply_to, dict):
+ return None
+ rid = str(reply_to.get("id") or "").strip()
+ if not rid:
+ return None
+ return {
+ "id": rid[:80],
+ "author": str(reply_to.get("author") or "游民").strip()[:48] or "游民",
+ "text": str(reply_to.get("text") or "").strip()[:240],
+ "seq": int(reply_to.get("seq") or 0) or None,
+ }
+
+
+def _normalize_attachments(items: list[Any] | None) -> list[dict[str, Any]]:
+ out: list[dict[str, Any]] = []
+ for raw in (items or [])[:8]:
+ if not isinstance(raw, dict):
+ continue
+ url = str(raw.get("url") or "").strip()
+ kind = str(raw.get("kind") or "file").strip().lower()
+ if kind not in {"image", "video", "file", "audio"}:
+ kind = "file"
+ if not url or len(url) > 800:
+ continue
+ out.append(
+ {
+ "id": str(raw.get("id") or _uid("att"))[:80],
+ "kind": kind,
+ "url": url,
+ "name": str(raw.get("name") or "file").strip()[:160] or "file",
+ "mime": str(raw.get("mime") or "application/octet-stream").strip()[:120],
+ "size": max(0, min(int(raw.get("size") or 0), 50 * 1024 * 1024)),
+ }
+ )
+ return out
+
+
+def add_message(
+ channel_id: str,
+ author: str,
+ text: str,
+ guest_id: str,
+ client_id: str | None = None,
+ *,
+ reply_to: dict[str, Any] | None = None,
+ attachments: list[Any] | None = None,
+ mentions: list[Any] | None = None,
+) -> dict[str, Any]:
+ from social_svc.im import check_rate
+
+ check_rate(guest_id)
+ body = (text or "").strip()[:2000]
+ atts = _normalize_attachments(attachments)
+ if not body and not atts:
+ raise ValueError("empty message")
+ reply = _normalize_reply(reply_to)
+ mention_list = [
+ str(m).strip()[:48]
+ for m in (mentions or [])[:12]
+ if str(m).strip()
]
+ meta: dict[str, Any] = {}
+ if reply:
+ meta["replyTo"] = reply
+ if atts:
+ meta["attachments"] = atts
+ if mention_list:
+ meta["mentions"] = mention_list
-
-def add_message(channel_id: str, author: str, text: str, guest_id: str, client_id: str | None = None) -> dict[str, Any]:
+ msg_id = (
+ "msg_"
+ + hashlib.sha256(json.dumps([guest_id, channel_id, client_id]).encode()).hexdigest()[:32]
+ if client_id
+ else _uid("msg")
+ )
item = {
- "id": ("msg_" + hashlib.sha256(json.dumps([guest_id, channel_id, client_id]).encode()).hexdigest()[:32]) if client_id else _uid("msg"),
+ "id": msg_id,
"channelId": channel_id,
"author": (author or "游民").strip()[:48] or "游民",
- "text": text.strip()[:2000],
+ "text": body,
"guestId": guest_id,
"at": _now(),
+ "seq": 0,
+ }
+ with db() as conn:
+ existing = _get_message(conn, msg_id)
+ if existing:
+ if existing["text"] != item["text"] or existing["author"] != item["author"]:
+ raise ValueError("同一请求标识不能用于不同消息")
+ out = _row_message(existing)
+ if client_id:
+ out["clientId"] = client_id
+ return out
+
+ ch_meta = conn.execute(
+ "SELECT next_seq FROM channel_meta WHERE channel_id = ?", (channel_id,)
+ ).fetchone()
+ if ch_meta:
+ seq = int(ch_meta["next_seq"])
+ conn.execute(
+ "UPDATE channel_meta SET next_seq = ? WHERE channel_id = ?",
+ (seq + 1, channel_id),
+ )
+ else:
+ seq = 1
+ conn.execute(
+ "INSERT INTO channel_meta(channel_id, next_seq) VALUES (?, ?)",
+ (channel_id, 2),
+ )
+ item["seq"] = seq
+ conn.execute(
+ f"""
+ INSERT INTO messages({_MSG_COLS})
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ item["id"],
+ item["channelId"],
+ item["author"],
+ item["text"],
+ guest_id,
+ item["at"],
+ seq,
+ client_id,
+ _dump_meta(meta),
+ ),
+ )
+ out = {**item, **{k: v for k, v in {
+ "clientId": client_id,
+ "replyTo": reply,
+ "attachments": atts or None,
+ "mentions": mention_list or None,
+ }.items() if v}}
+ return out
+
+
+def edit_message(channel_id: str, msg_id: str, guest_id: str, text: str) -> dict[str, Any]:
+ body = (text or "").strip()[:2000]
+ if not body:
+ raise ValueError("empty text")
+ with db() as conn:
+ row = _get_message(conn, msg_id)
+ if not row or row["channel_id"] != channel_id:
+ raise ValueError("message not found")
+ if row["guest_id"] != guest_id:
+ raise ValueError("not your message")
+ meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
+ if meta.get("recalled"):
+ raise ValueError("recalled")
+ meta["editedAt"] = _now()
+ conn.execute(
+ "UPDATE messages SET text = ?, meta = ? WHERE id = ?",
+ (body, _dump_meta(meta), msg_id),
+ )
+ row = _get_message(conn, msg_id)
+ return _row_message(row) # type: ignore[arg-type]
+
+
+def recall_message(channel_id: str, msg_id: str, guest_id: str) -> dict[str, Any]:
+ """Element-style redact: clear body, keep shell for timeline continuity."""
+ with db() as conn:
+ row = _get_message(conn, msg_id)
+ if not row or row["channel_id"] != channel_id:
+ raise ValueError("message not found")
+ if row["guest_id"] != guest_id:
+ raise ValueError("not your message")
+ meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
+ meta["recalled"] = True
+ meta["recalledAt"] = _now()
+ meta.pop("attachments", None)
+ meta.pop("reactions", None)
+ conn.execute(
+ "UPDATE messages SET text = '', meta = ? WHERE id = ?",
+ (_dump_meta(meta), msg_id),
+ )
+ row = _get_message(conn, msg_id)
+ return _row_message(row) # type: ignore[arg-type]
+
+
+def react_message(
+ channel_id: str, msg_id: str, guest_id: str, emoji: str
+) -> dict[str, Any]:
+ """Toggle annotation reaction (Element / Matrix m.annotation pattern)."""
+ key = (emoji or "").strip()[:16]
+ if not key:
+ raise ValueError("empty emoji")
+ with db() as conn:
+ row = _get_message(conn, msg_id)
+ if not row or row["channel_id"] != channel_id:
+ raise ValueError("message not found")
+ meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
+ if meta.get("recalled"):
+ raise ValueError("recalled")
+ reactions: dict[str, list[str]] = dict(meta.get("reactions") or {})
+ holders = list(reactions.get(key) or [])
+ if guest_id in holders:
+ holders = [g for g in holders if g != guest_id]
+ else:
+ holders.append(guest_id)
+ if holders:
+ reactions[key] = holders[:64]
+ else:
+ reactions.pop(key, None)
+ if reactions:
+ meta["reactions"] = reactions
+ else:
+ meta.pop("reactions", None)
+ conn.execute(
+ "UPDATE messages SET meta = ? WHERE id = ?",
+ (_dump_meta(meta), msg_id),
+ )
+ row = _get_message(conn, msg_id)
+ return _row_message(row) # type: ignore[arg-type]
+
+
+def pin_message(
+ channel_id: str, msg_id: str, guest_id: str, pinned: bool = True
+) -> dict[str, Any]:
+ with db() as conn:
+ row = _get_message(conn, msg_id)
+ if not row or row["channel_id"] != channel_id:
+ raise ValueError("message not found")
+ meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
+ if meta.get("recalled"):
+ raise ValueError("recalled")
+ if pinned:
+ meta["pinned"] = True
+ meta["pinnedAt"] = _now()
+ meta["pinnedBy"] = guest_id
+ else:
+ meta.pop("pinned", None)
+ meta.pop("pinnedAt", None)
+ meta.pop("pinnedBy", None)
+ conn.execute(
+ "UPDATE messages SET meta = ? WHERE id = ?",
+ (_dump_meta(meta), msg_id),
+ )
+ row = _get_message(conn, msg_id)
+ return _row_message(row) # type: ignore[arg-type]
+
+
+def save_upload(
+ channel_id: str,
+ guest_id: str,
+ *,
+ kind: str,
+ name: str,
+ mime: str,
+ data: bytes,
+) -> dict[str, Any]:
+ from social_svc.config import SOCIAL_UPLOAD_DIR, SOCIAL_UPLOAD_MAX_BYTES
+
+ if len(data) > SOCIAL_UPLOAD_MAX_BYTES:
+ raise ValueError("file too large")
+ if kind not in {"image", "video", "file", "audio"}:
+ kind = "file"
+ file_id = _uid("file")
+ safe_name = "".join(c for c in (name or "file") if c.isalnum() or c in "._- ")[:120] or "file"
+ root = SOCIAL_UPLOAD_DIR / channel_id
+ root.mkdir(parents=True, exist_ok=True)
+ path = root / f"{file_id}_{safe_name}"
+ path.write_bytes(data)
+ item = {
+ "id": file_id,
+ "kind": kind,
+ "name": safe_name,
+ "mime": (mime or "application/octet-stream")[:120],
+ "size": len(data),
+ "url": f"/api/social/v1/files/{file_id}",
}
with db() as conn:
conn.execute(
"""
- INSERT OR IGNORE INTO messages(id, channel_id, author, text, guest_id, created_at)
- VALUES (?, ?, ?, ?, ?, ?)
+ INSERT INTO files(id, channel_id, guest_id, kind, name, mime, size, path, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
- (item["id"], item["channelId"], item["author"], item["text"], guest_id, item["at"]),
+ (
+ file_id,
+ channel_id,
+ guest_id,
+ kind,
+ safe_name,
+ item["mime"],
+ item["size"],
+ str(path),
+ _now(),
+ ),
)
- row = conn.execute("SELECT * FROM messages WHERE id = ?", (item["id"],)).fetchone()
- if row["text"] != item["text"] or row["author"] != item["author"]:
- raise ValueError("同一请求标识不能用于不同消息")
- item["at"] = row["created_at"]
- if client_id:
- item["clientId"] = client_id
return item
+def get_file(file_id: str) -> dict[str, Any] | None:
+ with db() as conn:
+ row = conn.execute("SELECT * FROM files WHERE id = ?", (file_id,)).fetchone()
+ if not row:
+ return None
+ return {
+ "id": row["id"],
+ "channelId": row["channel_id"],
+ "kind": row["kind"],
+ "name": row["name"],
+ "mime": row["mime"],
+ "size": row["size"],
+ "path": row["path"],
+ }
+
+
+# Element-like soft presence (TTL heartbeat; UI-agnostic)
+_PRESENCE: dict[str, dict[str, dict[str, Any]]] = {}
+_PRESENCE_TTL_SEC = 45
+
+
+def touch_presence(
+ channel_id: str, guest_id: str, nick: str = ""
+) -> dict[str, Any]:
+ now = time.time()
+ room = _PRESENCE.setdefault(channel_id, {})
+ room[guest_id] = {
+ "guestId": guest_id,
+ "nick": (nick or "游民").strip()[:48] or "游民",
+ "at": now,
+ }
+ # prune
+ dead = [gid for gid, meta in room.items() if now - float(meta["at"]) > _PRESENCE_TTL_SEC]
+ for gid in dead:
+ room.pop(gid, None)
+ peers = online_peers(channel_id)
+ return {"channelId": channel_id, "online": len(peers), "peers": peers}
+
+
+def online_peers(channel_id: str) -> list[dict[str, Any]]:
+ now = time.time()
+ room = _PRESENCE.get(channel_id) or {}
+ out: list[dict[str, Any]] = []
+ for gid, meta in list(room.items()):
+ if now - float(meta["at"]) > _PRESENCE_TTL_SEC:
+ room.pop(gid, None)
+ continue
+ out.append({"guestId": gid, "nick": meta.get("nick") or "游民"})
+ out.sort(key=lambda p: p["nick"])
+ return out[:64]
+
+
+def report_message(
+ channel_id: str, msg_id: str, guest_id: str, reason: str = ""
+) -> dict[str, Any]:
+ with db() as conn:
+ row = _get_message(conn, msg_id)
+ if not row or row["channel_id"] != channel_id:
+ raise ValueError("message not found")
+ meta = _parse_meta(row["meta"] if "meta" in row.keys() else None)
+ reporters = list(meta.get("reporters") or [])
+ if guest_id not in reporters:
+ reporters.append(guest_id)
+ meta["reported"] = True
+ meta["reporters"] = reporters[:64]
+ meta["reportReason"] = (reason or "").strip()[:240]
+ meta["reportedAt"] = _now()
+ conn.execute(
+ "UPDATE messages SET meta = ? WHERE id = ?",
+ (_dump_meta(meta), msg_id),
+ )
+ row = _get_message(conn, msg_id)
+ return _row_message(row) # type: ignore[arg-type]
+
+
+def set_note(channel_id: str, guest_id: str, what: str, seq: int) -> dict[str, Any]:
+ """Persist recv/read watermark (Tinode {note})."""
+ what = (what or "").strip().lower()
+ if what not in {"recv", "read"}:
+ raise ValueError("what must be recv or read")
+ seq = max(0, int(seq))
+ init_db()
+ now = _now()
+ with db() as conn:
+ row = conn.execute(
+ """
+ SELECT recv_seq, read_seq FROM channel_read
+ WHERE guest_id = ? AND channel_id = ?
+ """,
+ (guest_id, channel_id),
+ ).fetchone()
+ recv = int(row["recv_seq"]) if row else 0
+ read = int(row["read_seq"]) if row else 0
+ if what == "recv":
+ recv = max(recv, seq)
+ else:
+ read = max(read, seq)
+ recv = max(recv, read)
+ conn.execute(
+ """
+ INSERT INTO channel_read(guest_id, channel_id, recv_seq, read_seq, updated_at)
+ VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(guest_id, channel_id) DO UPDATE SET
+ recv_seq = excluded.recv_seq,
+ read_seq = excluded.read_seq,
+ updated_at = excluded.updated_at
+ """,
+ (guest_id, channel_id, recv, read, now),
+ )
+ return {"channelId": channel_id, "what": what, "seq": seq, "recv": recv, "read": read}
+
+
def list_reviews(cafe_id: str, limit: int = 50) -> list[dict[str, Any]]:
with db() as conn:
rows = conn.execute(
@@ -227,6 +862,7 @@ def get_roster(guest_id: str) -> dict[str, Any] | None:
r = conn.execute("SELECT * FROM roster WHERE guest_id = ?", (guest_id,)).fetchone()
if not r:
return None
+ keys = set(r.keys())
return {
"guestId": r["guest_id"],
"name": r["name"],
@@ -236,12 +872,20 @@ def get_roster(guest_id: str) -> dict[str, Any] | None:
"linktree": r["linktree"] or "",
"skills": r["skills"] or "",
"bio": r["bio"] or "",
+ "avatar": (r["avatar"] if "avatar" in keys else "") or "",
"updatedAt": r["updated_at"],
}
def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
updated = _now()
+ avatar = str(payload.get("avatar") or "").strip()[:500]
+ if avatar and not (
+ avatar.startswith("https://")
+ or avatar.startswith("http://")
+ or avatar.startswith("/api/social/")
+ ):
+ avatar = ""
row = {
"guestId": guest_id,
"name": str(payload.get("name") or "").strip()[:64] or "游民",
@@ -251,13 +895,14 @@ def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
"linktree": str(payload.get("linktree") or "").strip()[:240],
"skills": str(payload.get("skills") or "").strip()[:200],
"bio": str(payload.get("bio") or "").strip()[:2000],
+ "avatar": avatar,
"updatedAt": updated,
}
with db() as conn:
conn.execute(
"""
- INSERT INTO roster(guest_id, name, title, city, phone, linktree, skills, bio, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ INSERT INTO roster(guest_id, name, title, city, phone, linktree, skills, bio, avatar, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(guest_id) DO UPDATE SET
name=excluded.name,
title=excluded.title,
@@ -266,6 +911,7 @@ def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
linktree=excluded.linktree,
skills=excluded.skills,
bio=excluded.bio,
+ avatar=excluded.avatar,
updated_at=excluded.updated_at
""",
(
@@ -277,6 +923,7 @@ def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]:
row["linktree"],
row["skills"],
row["bio"],
+ row["avatar"],
updated,
),
)
diff --git a/apps/api/social_main.py b/apps/api/social_main.py
index fb37360..6750a52 100644
--- a/apps/api/social_main.py
+++ b/apps/api/social_main.py
@@ -32,10 +32,14 @@ if SOCIAL_ENABLED:
@app.get("/health")
def health():
from social_svc.config import CENTRIFUGO_ENABLED
+ from social_svc.contract import IM_FEATURES, IM_PROTOCOL
return {
"ok": True,
"service": "nomadro-social",
"social": bool(SOCIAL_ENABLED),
"centrifugo": bool(CENTRIFUGO_ENABLED),
+ "imProtocol": IM_PROTOCOL,
+ "imFeatures": list(IM_FEATURES),
+ "uiAgnostic": True,
}
diff --git a/apps/coffee/README.md b/apps/coffee/README.md
new file mode 100644
index 0000000..2b7d951
--- /dev/null
+++ b/apps/coffee/README.md
@@ -0,0 +1,37 @@
+# Coffeechat booking — Cal.com-domain secondary-dev
+
+读开源 **Cal.com** 域模型后自研,挂游民社区 `/social/coffeechat`(Fair Use;非 iframe / 非原样塞 upstream UI):
+
+| Cal.com 概念 | Nomadro | API |
+|---|---|---|
+| User / Host | 主持人公开页 | `GET /api/coffee/v1/hosts/:user` |
+| EventType | 咖啡聊 / 视频聊等时长类型 | `.../event-types/:slug` |
+| Schedule + Availability | 周内可约窗口(分钟) | `.../schedule` |
+| availableSlots | 按日生成空档 | `.../slots?day=` |
+| Booking + Attendee | 预约确认 / 取消 | `POST /bookings` |
+
+## 本地
+
+```bash
+pnpm coffee:fetch # 可选对照 → apps/coffee/upstream/cal.com
+pnpm dev:coffee-api # uvicorn coffee_main:app :8024
+pnpm dev # http://localhost:3000/social/coffeechat
+```
+
+## 产品路由
+
+| 路由 | 说明 |
+|---|---|
+| `/social/coffeechat` | 品牌落地 · 主持人列表 |
+| `/social/coffeechat/:user` | 事件类型列表 |
+| `/social/coffeechat/:user/:slug` | 选日 → 时段 → 确认 |
+| `/social/coffeechat/manage` | 演示主持人日程与预约 |
+| `/social/coffeechat/bookings/:id` | 预约详情 / 取消 |
+
+数据:`data/coffee/coffee.sqlite3`。咖啡馆地图仍见 `/social/places?tab=cafes`。
+
+## 反模式
+
+- iframe / 嵌入官方 Cal.com
+- 跳 `cal.` 二级域
+- 把整包 Cal monorepo UI 硬塞进 Next
diff --git a/apps/coffee/scripts/fetch-upstream.mjs b/apps/coffee/scripts/fetch-upstream.mjs
new file mode 100644
index 0000000..f90ab50
--- /dev/null
+++ b/apps/coffee/scripts/fetch-upstream.mjs
@@ -0,0 +1,49 @@
+#!/usr/bin/env node
+/**
+ * Shallow-clone Cal.com into apps/coffee/upstream/ for secondary development.
+ * Does not commit upstream into git.
+ */
+import { spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const upstream = join(root, "upstream");
+
+const REPOS = [
+ {
+ name: "cal.com",
+ url: "https://github.com/calcom/cal.com.git",
+ branch: "main",
+ },
+];
+
+mkdirSync(upstream, { recursive: true });
+
+function run(cmd, args) {
+ console.log(`$ ${cmd} ${args.join(" ")}`);
+ const r = spawnSync(cmd, args, { stdio: "inherit", shell: false });
+ if (r.status !== 0) process.exit(r.status || 1);
+}
+
+for (const repo of REPOS) {
+ const dest = join(upstream, repo.name);
+ if (existsSync(join(dest, ".git"))) {
+ console.log(`[skip] ${repo.name} already cloned — pull --ff-only`);
+ run("git", ["-C", dest, "pull", "--ff-only", "origin", repo.branch]);
+ continue;
+ }
+ if (existsSync(dest)) rmSync(dest, { recursive: true, force: true });
+ run("git", [
+ "clone",
+ "--depth",
+ "1",
+ "--branch",
+ repo.branch,
+ repo.url,
+ dest,
+ ]);
+}
+
+console.log("DONE fetch-upstream →", upstream);
diff --git a/apps/com/README.md b/apps/com/README.md
new file mode 100644
index 0000000..258dbae
--- /dev/null
+++ b/apps/com/README.md
@@ -0,0 +1,68 @@
+# Nomadro `.com`(美国 VPS · 源码隔离)
+
+与 **`.cn` 备案线完全隔离**:本目录只服务 **未备案的 `.com` Web**,**禁止**微信 / 抖音 / 小红书小程序业务与后台入口。
+
+| 项 | `.cn`(国内) | `.com`(本目录) |
+|---|---|---|
+| 门户 | 仓库根 `src/` Next → `nomadro.cn` | 美国 VPS 单独部署(勿与 `.cn` 同进程混部) |
+| 管理后台 | [`apps/admin`](../admin) → `admin.nomadro.cn`(微信 / 抖音) | [`apps/com/admin`](./admin) → **`admin.nomadro.com`(仅 Web)** |
+| 小程序 | `apps/miniprogram/*` | **无** |
+
+## 子包
+
+| 路径 | 域名 | 说明 |
+|------|------|------|
+| `admin/` | `admin.nomadro.com` | Vite SPA,Web 运营模块 |
+
+后续若在美国机再拆门户,可在本目录新增 `portal/` 等,仍勿回写进 `apps/admin` / 小程序树。
+
+## 本地
+
+```bash
+# 仓库根
+pnpm install
+pnpm dev:admin-com # http://127.0.0.1:5174
+pnpm build:admin-com
+```
+
+### 线上分工(美国 VPS)
+
+| 站点 | 前端 | 后端 |
+|------|------|------|
+| `https://nomadro.com` | **本机** `pnpm dev`(`:3000`)调试 | **线上** `https://api.nomadro.com` |
+| `https://admin.nomadro.com` | **线上** 静态 SPA(`apps/com/admin`) | **线上** 同上 API |
+
+本地门户:根目录 `.env.local` 设 `API_URL=https://api.nomadro.com`,然后 `pnpm dev`。
+
+### 埋点 / ntfy(nomadro.com)
+
+| 层 | 作用 |
+|---|---|
+| 前端 `PortalAnalytics` + `~/lib/analytics/track` | 会话、路由 PV、`data-track` CTA、异常;受众 props |
+| Next `POST /api/track` | 关键事件推 `ntfy.nomadro.cn`(标题带 `[nomadro.com]`),并转发 `API_URL/api/track` 入库 |
+| Umami | `NEXT_PUBLIC_UMAMI_WEBSITE_ID` 聚合浏览(可选) |
+| `admin.nomadro.com` → 埋点 / ntfy | Events 回放 + 试推 |
+
+`.env.local` 建议:`NTFY_BASE_URL` / `NTFY_TOPIC`(可选 `NTFY_TOPIC_COM`)/ Umami website id。
+
+部署 `.com` 管理后台:
+
+```bash
+python apps/admin/deploy/_deploy_admin_com_us.py
+```
+
+登录:`hackrobot` / `Xiao4669805@`
+
+## 受众(强制)
+
+- **`.com` 默认 intl(英语 / 多语言)**;中文用户走 **cn 特殊线**
+- 模块 SoT:`src/modules/audience/{cn,intl}` — 支付 / 登录 / 关注 / 文案 / VIP / 埋点 / 社群
+- 调用:`resolveAudienceBundle()` / `useAudienceModule()`;禁止页面 `if (isChina)`
+- 后台:登录后选 `/cn` 或 `/intl`
+
+## 铁律
+
+- 不在本树引入 `weapp` / `tt` / Taro 小程序页面或开关
+- 不与 `admin.nomadro.cn` 共用前端源码目录(可各自调 API,token 键隔离)
+- 部署目标:美国 VPS;勿把本包静态资源发到 `.cn` 小程序后台目录
+- 功能按 `audience === 'cn' | 'intl'` 开发,禁止用 UI locale 反推支付
diff --git a/apps/com/admin/README.md b/apps/com/admin/README.md
new file mode 100644
index 0000000..2fc975f
--- /dev/null
+++ b/apps/com/admin/README.md
@@ -0,0 +1,29 @@
+# admin.nomadro.com(Web 运营台)
+
+包名:`@nomadro/admin-com`。源码在 `apps/com/admin`,与 `apps/admin`(`.cn` 微信/抖音)隔离。
+
+**生产**:前后端都在美国机(`admin.nomadro.com` + `api.nomadro.com`)。
+
+## 能力
+
+流程:登录 → **全屏选模块** → 进入该模块壳。
+
+| 页 | 路径 | 说明 |
+|---|---|---|
+| 选模块 | `/` | 登录后中间页(无侧栏) |
+| 中文用户 | `/cn/*` | 特殊线运营壳 |
+| 国际用户 | `/intl/*` | 默认线运营壳 |
+| 子页 | `…/switches|events|orders|users|ntfy|docs` | 模块内工具 |
+
+## 部署
+
+```bash
+pnpm build:admin-com
+python apps/admin/deploy/_deploy_admin_com_us.py
+# ntfy 试推 API(增量)
+python apps/admin/deploy/_deploy_ops_admin_us.py
+```
+
+登录:`hackrobot` / `Xiao4669805@`
+
+本地一般不启本包;门户调试见 [`apps/com/README.md`](../README.md)。
diff --git a/apps/com/admin/index.html b/apps/com/admin/index.html
new file mode 100644
index 0000000..edbfddd
--- /dev/null
+++ b/apps/com/admin/index.html
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+ Nomadro Admin · .com
+
+
+
+
+
+
diff --git a/apps/com/admin/package.json b/apps/com/admin/package.json
new file mode 100644
index 0000000..82cd6eb
--- /dev/null
+++ b/apps/com/admin/package.json
@@ -0,0 +1,23 @@
+{
+ "name": "@nomadro/admin-com",
+ "private": true,
+ "version": "1.0.0",
+ "type": "module",
+ "scripts": {
+ "dev": "vite --host 0.0.0.0 --port 5174",
+ "build": "tsc --noEmit && vite build",
+ "preview": "vite preview --host 0.0.0.0 --port 5174"
+ },
+ "dependencies": {
+ "react": "18.3.1",
+ "react-dom": "18.3.1",
+ "react-router-dom": "6.28.0"
+ },
+ "devDependencies": {
+ "@types/react": "18.3.12",
+ "@types/react-dom": "18.3.1",
+ "@vitejs/plugin-react": "^4.3.4",
+ "typescript": "^5.6.3",
+ "vite": "^5.4.11"
+ }
+}
diff --git a/apps/com/admin/src/App.tsx b/apps/com/admin/src/App.tsx
new file mode 100644
index 0000000..a86459b
--- /dev/null
+++ b/apps/com/admin/src/App.tsx
@@ -0,0 +1,80 @@
+import { Navigate, Route, Routes, useParams } from 'react-router-dom'
+import { getToken } from './api/client'
+import Login from './pages/Login'
+import ModuleSelect from './pages/ModuleSelect'
+import WebLayout from './components/WebLayout'
+import Docs from './pages/Docs'
+import Switches from './pages/Switches'
+import Events from './pages/Events'
+import Orders from './pages/Orders'
+import Users from './pages/Users'
+import Ntfy from './pages/Ntfy'
+import LaneHub, { type LaneKey } from './pages/LaneHub'
+
+/**
+ * https://admin.nomadro.com
+ * 登录 → 选模块 → /cn | /intl(对齐 .cn:登录 → PlatformSelect → /wechat|/douyin)
+ */
+function Private({ children }: { children: React.ReactNode }) {
+ if (!getToken()) return
+ return <>{children}>
+}
+
+function LaneGuard({ children }: { children: React.ReactNode }) {
+ const { lane } = useParams()
+ if (lane !== 'cn' && lane !== 'intl') return
+ return <>{children}>
+}
+
+function LaneHome() {
+ const { lane } = useParams()
+ return
+}
+
+export default function App() {
+ return (
+
+ } />
+
+
+
+
+ }
+ />
+
+
+
+
+
+
+ }
+ >
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+
+
+ {/* 旧路径 → 先选模块 */}
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+ } />
+
+ } />
+
+ )
+}
diff --git a/apps/com/admin/src/api/client.ts b/apps/com/admin/src/api/client.ts
new file mode 100644
index 0000000..fd330f6
--- /dev/null
+++ b/apps/com/admin/src/api/client.ts
@@ -0,0 +1,37 @@
+/** admin.nomadro.com — token 与 .cn admin 隔离 */
+const TOKEN_KEY = 'nomadro_admin_com_token'
+
+export const API_BASE = import.meta.env.VITE_API_BASE || ''
+
+export function getToken() {
+ return localStorage.getItem(TOKEN_KEY) || ''
+}
+
+export function setToken(t: string) {
+ localStorage.setItem(TOKEN_KEY, t)
+}
+
+export function clearToken() {
+ localStorage.removeItem(TOKEN_KEY)
+}
+
+export async function api(path: string, init: RequestInit = {}): Promise {
+ const headers: Record = {
+ 'Content-Type': 'application/json',
+ ...(init.headers as Record | undefined),
+ }
+ const token = getToken()
+ if (token) headers.Authorization = `Bearer ${token}`
+
+ const res = await fetch(`${API_BASE}${path}`, { ...init, headers })
+ if (res.status === 401) {
+ clearToken()
+ if (!path.includes('/login')) window.location.href = '/login'
+ }
+ const data = await res.json().catch(() => ({}))
+ if (!res.ok) {
+ const err = data as { detail?: string; message?: string }
+ throw new Error(err.detail || err.message || '请求失败')
+ }
+ return data as T
+}
diff --git a/apps/com/admin/src/components/Charts.tsx b/apps/com/admin/src/components/Charts.tsx
new file mode 100644
index 0000000..88ee46c
--- /dev/null
+++ b/apps/com/admin/src/components/Charts.tsx
@@ -0,0 +1,113 @@
+/** Lightweight SVG charts — no chart lib dependency. */
+
+type Point = { date: string; value: number }
+
+function niceMax(n: number) {
+ if (n <= 0) return 1
+ const p = 10 ** Math.floor(Math.log10(n))
+ return Math.ceil(n / p) * p
+}
+
+export function SparkBars({
+ title,
+ subtitle,
+ points,
+ format = (v) => String(v),
+ accent = '#f59e0b',
+}: {
+ title: string
+ subtitle?: string
+ points: Point[]
+ format?: (v: number) => string
+ accent?: string
+}) {
+ const w = 560
+ const h = 160
+ const pad = { t: 12, r: 8, b: 28, l: 8 }
+ const max = niceMax(Math.max(...points.map((p) => p.value), 0))
+ const bw = points.length ? (w - pad.l - pad.r) / points.length : 0
+ const innerH = h - pad.t - pad.b
+
+ return (
+
+
+
+ {title}
+ {subtitle ? {subtitle} : null}
+
+
峰值 {format(max)}
+
+
+
+ )
+}
+
+export function RankList({
+ title,
+ items,
+}: {
+ title: string
+ items: Array<{ name: string; count: number }>
+}) {
+ const max = Math.max(...items.map((i) => i.count), 1)
+ return (
+
+ )
+}
diff --git a/apps/com/admin/src/components/WebLayout.tsx b/apps/com/admin/src/components/WebLayout.tsx
new file mode 100644
index 0000000..f86ce13
--- /dev/null
+++ b/apps/com/admin/src/components/WebLayout.tsx
@@ -0,0 +1,128 @@
+import { useEffect, useState } from 'react'
+import { NavLink, Outlet, useLocation, useNavigate, useParams } from 'react-router-dom'
+import { clearToken } from '../api/client'
+import type { LaneKey } from '../pages/LaneHub'
+
+type NavItem = { to: string; end?: boolean; ico: string; label: string }
+
+const LANE_META: Record = {
+ cn: { title: '中文用户', sub: 'Chinese · 特殊对待', mark: '中' },
+ intl: { title: '国际用户', sub: 'International · English', mark: 'EN' },
+}
+
+function laneNav(lane: LaneKey): NavItem[] {
+ const p = `/${lane}`
+ return [
+ { to: p, end: true, ico: '◈', label: '模块总览' },
+ { to: `${p}/switches`, ico: '⏻', label: '动态开关' },
+ { to: `${p}/events`, ico: '📊', label: '埋点' },
+ { to: `${p}/orders`, ico: '🧾', label: '订单' },
+ { to: `${p}/users`, ico: '👥', label: '用户' },
+ { to: `${p}/ntfy`, ico: '🔔', label: 'ntfy' },
+ { to: `${p}/docs`, ico: '✓', label: '部署说明' },
+ ]
+}
+
+function titleFromPath(lane: LaneKey, pathname: string) {
+ const items = laneNav(lane)
+ const hit = items.find((n) => (n.end ? pathname === n.to : pathname.startsWith(n.to)))
+ const mod = LANE_META[lane].title
+ return hit && !hit.end ? `${mod} · ${hit.label}` : mod
+}
+
+/** 已选模块后的壳:只显示当前模块侧栏;切模块回选择页 */
+export default function WebLayout() {
+ const nav = useNavigate()
+ const { pathname } = useLocation()
+ const { lane: laneParam } = useParams()
+ const lane: LaneKey = laneParam === 'cn' ? 'cn' : 'intl'
+ const meta = LANE_META[lane]
+ const [open, setOpen] = useState(false)
+
+ useEffect(() => {
+ setOpen(false)
+ }, [pathname])
+
+ useEffect(() => {
+ document.body.style.overflow = open ? 'hidden' : ''
+ return () => {
+ document.body.style.overflow = ''
+ }
+ }, [open])
+
+ function logout() {
+ clearToken()
+ nav('/login')
+ }
+
+ return (
+
+
+
+
+
{meta.mark}
+
+
{meta.title}
+
{titleFromPath(lane, pathname)}
+
+
+
+
+
+ {open && (
+
+ )
+}
diff --git a/apps/com/admin/src/main.tsx b/apps/com/admin/src/main.tsx
new file mode 100644
index 0000000..7f64a2d
--- /dev/null
+++ b/apps/com/admin/src/main.tsx
@@ -0,0 +1,13 @@
+import React from 'react'
+import ReactDOM from 'react-dom/client'
+import { BrowserRouter } from 'react-router-dom'
+import App from './App'
+import './styles.css'
+
+ReactDOM.createRoot(document.getElementById('root')!).render(
+
+
+
+
+ ,
+)
diff --git a/apps/com/admin/src/pages/Docs.tsx b/apps/com/admin/src/pages/Docs.tsx
new file mode 100644
index 0000000..3bbd0cc
--- /dev/null
+++ b/apps/com/admin/src/pages/Docs.tsx
@@ -0,0 +1,32 @@
+export default function Docs() {
+ return (
+
+
+
+
部署说明
+
源码与发布目标都与 .cn 隔离。
+
+
+
+
+ 本地
+ {`pnpm install
+pnpm dev:admin-com # :5174
+pnpm build:admin-com`}
+
+
+
+ 线上
+
+ -
+ 静态产物:
apps/com/admin/dist → 美国 VPS · admin.nomadro.com
+
+ -
+ 勿发布到
/www/wwwroot/admin.nomadro.cn(那是 .cn 微信/抖音后台)
+
+ - 门户 Next 若在美国机,与仓库根
src/ 的 .cn 部署分开构建、分开进程
+
+
+
+ )
+}
diff --git a/apps/com/admin/src/pages/Events.tsx b/apps/com/admin/src/pages/Events.tsx
new file mode 100644
index 0000000..7f12698
--- /dev/null
+++ b/apps/com/admin/src/pages/Events.tsx
@@ -0,0 +1,257 @@
+import { useCallback, useEffect, useMemo, useState } from 'react'
+import { api } from '../api/client'
+
+type TrackEvent = {
+ id: number
+ name: string
+ page: string | null
+ label: string | null
+ props: Record
+ openid: string
+ client: string
+ ts: number
+ created_at: number
+}
+
+const FILTERS = [
+ '',
+ 'session_start',
+ 'page_view',
+ 'btn_click',
+ 'read_start',
+ 'unlock_click',
+ 'pay_start',
+ 'pay_success',
+ 'pay_fail',
+ 'pay_cancel',
+ 'pay_order_created',
+ 'pay_deliver',
+ 'pay_click',
+ 'buy_click',
+ 'login_ok',
+ 'login_fail',
+ 'error',
+ 'app_launch',
+ 'join_group_open',
+ 'follow_show',
+ 'follow_click',
+ 'share_x',
+ 'feedback_submit',
+ 'book_complete',
+]
+
+const CLIENTS = ['', 'web_com', 'web_intl', 'web_cn', 'web', 'h5', 'weapp', 'tt', 'api', 'vip_web']
+
+function clientLabel(c: string) {
+ if (c === 'tt') return '抖音'
+ if (c === 'weapp') return '微信'
+ if (c === 'web_com') return 'nomadro.com'
+ if (c === 'web_intl') return 'Web·intl'
+ if (c === 'web_cn') return 'Web·cn'
+ if (c === 'vip_web') return 'VIP Web'
+ if (c === 'h5' || c === 'web') return 'Web/H5'
+ return c || '全部'
+}
+
+function fmtTime(ts: number) {
+ if (!ts) return '—'
+ const d = new Date(ts < 1e12 ? ts * 1000 : ts)
+ return d.toLocaleString('zh-CN', { hour12: false })
+}
+
+function shortId(id: string, n = 8) {
+ if (!id) return '—'
+ return id.length <= n ? id : `…${id.slice(-n)}`
+}
+
+function tone(name: string) {
+ if (name.includes('success') || name === 'login_ok' || name === 'pay_deliver') return 'ok'
+ if (name.includes('fail') || name === 'error' || name === 'login_fail') return 'bad'
+ if (name.includes('cancel')) return 'warn'
+ if (name.startsWith('pay_') || name.startsWith('join_')) return 'info'
+ return 'muted'
+}
+
+export default function Events() {
+ const [events, setEvents] = useState([])
+ const [filter, setFilter] = useState('')
+ const [clientFilter, setClientFilter] = useState('')
+ const [q, setQ] = useState('')
+ const [loading, setLoading] = useState(false)
+ const [err, setErr] = useState('')
+ const [openId, setOpenId] = useState(null)
+ const [auto, setAuto] = useState(false)
+
+ const load = useCallback(() => {
+ setLoading(true)
+ setErr('')
+ const qs = new URLSearchParams({ limit: '200' })
+ if (filter) qs.set('name', filter)
+ if (clientFilter) qs.set('client', clientFilter)
+ api(`/api/admin/track-events?${qs}`)
+ .then(setEvents)
+ .catch((e: Error) => setErr(e.message || '加载失败'))
+ .finally(() => setLoading(false))
+ }, [filter, clientFilter])
+
+ useEffect(() => {
+ load()
+ }, [load])
+
+ useEffect(() => {
+ if (!auto) return
+ const t = window.setInterval(load, 12000)
+ return () => window.clearInterval(t)
+ }, [auto, load])
+
+ const filtered = useMemo(() => {
+ const needle = q.trim().toLowerCase()
+ if (!needle) return events
+ return events.filter((ev) => {
+ const blob = [ev.name, ev.page, ev.label, ev.openid, ev.client, JSON.stringify(ev.props || {})]
+ .join(' ')
+ .toLowerCase()
+ return blob.includes(needle)
+ })
+ }, [events, q])
+
+ const topNames = useMemo(() => {
+ const map = new Map()
+ for (const ev of events) map.set(ev.name, (map.get(ev.name) || 0) + 1)
+ return [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6)
+ }, [events])
+
+ return (
+
+
+
+ {err ?
{err}
: null}
+
+
+
+ 当前结果
+ {filtered.length}
+
+
+ 渠道
+ {clientLabel(clientFilter)}
+
+
+ 高频
+
+ {topNames.length ? topNames.map(([n, c]) => `${n}×${c}`).join(' · ') : '—'}
+
+
+
+
+ {topNames.length ? (
+
+
+ {topNames.map(([n, c]) => (
+
+ ))}
+
+ ) : null}
+
+
+
+
+ setQ(e.target.value)}
+ />
+
+
+
+ {filtered.length ? (
+
+
+
+ | 时间 |
+ 事件 |
+ 页面 |
+ 标签 |
+ 用户 |
+ 端 |
+ |
+
+
+
+ {filtered.map((ev) => {
+ const open = openId === ev.id
+ const propsText = Object.keys(ev.props || {}).length
+ ? JSON.stringify(ev.props, null, 2)
+ : ''
+ return (
+
+ | {fmtTime(ev.ts || ev.created_at)} |
+
+ {ev.name}
+ {open && propsText ? {propsText} : null}
+ |
+ {ev.page || '—'} |
+ {ev.label || '—'} |
+ {shortId(ev.openid)} |
+ {clientLabel(ev.client)} |
+
+
+ |
+
+ )
+ })}
+
+
+ ) : (
+
{loading ? '加载中…' : '暂无埋点数据'}
+ )}
+
+
+ )
+}
diff --git a/apps/com/admin/src/pages/LaneHub.tsx b/apps/com/admin/src/pages/LaneHub.tsx
new file mode 100644
index 0000000..a2aa8d8
--- /dev/null
+++ b/apps/com/admin/src/pages/LaneHub.tsx
@@ -0,0 +1,267 @@
+/**
+ * 单受众模块运营台:/cn 或 /intl
+ * 入口级区分中文用户 vs 国际(英语为主),再进开关 / 埋点等。
+ */
+import { useCallback, useEffect, useState } from 'react'
+import { Link } from 'react-router-dom'
+import { api } from '../api/client'
+
+export type LaneKey = 'cn' | 'intl'
+
+type Lane = {
+ payEnabled: boolean
+ socialFollow: boolean
+ followChannel: 'wechat' | 'x' | 'none'
+ vipCta: string
+ homeLead: string
+ note?: string
+}
+
+type AudienceCfg = {
+ defaultLane: 'cn' | 'intl'
+ cn: Lane
+ intl: Lane
+ version?: number
+ updatedAt?: string
+}
+
+const META: Record<
+ LaneKey,
+ {
+ title: string
+ titleEn: string
+ eyebrow: string
+ detect: string
+ pay: string
+ follow: string
+ accent: string
+ }
+> = {
+ cn: {
+ title: '中文用户',
+ titleEn: 'Chinese',
+ eyebrow: '特殊对待 · Special lane',
+ detect: '微信内置 MicroMessenger / is-china-user → 本模块',
+ pay: 'zpay · 微信内 xpay',
+ follow: '公众号二维码',
+ accent: 'cn',
+ },
+ intl: {
+ title: '国际用户',
+ titleEn: 'International',
+ eyebrow: '.com 默认 · English-first',
+ detect: '非中文信号 → 本模块(日/越/泰可切语言)',
+ pay: 'Creem · NOWPayments',
+ follow: 'X / Twitter',
+ accent: 'intl',
+ },
+}
+
+function Switch({
+ checked,
+ onChange,
+ label,
+ disabled,
+}: {
+ checked: boolean
+ onChange: (v: boolean) => void
+ label: string
+ disabled?: boolean
+}) {
+ return (
+
+ )
+}
+
+export default function LaneHub({ lane }: { lane: LaneKey }) {
+ const meta = META[lane]
+ const [cfg, setCfg] = useState(null)
+ const [busy, setBusy] = useState(false)
+ const [msg, setMsg] = useState('')
+ const [err, setErr] = useState('')
+ const [vipCta, setVipCta] = useState('')
+ const [homeLead, setHomeLead] = useState('')
+
+ const load = useCallback(async () => {
+ setErr('')
+ const data = await api('/api/admin/audience')
+ setCfg(data)
+ const L = data[lane]
+ setVipCta(L.vipCta)
+ setHomeLead(L.homeLead)
+ }, [lane])
+
+ useEffect(() => {
+ load().catch((e: Error) => setErr(e.message || '加载失败'))
+ }, [load])
+
+ async function patchLane(partial: Partial, okHint: string) {
+ setBusy(true)
+ setMsg('')
+ setErr('')
+ try {
+ const data = await api('/api/admin/audience', {
+ method: 'PUT',
+ body: JSON.stringify({ [lane]: partial }),
+ })
+ setCfg(data)
+ setVipCta(data[lane].vipCta)
+ setHomeLead(data[lane].homeLead)
+ setMsg(okHint)
+ } catch (e: unknown) {
+ setErr(e instanceof Error ? e.message : '保存失败')
+ await load().catch(() => undefined)
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ const L = cfg?.[lane]
+ const other: LaneKey = lane === 'cn' ? 'intl' : 'cn'
+
+ const tools = [
+ { to: `/${lane}/switches`, ico: '⏻', title: '动态开关', desc: '页面 / flag / VIP 入口' },
+ { to: `/${lane}/events`, ico: '📊', title: '埋点', desc: '本轨相关行为回放' },
+ { to: `/${lane}/orders`, ico: '🧾', title: '订单', desc: '支付与发货' },
+ { to: `/${lane}/users`, ico: '👥', title: '用户', desc: '解锁与干预' },
+ { to: `/${lane}/ntfy`, ico: '🔔', title: 'ntfy', desc: '通知试推' },
+ ]
+
+ return (
+
+
+
+ {msg ?
{msg}
: null}
+ {err ?
{err}
: null}
+
+
+ {tools.map((t) => (
+
+
+ {t.ico}
+
+ {t.title}
+ {t.desc}
+
+ ))}
+
+
+ {!L ? (
+
加载本轨配置…
+ ) : (
+
+
+
本轨开关与文案
+
{L.note || '写入 remote-config.audience.' + lane}
+
+
+
+
+
+
void patchLane({ payEnabled: v }, `支付已${v ? '开' : '关'}`)}
+ />
+
+
+
+
void patchLane({ socialFollow: v }, `关注已${v ? '开' : '关'}`)}
+ />
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ )}
+
+ )
+}
diff --git a/apps/com/admin/src/pages/Login.tsx b/apps/com/admin/src/pages/Login.tsx
new file mode 100644
index 0000000..76215ae
--- /dev/null
+++ b/apps/com/admin/src/pages/Login.tsx
@@ -0,0 +1,63 @@
+import { FormEvent, useState } from 'react'
+import { useNavigate } from 'react-router-dom'
+import { api, setToken } from '../api/client'
+
+export default function Login() {
+ const nav = useNavigate()
+ const [username, setUsername] = useState('hackrobot')
+ const [password, setPassword] = useState('')
+ const [err, setErr] = useState('')
+ const [loading, setLoading] = useState(false)
+
+ async function onSubmit(e: FormEvent) {
+ e.preventDefault()
+ setLoading(true)
+ setErr('')
+ try {
+ const data = await api<{ token: string }>('/api/admin/login', {
+ method: 'POST',
+ body: JSON.stringify({ username, password }),
+ })
+ setToken(data.token)
+ nav('/')
+ } catch (ex: unknown) {
+ setErr(ex instanceof Error ? ex.message : '登录失败')
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ return (
+
+ )
+}
diff --git a/apps/com/admin/src/pages/ModuleSelect.tsx b/apps/com/admin/src/pages/ModuleSelect.tsx
new file mode 100644
index 0000000..24f0d7c
--- /dev/null
+++ b/apps/com/admin/src/pages/ModuleSelect.tsx
@@ -0,0 +1,75 @@
+import { useNavigate } from 'react-router-dom'
+import { clearToken } from '../api/client'
+
+/**
+ * 登录后中间页:先选模块,再进壳。
+ * 对齐 admin.nomadro.cn 的 PlatformSelect(微信 / 抖音)。
+ */
+export default function ModuleSelect() {
+ const nav = useNavigate()
+
+ function logout() {
+ clearToken()
+ nav('/login')
+ }
+
+ return (
+
+
+
+
+
W
+
+
选择运营模块
+
+ admin.nomadro.com · 登录后先选受众模块
+
+ 中文用户特殊对待 · 国际线为 .com 默认
+
+
+
+
+
+
+
+
+
+
+
+
+ )
+}
diff --git a/apps/com/admin/src/pages/Ntfy.tsx b/apps/com/admin/src/pages/Ntfy.tsx
new file mode 100644
index 0000000..f878fb1
--- /dev/null
+++ b/apps/com/admin/src/pages/Ntfy.tsx
@@ -0,0 +1,137 @@
+import { useCallback, useEffect, useState } from 'react'
+import { api } from '../api/client'
+
+type NtfyStatus = {
+ enabled: boolean
+ baseUrl: string
+ topic: string
+ hasToken: boolean
+ publicHint: string
+}
+
+export default function Ntfy() {
+ const [status, setStatus] = useState(null)
+ const [title, setTitle] = useState('[WebAdmin] 试推')
+ const [message, setMessage] = useState('admin.nomadro.com 通知通路正常')
+ const [loading, setLoading] = useState(true)
+ const [busy, setBusy] = useState(false)
+ const [err, setErr] = useState('')
+ const [msg, setMsg] = useState('')
+
+ const load = useCallback(() => {
+ setLoading(true)
+ setErr('')
+ api('/api/admin/ops/ntfy')
+ .then(setStatus)
+ .catch((e: Error) => setErr(e.message || '加载失败'))
+ .finally(() => setLoading(false))
+ }, [])
+
+ useEffect(() => {
+ load()
+ }, [load])
+
+ async function sendTest() {
+ setBusy(true)
+ setMsg('')
+ setErr('')
+ try {
+ const res = await api<{ ok: boolean; topic: string }>('/api/admin/ops/ntfy/test', {
+ method: 'POST',
+ body: JSON.stringify({ title, message, priority: 3 }),
+ })
+ setMsg(res.ok ? `已推送到 topic「${res.topic || status?.topic || '—'}」` : '推送失败(检查 ntfy 服务与 token)')
+ await load()
+ } catch (e: unknown) {
+ setErr(e instanceof Error ? e.message : '试推失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ return (
+
+
+
+ {msg ?
{msg}
: null}
+ {err ?
{err}
: null}
+
+
+
+ 开关
+ {status ? (status.enabled ? '已启用' : '已关闭') : '…'}
+
+
+ Topic
+ {status?.topic || '—'}
+
+
+ Token
+ {status?.hasToken ? '已配置' : '未配置'}
+
+
+
+
+ 通路信息
+
+ -
+ 机内地址:
{status?.baseUrl || '—'}
+
+ -
+ 公开订阅:{' '}
+ {status?.publicHint ? (
+
+ {status.publicHint}
+
+ ) : (
+ '—'
+ )}
+
+ - 门户 nomadro.com:会话 / 支付 / 登录 / 关注 / 购买 / 异常 → Next
/api/track 推 ntfy,并转发 API 入库
+ - 小程序关键事件仍由 API track 服务推送;Web 客户端只入库避免双推
+
+
+
+
+
+ )
+}
diff --git a/apps/com/admin/src/pages/Orders.tsx b/apps/com/admin/src/pages/Orders.tsx
new file mode 100644
index 0000000..b779e9a
--- /dev/null
+++ b/apps/com/admin/src/pages/Orders.tsx
@@ -0,0 +1,207 @@
+import { useCallback, useEffect, useMemo, useState } from 'react'
+import { api } from '../api/client'
+
+type Order = {
+ out_trade_no: string
+ wx_order_id: string | null
+ openid: string
+ book_id: string
+ amount_fen: number
+ status: string
+ delivered: number
+ created_at: number
+}
+
+type StatusTab = 'all' | 'paid' | 'pending' | 'other'
+
+function fmtTime(ts: number) {
+ if (!ts) return '—'
+ const d = new Date(ts < 1e12 ? ts * 1000 : ts)
+ return d.toLocaleString('zh-CN', { hour12: false })
+}
+
+function fmtYuan(fen: number) {
+ return `¥${(fen / 100).toFixed(2)}`
+}
+
+function shortId(id: string, n = 10) {
+ if (!id) return '—'
+ return id.length <= n ? id : `…${id.slice(-n)}`
+}
+
+function statusLabel(status: string) {
+ const s = (status || '').toLowerCase()
+ if (s.includes('paid') || s.includes('success')) return '已支付'
+ if (s.includes('pend') || s.includes('creat') || s.includes('wait')) return '待支付'
+ if (s.includes('cancel')) return '已取消'
+ if (s.includes('fail')) return '失败'
+ if (s.includes('refund')) return '退款'
+ return status || '未知'
+}
+
+function statusTone(status: string) {
+ const s = (status || '').toLowerCase()
+ if (s.includes('paid') || s.includes('success')) return 'ok'
+ if (s.includes('pend') || s.includes('creat') || s.includes('wait')) return 'warn'
+ if (s.includes('fail') || s.includes('cancel') || s.includes('refund')) return 'bad'
+ return 'muted'
+}
+
+function isPaid(status: string) {
+ const s = (status || '').toLowerCase()
+ return s.includes('paid') || s.includes('success')
+}
+
+function isPending(status: string) {
+ const s = (status || '').toLowerCase()
+ return s.includes('pend') || s.includes('creat') || s.includes('wait')
+}
+
+export default function Orders() {
+ const [orders, setOrders] = useState([])
+ const [loading, setLoading] = useState(true)
+ const [err, setErr] = useState('')
+ const [q, setQ] = useState('')
+ const [tab, setTab] = useState('all')
+
+ const load = useCallback(() => {
+ setLoading(true)
+ setErr('')
+ api('/api/admin/orders')
+ .then(setOrders)
+ .catch((e: Error) => setErr(e.message || '加载失败'))
+ .finally(() => setLoading(false))
+ }, [])
+
+ useEffect(() => {
+ load()
+ }, [load])
+
+ const stats = useMemo(() => {
+ let paid = 0
+ let pending = 0
+ let amount = 0
+ for (const o of orders) {
+ if (isPaid(o.status)) {
+ paid += 1
+ amount += o.amount_fen || 0
+ } else if (isPending(o.status)) pending += 1
+ }
+ return { total: orders.length, paid, pending, amount }
+ }, [orders])
+
+ const filtered = useMemo(() => {
+ const needle = q.trim().toLowerCase()
+ return orders.filter((o) => {
+ if (tab === 'paid' && !isPaid(o.status)) return false
+ if (tab === 'pending' && !isPending(o.status)) return false
+ if (tab === 'other' && (isPaid(o.status) || isPending(o.status))) return false
+ if (!needle) return true
+ const blob = [o.out_trade_no, o.openid, o.book_id, o.status, o.wx_order_id || ''].join(' ').toLowerCase()
+ return blob.includes(needle)
+ })
+ }, [orders, q, tab])
+
+ return (
+
+
+
+ {err ?
{err}
: null}
+
+
+
+ 全部
+ {stats.total}
+
+
+ 已支付
+ {stats.paid}
+
+
+ 待支付
+ {stats.pending}
+
+
+ 成交额
+ {fmtYuan(stats.amount)}
+
+
+
+
+ {(
+ [
+ ['all', '全部'],
+ ['paid', '已支付'],
+ ['pending', '待支付'],
+ ['other', '其他'],
+ ] as const
+ ).map(([k, label]) => (
+
+ ))}
+
+
+
+ setQ(e.target.value)}
+ />
+
+
+
+ {filtered.length ? (
+
+
+
+ | 时间 |
+ 单号 |
+ 用户 |
+ 商品 |
+ 金额 |
+ 状态 |
+ 发货 |
+
+
+
+ {filtered.map((o) => (
+
+ | {fmtTime(o.created_at)} |
+
+ {shortId(o.out_trade_no, 14)}
+ |
+ {shortId(o.openid)} |
+ {o.book_id === '__vip__' ? 'VIP' : o.book_id || '—'} |
+ {fmtYuan(o.amount_fen || 0)} |
+
+
+ {statusLabel(o.status)}
+
+ |
+ {o.delivered ? '已发' : '—'} |
+
+ ))}
+
+
+ ) : (
+
{loading ? '加载中…' : '暂无订单'}
+ )}
+
+
+ )
+}
diff --git a/apps/com/admin/src/pages/Switches.tsx b/apps/com/admin/src/pages/Switches.tsx
new file mode 100644
index 0000000..5456886
--- /dev/null
+++ b/apps/com/admin/src/pages/Switches.tsx
@@ -0,0 +1,364 @@
+/**
+ * Web 动态开关 — 写入 remote-config;门户 / H5 约数秒热更新。
+ * 不引入微信提审 / 抖音专属控件。
+ */
+import { useCallback, useEffect, useMemo, useState } from 'react'
+import { api } from '../api/client'
+
+type Mod = { enabled: boolean; title: string; tabLabel?: string; note?: string }
+
+type SwitchesCfg = {
+ modules: Record
+ flags: {
+ payEnabled: boolean
+ socialFollow: boolean
+ offlineBadge: boolean
+ joinGroupAction: 'popup' | 'vip'
+ memoTrialBrowse?: boolean
+ joinGroupWechat?: boolean
+ }
+ copy: {
+ homeBrand: string
+ homeTagline: string
+ homeLead: string
+ vipCta: string
+ wechatOaName?: string
+ memoUnlockCta?: string
+ }
+ vipEntries: Record
+ vipHero?: {
+ heroEyebrow: string
+ heroTitleAccent: string
+ heroTitleRest: string
+ heroLead: string
+ }
+ version?: number
+ updatedAt?: string
+}
+
+type TabKey = 'pages' | 'flags' | 'vip' | 'copy'
+
+const TABS: Array<{ key: TabKey; label: string }> = [
+ { key: 'pages', label: '页面' },
+ { key: 'flags', label: '功能' },
+ { key: 'vip', label: 'VIP 入口' },
+ { key: 'copy', label: '文案' },
+]
+
+const PAGE_MODS = [
+ { key: 'home', label: '首页', ico: '⌂', desc: '门户首页模块' },
+ { key: 'nav', label: '出海导航', ico: '🧭', desc: '导航页入口' },
+ { key: 'book', label: '数字游民小册', ico: '📕', desc: '小册阅读' },
+ { key: 'community', label: '旅居社群', ico: '🏕️', desc: '社群入口' },
+ { key: 'social', label: '游民社区', ico: '💕', desc: '社交大厅;关则拦截入口' },
+ { key: 'vip', label: 'VIP 中心', ico: '👑', desc: '会员落地;关则加群改弹引导' },
+ { key: 'destinations', label: '目的地', ico: '📍', desc: '目的地列表' },
+ { key: 'meetups', label: '活动', ico: '📅', desc: '活动入口' },
+] as const
+
+const VIP_ENTRIES = [
+ { key: 'showStats', label: '数据条', desc: '落地页统计数字' },
+ { key: 'showTopics', label: '模块入口', desc: '社群 / 商城卡片' },
+ { key: 'showVideos', label: '视频教程', desc: '视频课区块' },
+ { key: 'showEbooks', label: '电子书', desc: '电子书区块' },
+ { key: 'showCompare', label: '对比表', desc: '单买 vs 会员' },
+ { key: 'showFaq', label: 'FAQ', desc: '常见问题' },
+ { key: 'showCta', label: '开通 CTA', desc: '底部立即加入' },
+ { key: 'reviewMode', label: '审核模式', desc: '隐藏促销诱导' },
+] as const
+
+function Switch({
+ checked,
+ onChange,
+ label,
+ disabled,
+}: {
+ checked: boolean
+ onChange: (v: boolean) => void
+ label: string
+ disabled?: boolean
+}) {
+ return (
+
+ )
+}
+
+export default function Switches() {
+ const [cfg, setCfg] = useState(null)
+ const [busy, setBusy] = useState(false)
+ const [msg, setMsg] = useState('')
+ const [err, setErr] = useState('')
+ const [tab, setTab] = useState('pages')
+ const [draftCopy, setDraftCopy] = useState({
+ homeBrand: '',
+ homeTagline: '',
+ homeLead: '',
+ vipCta: '',
+ })
+
+ const load = useCallback(async () => {
+ setErr('')
+ const data = await api('/api/admin/weapp/switches')
+ setCfg(data)
+ setDraftCopy({
+ homeBrand: data.copy?.homeBrand || '',
+ homeTagline: data.copy?.homeTagline || '',
+ homeLead: data.copy?.homeLead || '',
+ vipCta: data.copy?.vipCta || '',
+ })
+ }, [])
+
+ useEffect(() => {
+ load().catch((e: Error) => setErr(e.message || '加载失败'))
+ }, [load])
+
+ async function patch(body: Record, okHint: string) {
+ setBusy(true)
+ setMsg('')
+ setErr('')
+ try {
+ const data = await api('/api/admin/weapp/switches', {
+ method: 'PUT',
+ body: JSON.stringify(body),
+ })
+ setCfg(data)
+ setDraftCopy({
+ homeBrand: data.copy?.homeBrand || '',
+ homeTagline: data.copy?.homeTagline || '',
+ homeLead: data.copy?.homeLead || '',
+ vipCta: data.copy?.vipCta || '',
+ })
+ setMsg(okHint)
+ } catch (e: unknown) {
+ setErr(e instanceof Error ? e.message : '保存失败')
+ await load().catch(() => undefined)
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ const onCount = useMemo(() => {
+ if (!cfg) return 0
+ return PAGE_MODS.filter((m) => cfg.modules[m.key]?.enabled !== false).length
+ }, [cfg])
+
+ if (!cfg) {
+ return (
+
+
+ {err ?
{err}
: null}
+
+ )
+ }
+
+ return (
+
+
+ 动态开关
+
+ 页面显隐、功能 flag、VIP 入口与文案。写入 remote-config,Web 端热更新。
+
+
+ 版本 v{cfg.version ?? '—'}
+
+ 页面开启 {onCount}/{PAGE_MODS.length}
+
+ {cfg.updatedAt ? {cfg.updatedAt} : null}
+
+
+
+ {msg ?
{msg}
: null}
+ {err ?
{err}
: null}
+
+
+
+ {tab === 'pages' ? (
+
+ 页面模块
+ 关闭后对应入口隐藏或拦截
+
+ {PAGE_MODS.map((m) => {
+ const on = cfg.modules[m.key]?.enabled !== false
+ return (
+
+
+
+ {m.ico}
+
+ {
+ if (m.key === 'vip') {
+ void patch(
+ {
+ modules: { vip: { enabled: v } },
+ flags: { joinGroupAction: v ? 'vip' : 'popup' },
+ },
+ v ? 'VIP 已开启 · 加群跳会员' : 'VIP 已关闭 · 加群改弹窗',
+ )
+ return
+ }
+ void patch(
+ { modules: { [m.key]: { enabled: v } } },
+ `${m.label}已${v ? '开启' : '关闭'}`,
+ )
+ }}
+ />
+
+ {m.label}
+ {m.desc}
+ {on ? 'ON' : 'OFF'}
+
+ )
+ })}
+
+
+ ) : null}
+
+ {tab === 'flags' ? (
+
+ 功能 Flag
+
+ {(
+ [
+ { key: 'payEnabled', label: '支付总开关', desc: '关闭后隐藏付费 CTA' },
+ { key: 'socialFollow', label: '关注引导', desc: '公众号 / X 关注弹窗' },
+ { key: 'offlineBadge', label: '离线角标', desc: '展示「本地数据」提示' },
+ ] as const
+ ).map((f) => {
+ const on = Boolean(cfg.flags[f.key])
+ return (
+
+
+
+ void patch({ flags: { [f.key]: v } }, `${f.label}已${v ? '开启' : '关闭'}`)
+ }
+ />
+
+ )
+ })}
+
+
+
加群行为
+
popup=弹窗 · vip=跳会员页
+
+
+
+
+
+ ) : null}
+
+ {tab === 'vip' ? (
+
+ VIP 落地入口
+
+ {VIP_ENTRIES.map((f) => {
+ const on = cfg.vipEntries?.[f.key] !== false
+ return (
+
+
+
+ void patch(
+ { vipEntries: { [f.key]: v } },
+ `${f.label}已${v ? '开启' : '关闭'}`,
+ )
+ }
+ />
+
+ )
+ })}
+
+
+ ) : null}
+
+ {tab === 'copy' ? (
+
+ 门户文案
+
+ {(
+ [
+ ['homeBrand', '品牌名'],
+ ['homeTagline', '副标题'],
+ ['homeLead', '导语'],
+ ['vipCta', 'VIP CTA'],
+ ] as const
+ ).map(([key, label]) => (
+
+ ))}
+
+
+
+
+
+ ) : null}
+
+ )
+}
diff --git a/apps/com/admin/src/pages/Users.tsx b/apps/com/admin/src/pages/Users.tsx
new file mode 100644
index 0000000..621e168
--- /dev/null
+++ b/apps/com/admin/src/pages/Users.tsx
@@ -0,0 +1,276 @@
+import { useCallback, useEffect, useMemo, useState } from 'react'
+import { api } from '../api/client'
+
+type UnlockRow = { book_id: string; unlocked_at: number; source: string }
+
+type UserRow = {
+ openid: string
+ nickname?: string | null
+ status?: string
+ notes?: string | null
+ updated_at: number
+ unlocked_default: boolean
+ unlocked_vip?: boolean
+ unlocks: UnlockRow[]
+}
+
+type Tab = 'all' | 'unlocked' | 'vip' | 'locked' | 'blocked'
+
+function fmtTime(ts: number) {
+ if (!ts) return '—'
+ const d = new Date(ts < 1e12 ? ts * 1000 : ts)
+ return d.toLocaleString('zh-CN', { hour12: false })
+}
+
+function shortId(id: string, n = 10) {
+ if (!id) return '—'
+ return id.length <= n ? id : `…${id.slice(-n)}`
+}
+
+export default function Users() {
+ const [users, setUsers] = useState([])
+ const [q, setQ] = useState('')
+ const [tab, setTab] = useState('all')
+ const [err, setErr] = useState('')
+ const [msg, setMsg] = useState('')
+ const [loading, setLoading] = useState(true)
+ const [busy, setBusy] = useState('')
+ const [manualOpenid, setManualOpenid] = useState('')
+
+ const refresh = useCallback(async (search = q) => {
+ setLoading(true)
+ setErr('')
+ try {
+ const qs = search.trim() ? `?q=${encodeURIComponent(search.trim())}` : ''
+ setUsers(await api(`/api/admin/users${qs}`))
+ } catch (e: unknown) {
+ setErr(e instanceof Error ? e.message : String(e))
+ } finally {
+ setLoading(false)
+ }
+ }, [q])
+
+ useEffect(() => {
+ void refresh('')
+ }, [])
+
+ const counts = useMemo(() => {
+ let unlocked = 0
+ let vip = 0
+ let locked = 0
+ let blocked = 0
+ for (const u of users) {
+ if ((u.status || 'active') === 'blocked') blocked += 1
+ if (u.unlocked_vip) vip += 1
+ if (u.unlocked_default) unlocked += 1
+ else locked += 1
+ }
+ return { total: users.length, unlocked, vip, locked, blocked }
+ }, [users])
+
+ const filtered = useMemo(() => {
+ return users.filter((u) => {
+ if (tab === 'unlocked') return u.unlocked_default
+ if (tab === 'vip') return Boolean(u.unlocked_vip)
+ if (tab === 'locked') return !u.unlocked_default
+ if (tab === 'blocked') return (u.status || 'active') === 'blocked'
+ return true
+ })
+ }, [users, tab])
+
+ async function unlock(openid: string) {
+ setBusy(openid)
+ setMsg('')
+ setErr('')
+ try {
+ await api('/api/admin/unlock', {
+ method: 'POST',
+ body: JSON.stringify({ openid, book_id: 'default' }),
+ })
+ setMsg(`已解锁 ${shortId(openid)}`)
+ await refresh()
+ } catch (e: unknown) {
+ setErr(e instanceof Error ? e.message : '解锁失败')
+ } finally {
+ setBusy('')
+ }
+ }
+
+ async function revoke(openid: string) {
+ setBusy(openid)
+ setMsg('')
+ setErr('')
+ try {
+ await api('/api/admin/revoke-unlock', {
+ method: 'POST',
+ body: JSON.stringify({ openid, book_id: 'default' }),
+ })
+ setMsg(`已撤销 ${shortId(openid)}`)
+ await refresh()
+ } catch (e: unknown) {
+ setErr(e instanceof Error ? e.message : '撤销失败')
+ } finally {
+ setBusy('')
+ }
+ }
+
+ return (
+
+
+
+
+
+
+ {msg ?
{msg}
: null}
+ {err ?
{err}
: null}
+
+
+
+ 全部
+ {counts.total}
+
+
+ 已解锁
+ {counts.unlocked}
+
+
+ VIP
+ {counts.vip}
+
+
+ 未解锁
+ {counts.locked}
+
+
+ 封禁
+ {counts.blocked}
+
+
+
+
+ {(
+ [
+ ['all', '全部'],
+ ['unlocked', '已解锁'],
+ ['vip', 'VIP'],
+ ['locked', '未解锁'],
+ ['blocked', '封禁'],
+ ] as const
+ ).map(([k, label]) => (
+
+ ))}
+
+
+
+ setQ(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') void refresh()
+ }}
+ />
+
+
+
+
+
+
+ {filtered.length ? (
+
+
+
+ | 用户 |
+ 昵称 |
+ 状态 |
+ 解锁 |
+ 更新 |
+ 操作 |
+
+
+
+ {filtered.map((u) => (
+
+
+ {shortId(u.openid)}
+ |
+ {u.nickname || '—'} |
+
+
+ {u.status || 'active'}
+
+ |
+
+ {u.unlocked_vip ? 'VIP' : u.unlocked_default ? 'default' : '—'}
+ |
+ {fmtTime(u.updated_at)} |
+
+
+ {!u.unlocked_default ? (
+
+ ) : (
+
+ )}
+
+ |
+
+ ))}
+
+
+ ) : (
+
{loading ? '加载中…' : '暂无用户'}
+ )}
+
+
+ )
+}
diff --git a/apps/com/admin/src/styles.css b/apps/com/admin/src/styles.css
new file mode 100644
index 0000000..8dfcaa5
--- /dev/null
+++ b/apps/com/admin/src/styles.css
@@ -0,0 +1,1128 @@
+:root {
+ --bg: #0c0c0f;
+ --panel: #141418;
+ --line: rgba(245, 158, 11, 0.18);
+ --text: #f4f4f5;
+ --muted: #a1a1aa;
+ --accent: #f59e0b;
+ --accent-2: #38bdf8;
+ --danger: #f87171;
+ --font-display: system-ui, -apple-system, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
+ --font-body: system-ui, -apple-system, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
+}
+
+* {
+ box-sizing: border-box;
+}
+html,
+body,
+#root {
+ min-height: 100%;
+ margin: 0;
+}
+body {
+ font-family: var(--font-body);
+ color: var(--text);
+ background:
+ radial-gradient(800px 420px at 10% 0%, rgba(245, 158, 11, 0.14), transparent 55%),
+ radial-gradient(640px 360px at 90% 10%, rgba(56, 189, 248, 0.08), transparent 50%),
+ var(--bg);
+}
+
+a {
+ color: inherit;
+ text-decoration: none;
+}
+button,
+a,
+input {
+ touch-action: manipulation;
+}
+
+/* login */
+.login-page {
+ min-height: 100vh;
+ display: grid;
+ place-items: center;
+ padding: 24px;
+ position: relative;
+}
+.login-bg {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ background: radial-gradient(600px 360px at 50% 0%, rgba(245, 158, 11, 0.12), transparent 60%);
+}
+.login-card {
+ position: relative;
+ width: min(420px, 100%);
+ background: rgba(20, 20, 24, 0.92);
+ border: 1px solid var(--line);
+ border-radius: 20px;
+ padding: 28px 24px;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+}
+.login-brand {
+ display: flex;
+ gap: 12px;
+ align-items: center;
+ margin-bottom: 8px;
+}
+.login-mark {
+ width: 48px;
+ height: 48px;
+ border-radius: 14px;
+ display: grid;
+ place-items: center;
+ font-weight: 800;
+ background: linear-gradient(135deg, #f59e0b, #fbbf24);
+ color: #1c1408;
+}
+.login-brand h1 {
+ margin: 0 0 4px;
+ font-size: 22px;
+ font-family: var(--font-display);
+}
+.login-brand p {
+ margin: 0;
+ color: var(--muted);
+ font-size: 13px;
+}
+.login-card label {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ font-size: 13px;
+ color: var(--muted);
+}
+.login-card input {
+ border: 1px solid var(--line);
+ background: #0c0c0f;
+ color: var(--text);
+ border-radius: 12px;
+ padding: 12px 14px;
+ min-height: 44px;
+ font-size: 16px;
+}
+.login-card button {
+ margin-top: 6px;
+ min-height: 46px;
+ border: 0;
+ border-radius: 12px;
+ font-weight: 700;
+ cursor: pointer;
+ background: linear-gradient(135deg, #f59e0b, #d97706);
+ color: #1c1408;
+}
+.login-card button:disabled {
+ opacity: 0.6;
+ cursor: not-allowed;
+}
+.error {
+ color: var(--danger);
+ font-size: 13px;
+}
+.login-hint {
+ margin: 0;
+ color: var(--muted);
+ font-size: 12px;
+ line-height: 1.45;
+}
+
+/* shell */
+.com-shell {
+ display: grid;
+ grid-template-columns: 260px 1fr;
+ min-height: 100vh;
+ min-height: 100dvh;
+}
+.com-topbar {
+ display: none;
+}
+.com-nav-scrim {
+ display: none;
+}
+.com-side {
+ border-right: 1px solid var(--line);
+ padding: 28px 18px;
+ display: flex;
+ flex-direction: column;
+ gap: 18px;
+ background: rgba(10, 10, 12, 0.85);
+}
+.com-logo {
+ display: flex;
+ gap: 12px;
+ align-items: center;
+}
+.com-mark,
+.com-topbar-mark {
+ width: 42px;
+ height: 42px;
+ border-radius: 12px;
+ display: grid;
+ place-items: center;
+ font-weight: 800;
+ background: linear-gradient(135deg, #f59e0b, #fbbf24);
+ color: #1c1408;
+ flex-shrink: 0;
+}
+.com-title {
+ font-family: var(--font-display);
+ font-size: 15px;
+}
+.com-sub {
+ color: var(--muted);
+ font-size: 12px;
+}
+.com-pill {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 12px;
+ color: var(--muted);
+ padding: 8px 10px;
+ border-radius: 999px;
+ border: 1px solid var(--line);
+}
+.com-pill-dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--accent);
+ box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.2);
+}
+.com-nav {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ flex: 1;
+}
+.com-nav a {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 12px 14px;
+ border-radius: 12px;
+ color: var(--muted);
+ min-height: 44px;
+}
+.com-nav a.active,
+.com-nav a:hover {
+ background: rgba(245, 158, 11, 0.12);
+ color: var(--text);
+}
+.com-nav-ico {
+ width: 1.25em;
+ text-align: center;
+}
+.com-logout {
+ border: 1px solid var(--line);
+ background: transparent;
+ color: var(--muted);
+ border-radius: 12px;
+ padding: 10px 12px;
+ min-height: 44px;
+ cursor: pointer;
+}
+.com-main {
+ padding: 32px 36px 60px;
+ min-width: 0;
+}
+
+.com-page-head {
+ margin-bottom: 24px;
+}
+.com-page-head h1 {
+ margin: 0 0 8px;
+ font-family: var(--font-display);
+ font-size: 30px;
+}
+.com-page-head p {
+ margin: 0;
+ color: var(--muted);
+ line-height: 1.55;
+ max-width: 52rem;
+}
+.com-page-head code {
+ color: var(--accent-2);
+}
+
+.com-stat-grid {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 14px;
+ margin-bottom: 22px;
+}
+.com-stat {
+ border: 1px solid var(--line);
+ border-radius: 16px;
+ padding: 16px;
+ background: rgba(20, 20, 24, 0.7);
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+.com-stat-label {
+ color: var(--muted);
+ font-size: 12px;
+}
+.com-stat strong {
+ font-size: 18px;
+ font-family: var(--font-display);
+}
+.com-stat-note {
+ color: var(--muted);
+ font-size: 12px;
+}
+
+.com-panel {
+ border: 1px solid var(--line);
+ border-radius: 16px;
+ padding: 18px 20px;
+ background: rgba(20, 20, 24, 0.7);
+ margin-bottom: 16px;
+}
+.com-panel h2 {
+ margin: 0 0 12px;
+ font-size: 16px;
+}
+.com-list {
+ margin: 0;
+ padding-left: 1.2em;
+ color: var(--muted);
+ line-height: 1.7;
+}
+.com-list strong {
+ color: var(--text);
+}
+.com-list code {
+ color: var(--accent-2);
+}
+.com-pre {
+ margin: 0;
+ padding: 14px;
+ border-radius: 12px;
+ background: #09090b;
+ border: 1px solid var(--line);
+ overflow: auto;
+ font-size: 13px;
+ line-height: 1.5;
+}
+
+.com-module-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
+ gap: 14px;
+}
+.com-module-card {
+ border: 1px solid var(--line);
+ border-radius: 16px;
+ padding: 16px;
+ background: rgba(20, 20, 24, 0.7);
+}
+.com-module-top {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 8px;
+}
+.com-module-card p {
+ margin: 0;
+ color: var(--muted);
+ font-size: 13px;
+ line-height: 1.5;
+}
+.com-badge {
+ font-size: 11px;
+ font-weight: 700;
+ padding: 4px 8px;
+ border-radius: 999px;
+ color: var(--accent);
+ border: 1px solid rgba(245, 158, 11, 0.35);
+ background: rgba(245, 158, 11, 0.1);
+}
+
+@media (max-width: 860px) {
+ .com-shell {
+ grid-template-columns: 1fr;
+ }
+ .com-topbar {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 12px;
+ border-bottom: 1px solid var(--line);
+ position: sticky;
+ top: 0;
+ z-index: 20;
+ background: rgba(12, 12, 15, 0.92);
+ backdrop-filter: blur(10px);
+ }
+ .com-topbar-menu {
+ width: 44px;
+ height: 44px;
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ background: transparent;
+ display: grid;
+ place-content: center;
+ gap: 5px;
+ padding: 0;
+ }
+ .com-topbar-menu span {
+ display: block;
+ width: 18px;
+ height: 2px;
+ background: var(--text);
+ }
+ .com-topbar-brand {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex: 1;
+ min-width: 0;
+ }
+ .com-topbar-title {
+ font-weight: 700;
+ font-size: 14px;
+ }
+ .com-topbar-sub {
+ color: var(--muted);
+ font-size: 12px;
+ }
+ .com-topbar-action {
+ border: 1px solid var(--line);
+ background: transparent;
+ color: var(--muted);
+ border-radius: 12px;
+ min-height: 40px;
+ padding: 0 12px;
+ cursor: pointer;
+ }
+ .com-side {
+ position: fixed;
+ inset: 0 auto 0 0;
+ width: min(280px, 86vw);
+ z-index: 30;
+ transform: translateX(-105%);
+ transition: transform 0.2s ease;
+ }
+ .com-shell--nav-open .com-side {
+ transform: translateX(0);
+ }
+ .com-nav-scrim {
+ display: block;
+ position: fixed;
+ inset: 0;
+ z-index: 25;
+ border: 0;
+ background: rgba(0, 0, 0, 0.55);
+ }
+ .com-main {
+ padding: 20px 16px 40px;
+ }
+ .com-stat-grid {
+ grid-template-columns: 1fr;
+ }
+ .com-stat-grid-5,
+ .com-stat-grid-6,
+ .com-chart-grid,
+ .com-hub-grid,
+ .com-switch-grid,
+ .com-form-grid {
+ grid-template-columns: 1fr;
+ }
+ .com-page-head-row {
+ flex-direction: column;
+ }
+ .com-toolbar {
+ flex-direction: column;
+ }
+ .com-table {
+ min-width: 640px;
+ }
+}
+
+/* —— real ops UI —— */
+.com-page-head-row {
+ display: flex;
+ justify-content: space-between;
+ align-items: flex-start;
+ gap: 16px;
+}
+.com-stat-grid-5 {
+ grid-template-columns: repeat(5, minmax(0, 1fr));
+}
+.com-stat-grid-6 {
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+}
+.com-stat-link {
+ transition: border-color 0.15s ease, transform 0.15s ease;
+}
+.com-stat-link:hover {
+ border-color: rgba(245, 158, 11, 0.45);
+ transform: translateY(-1px);
+}
+.com-stat-warn {
+ border-color: rgba(248, 113, 113, 0.35);
+}
+.com-stat strong.is-loading {
+ opacity: 0.5;
+}
+
+.com-btn,
+.com-btn-ghost,
+.com-btn-sm {
+ min-height: 44px;
+ border-radius: 12px;
+ padding: 0 16px;
+ font-weight: 650;
+ cursor: pointer;
+ border: 1px solid transparent;
+ font-size: 14px;
+}
+.com-btn {
+ background: linear-gradient(135deg, #f59e0b, #d97706);
+ color: #1c1408;
+}
+.com-btn:disabled {
+ opacity: 0.55;
+ cursor: not-allowed;
+}
+.com-btn-ghost {
+ background: transparent;
+ border-color: var(--line);
+ color: var(--muted);
+}
+.com-btn-ghost.is-on {
+ border-color: rgba(52, 211, 153, 0.45);
+ color: #34d399;
+}
+.com-btn-sm {
+ min-height: 32px;
+ padding: 0 10px;
+ font-size: 12px;
+ background: transparent;
+ border-color: var(--line);
+ color: var(--muted);
+}
+.com-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 10px;
+ margin-top: 14px;
+}
+.com-row-actions {
+ display: flex;
+ gap: 6px;
+}
+
+.com-toast {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 12px;
+ padding: 12px 14px;
+ border-radius: 12px;
+ margin-bottom: 14px;
+ font-size: 13px;
+}
+.com-toast button {
+ border: 0;
+ background: transparent;
+ color: inherit;
+ cursor: pointer;
+ text-decoration: underline;
+}
+.com-toast-ok {
+ background: rgba(52, 211, 153, 0.12);
+ border: 1px solid rgba(52, 211, 153, 0.35);
+ color: #6ee7b7;
+}
+.com-toast-err {
+ background: rgba(248, 113, 113, 0.12);
+ border: 1px solid rgba(248, 113, 113, 0.35);
+ color: #fca5a5;
+}
+
+.com-panel-head {
+ margin-bottom: 14px;
+}
+.com-panel-head h2 {
+ margin: 0 0 4px;
+}
+.com-panel-head p,
+.com-panel-desc {
+ margin: 0 0 14px;
+ color: var(--muted);
+ font-size: 13px;
+}
+
+.com-chart-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 14px;
+ margin-bottom: 18px;
+}
+.com-chart {
+ border: 1px solid var(--line);
+ border-radius: 16px;
+ padding: 14px 16px;
+ background: rgba(20, 20, 24, 0.7);
+}
+.com-chart-head {
+ display: flex;
+ justify-content: space-between;
+ gap: 10px;
+ margin-bottom: 8px;
+ font-size: 14px;
+}
+.com-chart-sub,
+.com-chart-max {
+ display: block;
+ color: var(--muted);
+ font-size: 12px;
+ font-weight: 400;
+ margin-top: 2px;
+}
+.com-chart-max {
+ white-space: nowrap;
+}
+.com-chart-svg {
+ width: 100%;
+ height: auto;
+ color: var(--muted);
+}
+.com-rank {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+.com-rank-row {
+ display: flex;
+ justify-content: space-between;
+ gap: 8px;
+ font-size: 13px;
+}
+.com-rank-name {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.com-rank-n {
+ color: var(--muted);
+}
+.com-rank-track {
+ height: 6px;
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.06);
+ overflow: hidden;
+}
+.com-rank-track i {
+ display: block;
+ height: 100%;
+ background: linear-gradient(90deg, #f59e0b, #fbbf24);
+ border-radius: inherit;
+}
+.com-rank-empty {
+ color: var(--muted);
+ font-size: 13px;
+}
+
+.com-hub-grid {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 12px;
+}
+.com-hub {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 14px;
+ border-radius: 14px;
+ border: 1px solid var(--line);
+ background: rgba(12, 12, 15, 0.55);
+ min-height: 110px;
+}
+.com-hub-primary {
+ border-color: rgba(245, 158, 11, 0.4);
+ background: rgba(245, 158, 11, 0.08);
+}
+.com-hub span:last-child {
+ color: var(--muted);
+ font-size: 12px;
+ line-height: 1.45;
+}
+.com-hub-ico {
+ font-size: 18px;
+}
+
+.com-tabs {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-bottom: 16px;
+}
+.com-tab {
+ min-height: 40px;
+ padding: 0 14px;
+ border-radius: 999px;
+ border: 1px solid var(--line);
+ background: transparent;
+ color: var(--muted);
+ cursor: pointer;
+}
+.com-tab.is-on {
+ color: #1c1408;
+ background: var(--accent);
+ border-color: transparent;
+ font-weight: 700;
+}
+
+.com-chip-row {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin: 12px 0 16px;
+}
+.com-chip {
+ border: 1px solid var(--line);
+ background: rgba(20, 20, 24, 0.7);
+ color: var(--muted);
+ border-radius: 999px;
+ padding: 6px 12px;
+ font-size: 12px;
+ cursor: pointer;
+}
+button.com-chip.is-on,
+.com-chip-ok {
+ border-color: rgba(52, 211, 153, 0.4);
+ color: #6ee7b7;
+}
+
+.com-switch-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
+ gap: 12px;
+}
+.com-switch-card {
+ border: 1px solid var(--line);
+ border-radius: 14px;
+ padding: 14px;
+ background: rgba(12, 12, 15, 0.5);
+}
+.com-switch-card.is-on {
+ border-color: rgba(52, 211, 153, 0.35);
+}
+.com-switch-card.is-off {
+ opacity: 0.72;
+}
+.com-switch-card-top {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 8px;
+}
+.com-switch-card strong {
+ display: block;
+ margin-bottom: 4px;
+}
+.com-switch-card p {
+ margin: 0 0 10px;
+ color: var(--muted);
+ font-size: 12px;
+ line-height: 1.45;
+}
+.com-status {
+ font-size: 11px;
+ font-weight: 700;
+ letter-spacing: 0.04em;
+}
+.com-status.on {
+ color: #34d399;
+}
+.com-status.off {
+ color: var(--muted);
+}
+
+.com-switch {
+ position: relative;
+ width: 46px;
+ height: 28px;
+ display: inline-block;
+}
+.com-switch input {
+ opacity: 0;
+ width: 0;
+ height: 0;
+}
+.com-switch-track {
+ position: absolute;
+ inset: 0;
+ border-radius: 999px;
+ background: #27272a;
+ border: 1px solid var(--line);
+ transition: 0.15s ease;
+}
+.com-switch-thumb {
+ position: absolute;
+ top: 3px;
+ left: 3px;
+ width: 20px;
+ height: 20px;
+ border-radius: 50%;
+ background: #a1a1aa;
+ transition: 0.15s ease;
+}
+.com-switch input:checked + .com-switch-track {
+ background: rgba(245, 158, 11, 0.35);
+ border-color: rgba(245, 158, 11, 0.55);
+}
+.com-switch input:checked + .com-switch-track .com-switch-thumb {
+ left: 21px;
+ background: #f59e0b;
+}
+.com-switch input:disabled + .com-switch-track {
+ opacity: 0.5;
+}
+
+.com-flag-list {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+.com-flag-row {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 16px;
+ padding: 12px 0;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.05);
+}
+.com-flag-row p {
+ margin: 4px 0 0;
+ color: var(--muted);
+ font-size: 12px;
+}
+.com-select,
+.com-toolbar select,
+.com-toolbar input,
+.com-field input,
+.com-textarea {
+ min-height: 44px;
+ border-radius: 12px;
+ border: 1px solid var(--line);
+ background: #0c0c0f;
+ color: var(--text);
+ padding: 0 12px;
+ font-size: 14px;
+}
+.com-textarea {
+ padding: 12px;
+ resize: vertical;
+ width: 100%;
+ font-family: inherit;
+}
+.com-toolbar {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 10px;
+ margin-bottom: 14px;
+}
+.com-toolbar input,
+.com-toolbar select {
+ flex: 1;
+ min-width: 160px;
+}
+.com-form-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 12px;
+}
+.com-field {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ font-size: 13px;
+ color: var(--muted);
+}
+
+.com-table-wrap {
+ overflow: auto;
+ border: 1px solid var(--line);
+ border-radius: 16px;
+ background: rgba(20, 20, 24, 0.7);
+}
+.com-table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 13px;
+}
+.com-table th,
+.com-table td {
+ text-align: left;
+ padding: 12px 14px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.05);
+ vertical-align: top;
+}
+.com-table th {
+ color: var(--muted);
+ font-weight: 600;
+ white-space: nowrap;
+}
+.com-table code {
+ color: var(--accent-2);
+ font-size: 12px;
+}
+.com-detail {
+ margin: 8px 0 0;
+ padding: 10px;
+ border-radius: 10px;
+ background: #09090b;
+ border: 1px solid var(--line);
+ font-size: 11px;
+ overflow: auto;
+ max-width: 360px;
+}
+.com-empty {
+ padding: 36px 16px;
+ text-align: center;
+ color: var(--muted);
+}
+.com-badge.tone-ok {
+ color: #6ee7b7;
+ border-color: rgba(52, 211, 153, 0.35);
+ background: rgba(52, 211, 153, 0.1);
+}
+.com-badge.tone-bad {
+ color: #fca5a5;
+ border-color: rgba(248, 113, 113, 0.35);
+ background: rgba(248, 113, 113, 0.1);
+}
+.com-badge.tone-warn {
+ color: #fcd34d;
+ border-color: rgba(251, 191, 36, 0.35);
+ background: rgba(251, 191, 36, 0.1);
+}
+.com-badge.tone-info {
+ color: #7dd3fc;
+ border-color: rgba(56, 189, 248, 0.35);
+ background: rgba(56, 189, 248, 0.1);
+}
+.com-badge.tone-muted {
+ color: var(--muted);
+}
+.com-module-card-link {
+ transition: border-color 0.15s ease, transform 0.15s ease;
+}
+.com-module-card-link:hover {
+ border-color: rgba(245, 158, 11, 0.45);
+ transform: translateY(-1px);
+}
+.com-list a {
+ color: var(--accent-2);
+ text-decoration: underline;
+}
+
+.com-pill-btn {
+ cursor: pointer;
+ width: 100%;
+ text-align: left;
+ font: inherit;
+}
+
+/* 登录后选模块(无侧栏) */
+.modsel-page {
+ min-height: 100vh;
+ min-height: 100dvh;
+ display: grid;
+ place-items: center;
+ padding: 28px 16px;
+ position: relative;
+}
+.modsel-bg {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ background:
+ radial-gradient(700px 380px at 20% 0%, rgba(245, 158, 11, 0.14), transparent 55%),
+ radial-gradient(640px 360px at 85% 10%, rgba(56, 189, 248, 0.12), transparent 50%);
+}
+.modsel-inner {
+ position: relative;
+ width: min(880px, 100%);
+ display: flex;
+ flex-direction: column;
+ gap: 28px;
+}
+.modsel-brand {
+ display: flex;
+ align-items: flex-start;
+ gap: 14px;
+}
+.modsel-mark {
+ width: 48px;
+ height: 48px;
+ border-radius: 14px;
+ display: grid;
+ place-items: center;
+ font-weight: 800;
+ background: linear-gradient(135deg, #f59e0b, #fbbf24);
+ color: #1c1408;
+ flex-shrink: 0;
+}
+.modsel-brand h1 {
+ margin: 0 0 6px;
+ font-family: var(--font-display);
+ font-size: 28px;
+}
+.modsel-brand p {
+ margin: 0;
+ color: var(--muted);
+ line-height: 1.5;
+ font-size: 14px;
+}
+.modsel-brand code {
+ color: var(--accent-2);
+}
+.modsel-note {
+ opacity: 0.85;
+}
+.modsel-logout {
+ margin-left: auto;
+ min-height: 40px;
+ padding: 0 14px;
+ border-radius: 12px;
+ border: 1px solid var(--line);
+ background: transparent;
+ color: var(--muted);
+ cursor: pointer;
+}
+.modsel-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 16px;
+}
+.modsel-card {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 10px;
+ min-height: 240px;
+ padding: 24px;
+ border-radius: 20px;
+ border: 1px solid var(--line);
+ background: rgba(20, 20, 24, 0.85);
+ color: inherit;
+ text-align: left;
+ cursor: pointer;
+ font: inherit;
+ transition: transform 0.15s ease, border-color 0.15s ease;
+}
+.modsel-card:hover {
+ transform: translateY(-2px);
+}
+.modsel-card--cn {
+ border-color: rgba(245, 158, 11, 0.45);
+ background:
+ radial-gradient(360px 180px at 0% 0%, rgba(245, 158, 11, 0.2), transparent 65%),
+ rgba(20, 20, 24, 0.9);
+}
+.modsel-card--intl {
+ border-color: rgba(56, 189, 248, 0.4);
+ background:
+ radial-gradient(360px 180px at 100% 0%, rgba(56, 189, 248, 0.18), transparent 65%),
+ rgba(20, 20, 24, 0.9);
+}
+.modsel-card-top {
+ display: flex;
+ width: 100%;
+ justify-content: space-between;
+ align-items: center;
+}
+.modsel-ico {
+ width: 44px;
+ height: 44px;
+ border-radius: 12px;
+ display: grid;
+ place-items: center;
+ font-weight: 800;
+ background: rgba(245, 158, 11, 0.2);
+ color: var(--accent);
+}
+.modsel-ico--intl {
+ background: rgba(56, 189, 248, 0.18);
+ color: var(--accent-2);
+}
+.modsel-badge {
+ font-size: 11px;
+ font-weight: 700;
+ padding: 4px 8px;
+ border-radius: 999px;
+ border: 1px solid rgba(245, 158, 11, 0.35);
+ color: var(--accent);
+}
+.modsel-badge--intl {
+ border-color: rgba(56, 189, 248, 0.35);
+ color: var(--accent-2);
+}
+.modsel-card strong {
+ font-size: 26px;
+ font-family: var(--font-display);
+}
+.modsel-desc {
+ color: var(--muted);
+ font-size: 14px;
+ line-height: 1.5;
+ flex: 1;
+}
+.modsel-cta {
+ font-weight: 700;
+ color: var(--accent);
+}
+.modsel-card--intl .modsel-cta {
+ color: var(--accent-2);
+}
+@media (max-width: 720px) {
+ .modsel-grid {
+ grid-template-columns: 1fr;
+ }
+ .modsel-brand {
+ flex-wrap: wrap;
+ }
+ .modsel-logout {
+ margin-left: 0;
+ }
+}
+
+.com-lane-eyebrow {
+ font-size: 12px;
+ color: var(--muted);
+ letter-spacing: 0.04em;
+ margin-bottom: 6px;
+}
+.com-lane-en {
+ font-weight: 500;
+ color: var(--muted);
+ font-size: 0.55em;
+ margin-left: 8px;
+}
+.com-lane-hub--cn .com-hub-primary {
+ border-color: rgba(245, 158, 11, 0.35);
+}
+.com-lane-hub--intl .com-hub-primary {
+ border-color: rgba(56, 189, 248, 0.35);
+}
+
+@media (max-width: 860px) {
+ .com-entry-grid {
+ grid-template-columns: 1fr;
+ }
+}
diff --git a/apps/com/admin/src/vite-env.d.ts b/apps/com/admin/src/vite-env.d.ts
new file mode 100644
index 0000000..94a5d3a
--- /dev/null
+++ b/apps/com/admin/src/vite-env.d.ts
@@ -0,0 +1,9 @@
+///
+
+interface ImportMetaEnv {
+ readonly VITE_API_BASE?: string
+}
+
+interface ImportMeta {
+ readonly env: ImportMetaEnv
+}
diff --git a/apps/com/admin/tsconfig.json b/apps/com/admin/tsconfig.json
new file mode 100644
index 0000000..bbe1769
--- /dev/null
+++ b/apps/com/admin/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "useDefineForClassFields": true,
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "skipLibCheck": true,
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "noEmit": true,
+ "jsx": "react-jsx",
+ "strict": true,
+ "paths": {
+ "react": ["./node_modules/@types/react/index.d.ts"]
+ }
+ },
+ "include": ["src"]
+}
diff --git a/apps/com/admin/vite.config.ts b/apps/com/admin/vite.config.ts
new file mode 100644
index 0000000..c9c6100
--- /dev/null
+++ b/apps/com/admin/vite.config.ts
@@ -0,0 +1,32 @@
+import { defineConfig } from 'vite'
+import react from '@vitejs/plugin-react'
+
+/**
+ * admin.nomadro.com — Web only; isolated from apps/admin (.cn)
+ * 本地调试默认反代美国 VPS API(后端在服务器,前端本机)。
+ * 若要打本地 API:设 VITE_DEV_API=http://127.0.0.1:8080
+ */
+const DEV_API = process.env.VITE_DEV_API || 'https://api.nomadro.com'
+
+export default defineConfig({
+ plugins: [react()],
+ server: {
+ port: 5174,
+ proxy: {
+ '/api': {
+ target: DEV_API,
+ changeOrigin: true,
+ secure: true,
+ },
+ '/health': {
+ target: DEV_API,
+ changeOrigin: true,
+ secure: true,
+ },
+ },
+ },
+ build: {
+ outDir: 'dist',
+ },
+})
+
diff --git a/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts b/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts
index a10981b..c9dc837 100644
--- a/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts
+++ b/apps/miniprogram/h5/src/data/remoteConfig.defaults.ts
@@ -208,7 +208,7 @@ export const DEFAULT_REMOTE_CONFIG: NomadroRemoteConfig = {
homeBrand: 'nomadro',
homeTagline: '',
homeLead: '',
- vipPriceFen: 29800,
+ vipPriceFen: 8800,
vipProductId: 'tiktok',
vipCta: '立即加入',
wechatOaName: '异度世界',
diff --git a/apps/miniprogram/h5/src/data/socialCatalog.ts b/apps/miniprogram/h5/src/data/socialCatalog.ts
index 935d7b6..8568902 100644
--- a/apps/miniprogram/h5/src/data/socialCatalog.ts
+++ b/apps/miniprogram/h5/src/data/socialCatalog.ts
@@ -233,5 +233,12 @@ export const TEAM_KIND_LABEL: Record = {
fulltime: "全职机会",
};
-/** Same box as nomadro.cn (82.x). Prefer .cn — avoid .com→107 hop. */
-export const MIROTALK_URL = 'https://mirotalk.nomadro.cn'
+/**
+ * 自研 MiroTalk:生产同域 `/join`(nginx → :9300),禁止跳 mirotalk.*。
+ * H5 在浏览器里用当前 origin;小程序原生厅走 LivePusher,不依赖此 URL。
+ */
+export const MIROTALK_URL =
+ typeof window !== 'undefined' &&
+ /^(www\.)?nomadro\.(cn|com)$/.test(window.location.hostname)
+ ? window.location.origin
+ : 'https://nomadro.cn'
diff --git a/apps/miniprogram/h5/src/data/socialRoster.ts b/apps/miniprogram/h5/src/data/socialRoster.ts
index 40ccafa..dc85f5f 100644
--- a/apps/miniprogram/h5/src/data/socialRoster.ts
+++ b/apps/miniprogram/h5/src/data/socialRoster.ts
@@ -26,7 +26,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
title: "独立设计师",
city: "清迈 · Nimman",
tags: ["咖啡局", "设计", "日出"],
- avatar: "https://randomuser.me/api/portraits/women/65.jpg",
+ avatar: "https://images.unsplash.com/photo-1534528741775-53994a69daeb?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
bio: "喜欢把 cowork 聊成真实见面。周末常去 Graph Table,也爱清晨骑车去山上看雾。",
vibe: "温柔 · 有品味",
online: true,
@@ -46,7 +46,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
title: "全栈 / SaaS",
city: "里斯本",
tags: ["Next.js", "夜跑", "冲浪"],
- avatar: "https://randomuser.me/api/portraits/men/32.jpg",
+ avatar: "https://images.unsplash.com/photo-1681097561932-36d0df02b379?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
bio: "白天写代码,傍晚海边。欢迎 Coffeechat 聊产品与出海。",
vibe: "阳光 · 靠谱",
online: true,
@@ -65,7 +65,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
title: "内容创业者",
city: "巴厘岛 · Canggu",
tags: ["Vlog", "瑜伽", "出海"],
- avatar: "https://randomuser.me/api/portraits/women/44.jpg",
+ avatar: "https://images.unsplash.com/photo-1524548209323-6fb4a0d4a4a3?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
bio: "镜头前很活泼,线下更爱深度聊天。常在 Canggu cowork。",
vibe: "活力",
online: false,
@@ -81,7 +81,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
title: "产品经理",
city: "东京 / 远程",
tags: ["B2B", "胶片", "拉面"],
- avatar: "https://randomuser.me/api/portraits/men/75.jpg",
+ avatar: "https://images.unsplash.com/photo-1540569014015-19a7be504e3a?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
bio: "时差玩家。开视频见面时很稳,私下爱胶片机。",
vibe: "干净 · 有梗",
online: true,
@@ -97,7 +97,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
title: "增长黑客",
city: "曼谷",
tags: ["增长", "夜市", "泰语"],
- avatar: "https://randomuser.me/api/portraits/women/68.jpg",
+ avatar: "https://images.unsplash.com/photo-1515191627608-9f04cf8dc9d1?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
bio: "把增长聊成故事。欢迎约路边摊。",
vibe: "聪明 · 飒",
online: true,
@@ -113,7 +113,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
title: "独立开发者",
city: "成都 → 清迈",
tags: ["Flutter", "火锅", "副业"],
- avatar: "https://randomuser.me/api/portraits/men/52.jpg",
+ avatar: "https://images.unsplash.com/photo-1672155411493-d36070f0c8f8?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
bio: "刚到东南亚第三周,想认识本地局朋友。",
vibe: "真诚 · 幽默",
online: false,
@@ -129,7 +129,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
title: "摄影师",
city: "大城 / 曼谷",
tags: ["旅拍", "胶片", "咖啡"],
- avatar: "https://randomuser.me/api/portraits/women/21.jpg",
+ avatar: "https://images.unsplash.com/photo-1634552516330-ab1ccc0f605e?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
bio: "擅长拍人。可以帮你拍「游民证件照」。",
vibe: "氛围感",
online: true,
@@ -148,7 +148,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
title: "跨境电商",
city: "槟城",
tags: ["TikTok", "冲浪", "搞钱"],
- avatar: "https://randomuser.me/api/portraits/men/22.jpg",
+ avatar: "https://images.unsplash.com/photo-1611580839246-23c8de2e04aa?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
bio: "白天看数据,傍晚冲浪。社群里最活跃的那几个之一。",
vibe: "热情 · 靠谱",
online: true,
@@ -164,7 +164,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
title: "UX 研究员",
city: "柏林",
tags: ["访谈", "市集", "播客"],
- avatar: "https://randomuser.me/api/portraits/women/33.jpg",
+ avatar: "https://images.unsplash.com/photo-1549286386-efeff0dde84c?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
bio: "欧洲时区,擅长把陌生人聊成朋友。",
vibe: "知性",
online: false,
@@ -180,7 +180,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
title: "AI 工程师",
city: "首尔 / 远程",
tags: ["Agent", "开源", "咖啡"],
- avatar: "https://randomuser.me/api/portraits/men/41.jpg",
+ avatar: "https://images.unsplash.com/photo-1557862921-37829c790f19?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
bio: "技术宅但不社恐。经常来开视频见面。",
vibe: "稳 · 有趣",
online: true,
@@ -196,7 +196,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
title: "咖啡馆主理人",
city: "大理",
tags: ["手冲", "音乐会", "徒步"],
- avatar: "https://randomuser.me/api/portraits/women/90.jpg",
+ avatar: "https://images.unsplash.com/photo-1544168190-79c17527004f?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
bio: "店在古城边。来大理一定请你喝手冲。",
vibe: "松弛",
online: true,
@@ -212,7 +212,7 @@ export const MOCK_ROSTER: SocialRosterMember[] = [
title: "游民教练",
city: "里斯本",
tags: ["签证", "地理套利", "跑步"],
- avatar: "https://randomuser.me/api/portraits/men/11.jpg",
+ avatar: "https://images.unsplash.com/photo-1615109398623-88346a601842?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
bio: "帮过上百人规划第一站。Coffeechat 从不冷场。",
vibe: "温暖",
online: false,
diff --git a/apps/miniprogram/h5/src/hooks/useSocialChat.ts b/apps/miniprogram/h5/src/hooks/useSocialChat.ts
index 83d12b7..efef4cc 100644
--- a/apps/miniprogram/h5/src/hooks/useSocialChat.ts
+++ b/apps/miniprogram/h5/src/hooks/useSocialChat.ts
@@ -1,9 +1,16 @@
/** Community chat: persistent outbox, explicit retries, HTTP + WebSocket. */
import { useCallback, useEffect, useRef, useState } from 'react'
import Taro, { useDidHide, useDidShow } from '@tarojs/taro'
-import { createSocialRequestId, getSocialGuestId, socialApi, type SocialChatMessage } from '@/services/socialApi'
+import {
+ createSocialRequestId,
+ getSocialGuestId,
+ socialApi,
+ type SocialChatAttachment,
+ type SocialChatMessage,
+ type SocialChatReplyTo,
+} from '@/services/socialApi'
import { connectChatRealtime } from '@/services/socialRealtime'
-import { mergeChatMessages } from '@/services/socialChatState'
+import { maxChatSeq, mergeChatMessages } from '@/services/socialChatState'
import { readSocialLocal, writeSocialLocal } from '@/services/socialLocal'
import { getCachedRemoteConfig } from '@/services/remoteConfig'
import { isSocialFeatureEnabled, resolveSocialOps } from '@/utils/socialOps'
@@ -21,11 +28,15 @@ export function useSocialChat(channelId: string) {
})
const [status, setStatus] = useState('connecting')
const [sending, setSending] = useState(false)
+ const [typingPeers, setTypingPeers] = useState([])
+ const [online, setOnline] = useState(0)
const lock = useRef(false)
const active = useRef(channelId)
const mounted = useRef(false)
const initializedKey = useRef('')
const visible = useRef(true)
+ const typingBeat = useRef(0)
+ const typingClear = useRef | null>(null)
const refreshRef = useRef<() => Promise>(async () => {})
active.current = channelId
@@ -52,14 +63,26 @@ export function useSocialChat(channelId: string) {
let realtime = false
let failures = 0
let nextRefresh = 0
- const refresh = async () => {
+ let lastSeq = 0
+ const refresh = async (mode: 'full' | 'since' = 'since') => {
if (cancelled || refreshing || !visible.current) return
refreshing = true
try {
- const response = await socialApi.listMessages(channelId)
+ const since = mode === 'since' && lastSeq > 0 ? lastSeq : undefined
+ const response = await socialApi.listMessages(channelId, {
+ limit: since ? 200 : 100,
+ since,
+ })
if (cancelled) return
if (!Array.isArray(response.items)) throw new Error('消息格式异常')
- setMessages((current) => mergeChatMessages(current, response.items, guest))
+ setMessages((current) => {
+ const next = mergeChatMessages(current, response.items, guest)
+ lastSeq = Math.max(lastSeq, maxChatSeq(next), Number(response.seq || 0))
+ return next
+ })
+ if (lastSeq > 0) {
+ void socialApi.postNote(channelId, 'read', lastSeq).catch(() => undefined)
+ }
failures = 0
nextRefresh = 0
setStatus(realtime ? 'live' : 'polling')
@@ -77,22 +100,49 @@ export function useSocialChat(channelId: string) {
setSending(false)
lock.current = false
setStatus('connecting')
- void refresh()
+ const beatPresence = () => {
+ void socialApi.presence(channelId, nick).then((info) => {
+ if (!cancelled) setOnline(Number(info.online || 0))
+ }).catch(() => undefined)
+ }
+ void refresh('full')
+ beatPresence()
const timer = setInterval(() => {
- if (Date.now() >= nextRefresh) void refresh()
- }, 8000)
+ if (Date.now() >= nextRefresh) void refresh('since')
+ }, 12000)
+ const presenceTimer = setInterval(beatPresence, 20000)
const realtimeOn = isSocialFeatureEnabled(
resolveSocialOps(getCachedRemoteConfig()),
'chatRealtime',
)
if (realtimeOn) {
- void connectChatRealtime(channelId, (item) => {
- if (cancelled) return
- setMessages((current) => mergeChatMessages(current, [item], guest))
- }, (connected) => {
- realtime = connected
- if (!cancelled) setStatus(connected ? 'live' : 'polling')
- }).then((connection) => {
+ void connectChatRealtime(
+ channelId,
+ (item) => {
+ if (cancelled) return
+ setMessages((current) => {
+ const next = mergeChatMessages(current, [item], guest)
+ lastSeq = Math.max(lastSeq, maxChatSeq(next))
+ return next
+ })
+ if (item.seq) {
+ void socialApi.postNote(channelId, 'recv', item.seq).catch(() => undefined)
+ }
+ },
+ (connected) => {
+ realtime = connected
+ if (!cancelled) setStatus(connected ? 'live' : 'polling')
+ },
+ (note) => {
+ if (cancelled || note.guestId === guest) return
+ if (note.what !== 'kp') return
+ setTypingPeers((prev) => (prev.includes(note.guestId) ? prev : [...prev, note.guestId]))
+ if (typingClear.current) clearTimeout(typingClear.current)
+ typingClear.current = setTimeout(() => {
+ setTypingPeers((prev) => prev.filter((id) => id !== note.guestId))
+ }, 2800)
+ },
+ ).then((connection) => {
if (cancelled) connection?.disconnect()
else stopWs = connection?.disconnect
}).catch(() => { if (!cancelled) setStatus('polling') })
@@ -103,9 +153,15 @@ export function useSocialChat(channelId: string) {
cancelled = true
mounted.current = false
clearInterval(timer)
+ clearInterval(presenceTimer)
+ if (typingClear.current) clearTimeout(typingClear.current)
stopWs?.()
}
- }, [channelId, guest, outboxKey, draftKey])
+ }, [channelId, guest, nick, outboxKey, draftKey])
+
+ const mergeOne = useCallback((saved: SocialChatMessage) => {
+ setMessages((current) => mergeChatMessages(current, [{ ...saved, guestId: saved.guestId || guest }], guest))
+ }, [guest])
const deliver = useCallback(async (item: SocialChatMessage) => {
if (lock.current) return false
@@ -113,12 +169,19 @@ export function useSocialChat(channelId: string) {
setSending(true)
setMessages((current) => current.map((m) => m.id === item.id ? { ...m, delivery: 'pending' as const } : m))
try {
- const saved = await socialApi.sendMessage(channelId, item.author, item.text, item.clientId)
+ const saved = await socialApi.sendMessage(channelId, item.author, item.text, item.clientId, {
+ replyTo: item.replyTo,
+ attachments: item.attachments,
+ mentions: item.mentions,
+ })
if (!saved?.id) throw new Error('发送结果异常')
const pending = readSocialLocal(outboxKey, [])
if (Array.isArray(pending)) writeSocialLocal(outboxKey, pending.filter((message) => message.id !== item.id && (!item.clientId || message.clientId !== item.clientId)))
if (!mounted.current || active.current !== channelId) return true
- setMessages((current) => mergeChatMessages(current.filter((m) => m.id !== item.id), [{ ...saved, guestId: guest, clientId: item.clientId }], guest))
+ setMessages((current) => {
+ const next = mergeChatMessages(current.filter((m) => m.id !== item.id), [{ ...saved, guestId: guest, clientId: item.clientId }], guest)
+ return next
+ })
return true
} catch {
if (!mounted.current || active.current !== channelId) return false
@@ -134,15 +197,23 @@ export function useSocialChat(channelId: string) {
}
}, [channelId, guest, outboxKey])
- const send = useCallback(async () => {
+ const send = useCallback(async (opts?: {
+ replyTo?: SocialChatReplyTo | null
+ attachments?: SocialChatAttachment[]
+ mentions?: string[]
+ }) => {
const text = draft.trim()
- if (!text || text.length > 2000 || lock.current) return false
+ const atts = opts?.attachments || []
+ if ((!text && !atts.length) || text.length > 2000 || lock.current) return false
const clientId = createSocialRequestId()
+ const mentions = opts?.mentions || Array.from(text.matchAll(/@([\w\u4e00-\u9fff-]{1,24})/g)).map((m) => m[1])
const item: SocialChatMessage = {
id: `local_${clientId}`, clientId, channelId, author: nick.trim().slice(0, 24) || '游民',
text, at: new Date().toISOString(), guestId: guest, mine: true, delivery: 'pending',
+ replyTo: opts?.replyTo || undefined,
+ attachments: atts.length ? atts : undefined,
+ mentions: mentions.length ? mentions : undefined,
}
- // Save before clearing the input so navigating away cannot lose unsent text.
const existing = readSocialLocal(outboxKey, [])
if (!writeSocialLocal(outboxKey, [...(Array.isArray(existing) ? existing : []), { ...item, delivery: 'local' }].slice(-50))) {
void Taro.showToast({ title: '本地保存失败,请保留输入后重试', icon: 'none' })
@@ -160,5 +231,86 @@ export function useSocialChat(channelId: string) {
if (item) await deliver(item)
}, [deliver, messages])
- return { messages, draft, setDraft, nick, setNick, status, sending, send, retryLocal, refresh: () => refreshRef.current() }
+ const editMessage = useCallback(async (msgId: string, text: string) => {
+ try {
+ mergeOne(await socialApi.editMessage(channelId, msgId, text))
+ return true
+ } catch {
+ void Taro.showToast({ title: '编辑失败', icon: 'none' })
+ return false
+ }
+ }, [channelId, mergeOne])
+
+ const recallMessage = useCallback(async (msgId: string) => {
+ try {
+ mergeOne(await socialApi.recallMessage(channelId, msgId))
+ return true
+ } catch {
+ void Taro.showToast({ title: '撤回失败', icon: 'none' })
+ return false
+ }
+ }, [channelId, mergeOne])
+
+ const reactMessage = useCallback(async (msgId: string, emoji: string) => {
+ try {
+ mergeOne(await socialApi.reactMessage(channelId, msgId, emoji))
+ return true
+ } catch {
+ return false
+ }
+ }, [channelId, mergeOne])
+
+ const pinMessage = useCallback(async (msgId: string, pinned = true) => {
+ try {
+ mergeOne(await socialApi.pinMessage(channelId, msgId, pinned))
+ return true
+ } catch {
+ return false
+ }
+ }, [channelId, mergeOne])
+
+ const upload = useCallback(
+ (filePath: string, kind?: string, name?: string) => socialApi.upload(channelId, filePath, kind, name),
+ [channelId],
+ )
+
+ const reportMessage = useCallback(async (msgId: string, reason = '') => {
+ try {
+ await socialApi.reportMessage(channelId, msgId, reason)
+ void Taro.showToast({ title: '已提交举报', icon: 'none' })
+ return true
+ } catch {
+ void Taro.showToast({ title: '举报失败', icon: 'none' })
+ return false
+ }
+ }, [channelId])
+
+ const notifyTyping = useCallback(() => {
+ const now = Date.now()
+ if (now - typingBeat.current < 1800) return
+ typingBeat.current = now
+ void socialApi.postNote(channelId, 'kp', 0).catch(() => undefined)
+ }, [channelId])
+
+ return {
+ messages,
+ draft,
+ setDraft,
+ nick,
+ setNick,
+ status,
+ sending,
+ send,
+ retryLocal,
+ editMessage,
+ recallMessage,
+ reactMessage,
+ pinMessage,
+ reportMessage,
+ upload,
+ online,
+ typingPeers,
+ notifyTyping,
+ refresh: () => refreshRef.current(),
+ }
}
diff --git a/apps/miniprogram/h5/src/pages/social/chat/index.scss b/apps/miniprogram/h5/src/pages/social/chat/index.scss
index 9a35390..9d8e94e 100644
--- a/apps/miniprogram/h5/src/pages/social/chat/index.scss
+++ b/apps/miniprogram/h5/src/pages/social/chat/index.scss
@@ -159,6 +159,13 @@
color: #fbbf24;
}
+.im-typing {
+ flex: 0 0 auto;
+ padding: 0.25rem 0.9rem;
+ font-size: 0.7rem;
+ color: #94a3b8;
+}
+
.im-anchor {
height: 1PX;
width: 100%;
@@ -219,3 +226,189 @@
.soc-taro-root.im-root[data-theme] .im-input { min-width: 0; }
.soc-taro-root.im-root[data-theme] .im-bubble.is-mine { background: var(--social-raised); border-color: var(--social-accent); }
.soc-taro-root.im-root[data-theme='light'] .im-fail { color: #926000; }
+
+.im-bubble.is-pinned {
+ outline: 1PX solid rgba(245, 158, 11, 0.45);
+}
+.im-quote {
+ margin-bottom: 0.35rem;
+ padding: 0.35rem 0.5rem;
+ border-left: 2PX solid #f59e0b;
+ background: rgba(255, 255, 255, 0.05);
+ border-radius: 0 0.5rem 0.5rem 0;
+}
+.im-quote-a {
+ display: block;
+ font-size: 0.7rem;
+ color: #f59e0b;
+}
+.im-quote-t {
+ display: block;
+ font-size: 0.72rem;
+ color: #94a3b8;
+}
+.im-recalled {
+ font-style: italic;
+ color: #94a3b8;
+ font-size: 0.85rem;
+}
+.im-atts {
+ display: flex;
+ flex-direction: column;
+ gap: 0.45rem;
+ margin-top: 0.35rem;
+}
+.im-att-image,
+.im-att-video {
+ width: 100%;
+ max-width: 16rem;
+ border-radius: 0.75rem;
+}
+.im-att-file {
+ display: flex;
+ align-items: center;
+ min-height: 2.75rem;
+ padding: 0.5rem 0.75rem;
+ border-radius: 0.75rem;
+ background: rgba(255, 255, 255, 0.06);
+ color: #fbbf24;
+ font-size: 0.85rem;
+ border: 0;
+}
+.im-reactions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.3rem;
+ margin-top: 0.35rem;
+}
+.im-react-chip {
+ padding: 0.15rem 0.45rem;
+ border-radius: 999PX;
+ background: rgba(255, 255, 255, 0.08);
+ font-size: 0.75rem;
+}
+.im-react-chip.is-mine {
+ outline: 1PX solid #f59e0b;
+}
+.im-pinned {
+ flex: 0 0 auto;
+ display: flex;
+ flex-direction: column;
+ gap: 0.25rem;
+ padding: 0.35rem 0.75rem;
+}
+.im-pinned-item {
+ text-align: left;
+ min-height: 2.25rem;
+ padding: 0.35rem 0.65rem;
+ border-radius: 999PX;
+ border: 1PX solid rgba(245, 158, 11, 0.35);
+ background: rgba(245, 158, 11, 0.12);
+ color: #f8fafc;
+ font-size: 0.75rem;
+}
+.im-chip-row,
+.im-pending {
+ flex: 0 0 auto;
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.4rem;
+ padding: 0.35rem 0.75rem;
+ font-size: 0.75rem;
+ color: #cbd5e1;
+}
+.im-chip-row button,
+.im-pending-item {
+ min-height: 2.25rem;
+ padding: 0.25rem 0.65rem;
+ border: 0;
+ border-radius: 999PX;
+ background: rgba(255, 255, 255, 0.08);
+ color: #e2e8f0;
+ font-size: 0.75rem;
+}
+.im-composer-tools {
+ flex: 0 0 auto;
+ display: flex;
+ gap: 0.35rem;
+ padding: 0.25rem 0.75rem 0;
+}
+.im-tool {
+ min-width: 2.75rem;
+ min-height: 2.75rem;
+ border: 0;
+ border-radius: 0.85rem;
+ background: rgba(255, 255, 255, 0.06);
+ font-size: 1.15rem;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+.im-emoji-sheet {
+ flex: 0 0 auto;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.35rem;
+ padding: 0.5rem 0.75rem;
+ border-top: 1PX solid rgba(255, 255, 255, 0.06);
+ background: #080c14;
+}
+.im-emoji-btn {
+ min-width: 2.75rem;
+ min-height: 2.75rem;
+ border: 0;
+ border-radius: 0.75rem;
+ background: rgba(255, 255, 255, 0.06);
+ font-size: 1.25rem;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+.im-action-sheet {
+ position: fixed;
+ inset: 0;
+ z-index: 80;
+ background: rgba(0, 0, 0, 0.55);
+ display: flex;
+ align-items: flex-end;
+ justify-content: center;
+}
+.im-action-panel {
+ width: 100%;
+ max-width: 40rem;
+ padding: 0.85rem 0.85rem calc(0.85rem + env(safe-area-inset-bottom, 0PX));
+ border-radius: 1.1rem 1.1rem 0 0;
+ background: #101826;
+ display: flex;
+ flex-direction: column;
+ gap: 0.35rem;
+}
+.im-action-title {
+ text-align: center;
+ font-size: 0.8rem;
+ color: #94a3b8;
+ margin-bottom: 0.25rem;
+}
+.im-quick-react {
+ display: flex;
+ justify-content: space-around;
+ margin-bottom: 0.35rem;
+}
+.im-action-btn {
+ min-height: 2.85rem;
+ border: 0;
+ border-radius: 0.85rem;
+ background: rgba(255, 255, 255, 0.06);
+ color: #f8fafc;
+ font-size: 1rem;
+ font-weight: 600;
+}
+.im-action-btn.is-danger {
+ color: #f87171;
+}
+.im-action-btn.is-cancel {
+ margin-top: 0.25rem;
+ background: transparent;
+ color: #94a3b8;
+}
diff --git a/apps/miniprogram/h5/src/pages/social/chat/index.tsx b/apps/miniprogram/h5/src/pages/social/chat/index.tsx
index 37cb54a..c0acf1a 100644
--- a/apps/miniprogram/h5/src/pages/social/chat/index.tsx
+++ b/apps/miniprogram/h5/src/pages/social/chat/index.tsx
@@ -1,14 +1,19 @@
import { useSocialPage } from '@/hooks/useSocialPage'
import { useSocialContent } from '@/hooks/useSocialContent'
import { useEffect, useRef, useState } from 'react'
-import { Input, ScrollView, Text } from '@tarojs/components'
+import { Image, Input, ScrollView, Text, Video } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { SocialPageGate } from '@/components/SocialPageGate'
import { H5Box } from '@/components/H5Box'
import { useSocialChat } from '@/hooks/useSocialChat'
import { usePageShare } from '@/utils/pageShare'
import { usePageTrack } from '@/hooks/usePageTrack'
-import type { SocialChatMessage } from '@/services/socialApi'
+import {
+ getSocialGuestId,
+ type SocialChatAttachment,
+ type SocialChatMessage,
+ type SocialChatReplyTo,
+} from '@/services/socialApi'
import { H5El } from '../_components/H5El'
import { goSocialPage } from '@/utils/socialNavigation'
import '@/styles/social-next/entry'
@@ -17,6 +22,8 @@ import './index.scss'
/** 唯一总频道 */
const LOBBY = 'general'
+const EMOJIS = ['👋', '☕', '🌍', '✨', '🙌', '❤️', '💻', '🌴', '🚀', '🌙', '👍', '😂', '🔥', '💪', '✅']
+const QUICK_REACT = ['👍', '❤️', '😂', '😮', '🔥', '👏']
function statusLabel(s: string) {
if (s === 'live') return '实时'
@@ -32,33 +39,98 @@ function formatTime(iso?: string) {
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}
+function Atts({ items }: { items: SocialChatAttachment[] }) {
+ return (
+
+ {items.map((att) => {
+ if (att.kind === 'image') {
+ return (
+ void Taro.previewImage({ urls: [att.url], current: att.url })}
+ />
+ )
+ }
+ if (att.kind === 'video') {
+ return
+ }
+ return (
+ {
+ void Taro.setClipboardData({ data: att.url })
+ void Taro.showToast({ title: '已复制文件链接', icon: 'none' })
+ }}
+ >
+ 📎 {att.name}
+
+ )
+ })}
+
+ )
+}
+
function Bubble({
m,
onRetry,
+ onOpen,
}: {
m: SocialChatMessage
onRetry: (id: string) => void
+ onOpen: (m: SocialChatMessage) => void
}) {
return (
{
if (m.delivery === 'local') onRetry(m.id)
+ else if (!m.recalled) onOpen(m)
+ }}
+ onLongPress={() => {
+ if (!m.recalled && m.delivery !== 'local') onOpen(m)
}}
>
- {!m.mine ? (
- {m.author || '游民'}
+ {!m.mine ? {m.author || '游民'} : null}
+ {m.replyTo ? (
+
+ {m.replyTo.author}
+ {m.replyTo.text.slice(0, 80)}
+
+ ) : null}
+ {m.recalled ? (
+ 消息已撤回
+ ) : (
+ <>
+ {m.text ? {m.text} : null}
+ {m.attachments?.length ? : null}
+ >
+ )}
+ {m.reactions && Object.keys(m.reactions).length ? (
+
+ {Object.entries(m.reactions).map(([emoji, guests]) => (
+
+ {emoji} {guests.length}
+
+ ))}
+
) : null}
- {m.text}
{formatTime(m.at)}
+ {m.editedAt ? 已编辑 : null}
+ {m.pinned ? 📌 : null}
{m.delivery === 'pending' ? 发送中 : null}
- {m.delivery === 'local' ? (
- 未送达 · 点重试
- ) : null}
- {m.mine && m.delivery === 'sent' ? 已送达 : null}
+ {m.delivery === 'local' ? 未送达 · 点重试 : null}
+ {m.mine && m.delivery === 'sent' && !m.recalled ? 已送达 : null}
)
@@ -79,6 +151,15 @@ function SocialChatLobby() {
sending,
send,
retryLocal,
+ editMessage,
+ recallMessage,
+ reactMessage,
+ pinMessage,
+ reportMessage,
+ upload,
+ online,
+ typingPeers,
+ notifyTyping,
refresh,
} = useSocialChat(LOBBY)
@@ -86,7 +167,13 @@ function SocialChatLobby() {
const nearBottom = useRef(true)
const [unread, setUnread] = useState(false)
const [refreshing, setRefreshing] = useState(false)
+ const [emojiOpen, setEmojiOpen] = useState(false)
+ const [reply, setReply] = useState(null)
+ const [editingId, setEditingId] = useState(null)
+ const [pendingAtts, setPendingAtts] = useState([])
+ const [sheetMsg, setSheetMsg] = useState(null)
const lastId = messages[messages.length - 1]?.id
+ const pinned = messages.filter((m) => m.pinned && !m.recalled).slice(0, 3)
useEffect(() => {
try {
@@ -101,12 +188,15 @@ function SocialChatLobby() {
useEffect(() => {
if (!lastId) return
- if (!nearBottom.current && !messages[messages.length - 1]?.mine) { setUnread(true); return }
+ if (!nearBottom.current && !messages[messages.length - 1]?.mine) {
+ setUnread(true)
+ return
+ }
const t = setTimeout(() => setScrollInto(`msg_${lastId}`), 48)
return () => clearTimeout(t)
}, [lastId, messages.length])
- const canSend = Boolean(draft.trim()) && !sending
+ const canSend = (Boolean(draft.trim()) || pendingAtts.length > 0 || Boolean(editingId)) && !sending
const onSend = async () => {
if (!canSend) return
@@ -115,22 +205,80 @@ function SocialChatLobby() {
} catch {
/* ignore */
}
- const ok = await send()
- if (ok) setScrollInto('chat_bottom')
+ if (editingId) {
+ const ok = await editMessage(editingId, draft.trim())
+ if (ok) {
+ setEditingId(null)
+ setDraft('')
+ }
+ return
+ }
+ const ok = await send({ replyTo: reply, attachments: pendingAtts })
+ if (ok) {
+ setReply(null)
+ setPendingAtts([])
+ setEmojiOpen(false)
+ setScrollInto('chat_bottom')
+ }
+ }
+
+ const pickMedia = async (kind: 'image' | 'video' | 'file') => {
+ try {
+ if (kind === 'image' || kind === 'video') {
+ const res = await Taro.chooseMedia({
+ count: 3,
+ mediaType: kind === 'image' ? ['image'] : ['video'],
+ sourceType: ['album', 'camera'],
+ })
+ for (const file of res.tempFiles.slice(0, 3)) {
+ const att = await upload(file.tempFilePath, kind, file.tempFilePath.split('/').pop())
+ setPendingAtts((prev) => [...prev, att].slice(-8))
+ }
+ return
+ }
+ const res = await Taro.chooseMessageFile({ count: 1, type: 'file' })
+ const f = res.tempFiles[0]
+ if (!f) return
+ const att = await upload(f.path, 'file', f.name)
+ setPendingAtts((prev) => [...prev, att].slice(-8))
+ } catch {
+ void Taro.showToast({ title: '选择或上传失败', icon: 'none' })
+ }
+ }
+
+ const openActions = (m: SocialChatMessage) => {
+ setSheetMsg(m)
}
return (
- goSocialPage('/pages/social/index')}>← 社区
+ goSocialPage('/pages/social/index')}>
+ ← 社区
+
{pages.chat?.title || '游民大厅'}
- {
- setRefreshing(true); try { await refresh() } finally { setRefreshing(false) }
- }}>{refreshing ? '连接中…' : '刷新'}
+ {
+ setRefreshing(true)
+ try {
+ await refresh()
+ } finally {
+ setRefreshing(false)
+ }
+ }}
+ >
+ {refreshing ? '连接中…' : '刷新'}
+
- {statusLabel(status)}
+
+ {statusLabel(status)}
+ {online > 0 ? ` · ${online}在线` : ''}
+
+ {pinned.length ? (
+
+ {pinned.map((m) => (
+ setScrollInto(`msg_${m.id}`)}
+ >
+ 📌 {m.author}: {(m.text || '附件').slice(0, 28)}
+
+ ))}
+
+ ) : null}
+
{
const detail = event.detail as { scrollHeight: number; scrollTop: number }
- // Obtain the actual viewport so incoming messages do not pull users away from history.
- Taro.createSelectorQuery().select('.im-thread').boundingClientRect((rect: any) => {
- if (rect?.height) nearBottom.current = detail.scrollHeight - detail.scrollTop - rect.height < 100
- }).exec()
+ Taro.createSelectorQuery()
+ .select('.im-thread')
+ .boundingClientRect((rect: any) => {
+ if (rect?.height)
+ nearBottom.current =
+ detail.scrollHeight - detail.scrollTop - rect.height < 100
+ })
+ .exec()
+ }}
+ onScrollToLower={() => {
+ nearBottom.current = true
+ setUnread(false)
}}
- onScrollToLower={() => { nearBottom.current = true; setUnread(false) }}
>
{messages.length === 0 ? (
@@ -181,22 +351,115 @@ function SocialChatLobby() {
{messages.map((m) => (
- void retryLocal(id)} />
+ void retryLocal(id)}
+ onOpen={openActions}
+ />
))}
)}
- {unread ? {
- nearBottom.current = true; setUnread(false); setScrollInto('chat_bottom')
- }}>有新消息 · 回到最新 ↓ : null}
+ {unread ? (
+ {
+ nearBottom.current = true
+ setUnread(false)
+ setScrollInto('chat_bottom')
+ }}
+ >
+ 有新消息 · 回到最新 ↓
+
+ ) : null}
+ {typingPeers.length ? (
+
+ 有人正在输入…
+
+ ) : null}
+
+ {editingId ? (
+
+ 编辑消息
+ {
+ setEditingId(null)
+ setDraft('')
+ }}
+ >
+ 取消
+
+
+ ) : null}
+ {reply && !editingId ? (
+
+
+ 回复 {reply.author}:{reply.text.slice(0, 36)}
+
+ setReply(null)}>
+ 取消
+
+
+ ) : null}
+ {pendingAtts.length ? (
+
+ {pendingAtts.map((att) => (
+ setPendingAtts((p) => p.filter((x) => x.id !== att.id))}
+ >
+
+ {att.kind === 'image' ? '🖼' : att.kind === 'video' ? '🎬' : '📎'} {att.name} ×
+
+
+ ))}
+
+ ) : null}
+
+ {emojiOpen ? (
+
+ {EMOJIS.map((emoji) => (
+ {
+ setDraft((d) => (d + emoji).slice(0, 2000))
+ setEmojiOpen(false)
+ }}
+ >
+ {emoji}
+
+ ))}
+
+ ) : null}
+
+
+ setEmojiOpen((v) => !v)}>
+ 😀
+
+ void pickMedia('image')}>
+ 🖼
+
+ void pickMedia('video')}>
+ 🎬
+
+ void pickMedia('file')}>
+ 📎
+
+
{
setTimeout(() => setScrollInto('chat_bottom'), 120)
}}
- onInput={(e) => setDraft(e.detail.value)}
+ onInput={(e) => {
+ setDraft(e.detail.value)
+ notifyTyping()
+ }}
onConfirm={() => void onSend()}
/>
- void onSend()}
>
- {sending ? '…' : '发送'}
+ {sending ? '…' : editingId ? '保存' : '发送'}
+
+ {sheetMsg ? (
+ setSheetMsg(null)}>
+ {
+ /* keep sheet open when tapping panel */
+ }}
+ >
+ 消息操作
+
+ {QUICK_REACT.map((emoji) => (
+ {
+ void reactMessage(sheetMsg.id, emoji)
+ setSheetMsg(null)
+ }}
+ >
+ {emoji}
+
+ ))}
+
+ {
+ setReply({
+ id: sheetMsg.id,
+ author: sheetMsg.author,
+ text: sheetMsg.text || sheetMsg.attachments?.[0]?.name || '',
+ seq: sheetMsg.seq,
+ })
+ setEditingId(null)
+ setSheetMsg(null)
+ }}
+ >
+ 回复
+
+ {sheetMsg.mine ? (
+ {
+ setEditingId(sheetMsg.id)
+ setDraft(sheetMsg.text)
+ setReply(null)
+ setSheetMsg(null)
+ }}
+ >
+ 编辑
+
+ ) : null}
+ {
+ void pinMessage(sheetMsg.id, !sheetMsg.pinned)
+ setSheetMsg(null)
+ }}
+ >
+ {sheetMsg.pinned ? '取消置顶' : '置顶'}
+
+ {
+ void Taro.setClipboardData({ data: sheetMsg.text || '' })
+ setSheetMsg(null)
+ }}
+ >
+ 复制
+
+ {
+ setDraft(`转发 ${sheetMsg.author}:\n${sheetMsg.text}`.slice(0, 2000))
+ setSheetMsg(null)
+ }}
+ >
+ 转发
+
+ {sheetMsg.mine ? (
+ {
+ void recallMessage(sheetMsg.id)
+ setSheetMsg(null)
+ }}
+ >
+ 撤回
+
+ ) : (
+ {
+ void reportMessage(sheetMsg.id, 'spam')
+ setSheetMsg(null)
+ }}
+ >
+ 举报
+
+ )}
+ setSheetMsg(null)}>
+ 取消
+
+
+
+ ) : null}
)
}
diff --git a/apps/miniprogram/h5/src/pages/social/index.scss b/apps/miniprogram/h5/src/pages/social/index.scss
index 1b31b98..f29dcef 100644
--- a/apps/miniprogram/h5/src/pages/social/index.scss
+++ b/apps/miniprogram/h5/src/pages/social/index.scss
@@ -3,5 +3,97 @@
/* 页面级微调:主体视觉在 social-next/weapp-bridge */
.soc-taro-root.social-weapp .social-mobile-dock {
- padding-bottom: calc(8PX + env(safe-area-inset-bottom, 0PX));
+ left: 0;
+ right: 0;
+ bottom: 0;
+ border-radius: 0;
+ padding: 0.375rem 0.5rem calc(0.5rem + env(safe-area-inset-bottom, 0PX));
+ border: none;
+ border-top: 1PX solid rgba(255, 255, 255, 0.08);
+ box-shadow: 0 -0.5rem 1.75rem rgba(0, 0, 0, 0.14);
+}
+
+.soc-taro-root.social-weapp .social-mobile-dock a[aria-current='page'] {
+ color: #f59e0b;
+ background: rgba(245, 158, 11, 0.12);
+ box-shadow: none;
+}
+
+.soc-taro-root .footer.social-home-footer {
+ padding: 0.5rem 0 calc(5.5rem + env(safe-area-inset-bottom, 0PX));
+ border-top: none;
+}
+
+.soc-taro-root .footer-grid-rings {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 0.875rem;
+}
+
+.soc-taro-root .footer-brand {
+ text-align: center;
+}
+
+.soc-taro-root .footer-brand p {
+ margin: 0.5rem auto 0;
+ max-width: 16rem;
+ font-size: 0.75rem;
+ line-height: 1.5;
+ opacity: 0.55;
+}
+
+.soc-taro-root .footer-links {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 0.5rem;
+ width: 100%;
+}
+
+.soc-taro-root .footer-links h4 {
+ display: none;
+}
+
+.soc-taro-root .footer-links a,
+.soc-taro-root .footer-links .social-footer-link {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 2.5rem;
+ padding: 0 1rem;
+ border-radius: 999px;
+ border: 1PX solid rgba(255, 255, 255, 0.1);
+ background: rgba(255, 255, 255, 0.06);
+ font-size: 0.8125rem;
+ font-weight: 600;
+}
+
+.soc-taro-root .footer-bottom {
+ text-align: center;
+ padding: 0.5rem 0 0.25rem;
+ border: none;
+ font-size: 0.6875rem;
+ opacity: 0.4;
+}
+
+.soc-taro-root .connection-invite {
+ margin: 0.75rem 0.875rem 0.5rem;
+ padding: 1.25rem 1.125rem;
+ border-radius: 1.25rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.875rem;
+}
+
+.soc-taro-root .connection-invite-orbit {
+ display: none;
+}
+
+.soc-taro-root .connection-invite .connection-join,
+.soc-taro-root .connection-invite .btn {
+ width: 100%;
+ min-height: 3rem;
+ margin: 0;
+ justify-content: center;
}
diff --git a/apps/miniprogram/h5/src/pages/social/index.tsx b/apps/miniprogram/h5/src/pages/social/index.tsx
index e53bd5b..05d6a89 100644
--- a/apps/miniprogram/h5/src/pages/social/index.tsx
+++ b/apps/miniprogram/h5/src/pages/social/index.tsx
@@ -76,10 +76,11 @@ function SocialHome() {
const [creation, setCreation] = useState<{ item: SocialEbook | SocialVideo; kind: 'ebook' | 'video' } | null>(null)
const { copy, roster, meetups, gigs, ebooks, videos, promoUrl, hiddenSections, featureOn, sectionOn } =
useSocialContent()
- const datePreview = useMemo(
- () => roster.filter((m) => m.online).slice(0, 3),
- [roster],
- )
+ const datePreview = useMemo(() => {
+ const women = roster.filter((m) => m.gender === 'f')
+ const rest = roster.filter((m) => m.gender !== 'f' && m.online)
+ return [...women, ...rest].slice(0, 3)
+ }, [roster])
const cities = SOCIAL_CITIES.filter((c) => c.hot).slice(0, 8)
const safe = useMemo(() => getSafeAreaMetrics(), [])
const rootStyle = useMemo(
@@ -655,14 +656,14 @@ function SocialHome() {
) : null}
-
+
nomadro · 游民社区
认识同频的人 · 开视频聊聊 · 出来见一面 · 一起做点事
-
+
认识人
goPage('/pages/social/people/index')}>
想见的人
@@ -670,28 +671,12 @@ function SocialHome() {
goPage('/pages/social/date/index')}>
认识一下
- goPage('/pages/social/chat/index')}>
- 大家聊天
-
-
-
- 见面 · 做事
goPage('/pages/social/people/index?mode=cafe')}
+ as='button'
+ className='social-footer-link'
+ onClick={() => setJoinOpen(true)}
>
- 找城市见面
-
- goPage('/pages/social/team/index')}
- >
- 找搭子做事
-
- goPage('/pages/home/index')}>
- 门户首页
+ 加入社区
diff --git a/apps/miniprogram/h5/src/pages/social/meetup-live/index.tsx b/apps/miniprogram/h5/src/pages/social/meetup-live/index.tsx
index d5bcc53..413a451 100644
--- a/apps/miniprogram/h5/src/pages/social/meetup-live/index.tsx
+++ b/apps/miniprogram/h5/src/pages/social/meetup-live/index.tsx
@@ -43,8 +43,8 @@ function joinMiro(room: string, name: string) {
name,
notify: '0',
chat: '0',
- audio: '0',
- video: '0',
+ audio: '1',
+ video: '1',
}
const query = Object.entries(params).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join('&')
return `${MIROTALK_URL.replace(/\/$/, '')}/join?${query}`
diff --git a/apps/miniprogram/h5/src/services/socialApi.ts b/apps/miniprogram/h5/src/services/socialApi.ts
index bfdaed3..0451499 100644
--- a/apps/miniprogram/h5/src/services/socialApi.ts
+++ b/apps/miniprogram/h5/src/services/socialApi.ts
@@ -17,9 +17,12 @@ export function createSocialRequestId(): string {
return `c${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`
}
+/** IM SoT on US (.com); .cn kept as weapp 合法域名 fallback only. */
const SOCIAL_BASES = Array.from(
new Set(
[
+ 'https://nomadro.com',
+ 'https://api.nomadro.com',
API_BASE.replace(/\/$/, ''),
'https://api.nomadro.cn',
WEB_BASE.replace(/\/$/, ''),
@@ -61,7 +64,7 @@ function errText(e: unknown, fallback: string) {
async function req(
path: string,
- init?: { method?: 'GET' | 'POST' | 'PUT'; data?: Record },
+ init?: { method?: 'GET' | 'POST' | 'PUT' | 'PATCH'; data?: Record },
): Promise {
const gid = guestId()
const qs = path.includes('?') ? `&guest=${encodeURIComponent(gid)}` : `?guest=${encodeURIComponent(gid)}`
@@ -134,16 +137,41 @@ export type LiveJoinResult = {
engine: string
}
+export type SocialChatAttachment = {
+ id: string
+ kind: 'image' | 'video' | 'file' | 'audio'
+ url: string
+ name: string
+ mime: string
+ size: number
+}
+
+export type SocialChatReplyTo = {
+ id: string
+ author: string
+ text: string
+ seq?: number | null
+}
+
export type SocialChatMessage = {
id: string
channelId: string
author: string
text: string
at: string
+ /** Tinode-like monotonic seq per channel */
+ seq?: number
guestId?: string
mine?: boolean
delivery?: 'sent' | 'local' | 'pending'
clientId?: string
+ replyTo?: SocialChatReplyTo
+ attachments?: SocialChatAttachment[]
+ reactions?: Record
+ mentions?: string[]
+ editedAt?: string
+ recalled?: boolean
+ pinned?: boolean
}
export type SocialRealtimeToken = {
@@ -210,15 +238,121 @@ export const socialApi = {
`/realtime/token?channel_id=${encodeURIComponent(channelId)}`,
),
- listMessages: (channelId: string) =>
- req<{ items: SocialChatMessage[] }>(
- `/channels/${encodeURIComponent(channelId)}/messages`,
- ),
+ listMessages: (
+ 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()
+ return req<{ items: SocialChatMessage[]; seq?: number }>(
+ `/channels/${encodeURIComponent(channelId)}/messages${qs ? `?${qs}` : ''}`,
+ )
+ },
- sendMessage: (channelId: string, author: string, text: string, clientId?: string) =>
+ sendMessage: (
+ channelId: string,
+ author: string,
+ text: string,
+ clientId?: string,
+ extra?: {
+ replyTo?: SocialChatReplyTo | null
+ attachments?: SocialChatAttachment[]
+ mentions?: string[]
+ },
+ ) =>
req(
`/channels/${encodeURIComponent(channelId)}/messages`,
- { method: 'POST', data: { author, text, ...(clientId ? { clientId } : {}) } },
+ {
+ method: 'POST',
+ data: {
+ author,
+ text,
+ ...(clientId ? { clientId } : {}),
+ ...(extra?.replyTo ? { replyTo: extra.replyTo } : {}),
+ ...(extra?.attachments?.length ? { attachments: extra.attachments } : {}),
+ ...(extra?.mentions?.length ? { mentions: extra.mentions } : {}),
+ },
+ },
+ ),
+
+ editMessage: (channelId: string, msgId: string, text: string) =>
+ req(
+ `/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}`,
+ { method: 'PATCH', data: { text } },
+ ),
+
+ recallMessage: (channelId: string, msgId: string) =>
+ req(
+ `/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}/recall`,
+ { method: 'POST', data: {} },
+ ),
+
+ reactMessage: (channelId: string, msgId: string, emoji: string) =>
+ req(
+ `/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}/react`,
+ { method: 'POST', data: { emoji } },
+ ),
+
+ pinMessage: (channelId: string, msgId: string, pinned = true) =>
+ req(
+ `/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}/pin`,
+ { method: 'POST', data: { pinned } },
+ ),
+
+ reportMessage: (channelId: string, msgId: string, reason = '') =>
+ req(
+ `/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(msgId)}/report`,
+ { method: 'POST', data: { reason } },
+ ),
+
+ presence: (channelId: string, nick?: string) =>
+ req<{ channelId: string; online: number; peers: Array<{ guestId: string; nick: string }> }>(
+ `/channels/${encodeURIComponent(channelId)}/presence`,
+ { method: 'POST', data: { nick: nick || '游民' } },
+ ),
+
+ upload: (channelId: string, filePath: string, kind = 'file', name = 'file') =>
+ new Promise((resolve, reject) => {
+ const gid = guestId()
+ const bases = preferredBase
+ ? [preferredBase, ...SOCIAL_BASES.filter((b) => b !== preferredBase)]
+ : SOCIAL_BASES
+ const tryAt = (i: number) => {
+ if (i >= bases.length) {
+ reject(new Error('upload failed'))
+ return
+ }
+ Taro.uploadFile({
+ url: `${bases[i]}/api/social/v1/channels/${encodeURIComponent(channelId)}/upload?guest=${encodeURIComponent(gid)}`,
+ filePath,
+ name: 'file',
+ formData: { kind },
+ header: { 'X-Social-Guest-Id': gid },
+ success: (res) => {
+ if (res.statusCode >= 200 && res.statusCode < 300) {
+ try {
+ const data = JSON.parse(String(res.data || '{}')) as SocialChatAttachment
+ if (bases[i]) preferredBase = bases[i]
+ resolve({ ...data, name: data.name || name })
+ } catch (e) {
+ reject(e)
+ }
+ } else tryAt(i + 1)
+ },
+ fail: () => tryAt(i + 1),
+ })
+ }
+ tryAt(0)
+ }),
+
+ postNote: (channelId: string, what: 'recv' | 'read' | 'kp', seq = 0) =>
+ req<{ ok?: boolean; what: string; seq?: number }>(
+ `/channels/${encodeURIComponent(channelId)}/notes`,
+ { method: 'POST', data: { what, seq } },
),
applyGig: async (gigId: string, payload: GigApplyPayload) => {
diff --git a/apps/miniprogram/h5/src/services/socialChatState.ts b/apps/miniprogram/h5/src/services/socialChatState.ts
index bf93e88..3e45e28 100644
--- a/apps/miniprogram/h5/src/services/socialChatState.ts
+++ b/apps/miniprogram/h5/src/services/socialChatState.ts
@@ -1,5 +1,14 @@
import type { SocialChatMessage } from './socialApi'
+export function maxChatSeq(items: SocialChatMessage[]): number {
+ let m = 0
+ for (const item of items) {
+ const s = Number(item.seq || 0)
+ if (s > m) m = s
+ }
+ return m
+}
+
export function mergeChatMessages(current: SocialChatMessage[], incoming: SocialChatMessage[], guest: string): SocialChatMessage[] {
const byId = new Map(current.map((item) => [item.id, item]))
for (const item of incoming) {
@@ -11,5 +20,12 @@ export function mergeChatMessages(current: SocialChatMessage[], incoming: Social
}
byId.set(item.id, { ...item, mine: item.guestId === guest, delivery: 'sent' })
}
- return Array.from(byId.values()).sort((a, b) => a.at.localeCompare(b.at)).slice(-300)
+ return Array.from(byId.values())
+ .sort((a, b) => {
+ const sa = Number(a.seq || 0)
+ const sb = Number(b.seq || 0)
+ if (sa && sb && sa !== sb) return sa - sb
+ return String(a.at).localeCompare(String(b.at))
+ })
+ .slice(-300)
}
diff --git a/apps/miniprogram/h5/src/services/socialRealtime.ts b/apps/miniprogram/h5/src/services/socialRealtime.ts
index 03c2b17..763870f 100644
--- a/apps/miniprogram/h5/src/services/socialRealtime.ts
+++ b/apps/miniprogram/h5/src/services/socialRealtime.ts
@@ -3,8 +3,21 @@ import Taro from '@tarojs/taro'
import { socialApi, type SocialChatMessage } from './socialApi'
type PubHandler = (message: SocialChatMessage) => void
+export type SocialChatNote = {
+ type?: string
+ what: 'recv' | 'read' | 'kp'
+ guestId: string
+ seq?: number
+ channelId?: string
+}
+type NoteHandler = (note: SocialChatNote) => void
-export async function connectChatRealtime(channelId: string, onMessage: PubHandler, onConnection?: (connected: boolean) => void): Promise<{ disconnect: () => void } | null> {
+export async function connectChatRealtime(
+ channelId: string,
+ onMessage: PubHandler,
+ onConnection?: (connected: boolean) => void,
+ onNote?: NoteHandler,
+): Promise<{ disconnect: () => void } | null> {
let info
try { info = await socialApi.realtimeToken(channelId) } catch { return null }
if (!info?.ok || !info.enabled || !info.token || !info.wsUrl) return null
@@ -54,8 +67,13 @@ export async function connectChatRealtime(channelId: string, onMessage: PubHandl
resolve({ disconnect: stop })
}
const publication = message.push?.pub?.data
- const item = publication?.type === 'chat.message' ? publication.message : publication
- if (item?.id && item.channelId === channelId) onMessage(item)
+ if (publication?.type === 'chat.note' && onNote) {
+ const note = publication as SocialChatNote
+ if (note.what && note.guestId) onNote(note)
+ } else {
+ const item = publication?.type === 'chat.message' ? publication.message : publication
+ if (item?.id && item.channelId === channelId) onMessage(item)
+ }
if (!Object.keys(message).length) {
try { task.send({ data: '{}' }) } catch { failed() }
}
diff --git a/apps/miniprogram/tt/src/pages/vip/index.tsx b/apps/miniprogram/tt/src/pages/vip/index.tsx
index 73e8405..5b4cc7a 100644
--- a/apps/miniprogram/tt/src/pages/vip/index.tsx
+++ b/apps/miniprogram/tt/src/pages/vip/index.tsx
@@ -183,7 +183,7 @@ function VipLanding() {
/** 抖音无支付:全免费,不展示锁/不拉支付 */
const payOk = cfg.flags.payEnabled !== false
const freeMode = !payOk
- const priceFen = freeMode ? 0 : cfg.copy.vipPriceFen || 29800
+ const priceFen = freeMode ? 0 : cfg.copy.vipPriceFen || 8800
const productId = cfg.copy.vipProductId || 'vip_membership'
const cta = freeMode ? '本端免费开放' : cfg.copy.vipCta || '立即加入'
const brand = cfg.copy.homeBrand || 'nomadro'
diff --git a/apps/miniprogram/weapp/ai-pkg/socialSkill/SKILL.md b/apps/miniprogram/weapp/ai-pkg/socialSkill/SKILL.md
index f7eaacf..521cfa5 100644
--- a/apps/miniprogram/weapp/ai-pkg/socialSkill/SKILL.md
+++ b/apps/miniprogram/weapp/ai-pkg/socialSkill/SKILL.md
@@ -1,12 +1,15 @@
# 游民社区 socialSkill
-帮助用户完成 nomadro 游民社区三件事:加群收费、开语音视频、找搭子申请。
+帮助用户完成 nomadro 游民社区:加群收费、开语音视频、找搭子申请、看地图城市。
+
+与 Web 公开面同源:`https://nomadro.com/api/public/v1/*`(工具表见 `packages/sdk/tools.json`)。
## 何时使用
- 用户想加入游民社区、付费入群、认识同频的人 → `joinSocialCommunity`
- 用户想开视频/语音、参加线上见面、进入某场 meetup → `listMeetupRooms` / `openMeetupLive`
- 用户想找搭子、兼职、志愿、共创、报名岗位 → `listTeamGigs` / `applyTeamGig`
+- 用户想看全球城市 / 地图 → `listMapCities`(Web 接力 `/social/map`)
## 重要约束
@@ -14,6 +17,7 @@
2. 微信内视频用原生 live-pusher(RTC)+ 接力页;不要建议 web-view。
3. 申请岗位必须有称呼与联系方式;简介可选。失败时说明已先留本机,可重试。
4. 优先返回 handoff / page-link,让用户点进小程序接力页完成支付或填表。
+5. 默认数据源 `.com`;`.cn` 为独立中国站。
## 离线兜底
diff --git a/apps/miniprogram/weapp/ai-pkg/socialSkill/mcp.json b/apps/miniprogram/weapp/ai-pkg/socialSkill/mcp.json
index 3747c54..83f07b3 100644
--- a/apps/miniprogram/weapp/ai-pkg/socialSkill/mcp.json
+++ b/apps/miniprogram/weapp/ai-pkg/socialSkill/mcp.json
@@ -2,12 +2,13 @@
"apis": [
{
"name": "joinSocialCommunity",
- "description": "加入游民社区(加群收费,微信虚拟支付)。与 VIP 会员、community 付费体系不同。返回加群说明与接力到支付页。",
+ "description": "加入游民社区(加群收费,微信虚拟支付)。与 VIP 会员、community 付费体系不同。返回加群说明与接力到支付页。对齐公开 API GET /api/public/v1/social/join。",
"_meta": {
"ui": {
"componentPath": "components/join-card/index",
"pagePath": "/pages/social/index"
- }
+ },
+ "http": { "method": "GET", "path": "/api/public/v1/social/join" }
},
"inputSchema": {
"type": "object",
@@ -35,12 +36,13 @@
},
{
"name": "listMeetupRooms",
- "description": "列出可开语音/视频的线上见面场次(MiroTalk / 微信 live-pusher RTC)。",
+ "description": "列出可开语音/视频的线上见面场次。对齐 GET /api/public/v1/social/meetups。",
"_meta": {
"ui": {
"componentPath": "components/meetup-list/index",
"pagePath": "/pages/social/meetup/index"
- }
+ },
+ "http": { "method": "GET", "path": "/api/public/v1/social/meetups" }
},
"inputSchema": {
"type": "object",
@@ -66,11 +68,15 @@
},
{
"name": "openMeetupLive",
- "description": "打开指定场次的语音视频厅。微信内原生 live-pusher;H5 为 MiroTalk WebRTC。",
+ "description": "打开指定场次的语音视频厅。微信内原生 live-pusher;H5 为 MiroTalk。对齐 GET /api/public/v1/social/meetups/{meetupId}。",
"_meta": {
"ui": {
"componentPath": "components/meetup-live-card/index",
"pagePath": "/pages/social/meetup-live/index"
+ },
+ "http": {
+ "method": "GET",
+ "path": "/api/public/v1/social/meetups/{meetupId}"
}
},
"inputSchema": {
@@ -102,12 +108,13 @@
},
{
"name": "listTeamGigs",
- "description": "列出找搭子/共创机会(志愿、兼职、全职),供用户挑选后申请。",
+ "description": "列出找搭子/共创机会。对齐 GET /api/public/v1/social/gigs。",
"_meta": {
"ui": {
"componentPath": "components/gig-list/index",
"pagePath": "/pages/social/team/index"
- }
+ },
+ "http": { "method": "GET", "path": "/api/public/v1/social/gigs" }
},
"inputSchema": {
"type": "object",
@@ -135,13 +142,17 @@
},
{
"name": "applyTeamGig",
- "description": "提交找搭子/共创申请表。需称呼与联系方式;可接力到申请页补全。",
+ "description": "提交找搭子/共创申请。对齐 POST /api/public/v1/social/gigs/{gigId}/apply。",
"_meta": {
"ui": {
"componentPath": "components/apply-card/index",
"pagePath": "/pages/social/team/index"
},
- "context": { "query": true }
+ "context": { "query": true },
+ "http": {
+ "method": "POST",
+ "path": "/api/public/v1/social/gigs/{gigId}/apply"
+ }
},
"inputSchema": {
"type": "object",
@@ -165,6 +176,34 @@
"linkText": { "type": "string" }
}
}
+ },
+ {
+ "name": "listMapCities",
+ "description": "全球城市地图点位。对齐 GET /api/public/v1/social/cities;H5/Web 打开 /social/map。",
+ "_meta": {
+ "http": { "method": "GET", "path": "/api/public/v1/social/cities" }
+ },
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "west": { "type": "number" },
+ "south": { "type": "number" },
+ "east": { "type": "number" },
+ "north": { "type": "number" }
+ }
+ },
+ "outputSchema": {
+ "type": "object",
+ "properties": {
+ "items": { "type": "array" },
+ "pagePath": {
+ "type": "string",
+ "format": "page-link",
+ "x-link-text-field": "linkText"
+ },
+ "linkText": { "type": "string" }
+ }
+ }
}
]
}
diff --git a/apps/notify/README.md b/apps/notify/README.md
new file mode 100644
index 0000000..384672e
--- /dev/null
+++ b/apps/notify/README.md
@@ -0,0 +1,36 @@
+# Notify — Novu-domain secondary-dev (Next + FastAPI)
+
+读开源 **Novu** 域模型后自研,模块化进 Nomadro(Fair Use;非 iframe / 非原样塞 upstream UI):
+
+| 能力 | 参考源码 | UI | API |
+|------|----------|----|-----|
+| Inbox | Novu Inbox / messages | `/social/notifications`(分类 · 已读 · 删除) | FastAPI `notify_svc` `/api/notify/v1` |
+| Settings | Preferences / channels | `/social/notifications/settings` | 免打扰 · 邮件 · 浏览器推送 |
+| Workflows | Workflow + steps (in_app / email / sms / push / chat / delay / digest) | `/social/notify/workflows` | 同上 |
+| Subscribers / Topics | Subscriber · Topic | `/social/notify/subscribers` · `/topics` | 同上 |
+| Trigger / Activity | Event · Notification · Jobs | `/social/notify/activity` | `POST /events/trigger` |
+
+## 本地
+
+```bash
+pnpm notify:fetch # 可选:对照源码 → apps/notify/upstream/novu
+pnpm dev:notify-api # uvicorn notify_main:app :8023
+pnpm dev # http://localhost:3000/notifications
+```
+
+门户经 `src/app/api/notify/v1/[[...path]]` 同源代理到 `NOTIFY_API_URL`(默认 `http://127.0.0.1:8023`)。顶部铃铛在 `SiteShell`。
+
+## 首期范围
+
+- **用户收件箱**:分类(社交/搭子/项目/系统)、点击跳转、全部/单条已读、删除
+- **偏好**:免打扰、邮件订阅、浏览器推送授权
+- **In-App**:即时写入收件箱;编排台仍在 `/social/notify`
+- **Workflow 编辑与触发**:订阅者或 Topic fan-out
+- **外发通道**(email / sms / push / chat):记录 `queued_stub` 投递意图,不接真实供应商
+- **Delay / Digest / Throttle**:步骤可编排,执行记 `skipped_recorded`
+
+## 数据与反模式
+
+- SQLite:`data/notify/notify.sqlite3`(或 `NOTIFY_DATA_DIR`)
+- Upstream 仅参考:`apps/notify/upstream/*`(`pnpm notify:fetch`)
+- **禁止** iframe / 二级域 / 跑官方 Novu Docker UI 当产品页
diff --git a/apps/notify/scripts/fetch-upstream.mjs b/apps/notify/scripts/fetch-upstream.mjs
new file mode 100644
index 0000000..a495fef
--- /dev/null
+++ b/apps/notify/scripts/fetch-upstream.mjs
@@ -0,0 +1,49 @@
+#!/usr/bin/env node
+/**
+ * Shallow-clone Novu into apps/notify/upstream/ for secondary development.
+ * Does not commit upstream into git.
+ */
+import { spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const upstream = join(root, "upstream");
+
+const REPOS = [
+ {
+ name: "novu",
+ url: "https://github.com/novuhq/novu.git",
+ branch: "next",
+ },
+];
+
+mkdirSync(upstream, { recursive: true });
+
+function run(cmd, args, cwd) {
+ console.log(`$ ${cmd} ${args.join(" ")}`);
+ const r = spawnSync(cmd, args, { cwd, stdio: "inherit", shell: false });
+ if (r.status !== 0) process.exit(r.status || 1);
+}
+
+for (const repo of REPOS) {
+ const dest = join(upstream, repo.name);
+ if (existsSync(join(dest, ".git"))) {
+ console.log(`[skip] ${repo.name} already cloned — pull --ff-only`);
+ run("git", ["-C", dest, "pull", "--ff-only", "origin", repo.branch]);
+ continue;
+ }
+ if (existsSync(dest)) rmSync(dest, { recursive: true, force: true });
+ run("git", [
+ "clone",
+ "--depth",
+ "1",
+ "--branch",
+ repo.branch,
+ repo.url,
+ dest,
+ ]);
+}
+
+console.log("DONE fetch-upstream →", upstream);
diff --git a/apps/work/README.md b/apps/work/README.md
index 1cda957..da05789 100644
--- a/apps/work/README.md
+++ b/apps/work/README.md
@@ -14,7 +14,18 @@ pnpm dev:work-api # uvicorn work_main:app :8021
pnpm dev # http://localhost:3000/social/work
```
-门户经 `src/app/api/work/v1/[[...path]]` 同源代理到 `WORK_API_URL`(默认 `http://127.0.0.1:8021`)。
+门户经 `src/app/api/work/v1/[[...path]]` 同源代理到 `WORK_API_URL`(默认 `http://127.0.0.1:8021`)。代理只转发 `content-type` / `authorization`,避免把 nginx 的 `Connection: upgrade` 带给 uvicorn。
+
+## 生产(`.com` / 美国机)
+
+```bash
+pnpm exec next build
+python deploy/work/deploy_us.py
+```
+
+- systemd:`nomadro-work` → `127.0.0.1:8021`
+- nginx:`deploy/work/nginx-work-api.conf` → `location ^~ /api/work/` 直连 8021(与 `/api/social/` 同模式)
+- 页面仍走门户 `:4003`;API 不经过 Next
## 看板能力(Planka 对齐子集)
diff --git a/data/remote-config.json b/data/remote-config.json
index cde8683..d9bf3e2 100644
--- a/data/remote-config.json
+++ b/data/remote-config.json
@@ -59,9 +59,9 @@
"homeBrand": "nomadro",
"homeTagline": "",
"homeLead": "",
- "vipPriceFen": 29800,
+ "vipPriceFen": 8800,
"vipProductId": "tiktok",
- "vipCta": "立即加入 · ¥298",
+ "vipCta": "立即加入 · ¥88",
"vipOfferKey": "tiktok",
"wechatOaName": "异度世界",
"joinGroupDouyinHint": "打开抖音搜群「数字游民」或扫码进群",
diff --git a/deploy/coffee/_smoke_local.py b/deploy/coffee/_smoke_local.py
new file mode 100644
index 0000000..0e2ee59
--- /dev/null
+++ b/deploy/coffee/_smoke_local.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import json
+import urllib.request
+from datetime import date, timedelta
+
+BASE = "http://127.0.0.1:8024/api/coffee/v1"
+
+
+def req(method: str, path: str, body=None):
+ data = None if body is None else json.dumps(body).encode()
+ r = urllib.request.Request(
+ BASE + path,
+ data=data,
+ method=method,
+ headers={"Content-Type": "application/json"} if body is not None else {},
+ )
+ with urllib.request.urlopen(r, timeout=10) as res:
+ return json.loads(res.read().decode())
+
+
+def main() -> int:
+ print("hosts", [h["username"] for h in req("GET", "/hosts")["hosts"]])
+ h = req("GET", "/hosts/alice")["host"]
+ print("alice events", [e["slug"] for e in h["event_types"]])
+ day = None
+ slot = None
+ for i in range(0, 10):
+ d = (date.today() + timedelta(days=i)).isoformat()
+ s = req("GET", f"/hosts/alice/event-types/coffee-30/slots?day={d}")
+ if s["slots"]:
+ day = d
+ slot = s["slots"][0]
+ break
+ print("day", day, "slot", slot)
+ assert day and slot
+ bk = req(
+ "POST",
+ "/bookings",
+ {
+ "username": "alice",
+ "event_slug": "coffee-30",
+ "start": slot["start"],
+ "attendee_name": "Smoke Tester",
+ "attendee_email": "smoke@nomadro.com",
+ "notes": "cal secondary-dev",
+ },
+ )
+ print("booked", bk["booking"]["id"], bk["booking"]["status"])
+ s2 = req("GET", f"/hosts/alice/event-types/coffee-30/slots?day={day}")
+ assert slot["start"] not in {x["start"] for x in s2["slots"]}
+ print("slot_removed_ok")
+ c = req("POST", f"/bookings/{bk['booking']['id']}/cancel")
+ print("cancel", c["booking"]["status"])
+ print("OK")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/deploy/observability/README.md b/deploy/observability/README.md
index ae17342..3500d99 100644
--- a/deploy/observability/README.md
+++ b/deploy/observability/README.md
@@ -53,6 +53,18 @@ curl -H "Title: test" -d "hello" https://ntfy.nomadro.cn/nomadro
健康检查:`deploy/observability/healthcheck.sh`(建议 cron 每 5 分钟),失败/恢复边沿推 ntfy。
+## vip.hackrobot.cn(129 旁路)
+
+- 埋点 sidecar:`pm2 vip-track` · `/opt/vip-track` · 独立 `events.db`
+- ntfy topic:`vip-hackrobot`(订阅需 `hackrobot` 账号;见 `apps/admin/deploy/_vip_track_assets/README.md`)
+- 安全部署:`python apps/admin/deploy/_push_vip_track_v2.py`(不重启业务 `vip`)
+
+## vip.hackrobot.cn(129 旁路)
+
+- 埋点 sidecar:`pm2 vip-track` · `/opt/vip-track` · 独立 `events.db`
+- ntfy topic:`vip-hackrobot`(订阅需 `hackrobot` 账号;见 `apps/admin/deploy/_vip_track_assets/README.md`)
+- 安全部署:`python apps/admin/deploy/_push_vip_track_v2.py`(不重启业务 `vip`)
+
## 门户部署(日常)
1. 本地 `pnpm build`
diff --git a/deploy/router/README.md b/deploy/router/README.md
index 2421f81..dcbd768 100644
--- a/deploy/router/README.md
+++ b/deploy/router/README.md
@@ -10,7 +10,11 @@
First HTML visit without a cookie gets a same-origin sniff page that sets `nomadro_route` and reloads.
-Detection matches `is-china-user` language + timezone signals (any Chinese language in `navigator.languages` counts).
+Detection(对齐 `src/lib/audience.ts`):
+
+1. WeChat / WeCom in-app UA (`MicroMessenger` / `wxwork`) → Chinese lane
+2. Else `is-china-user` language + timezone sniff (any Chinese in `navigator.languages`)
+3. Else English / intl → WordPress
Router listens on `127.0.0.1:4403`.
diff --git a/deploy/router/server.mjs b/deploy/router/server.mjs
index b33ba9d..9904222 100644
--- a/deploy/router/server.mjs
+++ b/deploy/router/server.mjs
@@ -103,7 +103,16 @@ function sniffHtml() {
} catch (e2) {}
return false;
}
- var china = byLang() || byTz();
+ function byWeChat() {
+ try {
+ var ua = navigator.userAgent || "";
+ // 微信 / 企业微信内置 → 强制中文用户特殊线
+ if (/micromessenger/i.test(ua) || /wxwork|wecom/i.test(ua)) return true;
+ } catch (e) {}
+ return false;
+ }
+ // 对齐 src/lib/audience.ts:微信内置优先,再语言/时区(is-china-user)
+ var china = byWeChat() || byLang() || byTz();
var value = china ? "zh" : "en";
document.cookie = "${COOKIE}=" + value + "; Path=/; Max-Age=${COOKIE_MAX_AGE}; SameSite=Lax";
location.replace(location.pathname + location.search + location.hash);
@@ -129,6 +138,10 @@ function resolveTarget(req) {
if (route === "zh") return NEXT;
if (route === "en") return WP;
+ // 无 cookie 时:微信 UA 直接进中文线,避免再 sniff 丢上下文
+ const ua = String(req.headers["user-agent"] || "");
+ if (/micromessenger/i.test(ua) || /wxwork|wecom/i.test(ua)) return NEXT;
+
if (wantsHtml(req)) return "SNIFF";
const lang = String(req.headers["accept-language"] || "").toLowerCase();
diff --git a/deploy/social/README.md b/deploy/social/README.md
index 7138963..ac83933 100644
--- a/deploy/social/README.md
+++ b/deploy/social/README.md
@@ -60,13 +60,18 @@ python deploy/social/deploy_local_build_82.py
- `SOCIAL_DB_PATH=/var/www/nomadro-data/social/social.db`
- `NEXT_PUBLIC_MIROTALK_URL=https://mirotalk.nomadro.cn`(`/etc/nomadro/portal.env`)
- Centrifugo:`CENTRIFUGO_*`(见 `/etc/nomadro/centrifugo.env`,可并入 `portal.env`)
+- 头像 / 媒体(美国机 SeaweedFS,与 community 共用):`S3_ENABLED` · `S3_ENDPOINT=http://127.0.0.1:8333` · `S3_PUBLIC_URL=https://s3.nomadro.com` · `S3_BUCKET=nomadweb` · `S3_ACCESS_KEY` · `S3_SECRET_KEY` · `S3_UPLOAD_PREFIX=social`
-**前端发版**:先本地 `pnpm dev` 验收 `/social`;**未经负责人允许不上线**门户 `.next`。发版线:`test7`(H5 深优见根 `README.md`);当前开发:`test8`。
+**加入头像**:`POST /api/social/v1/upload`(multipart `file` + `purpose=avatar`,头 `X-Social-Guest-Id`)→ 公网 URL 或本地 `/api/social/v1/files/avatar/*`。
+
+**前端发版**:先本地 `pnpm dev` 验收 `/social`;**未经负责人允许不上线**门户 `.next`。当前开发 / 提审:`test9`(见根 `README.md`)。
**H5(≤900px)**:`src/modules/social/app/h5.css` 最后加载;Ways 竖列表(群组聊天优先)、底栏聊天在「认识」左侧、滑卡/composer 避开 dock。
冒烟:
- `https://nomadro.cn/social` → 200
+- `https://nomadro.cn/social/map` · `/social/places` → 200
+- `GET /api/social/v1/map/cities` → 200(种子城)
- `https://nomadro.cn/social/chat` · `/social/date` → 200(手机视口)
- `https://mirotalk.nomadro.cn/join?...` → 200(勿再用 `.com`)
- `GET /api/social/v1/health` → `centrifugo: true`
@@ -91,12 +96,11 @@ python deploy/social/deploy_local_build_82.py
| 域名 | IP | 说明 |
|---|---|---|
| `nomadro.cn` | **82.157.112.245** | 门户直连 |
-| `mirotalk.nomadro.cn` | **82.157.112.245** | 本机 nginx → `127.0.0.1:9300`(**推荐进房 URL**) |
-| `mirotalk.nomadro.com` | 107.173.30.245 | 旧边车 Caddy 反代,多一跳,慢 |
+| `nomadro.cn/join` · `nomadro.com/join` | 同机 nginx → `127.0.0.1:9300` | **推荐进房 URL(同域 iframe,禁止跳二级域)** |
+| `mirotalk.nomadro.cn` | **82.157.112.245** | 兼容旧链;新进房勿再用 |
+| `mirotalk.nomadro.com` | 同 US / 旧边车 | 兼容旧链;新进房勿再用 |
-门户默认用 **`https://mirotalk.nomadro.cn`**(与主站同机)。`ALLOWED_EMBED_ORIGINS` 在 82 上 MiroTalk `.env`;`.com` 边车 CSP 在 107:`/etc/caddy/sites/mirotalk.nomadro.com.caddy`。
-
-本地 `pnpm dev`(:3000)活动页应可 iframe;若仍被拒,`MeetupLiveClient` 会本页 `location.assign` 进入(不新开标签)。
+门户默认 **`window.location.origin`**(同域 `/join`)。`ALLOWED_EMBED_ORIGINS` 在 MiroTalk `.env`。`MeetupLiveClient` **始终页内 iframe**,绝不 `location.assign` 到 `mirotalk.*`。
### 白标(去 MiroTalk 品牌 / 禁弹窗)
diff --git a/deploy/social/deploy_local_build_82.py b/deploy/social/deploy_local_build_82.py
index 0bf0ad9..69802bf 100644
--- a/deploy/social/deploy_local_build_82.py
+++ b/deploy/social/deploy_local_build_82.py
@@ -27,6 +27,10 @@ SRC_INCLUDE = [
"pnpm-lock.yaml",
"README.md",
"deploy/social",
+ "apps/api/services/social_svc",
+ "apps/api/social_main.py",
+ "apps/api/requirements.txt",
+ "public/maplibre",
]
@@ -106,6 +110,7 @@ if [ -f .next/BUILD_ID ]; then
rm -rf /tmp/nomadro.next.bak
mv .next /tmp/nomadro.next.bak
fi
+find "$APP/apps/api/services/social_svc" -type d -name '__pycache__' -prune -exec rm -rf {{}} + 2>/dev/null || true
tar -xzf /tmp/portal_local.tgz --no-same-owner
test -f .next/BUILD_ID
echo BUILD_ID=$(cat .next/BUILD_ID)
@@ -118,14 +123,28 @@ node -e "require('next/package.json')"
test -e node_modules/next/dist/compiled/cookie/index.js \\
|| test -e node_modules/.pnpm/next@*/node_modules/next/dist/compiled/cookie/index.js \\
|| {{ echo 'next cookie missing after install'; exit 4; }}
+# social API deps (upload + geo)
+if [ -x "$APP/apps/api/.venv-social/bin/pip" ]; then
+ "$APP/apps/api/.venv-social/bin/pip" install -q 'python-multipart' 'h3' 'httpx' || true
+fi
sudo systemctl reset-failed nomadro.service || true
sudo systemctl start nomadro.service
-sleep 6
+sudo systemctl restart nomadro-social.service || true
+sleep 8
systemctl is-active nomadro.service
+# social may briefly report activating after restart
+for _ in 1 2 3 4 5 6; do
+ systemctl is-active nomadro-social.service && break
+ sleep 2
+done
+systemctl is-active nomadro-social.service || true
curl -sS -m 12 -o /dev/null -w 'local=%{{http_code}}\\n' http://127.0.0.1:4003/ || true
curl -sS -m 12 -o /dev/null -w 'home=%{{http_code}}\\n' https://nomadro.cn/ || true
curl -sS -m 12 -o /dev/null -w 'social=%{{http_code}}\\n' https://nomadro.cn/social || true
-curl -sS -m 12 -o /dev/null -w 'date=%{{http_code}}\\n' https://nomadro.cn/social/date || true
+curl -sS -m 12 -o /dev/null -w 'map=%{{http_code}}\\n' https://nomadro.cn/social/map || true
+curl -sS -m 12 -o /dev/null -w 'places=%{{http_code}}\\n' https://nomadro.cn/social/places || true
+curl -sS -m 12 -o /dev/null -w 'health=%{{http_code}}\\n' https://nomadro.cn/api/social/v1/health || true
+curl -sS -m 12 -o /dev/null -w 'map_cities=%{{http_code}}\\n' https://nomadro.cn/api/social/v1/map/cities || true
free -h | head -2
echo DONE_LOCAL_DEPLOY
"""
diff --git a/deploy/work/_debug_proxy_us.py b/deploy/work/_debug_proxy_us.py
new file mode 100644
index 0000000..e14bee4
--- /dev/null
+++ b/deploy/work/_debug_proxy_us.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import sys
+import paramiko
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
+
+CMD = r"""
+set +e
+echo '=== local next proxy ==='
+curl -sS -m 10 http://127.0.0.1:4003/api/work/v1/boards | head -c 400; echo
+curl -sS -m 10 http://127.0.0.1:4003/api/work/v1/health | head -c 200; echo
+echo '=== node fetch ==='
+cd /var/www/nomadro.cn
+node <<'NODE'
+fetch('http://127.0.0.1:8021/api/work/v1/boards')
+ .then(async (r) => {
+ console.log('status', r.status);
+ console.log((await r.text()).slice(0, 200));
+ })
+ .catch((e) => console.error('ERR', e));
+NODE
+echo '=== disk routes ==='
+ls -la src/app/api/work/v1/ || true
+find src/app/api/work -type f | head -40
+echo '--- .next ---'
+find .next/server/app/api/work -type f 2>/dev/null | head -50
+"""
+
+c = paramiko.SSHClient()
+c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False)
+_, o, e = c.exec_command(CMD, timeout=60)
+print(o.read().decode())
+err = e.read().decode()
+if err.strip():
+ print("STDERR", err[-2000:])
+c.close()
diff --git a/deploy/work/_fix_nginx_work_api_us.py b/deploy/work/_fix_nginx_work_api_us.py
new file mode 100644
index 0000000..7b01300
--- /dev/null
+++ b/deploy/work/_fix_nginx_work_api_us.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""Install /api/work/ → :8021 nginx snippet on US and smoke."""
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import paramiko
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
+
+ROOT = Path(__file__).resolve().parent
+US = ("108.174.50.68", "root", "Xiao4669805")
+SNIPPET = (ROOT / "nginx-work-api.conf").read_text(encoding="utf-8")
+CONF = "/etc/nginx/sites-enabled/nomadro.com.conf"
+INCLUDE = "include /etc/nginx/snippets/nomadro-work-api.conf;"
+
+
+def main() -> int:
+ c = paramiko.SSHClient()
+ c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+ h, u, p = US
+ c.connect(h, 22, u, p, timeout=40, allow_agent=False, look_for_keys=False)
+ try:
+ sftp = c.open_sftp()
+ with sftp.file("/tmp/nomadro-work-api.conf", "w") as f:
+ f.write(SNIPPET)
+ sftp.close()
+
+ cmd = f"""
+set -euo pipefail
+install -m 644 /tmp/nomadro-work-api.conf /etc/nginx/snippets/nomadro-work-api.conf
+rm -f /tmp/nomadro-work-api.conf
+# ensure include once inside each https server, before location /
+if ! grep -q 'nomadro-work-api.conf' {CONF}; then
+ # insert after work-mf include if present, else before location /
+ if grep -q 'nomadro-work-mf.conf' {CONF}; then
+ sed -i 's|include /etc/nginx/snippets/nomadro-work-mf.conf;|include /etc/nginx/snippets/nomadro-work-mf.conf;\\n {INCLUDE}|g' {CONF}
+ else
+ sed -i 's|location / {{| {INCLUDE}\\n location / {{|g' {CONF}
+ fi
+fi
+nginx -t
+systemctl reload nginx
+systemctl is-active nomadro-work
+curl -sS -m 5 http://127.0.0.1:8021/api/work/v1/health; echo
+curl -sk -m 10 -o /dev/null -w 'nginx_local=%{{http_code}}\\n' -H 'Host: nomadro.com' https://127.0.0.1/api/work/v1/boards
+curl -sS -m 12 -o /dev/null -w 'com_boards=%{{http_code}}\\n' https://nomadro.com/api/work/v1/boards
+curl -sS -m 12 https://nomadro.com/api/work/v1/boards | head -c 320; echo
+curl -sS -m 8 -o /dev/null -w 'com_health=%{{http_code}}\\n' https://nomadro.com/api/work/v1/health
+curl -sS -m 8 -o /dev/null -w 'com_work=%{{http_code}}\\n' https://nomadro.com/social/work
+curl -sS -m 8 -o /dev/null -w 'com_page_boards=%{{http_code}}\\n' https://nomadro.com/social/work/boards
+grep -n 'work-api' {CONF} | head -10
+"""
+ _, o, e = c.exec_command(cmd, timeout=60)
+ out = o.read().decode("utf-8", "replace")
+ err = e.read().decode("utf-8", "replace")
+ code = o.channel.recv_exit_status()
+ print(out)
+ if err.strip():
+ print("STDERR", err[-2000:])
+ print("exit", code)
+ return code
+ finally:
+ c.close()
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/deploy/work/_fix_work_env_us.py b/deploy/work/_fix_work_env_us.py
new file mode 100644
index 0000000..dd1c910
--- /dev/null
+++ b/deploy/work/_fix_work_env_us.py
@@ -0,0 +1,76 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""Ensure WORK_API_URL reaches Next on US and re-smoke /api/work/v1."""
+from __future__ import annotations
+
+import sys
+import time
+
+import paramiko
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
+
+US = ("108.174.50.68", "root", "Xiao4669805")
+
+REMOTE = r"""
+set -euo pipefail
+mkdir -p /etc/systemd/system/nomadro.service.d /etc/nomadro
+grep -q '^WORK_API_URL=' /etc/nomadro/portal.env 2>/dev/null \
+ && sed -i 's|^WORK_API_URL=.*|WORK_API_URL=http://127.0.0.1:8021|' /etc/nomadro/portal.env \
+ || echo 'WORK_API_URL=http://127.0.0.1:8021' >> /etc/nomadro/portal.env
+cat >/etc/systemd/system/nomadro.service.d/work-api.conf <<'EOF'
+[Service]
+EnvironmentFile=-/etc/nomadro/portal.env
+Environment=WORK_API_URL=http://127.0.0.1:8021
+EOF
+systemctl daemon-reload
+systemctl restart nomadro-work || true
+sleep 3
+systemctl is-active nomadro-work || true
+curl -sS -m 5 http://127.0.0.1:8021/health || true
+echo
+systemctl kill -s9 nomadro.service 2>/dev/null || true
+fuser -k 4003/tcp 2>/dev/null || true
+sleep 1
+systemctl reset-failed nomadro || true
+systemctl start nomadro
+sleep 7
+systemctl is-active nomadro || true
+pid=$(systemctl show -p MainPID --value nomadro)
+echo PID=$pid
+tr '\0' '\n' < /proc/$pid/environ 2>/dev/null | grep -E '^WORK_' || echo NO_WORK_ENV_PARENT
+# next may spawn child — check children too
+for p in $(pgrep -P "$pid" 2>/dev/null); do
+ echo child=$p
+ tr '\0' '\n' < /proc/$p/environ 2>/dev/null | grep -E '^WORK_' || true
+done
+curl -sS -m 5 http://127.0.0.1:8021/api/work/v1/health || true
+echo
+curl -sS -m 12 -o /dev/null -w 'api_boards=%{http_code}\n' https://nomadro.com/api/work/v1/boards || true
+curl -sS -m 12 https://nomadro.com/api/work/v1/boards | head -c 320; echo
+curl -sS -m 8 -o /dev/null -w 'api_health=%{http_code}\n' https://nomadro.com/api/work/v1/health || true
+curl -sS -m 8 -o /dev/null -w 'work=%{http_code}\n' https://nomadro.com/social/work || true
+"""
+
+
+def main() -> int:
+ c = paramiko.SSHClient()
+ c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+ h, u, p = US
+ c.connect(h, 22, u, p, timeout=40, allow_agent=False, look_for_keys=False)
+ try:
+ _, o, e = c.exec_command(REMOTE, timeout=120)
+ out = o.read().decode("utf-8", "replace")
+ err = e.read().decode("utf-8", "replace")
+ code = o.channel.recv_exit_status()
+ print(out)
+ if err.strip():
+ print("STDERR", err[-1500:])
+ print("exit", code)
+ return code
+ finally:
+ c.close()
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/deploy/work/_probe_headers_us.py b/deploy/work/_probe_headers_us.py
new file mode 100644
index 0000000..6afc6ba
--- /dev/null
+++ b/deploy/work/_probe_headers_us.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+import sys
+import paramiko
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
+
+CMD = r"""
+set +e
+# reproduce nginx-like headers against Next
+curl -sS -m 10 -o /tmp/out.json -w 'code=%{http_code}\n' \
+ -H 'Host: nomadro.com' \
+ -H 'X-Forwarded-For: 8.8.8.8' \
+ -H 'X-Forwarded-Proto: https' \
+ -H 'X-Forwarded-Host: nomadro.com' \
+ -H 'Connection: close' \
+ -H 'Accept-Encoding: gzip' \
+ http://127.0.0.1:4003/api/work/v1/boards
+head -c 200 /tmp/out.json; echo
+# nginx https again
+curl -sk -m 10 -o /tmp/out2.json -w 'nginx=%{http_code}\n' -H 'Host: nomadro.com' https://127.0.0.1/api/work/v1/boards
+head -c 200 /tmp/out2.json; echo
+# show location / proxy block
+grep -n 'location /\|proxy_pass.*4003\|proxy_set_header' /etc/nginx/sites-enabled/nomadro.com.conf | head -80
+# work-mf snippet
+cat /etc/nginx/snippets/nomadro-work-mf.conf
+"""
+
+c = paramiko.SSHClient()
+c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+c.connect("108.174.50.68", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False)
+_, o, e = c.exec_command(CMD, timeout=45)
+print(o.read().decode())
+err = e.read().decode()
+if err.strip():
+ print("STDERR", err[-800:])
+c.close()
diff --git a/deploy/work/_smoke_com_work.py b/deploy/work/_smoke_com_work.py
new file mode 100644
index 0000000..aa4138a
--- /dev/null
+++ b/deploy/work/_smoke_com_work.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""Smoke https://nomadro.com work pages + API (no PowerShell curl alias)."""
+from __future__ import annotations
+
+import json
+import sys
+import urllib.error
+import urllib.request
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
+
+BASE = "https://nomadro.com"
+PATHS = [
+ "/social/work",
+ "/social/work/boards",
+ "/social/work/pads",
+ "/api/work/v1/health",
+ "/api/work/v1/boards",
+ "/api/work/v1/projects",
+ "/api/work/v1/pads",
+]
+
+
+def fetch(path: str) -> tuple[int, str]:
+ req = urllib.request.Request(
+ BASE + path,
+ headers={"User-Agent": "nomadro-work-smoke/1.0", "Accept": "*/*"},
+ method="GET",
+ )
+ try:
+ with urllib.request.urlopen(req, timeout=20) as res:
+ body = res.read().decode("utf-8", "replace")
+ return res.status, body
+ except urllib.error.HTTPError as e:
+ return e.code, e.read().decode("utf-8", "replace")
+ except Exception as e:
+ return 0, str(e)
+
+
+def main() -> int:
+ bad = 0
+ for path in PATHS:
+ code, body = fetch(path)
+ preview = body.replace("\n", " ")[:160]
+ print(f"{code} {path} {preview}")
+ if code != 200:
+ bad += 1
+ continue
+ if path.startswith("/api/"):
+ try:
+ data = json.loads(body)
+ except json.JSONDecodeError:
+ print(" ! not json")
+ bad += 1
+ continue
+ if data.get("ok") is not True:
+ print(" ! ok!=true", data.keys())
+ bad += 1
+ elif "Nomadro Work" not in body and "进入看板" not in body and "看板" not in body:
+ # boards/pads pages may omit hero copy; accept any 200 HTML
+ if "" not in body and " paramiko.SSHClient:
+ c = paramiko.SSHClient()
+ c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+ h, u, p = US
+ c.connect(h, 22, u, p, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=90)
+ t = c.get_transport()
+ if t:
+ t.set_keepalive(15)
+ return c
+
+
+def sh(c: paramiko.SSHClient, cmd: str, timeout: int = 180) -> tuple[int, str]:
+ print(f"$ {cmd[:220].replace(chr(10), ' ')}", flush=True)
+ _, o, e = c.exec_command(cmd, timeout=timeout, get_pty=False)
+ out = o.read().decode("utf-8", "replace")
+ err = e.read().decode("utf-8", "replace")
+ code = o.channel.recv_exit_status()
+ text = out + (("\n" + err) if err.strip() else "")
+ if text.strip():
+ print(text[-6000:], flush=True)
+ print("exit", code, flush=True)
+ return code, text
+
+
+def main() -> int:
+ nxt = ROOT / ".next"
+ if not (nxt / "BUILD_ID").is_file():
+ print("missing .next — run: pnpm exec next build")
+ return 1
+ build_id = (nxt / "BUILD_ID").read_text(encoding="utf-8").strip()
+ print("BUILD_ID", build_id, flush=True)
+
+ with tempfile.TemporaryDirectory() as td:
+ tgz = Path(td) / "bundle.tgz"
+ cmd = [
+ "tar",
+ "-czf",
+ str(tgz),
+ "--exclude=node_modules",
+ "--exclude=.next/cache",
+ "--exclude=.next/dev",
+ "--exclude=.next/types",
+ "--exclude=__pycache__",
+ "--exclude=*.pyc",
+ "-C",
+ str(ROOT),
+ ".next",
+ "src",
+ "public",
+ "packages/pay",
+ "packages/pb",
+ "packages/sdk",
+ "next.config.ts",
+ "package.json",
+ "pnpm-lock.yaml",
+ "apps/api/work_main.py",
+ "apps/api/services/work_svc",
+ "apps/work/README.md",
+ ]
+ print("packing…", flush=True)
+ subprocess.check_call(cmd)
+ size = tgz.stat().st_size
+ print(f"tarball {size / 1024 / 1024:.1f} MB", flush=True)
+
+ c = connect()
+ try:
+ print("upload…", flush=True)
+ sftp = c.open_sftp()
+ with open(tgz, "rb") as f, sftp.file(REMOTE_TGZ, "wb") as rf:
+ rf.set_pipelined(True)
+ sent = 0
+ while True:
+ chunk = f.read(512 * 1024)
+ if not chunk:
+ break
+ rf.write(chunk)
+ sent += len(chunk)
+ if sent % (8 * 1024 * 1024) < 512 * 1024:
+ print(f" {sent / 1024 / 1024:.1f}/{size / 1024 / 1024:.1f} MB", flush=True)
+ # unit file + nginx snippet (API must not go via Next Connection: upgrade)
+ snippet = (Path(__file__).resolve().parent / "nginx-work-api.conf").read_text(
+ encoding="utf-8"
+ )
+ with sftp.file("/tmp/nomadro-work.service", "w") as uf:
+ uf.write(UNIT)
+ with sftp.file("/tmp/nomadro-work-api.conf", "w") as nf:
+ nf.write(snippet)
+ sftp.close()
+
+ code, _ = sh(
+ c,
+ f"""
+set -euo pipefail
+cd {REMOTE}
+cp -a data/remote-config.json /tmp/rc.preserve.json 2>/dev/null || true
+mkdir -p /var/www/nomadro-data/work apps/api/services
+systemctl kill -s9 nomadro.service 2>/dev/null || true
+fuser -k 4003/tcp 2>/dev/null || true
+sleep 1
+rm -rf .next.bak
+[ -d .next ] && mv .next .next.bak || true
+# drop legacy Next JSON work routes if present (replaced by catch-all proxy)
+rm -rf src/app/api/work/v1/boards src/app/api/work/v1/pads src/app/api/work/v1/projects 2>/dev/null || true
+tar -xzf {REMOTE_TGZ} -C {REMOTE}
+rm -f {REMOTE_TGZ}
+test -f .next/BUILD_ID
+test -f apps/api/work_main.py
+test -d apps/api/services/work_svc
+echo BUILD_ID=$(cat .next/BUILD_ID)
+[ -f /tmp/rc.preserve.json ] && cp -a /tmp/rc.preserve.json data/remote-config.json || true
+
+# portal env: point Next proxy at work_svc
+mkdir -p /etc/nomadro
+touch /etc/nomadro/portal.env
+grep -q '^WORK_API_URL=' /etc/nomadro/portal.env 2>/dev/null \\
+ && sed -i 's|^WORK_API_URL=.*|WORK_API_URL=http://127.0.0.1:8021|' /etc/nomadro/portal.env \\
+ || echo 'WORK_API_URL=http://127.0.0.1:8021' >> /etc/nomadro/portal.env
+grep -q '^WORK_ENABLED=' /etc/nomadro/portal.env 2>/dev/null \\
+ || echo 'WORK_ENABLED=true' >> /etc/nomadro/portal.env
+
+install -m 644 /tmp/nomadro-work.service /etc/systemd/system/nomadro-work.service
+rm -f /tmp/nomadro-work.service
+install -m 644 /tmp/nomadro-work-api.conf /etc/nginx/snippets/nomadro-work-api.conf
+rm -f /tmp/nomadro-work-api.conf
+NGCONF=/etc/nginx/sites-enabled/nomadro.com.conf
+INCLUDE='include /etc/nginx/snippets/nomadro-work-api.conf;'
+if [ -f "$NGCONF" ] && ! grep -q 'nomadro-work-api.conf' "$NGCONF"; then
+ if grep -q 'nomadro-work-mf.conf' "$NGCONF"; then
+ sed -i 's|include /etc/nginx/snippets/nomadro-work-mf.conf;|include /etc/nginx/snippets/nomadro-work-mf.conf;\\n '"$INCLUDE"'|g' "$NGCONF"
+ else
+ sed -i 's|location / {{| '"$INCLUDE"'\\n location / {{|g' "$NGCONF"
+ fi
+fi
+nginx -t && systemctl reload nginx
+systemctl daemon-reload
+systemctl enable nomadro-work
+systemctl restart nomadro-work
+sleep 2
+systemctl is-active nomadro-work
+curl -sS -m 5 http://127.0.0.1:8021/api/work/v1/health || true
+
+export CI=true
+export NODE_OPTIONS='--max-old-space-size=1536'
+/usr/local/bin/pnpm install --prefer-offline || pnpm install --prefer-offline || true
+systemctl reset-failed nomadro 2>/dev/null || true
+systemctl start nomadro
+sleep 6
+systemctl is-active nomadro || true
+""",
+ timeout=480,
+ )
+ if code != 0:
+ print("DEPLOY_FAIL", code)
+ return code
+
+ for i in range(12):
+ _, out = sh(
+ c,
+ "curl -sS -o /dev/null -w '%{http_code}' --max-time 8 http://127.0.0.1:4003/ || echo 000",
+ timeout=20,
+ )
+ http = out.strip().splitlines()[-1] if out.strip() else "000"
+ print("probe", i, http, flush=True)
+ if http in ("200", "301", "302", "307", "308"):
+ break
+ time.sleep(2)
+
+ sh(
+ c,
+ r"""
+set +e
+echo BUILD=$(cat /var/www/nomadro.cn/.next/BUILD_ID)
+systemctl is-active nomadro nomadro-work
+curl -sS -m 8 http://127.0.0.1:8021/health; echo
+curl -sS -m 12 -o /dev/null -w 'home=%{http_code}\n' https://nomadro.com/
+curl -sS -m 12 -o /dev/null -w 'work=%{http_code}\n' https://nomadro.com/social/work
+curl -sS -m 12 -o /dev/null -w 'boards=%{http_code}\n' https://nomadro.com/social/work/boards
+curl -sS -m 12 -o /dev/null -w 'pads=%{http_code}\n' https://nomadro.com/social/work/pads
+curl -sS -m 12 -o /dev/null -w 'api_boards=%{http_code}\n' https://nomadro.com/api/work/v1/boards
+curl -sS -m 12 -o /dev/null -w 'api_health=%{http_code}\n' https://nomadro.com/api/work/v1/health
+curl -sS -m 12 https://nomadro.com/api/work/v1/boards | head -c 360; echo
+curl -sS -m 12 https://nomadro.com/social/work | tr '\n' ' ' | grep -oE 'Nomadro Work|进入看板|Kanban|/social/work/boards|work\.(nomadro)' | head -15
+""",
+ timeout=90,
+ )
+ print("DONE_US_WORK", flush=True)
+ return 0
+ finally:
+ c.close()
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/deploy/work/nginx-work-api.conf b/deploy/work/nginx-work-api.conf
new file mode 100644
index 0000000..d2c4c02
--- /dev/null
+++ b/deploy/work/nginx-work-api.conf
@@ -0,0 +1,13 @@
+# Nomadro work_svc — include inside HTTPS server BEFORE location /
+# Same-origin /api/work/v1 → FastAPI :8021 (do not route via Next; avoids Connection: upgrade break)
+
+location ^~ /api/work/ {
+ proxy_pass http://127.0.0.1:8021;
+ proxy_http_version 1.1;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_read_timeout 60s;
+ add_header Cache-Control "no-store";
+}
diff --git a/deploy/work/nginx-work-mf.conf b/deploy/work/nginx-work-mf.conf
new file mode 100644
index 0000000..9493d68
--- /dev/null
+++ b/deploy/work/nginx-work-mf.conf
@@ -0,0 +1,81 @@
+# Planka API/socket for Next-forked UI — include inside HTTPS server BEFORE location /
+# UI is native Next at /social/work/app ; only /work-api hits Docker Planka :1337
+
+location ^~ /work-api/ {
+ proxy_pass http://127.0.0.1:1337/;
+ proxy_http_version 1.1;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection $connection_upgrade;
+ proxy_read_timeout 3600s;
+ proxy_buffering off;
+}
+
+location = /work-api {
+ proxy_pass http://127.0.0.1:1337/;
+ proxy_http_version 1.1;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+}
+
+# Legacy path proxy (Etherpad UI until ported)
+location ^~ /work-mf/planka/ {
+ proxy_pass http://127.0.0.1:1337/;
+ proxy_http_version 1.1;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection $connection_upgrade;
+ proxy_read_timeout 3600s;
+ proxy_buffering off;
+ proxy_hide_header X-Frame-Options;
+ proxy_hide_header Content-Security-Policy;
+ add_header Content-Security-Policy "frame-ancestors 'self' https://nomadro.com https://www.nomadro.com" always;
+}
+
+location = /work-mf/planka {
+ proxy_pass http://127.0.0.1:1337/;
+ proxy_http_version 1.1;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_hide_header X-Frame-Options;
+ proxy_hide_header Content-Security-Policy;
+ add_header Content-Security-Policy "frame-ancestors 'self' https://nomadro.com https://www.nomadro.com" always;
+}
+
+location ^~ /work-mf/etherpad/ {
+ proxy_pass http://127.0.0.1:9001/;
+ proxy_http_version 1.1;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection $connection_upgrade;
+ proxy_read_timeout 3600s;
+ proxy_buffering off;
+ proxy_hide_header X-Frame-Options;
+ proxy_hide_header Content-Security-Policy;
+ add_header Content-Security-Policy "frame-ancestors 'self' https://nomadro.com https://www.nomadro.com" always;
+}
+
+location = /work-mf/etherpad {
+ proxy_pass http://127.0.0.1:9001/;
+ proxy_http_version 1.1;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_hide_header X-Frame-Options;
+ proxy_hide_header Content-Security-Policy;
+ add_header Content-Security-Policy "frame-ancestors 'self' https://nomadro.com https://www.nomadro.com" always;
+}
diff --git a/docs/public-api.md b/docs/public-api.md
new file mode 100644
index 0000000..af13b0e
--- /dev/null
+++ b/docs/public-api.md
@@ -0,0 +1,54 @@
+# Nomadro Public API / SDK / MCP / Skill
+
+结构化对外服务面(同源):
+
+```
+packages/sdk/tools.json
+ │
+ ├─ OpenAPI → GET /api/public/v1/openapi.json
+ ├─ HTTP → /api/public/v1/*
+ ├─ SDK → @nomadro/sdk createNomadroClient
+ ├─ MCP → @nomadro/mcp (stdio)
+ └─ Skill → .cursor/skills/nomadro-platform
+ apps/miniprogram/weapp/ai-pkg/socialSkill
+```
+
+## 部署
+
+| 环境 | 说明 |
+|---|---|
+| `https://nomadro.com` | **主站 / 默认**(美国 VPS) |
+| `https://nomadro.cn` | 中国独立站;`.com` 中文轨测稳后再同步 |
+| `localhost:3000` | 本地 Next |
+
+可选鉴权:服务端设 `NOMADRO_PUBLIC_API_KEY`,客户端头 `X-Nomadro-Key`。
+
+## 文档界面
+
+| URL | 说明 |
+|---|---|
+| [`/developers`](https://nomadro.com/developers) | Scalar 交互式 API Reference(深色) |
+| `/api/public/docs` | 307 → `/developers` |
+| `/api/public/v1/openapi.json` | 原始 OpenAPI |
+
+## 端点摘要
+
+| Method | Path | Tool |
+|---|---|---|
+| GET | `/api/public/v1/health` | health |
+| GET | `/api/public/v1/meta` | getMeta |
+| GET | `/api/public/v1/config` | getConfig |
+| GET | `/api/public/v1/tools` | — |
+| GET | `/api/public/v1/openapi.json` | — |
+| GET | `/api/public/v1/social/cities` | listMapCities |
+| GET | `/api/public/v1/social/cities/search` | searchCities |
+| GET | `/api/public/v1/social/meetups` | listMeetups |
+| GET | `/api/public/v1/social/meetups/{id}` | openMeetup |
+| GET | `/api/public/v1/social/gigs` | listGigs |
+| POST | `/api/public/v1/social/gigs/{id}/apply` | applyGig |
+| GET | `/api/public/v1/social/join` | joinSocial |
+| GET | `/api/public/v1/social/routes` | listSocialRoutes |
+| GET | `/api/public/v1/vip/check?email=` | checkVip |
+| GET | `/api/public/v1/nav/links` | listNavLinks |
+
+Social 读接口优先反代 `SOCIAL_API_URL`,失败回落本地种子(离线兜底)。
diff --git a/package.json b/package.json
index 5622f6a..47d1d1b 100644
--- a/package.json
+++ b/package.json
@@ -12,6 +12,8 @@
"dev:admin-com": "pnpm --filter @nomadro/admin-com dev",
"dev:api": "node scripts/dev-api.mjs",
"dev:work-api": "python -m uvicorn work_main:app --reload --port 8021 --app-dir apps/api",
+ "dev:notify-api": "python -m uvicorn notify_main:app --reload --port 8023 --app-dir apps/api",
+ "dev:coffee-api": "python -m uvicorn coffee_main:app --reload --port 8024 --app-dir apps/api",
"build": "next build",
"build:portal": "next build",
"build:h5": "pnpm --filter @nomadro/miniprogram-h5 build",
@@ -27,6 +29,8 @@
"mcp": "pnpm --filter @nomadro/mcp start",
"dev:mcp": "pnpm --filter @nomadro/mcp start",
"work:fetch": "node apps/work/scripts/fetch-upstream.mjs",
+ "notify:fetch": "node apps/notify/scripts/fetch-upstream.mjs",
+ "coffee:fetch": "node apps/coffee/scripts/fetch-upstream.mjs",
"work:overlay": "node apps/work/scripts/apply-overlay.mjs",
"work:sync-ui": "node apps/work/scripts/sync-planka-ui.mjs",
"work:patch-ui": "node apps/work/scripts/patch-planka-for-next.mjs",
diff --git a/packages/mcp/package.json b/packages/mcp/package.json
new file mode 100644
index 0000000..7ccbb10
--- /dev/null
+++ b/packages/mcp/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "@nomadro/mcp",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "bin": {
+ "nomadro-mcp": "./src/cli.mjs"
+ },
+ "main": "./src/server.mjs",
+ "scripts": {
+ "start": "node ./src/cli.mjs",
+ "dev": "node ./src/cli.mjs"
+ },
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.12.1"
+ }
+}
diff --git a/packages/mcp/src/cli.mjs b/packages/mcp/src/cli.mjs
new file mode 100644
index 0000000..d4b6d5c
--- /dev/null
+++ b/packages/mcp/src/cli.mjs
@@ -0,0 +1,7 @@
+#!/usr/bin/env node
+import { startNomadroMcp } from "./server.mjs";
+
+startNomadroMcp().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/packages/mcp/src/server.mjs b/packages/mcp/src/server.mjs
new file mode 100644
index 0000000..aeb29e2
--- /dev/null
+++ b/packages/mcp/src/server.mjs
@@ -0,0 +1,103 @@
+/**
+ * Nomadro MCP server (stdio).
+ * Tools = packages/sdk/tools.json → HTTP /api/public/v1
+ *
+ * Env:
+ * NOMADRO_PUBLIC_ORIGIN default https://nomadro.com
+ * NOMADRO_PUBLIC_API_KEY optional
+ * NOMADRO_SOCIAL_GUEST_ID optional
+ */
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { Server } from "@modelcontextprotocol/sdk/server/index.js";
+import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
+import {
+ CallToolRequestSchema,
+ ListToolsRequestSchema,
+} from "@modelcontextprotocol/sdk/types.js";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const TOOLS = JSON.parse(
+ readFileSync(join(__dirname, "../../sdk/tools.json"), "utf8"),
+);
+const PREFIX = "/api/public/v1";
+const VERSION = "1.0.0";
+
+function baseUrl() {
+ return (process.env.NOMADRO_PUBLIC_ORIGIN || "https://nomadro.com").replace(
+ /\/$/,
+ "",
+ );
+}
+
+function fillPath(template, args) {
+ return template.replace(/\{(\w+)\}/g, (_, key) => {
+ if (args[key] == null) throw new Error(`missing ${key}`);
+ return encodeURIComponent(String(args[key]));
+ });
+}
+
+async function callTool(name, args = {}) {
+ 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]);
+ const path = fillPath(tool.path, args);
+ const url = new URL(`${baseUrl()}${PREFIX}${path}`);
+ const headers = { Accept: "application/json" };
+ if (process.env.NOMADRO_PUBLIC_API_KEY) {
+ headers["X-Nomadro-Key"] = process.env.NOMADRO_PUBLIC_API_KEY;
+ }
+ if (process.env.NOMADRO_SOCIAL_GUEST_ID) {
+ headers["X-Social-Guest-Id"] = process.env.NOMADRO_SOCIAL_GUEST_ID;
+ }
+ let body;
+ if (tool.method === "GET") {
+ for (const [k, v] of Object.entries(args)) {
+ if (pathParams.includes(k) || v == null || v === "") continue;
+ url.searchParams.set(k, String(v));
+ }
+ } else {
+ headers["Content-Type"] = "application/json";
+ const payload = { ...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(() => ({}));
+ if (!res.ok) {
+ throw new Error(data.detail || data.error || `HTTP ${res.status}`);
+ }
+ return data;
+}
+
+export async function startNomadroMcp() {
+ const server = new Server(
+ { name: "nomadro", version: VERSION },
+ { capabilities: { tools: {} } },
+ );
+
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
+ tools: TOOLS.map((t) => ({
+ name: t.name,
+ description: `${t.description} [${t.method} ${t.path}]`,
+ inputSchema: t.inputSchema,
+ })),
+ }));
+
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
+ try {
+ const data = await callTool(req.params.name, req.params.arguments || {});
+ return {
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
+ };
+ } catch (e) {
+ return {
+ isError: true,
+ content: [{ type: "text", text: e instanceof Error ? e.message : String(e) }],
+ };
+ }
+ });
+
+ await server.connect(new StdioServerTransport());
+}
diff --git a/packages/pay/src/index.ts b/packages/pay/src/index.ts
index 8ce3ca2..55ce2df 100644
--- a/packages/pay/src/index.ts
+++ b/packages/pay/src/index.ts
@@ -18,8 +18,10 @@ export type PayRegion = "cn" | "overseas" | "auto";
export type ResolvePayInput = {
region?: PayRegion;
- /** Force China user (e.g. from is-china-user) */
+ /** Force China user (e.g. from is-china-user / audience module) */
isChinaUser?: boolean;
+ /** Prefer over isChinaUser when set: cn → 国内网关;intl → Creem */
+ audience?: "cn" | "intl";
userAgent?: string;
};
@@ -63,14 +65,15 @@ export function resolvePayProvider(input: ResolvePayInput = {}): {
channel: PayChannel;
} {
const env = getPayEnv(input.userAgent);
- const region =
- input.region === "auto" || !input.region
- ? input.isChinaUser === false
+ const region: PayRegion =
+ input.region && input.region !== "auto"
+ ? input.region
+ : input.audience === "intl" || input.isChinaUser === false
? "overseas"
- : "cn"
- : input.region;
+ : "cn";
if (region === "overseas") {
+ // 默认 Creem;后端无 CREEM_API_KEY 时自动回退 nowpayments(加密货币)
return {
env,
provider: "creem",
@@ -91,7 +94,12 @@ export function resolvePayProvider(input: ResolvePayInput = {}): {
/** Default public endpoints — override via env in apps */
export const PAY_DEFAULTS = {
- payjsapiPublic: "https://api.hackrobot.cn",
- payjsapiInternal: "http://127.0.0.1:8007",
+ /** .com 美国公网支付 API(/nomadvip/*) */
+ payPublic: "https://api.nomadro.com",
+ payInternal: "http://127.0.0.1:8011",
+ /** @deprecated 旧名,指向美国公网 */
+ payjsapiPublic: "https://api.nomadro.com",
+ /** @deprecated 旧国内端口,勿再当 .com 默认 */
+ payjsapiInternal: "http://127.0.0.1:8011",
zpaySubmit: "https://zpayz.cn/submit.php",
} as const;
diff --git a/packages/pb/schemas/social_trips.json b/packages/pb/schemas/social_trips.json
new file mode 100644
index 0000000..4cbb347
--- /dev/null
+++ b/packages/pb/schemas/social_trips.json
@@ -0,0 +1,29 @@
+{
+ "name": "social_trips",
+ "type": "base",
+ "note": "Created/ensured by social_svc.geo_pb.ensure_collection when PB admin creds are set. Dual-written with SQLite mirror.",
+ "fields": [
+ { "name": "guest_id", "type": "text", "required": true },
+ { "name": "city_id", "type": "text", "required": false },
+ { "name": "city", "type": "text", "required": true },
+ { "name": "country", "type": "text", "required": false },
+ { "name": "lat", "type": "number", "required": false },
+ { "name": "lng", "type": "number", "required": false },
+ { "name": "h3_cell", "type": "text", "required": false },
+ { "name": "arrival_date", "type": "text", "required": false },
+ { "name": "departure_date", "type": "text", "required": false },
+ {
+ "name": "visibility",
+ "type": "select",
+ "required": true,
+ "values": ["public", "friends", "private"]
+ },
+ {
+ "name": "status",
+ "type": "select",
+ "required": true,
+ "values": ["here", "planned", "past"]
+ },
+ { "name": "updated_at", "type": "text", "required": true }
+ ]
+}
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
new file mode 100644
index 0000000..f003c57
--- /dev/null
+++ b/packages/sdk/README.md
@@ -0,0 +1,29 @@
+# `@nomadro/sdk`
+
+Stable Nomadro client + public contract.
+
+## Public API
+
+- Prefix: `/api/public/v1`
+- OpenAPI: `/api/public/v1/openapi.json`
+- Tool SoT: [`tools.json`](./tools.json)
+
+Default host: **`https://nomadro.com`**.
+
+```ts
+import { createNomadroClient } from "@nomadro/sdk";
+
+const api = createNomadroClient({ baseUrl: "https://nomadro.com" });
+await api.health();
+await api.listMapCities();
+await api.callTool("searchCities", { q: "清迈" });
+```
+
+## MCP
+
+```bash
+pnpm mcp
+# NOMADRO_PUBLIC_ORIGIN=https://nomadro.com node packages/mcp/src/cli.mjs
+```
+
+See `.cursor/skills/nomadro-platform/SKILL.md`.
diff --git a/packages/sdk/package.json b/packages/sdk/package.json
index e7b74eb..63056aa 100644
--- a/packages/sdk/package.json
+++ b/packages/sdk/package.json
@@ -1,12 +1,15 @@
{
"name": "@nomadro/sdk",
- "version": "0.2.1",
+ "version": "0.3.0",
"private": true,
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./tools": "./src/tools.ts",
+ "./openapi": "./src/openapi.ts",
+ "./client": "./src/client.ts"
},
"dependencies": {
"@nomadro/pay": "workspace:*",
diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts
new file mode 100644
index 0000000..8665a25
--- /dev/null
+++ b/packages/sdk/src/client.ts
@@ -0,0 +1,166 @@
+import { buildOpenApiDocument } from "./openapi";
+import {
+ NOMADRO_TOOLS,
+ PUBLIC_API_PREFIX,
+ PUBLIC_API_VERSION,
+ type NomadroToolName,
+} from "./tools";
+
+export type NomadroClientOptions = {
+ /** Origin of portal, e.g. https://nomadro.com — no trailing slash */
+ baseUrl?: string;
+ /** Optional public API key */
+ apiKey?: string;
+ /** Social guest id for write endpoints */
+ guestId?: string;
+ fetch?: typeof fetch;
+};
+
+export type JsonMap = Record;
+
+function joinUrl(base: string, path: string): string {
+ return `${base.replace(/\/$/, "")}${path.startsWith("/") ? path : `/${path}`}`;
+}
+
+function fillPath(template: string, params: JsonMap): string {
+ return template.replace(/\{(\w+)\}/g, (_, key: string) => {
+ const v = params[key];
+ if (v == null) throw new Error(`missing path param ${key}`);
+ return encodeURIComponent(String(v));
+ });
+}
+
+export function createNomadroClient(opts: NomadroClientOptions = {}) {
+ const envOrigin =
+ (typeof process !== "undefined" &&
+ (process.env?.NOMADRO_PUBLIC_ORIGIN ||
+ process.env?.NEXT_PUBLIC_SITE_URL)) ||
+ "";
+ const baseUrl = (
+ opts.baseUrl ||
+ envOrigin ||
+ "https://nomadro.com"
+ ).replace(/\/$/, "");
+ const doFetch = opts.fetch || fetch;
+
+ async function request(
+ method: "GET" | "POST",
+ path: string,
+ query?: JsonMap,
+ body?: JsonMap,
+ ): Promise {
+ const url = new URL(joinUrl(baseUrl, `${PUBLIC_API_PREFIX}${path}`));
+ if (query) {
+ for (const [k, v] of Object.entries(query)) {
+ if (v == null || v === "") continue;
+ url.searchParams.set(k, String(v));
+ }
+ }
+ const headers: Record = {
+ Accept: "application/json",
+ };
+ if (opts.apiKey) headers["X-Nomadro-Key"] = opts.apiKey;
+ if (opts.guestId) headers["X-Social-Guest-Id"] = opts.guestId;
+ if (body) headers["Content-Type"] = "application/json";
+ const res = await doFetch(url.toString(), {
+ method,
+ headers,
+ body: body ? JSON.stringify(body) : undefined,
+ cache: "no-store",
+ });
+ const data = (await res.json().catch(() => ({}))) as JsonMap;
+ if (!res.ok) {
+ const err = new Error(
+ String(data.detail || data.error || `HTTP ${res.status}`),
+ ) as Error & { status?: number; data?: JsonMap };
+ err.status = res.status;
+ err.data = data;
+ throw err;
+ }
+ return data;
+ }
+
+ return {
+ baseUrl,
+ version: PUBLIC_API_VERSION,
+ tools: NOMADRO_TOOLS,
+ openapi: () => buildOpenApiDocument({ servers: [{ url: baseUrl }] }),
+
+ health: () => request("GET", "/health"),
+ getMeta: () => request("GET", "/meta"),
+ getConfig: () => request("GET", "/config"),
+ listTools: () => request("GET", "/tools"),
+
+ listMapCities: (q?: {
+ west?: number;
+ south?: number;
+ east?: number;
+ north?: number;
+ }) => request("GET", "/social/cities", q as JsonMap),
+ searchCities: (q: { q: string; limit?: number; lang?: string }) =>
+ request("GET", "/social/cities/search", q as JsonMap),
+ listMeetups: (q?: { keyword?: string }) =>
+ request("GET", "/social/meetups", q as JsonMap),
+ openMeetup: (q: { meetupId: string; nick?: string }) =>
+ request("GET", fillPath("/social/meetups/{meetupId}", q), {
+ nick: q.nick,
+ }),
+ listGigs: (q?: { kind?: string; keyword?: string }) =>
+ request("GET", "/social/gigs", q as JsonMap),
+ applyGig: (q: {
+ gigId: string;
+ name: string;
+ contact: string;
+ note?: string;
+ }) =>
+ request(
+ "POST",
+ fillPath("/social/gigs/{gigId}/apply", q),
+ undefined,
+ { name: q.name, contact: q.contact, note: q.note },
+ ),
+ joinSocial: (q?: { email?: string; locale?: string }) =>
+ request("GET", "/social/join", q as JsonMap),
+ checkVip: (q: { email: string }) =>
+ request("GET", "/vip/check", q as JsonMap),
+ listNavLinks: (q?: { q?: string; limit?: number }) =>
+ request("GET", "/nav/links", q as JsonMap),
+ listSocialRoutes: () => request("GET", "/social/routes"),
+
+ /** 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}`);
+ }
+ },
+ };
+}
+
+export type NomadroClient = ReturnType;
diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts
index 6842eec..f1760e5 100644
--- a/packages/sdk/src/index.ts
+++ b/packages/sdk/src/index.ts
@@ -1,9 +1,9 @@
/**
- * @nomadro/sdk — stable façade for other projects / mini-programs.
- * Keep this surface tiny and versioned; expand via OpenAPI later.
+ * @nomadro/sdk — stable façade for apps, agents (MCP), and skills.
+ * Public HTTP SoT: /api/public/v1 · OpenAPI: /api/public/v1/openapi.json
*/
-export const SDK_VERSION = "0.2.1";
+export const SDK_VERSION = "0.3.0";
/** Shared theme localStorage key across portal + verticals */
export const THEME_STORAGE_KEY = "nomadro-theme";
@@ -16,10 +16,18 @@ export const PORTAL_ROUTES = {
nav: "/nav",
book: "/book",
community: "/community",
+ social: "/social",
vip: "/vip",
admin: "/admin",
+ publicApi: "/api/public/v1",
+ openapi: "/api/public/v1/openapi.json",
+ docs: "/developers",
} as const;
+/** 受众轨:与 src/modules/audience 对齐;.com 默认 intl */
+export const AUDIENCE_LANES = ["cn", "intl"] as const;
+export type AudienceLaneId = (typeof AUDIENCE_LANES)[number];
+
export {
resolvePayProvider,
getPayEnv,
@@ -42,39 +50,22 @@ export {
type ModuleToggle,
} from "./remote-config";
-import { PAY_DEFAULTS } from "@nomadro/pay";
+export {
+ PUBLIC_API_PREFIX,
+ PUBLIC_API_VERSION,
+ NOMADRO_TOOLS,
+ toolByName,
+ type NomadroToolName,
+ type NomadroToolDef,
+} from "./tools";
-export type NomadroClientOptions = {
- apiBase?: string;
- siteId?: string;
-};
+export { buildOpenApiDocument } from "./openapi";
-export type HealthResult = {
- ok: boolean;
- status: number;
- latencyMs: number;
-};
+export {
+ createNomadroClient,
+ type NomadroClient,
+ type NomadroClientOptions,
+ type JsonMap,
+} from "./client";
-export function createNomadroClient(opts: NomadroClientOptions = {}) {
- const apiBase = (opts.apiBase || PAY_DEFAULTS.payjsapiPublic).replace(
- /\/$/,
- "",
- );
- const siteId = opts.siteId || "nomadro";
-
- return {
- apiBase,
- siteId,
- version: SDK_VERSION,
- routes: PORTAL_ROUTES,
- async health(): Promise {
- const started = Date.now();
- try {
- const res = await fetch(`${apiBase}/health`, { cache: "no-store" });
- return { ok: res.ok, status: res.status, latencyMs: Date.now() - started };
- } catch {
- return { ok: false, status: 0, latencyMs: Date.now() - started };
- }
- },
- };
-}
+export { createNomadroClient as createClient } from "./client";
diff --git a/packages/sdk/src/openapi.ts b/packages/sdk/src/openapi.ts
new file mode 100644
index 0000000..ce0e633
--- /dev/null
+++ b/packages/sdk/src/openapi.ts
@@ -0,0 +1,147 @@
+import {
+ NOMADRO_TOOLS,
+ PUBLIC_API_PREFIX,
+ PUBLIC_API_VERSION,
+} from "./tools";
+
+/** OpenAPI 3.1 document for Nomadro public surface. */
+export function buildOpenApiDocument(opts?: {
+ servers?: { url: string; description?: string }[];
+}) {
+ const paths: Record = {};
+ for (const tool of NOMADRO_TOOLS) {
+ const pathKey = `${PUBLIC_API_PREFIX}${tool.path.replace(/\{(\w+)\}/g, "{$1}")}`;
+ const op = {
+ operationId: tool.name,
+ summary: tool.description,
+ tags: [tool.path.split("/")[1] || "platform"],
+ parameters: [] as unknown[],
+ requestBody: undefined as unknown,
+ responses: {
+ "200": {
+ description: "OK",
+ content: {
+ "application/json": {
+ schema: { type: "object", additionalProperties: true },
+ },
+ },
+ },
+ },
+ };
+ const props = (tool.inputSchema.properties || {}) as Record<
+ string,
+ { type?: string; description?: string; enum?: string[] }
+ >;
+ const required = new Set(
+ (tool.inputSchema.required as string[] | undefined) || [],
+ );
+ const pathParams = [...tool.path.matchAll(/\{(\w+)\}/g)].map((m) => m[1]);
+ for (const [key, schema] of Object.entries(props)) {
+ if (pathParams.includes(key)) {
+ op.parameters.push({
+ name: key,
+ in: "path",
+ required: true,
+ schema: { type: schema.type || "string" },
+ description: schema.description,
+ });
+ } else if (tool.method === "GET") {
+ op.parameters.push({
+ name: key,
+ in: "query",
+ required: required.has(key),
+ schema: {
+ type: schema.type || "string",
+ ...(schema.enum ? { enum: schema.enum } : {}),
+ },
+ description: schema.description,
+ });
+ }
+ }
+ if (tool.method === "POST") {
+ const bodyProps: Record = {};
+ const bodyRequired: string[] = [];
+ for (const [key, schema] of Object.entries(props)) {
+ if (pathParams.includes(key)) continue;
+ bodyProps[key] = schema;
+ if (required.has(key)) bodyRequired.push(key);
+ }
+ op.requestBody = {
+ required: true,
+ content: {
+ "application/json": {
+ schema: {
+ type: "object",
+ properties: bodyProps,
+ required: bodyRequired,
+ },
+ },
+ },
+ };
+ }
+ const existing = (paths[pathKey] as Record) || {};
+ existing[tool.method.toLowerCase()] = op;
+ paths[pathKey] = existing;
+ }
+
+ paths[`${PUBLIC_API_PREFIX}/openapi.json`] = {
+ get: {
+ operationId: "getOpenApi",
+ summary: "This OpenAPI document",
+ tags: ["platform"],
+ responses: {
+ "200": {
+ description: "OpenAPI 3.1 JSON",
+ content: { "application/json": { schema: { type: "object" } } },
+ },
+ },
+ },
+ };
+
+ paths[`${PUBLIC_API_PREFIX}/tools`] = {
+ get: {
+ operationId: "listTools",
+ summary: "List MCP/SDK tool descriptors (same as NOMADRO_TOOLS)",
+ tags: ["platform"],
+ responses: {
+ "200": {
+ description: "Tool list",
+ content: { "application/json": { schema: { type: "object" } } },
+ },
+ },
+ },
+ };
+
+ return {
+ openapi: "3.1.0",
+ info: {
+ title: "Nomadro Public API",
+ version: PUBLIC_API_VERSION,
+ description:
+ "Standardized Nomadro surface for apps, agents (MCP), and skills. Interactive docs: https://nomadro.com/developers . Core deploy target: nomadro.com (US). .cn is an independent China mirror after cn-audience validation.",
+ contact: { url: "https://nomadro.com/developers" },
+ },
+ servers: opts?.servers || [
+ { url: "https://nomadro.com", description: "Production .com (US, primary)" },
+ { url: "https://nomadro.cn", description: "China .cn (independent)" },
+ { url: "http://localhost:3000", description: "Local Next portal" },
+ ],
+ paths,
+ components: {
+ securitySchemes: {
+ ApiKey: {
+ type: "apiKey",
+ in: "header",
+ name: "X-Nomadro-Key",
+ description: "Optional. Required only when NOMADRO_PUBLIC_API_KEY is set on server.",
+ },
+ SocialGuest: {
+ type: "apiKey",
+ in: "header",
+ name: "X-Social-Guest-Id",
+ description: "Guest id for social write ops (apply / trips).",
+ },
+ },
+ },
+ };
+}
diff --git a/packages/sdk/src/tools.ts b/packages/sdk/src/tools.ts
new file mode 100644
index 0000000..6dd0480
--- /dev/null
+++ b/packages/sdk/src/tools.ts
@@ -0,0 +1,37 @@
+/**
+ * Shared tool descriptors — SoT JSON: packages/sdk/tools.json
+ * SDK / OpenAPI / MCP / skills must stay aligned with that file.
+ */
+import toolsJson from "../tools.json";
+
+export const PUBLIC_API_PREFIX = "/api/public/v1" as const;
+export const PUBLIC_API_VERSION = "1.0.0" as const;
+
+export type NomadroToolName =
+ | "health"
+ | "getMeta"
+ | "getConfig"
+ | "listMapCities"
+ | "searchCities"
+ | "listMeetups"
+ | "openMeetup"
+ | "listGigs"
+ | "applyGig"
+ | "joinSocial"
+ | "checkVip"
+ | "listNavLinks"
+ | "listSocialRoutes";
+
+export type NomadroToolDef = {
+ name: NomadroToolName;
+ description: string;
+ method: "GET" | "POST";
+ path: string;
+ inputSchema: Record;
+};
+
+export const NOMADRO_TOOLS = toolsJson as NomadroToolDef[];
+
+export function toolByName(name: string): NomadroToolDef | undefined {
+ return NOMADRO_TOOLS.find((t) => t.name === name);
+}
diff --git a/packages/sdk/tools.json b/packages/sdk/tools.json
new file mode 100644
index 0000000..e1efad6
--- /dev/null
+++ b/packages/sdk/tools.json
@@ -0,0 +1,153 @@
+[
+ {
+ "name": "health",
+ "description": "Portal + public API health probe.",
+ "method": "GET",
+ "path": "/health",
+ "inputSchema": { "type": "object", "properties": {} }
+ },
+ {
+ "name": "getMeta",
+ "description": "Platform metadata: version, audience lanes (cn/intl), portal routes, deploy targets (.com first).",
+ "method": "GET",
+ "path": "/meta",
+ "inputSchema": { "type": "object", "properties": {} }
+ },
+ {
+ "name": "getConfig",
+ "description": "Sanitized remote config (modules / flags / copy). Offline-safe when server falls back to seed.",
+ "method": "GET",
+ "path": "/config",
+ "inputSchema": { "type": "object", "properties": {} }
+ },
+ {
+ "name": "listMapCities",
+ "description": "Geo discovery city pins for /social/map (lat/lng + vibe).",
+ "method": "GET",
+ "path": "/social/cities",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "west": { "type": "number" },
+ "south": { "type": "number" },
+ "east": { "type": "number" },
+ "north": { "type": "number" }
+ }
+ }
+ },
+ {
+ "name": "searchCities",
+ "description": "Search cities (seed + Photon when available).",
+ "method": "GET",
+ "path": "/social/cities/search",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "q": { "type": "string", "description": "Query, e.g. Bangkok" },
+ "limit": { "type": "number" },
+ "lang": { "type": "string", "description": "zh | en" }
+ },
+ "required": ["q"]
+ }
+ },
+ {
+ "name": "listMeetups",
+ "description": "List video/voice meetup rooms (MiroTalk / native live).",
+ "method": "GET",
+ "path": "/social/meetups",
+ "inputSchema": {
+ "type": "object",
+ "properties": { "keyword": { "type": "string" } }
+ }
+ },
+ {
+ "name": "openMeetup",
+ "description": "Resolve deep-link / handoff for a meetup room.",
+ "method": "GET",
+ "path": "/social/meetups/{meetupId}",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "meetupId": { "type": "string" },
+ "nick": { "type": "string" }
+ },
+ "required": ["meetupId"]
+ }
+ },
+ {
+ "name": "listGigs",
+ "description": "List team / co-create gigs (volunteer / parttime / fulltime).",
+ "method": "GET",
+ "path": "/social/gigs",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["all", "volunteer", "parttime", "fulltime"]
+ },
+ "keyword": { "type": "string" }
+ }
+ }
+ },
+ {
+ "name": "applyGig",
+ "description": "Submit a gig application (name + contact required).",
+ "method": "POST",
+ "path": "/social/gigs/{gigId}/apply",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "gigId": { "type": "string" },
+ "name": { "type": "string" },
+ "contact": { "type": "string" },
+ "note": { "type": "string" }
+ },
+ "required": ["gigId", "name", "contact"]
+ }
+ },
+ {
+ "name": "joinSocial",
+ "description": "Join-social handoff (paid community join; isolated from VIP __vip__).",
+ "method": "GET",
+ "path": "/social/join",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "email": { "type": "string" },
+ "locale": { "type": "string" }
+ }
+ }
+ },
+ {
+ "name": "checkVip",
+ "description": "Check VIP status by email (read-only).",
+ "method": "GET",
+ "path": "/vip/check",
+ "inputSchema": {
+ "type": "object",
+ "properties": { "email": { "type": "string" } },
+ "required": ["email"]
+ }
+ },
+ {
+ "name": "listNavLinks",
+ "description": "Digital nomad navigation link catalog (offline seed).",
+ "method": "GET",
+ "path": "/nav/links",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "q": { "type": "string" },
+ "limit": { "type": "number" }
+ }
+ }
+ },
+ {
+ "name": "listSocialRoutes",
+ "description": "Social hub IA routes for agents / mini-programs.",
+ "method": "GET",
+ "path": "/social/routes",
+ "inputSchema": { "type": "object", "properties": {} }
+ }
+]
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index e1d0d39..f48ccf9 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -1,6 +1,7 @@
packages:
- "packages/*"
- "apps/admin"
+ - "apps/com/admin"
- "apps/miniprogram/h5"
- "apps/miniprogram/weapp"
- "apps/miniprogram/tt"
diff --git a/public/maplibre/maplibre-gl-shared.mjs b/public/maplibre/maplibre-gl-shared.mjs
new file mode 100644
index 0000000..e69de29
diff --git a/public/maplibre/maplibre-gl-worker.mjs b/public/maplibre/maplibre-gl-worker.mjs
new file mode 100644
index 0000000..1421199
--- /dev/null
+++ b/public/maplibre/maplibre-gl-worker.mjs
@@ -0,0 +1,10 @@
+/**
+* MapLibre GL JS
+* @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v6.16.0/LICENSE.txt
+*/
+var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));function l(e,t){this.x=e,this.y=t}l.prototype={clone(){return new l(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){let t=e.x-this.x,n=e.y-this.y;return t*t+n*n},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){let t=e[0]*this.x+e[1]*this.y,n=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=n,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){let e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){let t=Math.cos(e),n=Math.sin(e),r=t*this.x-n*this.y,i=n*this.x+t*this.y;return this.x=r,this.y=i,this},_rotateAround(e,t){let n=Math.cos(e),r=Math.sin(e),i=t.x+n*(this.x-t.x)-r*(this.y-t.y),a=t.y+r*(this.x-t.x)+n*(this.y-t.y);return this.x=i,this.y=a,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:l},l.convert=function(e){if(e instanceof l)return e;if(Array.isArray(e))return new l(+e[0],+e[1]);if(e.x!==void 0&&e.y!==void 0)return new l(+e.x,+e.y);throw Error(`Expected [x, y] or {x, y} point format`)};function u(e,t,n,r){let i=3*e,a=3*(n-e)-i,o=1-i-a,s=3*t,c=3*(r-t)-s,l=1-s-c;return function(e,t=1e-6){if(e<=0)return 0;if(e>=1)return 1;let n=e;for(let r=0;r<8;r++){let r=((o*n+a)*n+i)*n-e;if(Math.abs(r)s?r=n:u=n,n=(r+u)*.5}return((l*n+c)*n+s)*n}}let d;function f(){return d??=typeof OffscreenCanvas<`u`&&!!new OffscreenCanvas(1,1).getContext(`2d`)&&typeof createImageBitmap==`function`,d}let p;function m(){if(p==null&&(p=!1,f())){let e=new OffscreenCanvas(5,5).getContext(`2d`,{willReadFrequently:!0});if(e){for(let t=0;t<25;t++){let n=t*4;e.fillStyle=`rgb(${n},${n+1},${n+2})`,e.fillRect(t%5,Math.floor(t/5),1,1)}let t=e.getImageData(0,0,5,5).data;for(let e=0;e<100;e++)if(e%4!=3&&t[e]!==e){p=!0;break}}}return p||!1}var h=typeof Float32Array<`u`?Float32Array:Array;function g(){var e=new h(4);return h!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0,e[3]=0),e}function _(e,t,n){var r=t[0],i=t[1],a=t[2],o=t[3];return e[0]=n[0]*r+n[4]*i+n[8]*a+n[12]*o,e[1]=n[1]*r+n[5]*i+n[9]*a+n[13]*o,e[2]=n[2]*r+n[6]*i+n[10]*a+n[14]*o,e[3]=n[3]*r+n[7]*i+n[11]*a+n[15]*o,e}(function(){var e=g();return function(t,n,r,i,a,o){var s,c;for(n||=4,r||=0,c=i?Math.min(i*n+r,t.length):t.length,s=r;s=1)return 1;let t=e*e,n=t*e;return 4*(e<.5?n:3*(e-t)+n-.75)}function x(e,t,n,r){return u(e,t,n,r)}x(.25,.1,.25,1);function S(e,t,n){return Math.min(n,Math.max(t,e))}function C(e,t,n){let r=n-t,i=((e-t)%r+r)%r+t;return i===t?n:i}function w(e,...t){for(let n of t)for(let t in n)e[t]=n[t];return e}function T(e){return Math.log(e)/Math.LN2%1==0}function E(e,t,n){let r={};for(let i in e)r[i]=t.call(n||this,e[i],i,e);return r}function D(e,t,n){let r={};for(let i in e)t.call(n||this,e[i],i,e)&&(r[i]=e[i]);return r}function O(e,t){if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n(t.y-e.y)*(n.x-e.x)}function te(e){return typeof WorkerGlobalScope<`u`&&e!==void 0&&e instanceof WorkerGlobalScope}function ne(e){return typeof ImageBitmap<`u`&&e instanceof ImageBitmap}function re(e,t,n,r,i){let a=Math.max(-t,0)*4,o=(Math.max(0,n)-n)*r*4+a,s=r*4,c=Math.max(0,t),l=Math.max(0,n),u=Math.min(e.width,t+r),d=Math.min(e.height,n+i);return{rect:{x:c,y:l,width:u-c,height:d-l},layout:[{offset:o,stride:s}]}}async function ie(e,t,n,r,i){if(typeof VideoFrame>`u`)throw Error(`VideoFrame not supported`);let a=new VideoFrame(e,{timestamp:0});try{let o=a?.format;if(!o||!(o.startsWith(`BGR`)||o.startsWith(`RGB`)))throw Error(`Unrecognized format ${o}`);let s=o.startsWith(`BGR`),c=new Uint8ClampedArray(r*i*4);if(await a.copyTo(c,re(e,t,n,r,i)),s)for(let e=0;e{e.removeEventListener(t,n,r)}}}function ue(e){return e*Math.PI/180}function de(e,t,n){n[e]?.includes(t)||(n[e]||=[],n[e].push(t))}function fe(e,t,n){if(n?.[e]){let r=n[e].indexOf(t);r!==-1&&n[e].splice(r,1)}}var pe=class{constructor(e,t={}){w(this,t),this.type=e}},me=class extends pe{constructor(e,t={}){super(`error`,w({error:e},t))}},he=class{on(e,t){return this._listeners||={},de(e,t,this._listeners),{unsubscribe:()=>{this.off(e,t)}}}off(e,t){return fe(e,t,this._listeners),fe(e,t,this._oneTimeListeners),this}once(e,t){return t?(this._oneTimeListeners||={},de(e,t,this._oneTimeListeners),this):new Promise(t=>this.once(e,t))}fire(e,t){let n=typeof e==`string`?new pe(e,t||{}):e,r=n.type;if(this.listens(r)){n.target=this;let e=this._listeners?.[r]?.slice()??[];for(let t of e)t.call(this,n);let t=this._oneTimeListeners?.[r]?.slice()??[];for(let e of t)fe(r,e,this._oneTimeListeners),e.call(this,n);let i=this._eventedParent;i&&(w(n,typeof this._eventedParentData==`function`?this._eventedParentData():this._eventedParentData),i.fire(n))}else n instanceof me&&console.error(n.error);return this}listens(e){return!!(this._listeners?.[e]?.length||this._oneTimeListeners?.[e]?.length||this._eventedParent?.listens(e))}setEventedParent(e,t){return this._eventedParent=e,this._eventedParentData=t,this}};const M=`AbortError`;var ge=class extends Error{constructor(e=M){super(e instanceof Error?e.message:e),this.name=M,e instanceof Error&&e.stack&&(this.stack=e.stack)}};function _e(e){return e instanceof Error&&e.name===`AbortError`}function ve(e){if(e.aborted)throw new ge(e.reason)}var ye=class e{constructor(e,t,n){let r=this.cells=[];if(e instanceof ArrayBuffer){this.arrayBuffer=e;let i=new Int32Array(this.arrayBuffer);e=i[0],t=i[1],n=i[2],this.d=t+2*n;for(let e=0;e=l[c+0]&&r>=l[c+1])?(o[u]=!0,a.push(i[u])):o[u]=!1}}}_forEachCell(e,t,n,r,i,a,o,s){let c=this._convertToCellCoord(e),l=this._convertToCellCoord(t),u=this._convertToCellCoord(n),d=this._convertToCellCoord(r);for(let f=c;f<=u;f++)for(let c=l;c<=d;c++){let l=this.d*c+f;if((!s||s(this._convertFromCellCoord(f),this._convertFromCellCoord(c),this._convertFromCellCoord(f+1),this._convertFromCellCoord(c+1)))&&i.call(this,e,t,n,r,l,a,o,s))return}}_convertFromCellCoord(e){return(e-this.padding)/this.scale}_convertToCellCoord(e){return Math.max(0,Math.min(this.d-1,Math.floor(e*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;let e=this.cells,t=3+this.cells.length+1+1,n=0;for(let e of this.cells)n+=e.length;let r=new Int32Array(t+n+this.keys.length+this.bboxes.length);r[0]=this.extent,r[1]=this.n,r[2]=this.padding;let i=t;for(let t=0;t":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:`enum`,values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:`expression`},stops:{type:`array`,value:`function_stop`},base:{type:`number`,default:1,minimum:0},property:{type:`string`,default:`$zoom`},type:{type:`enum`,values:{identity:{},exponential:{},interval:{},categorical:{}},default:`exponential`},colorSpace:{type:`enum`,values:{rgb:{},lab:{},hcl:{}},default:`rgb`},default:{type:`*`,required:!1}},function_stop:{type:`array`,minimum:0,maximum:24,value:[`number`,`color`],length:2},expression:{type:`array`,value:`expression_name`,minimum:1},light:{anchor:{type:`enum`,default:`viewport`,values:{map:{},viewport:{}},"property-type":`data-constant`,transition:!1,expression:{interpolated:!1,parameters:[`zoom`]}},position:{type:`array`,default:[1.15,210,30],length:3,value:`number`,"property-type":`data-constant`,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]}},color:{type:`color`,"property-type":`data-constant`,default:`#ffffff`,expression:{interpolated:!0,parameters:[`zoom`]},transition:!0},intensity:{type:`number`,"property-type":`data-constant`,default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:[`zoom`]},transition:!0}},sky:{"sky-color":{type:`color`,"property-type":`data-constant`,default:`#88C6FC`,expression:{interpolated:!0,parameters:[`zoom`]},transition:!0},"horizon-color":{type:`color`,"property-type":`data-constant`,default:`#ffffff`,expression:{interpolated:!0,parameters:[`zoom`]},transition:!0},"fog-color":{type:`color`,"property-type":`data-constant`,default:`#ffffff`,expression:{interpolated:!0,parameters:[`zoom`]},transition:!0},"fog-ground-blend":{type:`number`,"property-type":`data-constant`,default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:[`zoom`]},transition:!0},"horizon-fog-blend":{type:`number`,"property-type":`data-constant`,default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:[`zoom`]},transition:!0},"sky-horizon-blend":{type:`number`,"property-type":`data-constant`,default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:[`zoom`]},transition:!0},"atmosphere-blend":{type:`number`,"property-type":`data-constant`,default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:[`zoom`]},transition:!0}},terrain:{source:{type:`string`,required:!0},exaggeration:{type:`number`,minimum:0,default:1}},projection:{type:{type:`projectionDefinition`,default:`mercator`,"property-type":`data-constant`,transition:!1,expression:{interpolated:!0,parameters:[`zoom`]}}},paint:[`paint_fill`,`paint_line`,`paint_circle`,`paint_heatmap`,`paint_fill-extrusion`,`paint_symbol`,`paint_raster`,`paint_hillshade`,`paint_color-relief`,`paint_background`],paint_fill:{"fill-antialias":{type:`boolean`,default:!0,expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`},"fill-opacity":{type:`number`,default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"fill-layer-opacity":{type:`number`,default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`,`global-state`]},"property-type":`data-constant`},"fill-color":{type:`color`,default:`#000000`,transition:!0,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"fill-outline-color":{type:`color`,transition:!0,requires:[{"!":`fill-pattern`},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"fill-translate":{type:`array`,value:`number`,length:2,default:[0,0],transition:!0,units:`pixels`,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"fill-translate-anchor":{type:`enum`,values:{map:{},viewport:{}},default:`map`,requires:[`fill-translate`],expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`},"fill-pattern":{type:`resolvedImage`,transition:!0,expression:{interpolated:!1,parameters:[`zoom`,`feature`]},"property-type":`cross-faded-data-driven`}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:`number`,default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"fill-extrusion-color":{type:`color`,default:`#000000`,transition:!0,requires:[{"!":`fill-extrusion-pattern`}],expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"fill-extrusion-translate":{type:`array`,value:`number`,length:2,default:[0,0],transition:!0,units:`pixels`,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"fill-extrusion-translate-anchor":{type:`enum`,values:{map:{},viewport:{}},default:`map`,requires:[`fill-extrusion-translate`],expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`},"fill-extrusion-pattern":{type:`resolvedImage`,transition:!0,expression:{interpolated:!1,parameters:[`zoom`,`feature`]},"property-type":`cross-faded-data-driven`},"fill-extrusion-height":{type:`number`,default:0,units:`meters`,transition:!0,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"fill-extrusion-base":{type:`number`,default:0,units:`meters`,transition:!0,requires:[`fill-extrusion-height`],expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"fill-extrusion-vertical-gradient":{type:`boolean`,default:!0,transition:!1,expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`}},paint_line:{"line-opacity":{type:`number`,default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"line-layer-opacity":{type:`number`,default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`,`global-state`]},"property-type":`data-constant`},"line-color":{type:`color`,default:`#000000`,transition:!0,requires:[{"!":`line-pattern`}],expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"line-translate":{type:`array`,value:`number`,length:2,default:[0,0],transition:!0,units:`pixels`,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"line-translate-anchor":{type:`enum`,values:{map:{},viewport:{}},default:`map`,requires:[`line-translate`],expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`},"line-width":{type:`number`,default:1,minimum:0,transition:!0,units:`pixels`,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"line-gap-width":{type:`number`,default:0,minimum:0,transition:!0,units:`pixels`,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"line-offset":{type:`number`,default:0,transition:!0,units:`pixels`,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"line-blur":{type:`number`,default:0,minimum:0,transition:!0,units:`pixels`,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"line-dasharray":{type:`array`,value:`number`,minimum:0,transition:!0,units:`line widths`,requires:[{"!":`line-pattern`}],expression:{interpolated:!1,parameters:[`zoom`,`feature`]},"property-type":`cross-faded-data-driven`},"line-pattern":{type:`resolvedImage`,transition:!0,expression:{interpolated:!1,parameters:[`zoom`,`feature`]},"property-type":`cross-faded-data-driven`},"line-gradient":{type:`color`,transition:!1,requires:[{"!":`line-dasharray`},{"!":`line-pattern`},{source:`geojson`,has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:[`line-progress`]},"property-type":`color-ramp`}},paint_circle:{"circle-radius":{type:`number`,default:5,minimum:0,transition:!0,units:`pixels`,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"circle-color":{type:`color`,default:`#000000`,transition:!0,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"circle-blur":{type:`number`,default:0,transition:!0,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"circle-opacity":{type:`number`,default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"circle-translate":{type:`array`,value:`number`,length:2,default:[0,0],transition:!0,units:`pixels`,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"circle-translate-anchor":{type:`enum`,values:{map:{},viewport:{}},default:`map`,requires:[`circle-translate`],expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`},"circle-pitch-scale":{type:`enum`,values:{map:{},viewport:{}},default:`map`,expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`},"circle-pitch-alignment":{type:`enum`,values:{map:{},viewport:{}},default:`viewport`,expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`},"circle-stroke-width":{type:`number`,default:0,minimum:0,transition:!0,units:`pixels`,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"circle-stroke-color":{type:`color`,default:`#000000`,transition:!0,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"circle-stroke-opacity":{type:`number`,default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`}},paint_heatmap:{"heatmap-radius":{type:`number`,default:30,minimum:1,transition:!0,units:`pixels`,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"heatmap-weight":{type:`number`,default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"heatmap-intensity":{type:`number`,default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"heatmap-color":{type:`color`,default:[`interpolate`,[`linear`],[`heatmap-density`],0,`rgba(0, 0, 255, 0)`,.1,`royalblue`,.3,`cyan`,.5,`lime`,.7,`yellow`,1,`red`],transition:!1,expression:{interpolated:!0,parameters:[`heatmap-density`]},"property-type":`color-ramp`},"heatmap-opacity":{type:`number`,default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`}},paint_symbol:{"icon-opacity":{type:`number`,default:1,minimum:0,maximum:1,transition:!0,requires:[`icon-image`],expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"icon-color":{type:`color`,default:`#000000`,transition:!0,requires:[`icon-image`],expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"icon-halo-color":{type:`color`,default:`rgba(0, 0, 0, 0)`,transition:!0,requires:[`icon-image`],expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"icon-halo-width":{type:`number`,default:0,minimum:0,transition:!0,units:`pixels`,requires:[`icon-image`],expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"icon-halo-blur":{type:`number`,default:0,minimum:0,transition:!0,units:`pixels`,requires:[`icon-image`],expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"icon-translate":{type:`array`,value:`number`,length:2,default:[0,0],transition:!0,units:`pixels`,requires:[`icon-image`],expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"icon-translate-anchor":{type:`enum`,values:{map:{},viewport:{}},default:`map`,requires:[`icon-image`,`icon-translate`],expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`},"text-opacity":{type:`number`,default:1,minimum:0,maximum:1,transition:!0,requires:[`text-field`],expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"text-color":{type:`color`,default:`#000000`,transition:!0,overridable:!0,requires:[`text-field`],expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"text-halo-color":{type:`color`,default:`rgba(0, 0, 0, 0)`,transition:!0,requires:[`text-field`],expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"text-halo-width":{type:`number`,default:0,minimum:0,transition:!0,units:`pixels`,requires:[`text-field`],expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"text-halo-blur":{type:`number`,default:0,minimum:0,transition:!0,units:`pixels`,requires:[`text-field`],expression:{interpolated:!0,parameters:[`zoom`,`feature`,`feature-state`]},"property-type":`data-driven`},"text-translate":{type:`array`,value:`number`,length:2,default:[0,0],transition:!0,units:`pixels`,requires:[`text-field`],expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"text-translate-anchor":{type:`enum`,values:{map:{},viewport:{}},default:`map`,requires:[`text-field`,`text-translate`],expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`}},paint_raster:{"raster-opacity":{type:`number`,default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"raster-hue-rotate":{type:`number`,default:0,period:360,transition:!0,units:`degrees`,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"raster-brightness-min":{type:`number`,default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"raster-brightness-max":{type:`number`,default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"raster-saturation":{type:`number`,default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"raster-contrast":{type:`number`,default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},resampling:{type:`enum`,values:{linear:{},nearest:{}},default:`linear`,expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`},"raster-resampling":{type:`enum`,values:{linear:{},nearest:{}},default:`linear`,expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`},"raster-fade-duration":{type:`number`,default:300,minimum:0,transition:!1,units:`milliseconds`,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`}},paint_hillshade:{"hillshade-illumination-direction":{type:`numberArray`,default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"hillshade-illumination-altitude":{type:`numberArray`,default:45,minimum:0,maximum:90,transition:!1,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"hillshade-illumination-anchor":{type:`enum`,values:{map:{},viewport:{}},default:`viewport`,expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`},"hillshade-exaggeration":{type:`number`,default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"hillshade-shadow-color":{type:`colorArray`,default:`#000000`,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"hillshade-highlight-color":{type:`colorArray`,default:`#FFFFFF`,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"hillshade-accent-color":{type:`color`,default:`#000000`,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"hillshade-method":{type:`enum`,values:{standard:{},basic:{},combined:{},igor:{},multidirectional:{}},default:`standard`,expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`},resampling:{type:`enum`,values:{linear:{},nearest:{}},default:`linear`,expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`}},"paint_color-relief":{"color-relief-opacity":{type:`number`,default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"color-relief-color":{type:`color`,transition:!1,expression:{interpolated:!0,parameters:[`elevation`]},"property-type":`color-ramp`},resampling:{type:`enum`,values:{linear:{},nearest:{}},default:`linear`,expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`data-constant`}},paint_background:{"background-color":{type:`color`,default:`#000000`,transition:!0,requires:[{"!":`background-pattern`}],expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`},"background-pattern":{type:`resolvedImage`,transition:!0,expression:{interpolated:!1,parameters:[`zoom`]},"property-type":`cross-faded`},"background-opacity":{type:`number`,default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:[`zoom`]},"property-type":`data-constant`}},transition:{duration:{type:`number`,default:300,minimum:0,units:`milliseconds`},delay:{type:`number`,default:0,minimum:0,units:`milliseconds`}},"property-type":{"data-driven":{type:`property-type`},"cross-faded":{type:`property-type`},"cross-faded-data-driven":{type:`property-type`},"color-ramp":{type:`property-type`},"data-constant":{type:`property-type`},constant:{type:`property-type`}},promoteId:{"*":{type:`string`}},interpolation:{type:`array`,value:`interpolation_name`,minimum:1},interpolation_name:{type:`enum`,values:{linear:{syntax:{overloads:[{parameters:[],"output-type":`interpolation`}],parameters:[]}},exponential:{syntax:{overloads:[{parameters:[`base`],"output-type":`interpolation`}],parameters:[{name:`base`,type:`number literal`}]}},"cubic-bezier":{syntax:{overloads:[{parameters:[`x1`,`y1`,`x2`,`y2`],"output-type":`interpolation`}],parameters:[{name:`x1`,type:`number literal`},{name:`y1`,type:`number literal`},{name:`x2`,type:`number literal`},{name:`y2`,type:`number literal`}]}}}}};const N=be,xe=[`type`,`source`,`source-layer`,`minzoom`,`maxzoom`,`filter`,`layout`];var P=class{constructor(e,t,n,r,i=`error`){this.message=(e?`${e}: `:``)+n,r&&(this.identifier=r),this.severity=i,t!=null&&t.__line__&&(this.line=t.__line__)}};const Se={kind:`null`},F={kind:`number`},I={kind:`string`},L={kind:`boolean`},Ce={kind:`color`},we={kind:`projectionDefinition`},Te={kind:`object`},R={kind:`value`},Ee={kind:`error`},De={kind:`collator`},Oe={kind:`formatted`},ke={kind:`padding`},Ae={kind:`colorArray`},je={kind:`numberArray`},Me={kind:`resolvedImage`},Ne={kind:`variableAnchorOffsetCollection`};function Pe(e,t){return{kind:`array`,itemType:e,N:t}}function z(e){if(e.kind===`array`){let t=z(e.itemType);return typeof e.N==`number`?`array<${t}, ${e.N}>`:e.itemType.kind===`value`?`array`:`array<${t}>`}return e.kind}const Fe=[Se,F,I,L,Ce,we,Oe,Te,Pe(R),ke,je,Ae,Me,Ne];function Ie(e,t){if(t.kind===`error`)return null;if(e.kind===`array`){if(t.kind===`array`&&(t.N===0&&t.itemType.kind===`value`||!Ie(e.itemType,t.itemType))&&(typeof e.N!=`number`||e.N===t.N))return null}else if(e.kind===t.kind)return null;else if(e.kind===`value`){for(let e of Fe)if(!Ie(e,t))return null}return`Expected ${z(e)} but found ${z(t)} instead.`}function Le(e,t){return t.some(t=>t.kind===e.kind)}function Re(e,t){return t.some(t=>t===`null`?e===null:t===`array`?Array.isArray(e):t===`object`?e&&!Array.isArray(e)&&typeof e==`object`:t===typeof e)}function ze(e,t){return e.kind===`array`&&t.kind===`array`?e.itemType.kind===t.itemType.kind&&typeof e.N==`number`:e.kind===t.kind}const Be=.96422,Ve=.82521,He=4/29,Ue=6/29,B=3*Ue*Ue,We=Math.PI/180,Ge=180/Math.PI;function Ke(e){return e%=360,e<0&&(e+=360),e}function qe([e,t,n,r]){e=Je(e),t=Je(t),n=Je(n);let i,a,o=Ye((.2225045*e+.7168786*t+.0606169*n)/1);e===t&&t===n?i=a=o:(i=Ye((.4360747*e+.3850649*t+.1430804*n)/Be),a=Ye((.0139322*e+.0971045*t+.7141733*n)/Ve));let s=116*o-16;return[s<0?0:s,500*(i-o),200*(o-a),r]}function Je(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function Ye(e){return e>.008856451679035631?e**(1/3):e/B+He}function Xe([e,t,n,r]){let i=(e+16)/116,a=isNaN(t)?i:i+t/500,o=isNaN(n)?i:i-n/200;return i=1*Qe(i),a=Be*Qe(a),o=Ve*Qe(o),[Ze(3.1338561*a-1.6168667*i-.4906146*o),Ze(-.9787684*a+1.9161415*i+.033454*o),Ze(.0719453*a-.2289914*i+1.4052427*o),r]}function Ze(e){return e=e<=.00304?12.92*e:1.055*e**(1/2.4)-.055,e<0?0:e>1?1:e}function Qe(e){return e>Ue?e*e*e:B*(e-He)}function $e(e){let[t,n,r,i]=qe(e),a=Math.sqrt(n*n+r*r);return[Math.round(a*1e4)?Ke(Math.atan2(r,n)*Ge):NaN,a,t,i]}function et([e,t,n,r]){return e=isNaN(e)?0:e*We,Xe([n,Math.cos(e)*t,Math.sin(e)*t,r])}function tt([e,t,n,r]){e=Ke(e),t/=100,n/=100;function i(r){let i=(r+e/30)%12,a=t*Math.min(n,1-n);return n-a*Math.max(-1,Math.min(i-3,9-i,1))}return[i(0),i(8),i(4),r]}const nt=Object.hasOwn||function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};function rt(e,t){return nt(e,t)?e[t]:void 0}function it(e){if(e=e.toLowerCase().trim(),e===`transparent`)return[0,0,0,0];let t=rt(lt,e);if(t){let[e,n,r]=t;return[e/255,n/255,r/255,1]}if(e.startsWith(`#`)&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(e)){let t=e.length<6?1:2,n=1;return[at(e.slice(n,n+=t)),at(e.slice(n,n+=t)),at(e.slice(n,n+=t)),at(e.slice(n,n+t)||`ff`)]}if(e.startsWith(`rgb`)){let t=e.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(t){let[e,n,r,i,a,o,s,c,l,u,d,f]=t,p=[i||` `,s||` `,u].join(``);if(p===` `||p===` /`||p===`,,`||p===`,,,`){let e=[r,o,l].join(``),t=e===`%%%`?100:e===``?255:0;if(t){let e=[st(+n/t,0,1),st(+a/t,0,1),st(+c/t,0,1),d?ot(+d,f):1];if(ct(e))return e}}return}}let n=e.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(n){let[e,t,r,i,a,o,s,c,l]=n,u=[r||` `,a||` `,s].join(``);if(u===` `||u===` /`||u===`,,`||u===`,,,`){let e=[+t,st(+i,0,100),st(+o,0,100),c?ot(+c,l):1];if(ct(e))return tt(e)}}}function at(e){return parseInt(e.padEnd(2,e),16)/255}function ot(e,t){return st(t?e/100:e,0,1)}function st(e,t,n){return Math.min(Math.max(t,e),n)}function ct(e){return!e.some(Number.isNaN)}const lt={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function ut(e,t,n){return e+n*(t-e)}function dt(e,t,n){return e.map((e,r)=>ut(e,t[r],n))}function ft(e){return e===`rgb`||e===`hcl`||e===`lab`}var V=class e{constructor(e,t,n,r=1,i=!0){this.r=e,this.g=t,this.b=n,this.a=r,i||(this.r*=r,this.g*=r,this.b*=r,r||this.overwriteGetter(`rgb`,[e,t,n,r]))}static{this.black=new e(0,0,0,1)}static{this.white=new e(1,1,1,1)}static{this.transparent=new e(0,0,0,0)}static{this.red=new e(1,0,0,1)}static parse(t){if(t instanceof e)return t;if(typeof t!=`string`)return;let n=it(t);if(n)return new e(...n,!1)}get rgb(){let{r:e,g:t,b:n,a:r}=this,i=r||1/0;return this.overwriteGetter(`rgb`,[e/i,t/i,n/i,r])}get hcl(){return this.overwriteGetter(`hcl`,$e(this.rgb))}get lab(){return this.overwriteGetter(`lab`,qe(this.rgb))}overwriteGetter(e,t){return Object.defineProperty(this,e,{value:t}),t}toString(){let[e,t,n,r]=this.rgb;return`rgba(${[e,t,n].map(e=>Math.round(e*255)).join(`,`)},${r})`}static interpolate(t,n,r,i=`rgb`){switch(i){case`rgb`:{let[i,a,o,s]=dt(t.rgb,n.rgb,r);return new e(i,a,o,s,!1)}case`hcl`:{let[i,a,o,s]=t.hcl,[c,l,u,d]=n.hcl,f,p;if(!isNaN(i)&&!isNaN(c)){let e=c-i;c>i&&e>180?e-=360:c180&&(e+=360),f=i+r*e}else isNaN(i)?isNaN(c)?f=NaN:(f=c,(o===1||o===0)&&(p=l)):(f=i,(u===1||u===0)&&(p=a));let[m,h,g,_]=et([f,p??ut(a,l,r),ut(o,u,r),ut(s,d,r)]);return new e(m,h,g,_,!1)}case`lab`:{let[i,a,o,s]=Xe(dt(t.lab,n.lab,r));return new e(i,a,o,s,!1)}}}};const pt=[`bottom`,`center`,`top`];var mt=class{constructor(e,t,n,r,i,a){this.text=e,this.image=t,this.scale=n,this.fontStack=r,this.textColor=i,this.verticalAlign=a}},ht=class e{constructor(e){this.sections=e}static fromString(t){return new e([new mt(t,null,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(e=>e.text.length!==0||e.image&&e.image.name.length!==0)}static factory(t){return t instanceof e?t:e.fromString(t)}toString(){return this.sections.length===0?``:this.sections.map(e=>e.text).join(``)}},gt=class e{constructor(e){this.values=e.slice()}static parse(t){if(t instanceof e)return t;if(typeof t==`number`)return new e([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(let e of t)if(typeof e!=`number`)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]]}return new e(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,n,r){return new e(dt(t.values,n.values,r))}},_t=class e{constructor(e){this.values=e.slice()}static parse(t){if(t instanceof e)return t;if(typeof t==`number`)return new e([t]);if(Array.isArray(t)){for(let e of t)if(typeof e!=`number`)return;return new e(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,n,r){return new e(dt(t.values,n.values,r))}},vt=class e{constructor(e){this.values=e.slice()}static parse(t){if(t instanceof e)return t;if(typeof t==`string`){let n=V.parse(t);return n?new e([n]):void 0}if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`string`)return;let t=V.parse(e);if(!t)return;n.push(t)}return new e(n)}toString(){return JSON.stringify(this.values)}static interpolate(t,n,r,i=`rgb`){let a=[];if(t.values.length!=n.values.length)throw Error(`colorArray: Arrays have mismatched length (${t.values.length} vs. ${n.values.length}), cannot interpolate.`);for(let e=0;e=0&&e<=255&&typeof t==`number`&&t>=0&&t<=255&&typeof n==`number`&&n>=0&&n<=255?r===void 0||typeof r==`number`&&r>=0&&r<=1?null:`Invalid rgba value [${[e,t,n,r].join(`, `)}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof r==`number`?[e,t,n,r]:[e,t,n]).join(`, `)}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Tt(e){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`||e instanceof St||e instanceof V||e instanceof Ct||e instanceof ht||e instanceof gt||e instanceof _t||e instanceof vt||e instanceof bt||e instanceof xt)return!0;if(Array.isArray(e)){for(let t of e)if(!Tt(t))return!1;return!0}if(typeof e==`object`){for(let t in e)if(!Tt(e[t]))return!1;return!0}return!1}function U(e){if(e===null)return Se;if(typeof e==`string`)return I;if(typeof e==`boolean`)return L;if(typeof e==`number`)return F;if(e instanceof V)return Ce;if(e instanceof St)return we;if(e instanceof Ct)return De;if(e instanceof ht)return Oe;if(e instanceof gt)return ke;if(e instanceof _t)return je;if(e instanceof vt)return Ae;if(e instanceof bt)return Ne;if(e instanceof xt)return Me;if(Array.isArray(e)){let t=e.length,n;for(let t of e){let e=U(t);if(!n)n=e;else if(n===e)continue;else{n=R;break}}return Pe(n||R,t)}return Te}function Et(e){let t=typeof e;return e===null?``:t===`string`||t===`number`||t===`boolean`?String(e):e instanceof V||e instanceof St||e instanceof ht||e instanceof gt||e instanceof _t||e instanceof vt||e instanceof bt||e instanceof xt?e.toString():JSON.stringify(e)}var Dt=class e{constructor(e,t){this.type=e,this.value=t}static parse(t,n){if(t.length!==2)return n.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!Tt(t[1]))return n.error(`invalid value of type "${typeof t[1]}"`);let r=t[1],i=U(r),a=n.expectedType;return i.kind===`array`&&i.N===0&&a&&a.kind===`array`&&(typeof a.N!=`number`||a.N===0)&&(i=a),new e(i,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}};const Ot=[`Unknown`,`Point`,`LineString`,`Polygon`];var kt=class{constructor(){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache=/* @__PURE__ */ new Map,this.availableImages=null,this.canonical=null}id(){return this.feature&&`id`in this.feature?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type==`number`?Ot[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&`geometry`in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}parseColor(e){let t=this._parseColorCache.get(e);return t||(t=V.parse(e),this._parseColorCache.set(e,t)),t}};function At(e,t,n){let r=e.length-1,i=0,a=r,o=0,s,c;for(;i<=a;)if(o=Math.floor((i+a)/2),s=e[o],c=e[o+1],s<=t){if(o===r||tt)a=o-1;else throw new H(`Input is not a number.`,n);return 0}var jt=class e{constructor(e,t,n,r){this.type=e,this.input=t,this.key=r,this.labels=[],this.outputs=[];for(let[e,t]of n)this.labels.push(e),this.outputs.push(t)}static parse(t,n){if(t.length-1<4)return n.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return n.error(`Expected an even number of arguments.`);let r=n.parse(t[1],1,F);if(!r)return null;let i=[],a=null;n.expectedType&&n.expectedType.kind!==`value`&&(a=n.expectedType);for(let e=1;e=r)return n.error(`Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.`,s);let l=n.parse(o,c,a);if(!l)return null;a||=l.type,i.push([r,l])}return new e(a,r,i,n.key)}evaluate(e){let t=this.labels,n=this.outputs;if(t.length===1)return n[0].evaluate(e);let r=this.input.evaluate(e);if(r<=t[0])return n[0].evaluate(e);let i=t.length;return r>=t[i-1]?n[i-1].evaluate(e):n[At(t,r,this.key)].evaluate(e)}eachChild(e){e(this.input);for(let t of this.outputs)e(t)}outputDefined(){return this.outputs.every(e=>e.outputDefined())}};function Mt(e,t,n,r){let i=3*e,a=3*(n-e)-i,o=1-i-a,s=3*t,c=3*(r-t)-s,l=1-s-c;return function(e,t=1e-6){if(e<=0)return 0;if(e>=1)return 1;let n=e;for(let r=0;r<8;r++){let r=((o*n+a)*n+i)*n-e;if(Math.abs(r)s?r=n:u=n,n=(r+u)*.5}return((l*n+c)*n+s)*n}}var Nt=class e{constructor(e,t,n,r,i,a){this.type=e,this.operator=t,this.interpolation=n,this.input=r,this.key=a,this.labels=[],this.outputs=[];for(let[e,t]of i)this.labels.push(e),this.outputs.push(t)}static interpolationFactor(e,t,n,r){let i=0;if(e.name===`exponential`)i=Pt(t,e.base,n,r);else if(e.name===`linear`)i=Pt(t,1,n,r);else if(e.name===`cubic-bezier`){let a=e.controlPoints;i=Mt(a[0],a[1],a[2],a[3])(Pt(t,1,n,r))}return i}static parse(t,n){let[r,i,a,...o]=t;if(!Array.isArray(i)||i.length===0)return n.error(`Expected an interpolation type expression.`,1);if(i[0]===`linear`)i={name:`linear`};else if(i[0]===`exponential`){let e=i[1];if(typeof e!=`number`)return n.error(`Exponential interpolation requires a numeric base.`,1,1);i={name:`exponential`,base:e}}else if(i[0]===`cubic-bezier`){let e=i.slice(1);if(e.length!==4||e.some(e=>typeof e!=`number`||e<0||e>1))return n.error(`Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.`,1);i={name:`cubic-bezier`,controlPoints:e}}else return n.error(`Unknown interpolation type ${String(i[0])}`,1,0);if(t.length-1<4)return n.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return n.error(`Expected an even number of arguments.`);if(a=n.parse(a,2,F),!a)return null;let s=[],c=null;(r===`interpolate-hcl`||r===`interpolate-lab`)&&n.expectedType!=Ae?c=Ce:n.expectedType&&n.expectedType.kind!==`value`&&(c=n.expectedType);for(let e=0;e=t)return n.error(`Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.`,i);let l=n.parse(r,a,c);if(!l)return null;c||=l.type,s.push([t,l])}return!ze(c,F)&&!ze(c,we)&&!ze(c,Ce)&&!ze(c,ke)&&!ze(c,je)&&!ze(c,Ae)&&!ze(c,Ne)&&!ze(c,Pe(F))?n.error(`Type ${z(c)} is not interpolatable.`):new e(c,r,i,a,s,n.key)}evaluate(t){let n=this.labels,r=this.outputs;if(n.length===1)return r[0].evaluate(t);let i=this.input.evaluate(t);if(i<=n[0])return r[0].evaluate(t);let a=n.length;if(i>=n[a-1])return r[a-1].evaluate(t);let o=At(n,i,this.key),s=n[o],c=n[o+1],l=e.interpolationFactor(this.interpolation,i,s,c),u=r[o].evaluate(t),d=r[o+1].evaluate(t);switch(this.operator){case`interpolate`:switch(this.type.kind){case`number`:return ut(u,d,l);case`color`:return V.interpolate(u,d,l);case`padding`:return gt.interpolate(u,d,l);case`colorArray`:return vt.interpolate(u,d,l);case`numberArray`:return _t.interpolate(u,d,l);case`variableAnchorOffsetCollection`:return bt.interpolate(u,d,l,this.key);case`array`:return dt(u,d,l);case`projectionDefinition`:return St.interpolate(u,d,l)}case`interpolate-hcl`:switch(this.type.kind){case`color`:return V.interpolate(u,d,l,`hcl`);case`colorArray`:return vt.interpolate(u,d,l,`hcl`)}case`interpolate-lab`:switch(this.type.kind){case`color`:return V.interpolate(u,d,l,`lab`);case`colorArray`:return vt.interpolate(u,d,l,`lab`)}}}eachChild(e){e(this.input);for(let t of this.outputs)e(t)}outputDefined(){return this.outputs.every(e=>e.outputDefined())}};function Pt(e,t,n,r){let i=r-n,a=e-n;return i===0?0:t===1?a/i:(t**+a-1)/(t**+i-1)}const Ft={color:V.interpolate,number:ut,padding:gt.interpolate,numberArray:_t.interpolate,colorArray:vt.interpolate,variableAnchorOffsetCollection:bt.interpolate,array:dt};var It=class e{constructor(e){this.type=Oe,this.sections=e}static parse(t,n){if(t.length<2)return n.error(`Expected at least one argument.`);let r=t[1];if(!Array.isArray(r)&&typeof r==`object`)return n.error(`First argument must be an image or text section.`);let i=[],a=!1;for(let e=1;e<=t.length-1;++e){let r=t[e];if(a&&typeof r==`object`&&!Array.isArray(r)){a=!1;let e=null;if(r[`font-scale`]&&(e=n.parse(r[`font-scale`],1,F),!e))return null;let t=null;if(r[`text-font`]&&(t=n.parse(r[`text-font`],1,Pe(I)),!t))return null;let o=null;if(r[`text-color`]&&(o=n.parse(r[`text-color`],1,Ce),!o))return null;let s=null;if(r[`vertical-align`]){if(typeof r[`vertical-align`]==`string`&&!pt.includes(r[`vertical-align`]))return n.error(`'vertical-align' must be one of: 'bottom', 'center', 'top' but found '${r[`vertical-align`]}' instead.`);if(s=n.parse(r[`vertical-align`],1,I),!s)return null}let c=i[i.length-1];c.scale=e,c.font=t,c.textColor=o,c.verticalAlign=s}else{let r=n.parse(t[e],1,R);if(!r)return null;let o=r.type.kind;if(o!==`string`&&o!==`value`&&o!==`null`&&o!==`resolvedImage`)return n.error(`Formatted text type must be 'string', 'value', 'image' or 'null'.`);a=!0,i.push({content:r,scale:null,font:null,textColor:null,verticalAlign:null})}}return new e(i)}evaluate(e){return new ht(this.sections.map(t=>{let n=t.content.evaluate(e);return U(n)===Me?new mt(``,n,null,null,null,t.verticalAlign?t.verticalAlign.evaluate(e):null):new mt(Et(n),null,t.scale?t.scale.evaluate(e):null,t.font?t.font.evaluate(e).join(`,`):null,t.textColor?t.textColor.evaluate(e):null,t.verticalAlign?t.verticalAlign.evaluate(e):null)}))}eachChild(e){for(let t of this.sections)e(t.content),t.scale&&e(t.scale),t.font&&e(t.font),t.textColor&&e(t.textColor),t.verticalAlign&&e(t.verticalAlign)}outputDefined(){return!1}};function Lt(e,t,n=0,r=e.length-1,i=zt){for(;r>n;){if(r-n>600){let a=r-n+1,o=t-n+1,s=Math.log(a),c=.5*Math.exp(2*s/3),l=.5*Math.sqrt(s*c*(a-c)/a)*(o-a/2<0?-1:1);Lt(e,t,Math.max(n,Math.floor(t-o*c/a+l)),Math.min(r,Math.floor(t+(a-o)*c/a+l)),i)}let a=e[t],o=n,s=r;for(Rt(e,n,t),i(e[r],a)>0&&Rt(e,n,r);o0;)s--}i(e[n],a)===0?Rt(e,n,s):(s++,Rt(e,s,r)),s<=t&&(n=s+1),t<=s&&(r=s-1)}}function Rt(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}function zt(e,t){return et)}function Bt(e,t){if(e.length<=1)return[e];let n=[],r,i;for(let t of e){let e=Ht(t);e!==0&&(t.area=Math.abs(e),i===void 0&&(i=e<0),i===e<0?(r&&n.push(r),r=[t]):r.push(t))}if(r&&n.push(r),t>1)for(let e=0;e2){let i=t[1];if(typeof i!=`string`||!(i in Ut)||i===`object`)return n.error(`The item type argument of "array" must be one of string, number, boolean`,1);e=Ut[i],r++}else e=R;let a;if(t.length>3){if(t[2]!==null&&(typeof t[2]!=`number`||t[2]<0||t[2]!==Math.floor(t[2])))return n.error(`The length argument to "array" must be a positive integer literal`,2);a=t[2],r++}i=Pe(e,a)}else{if(!Ut[a])throw Error(`Types doesn't contain name = ${a}`);i=Ut[a]}let o=[];for(;re.outputDefined())}};const Gt={"to-boolean":L,"to-color":Ce,"to-number":F,"to-string":I};var Kt=class e{constructor(e,t,n){this.type=e,this.args=t,this.key=n}static parse(t,n){if(t.length<2)return n.error(`Expected at least one argument.`);let r=t[0];if(!Gt[r])throw Error(`Can't parse ${r} as it is not part of the known types`);if((r===`to-boolean`||r===`to-string`)&&t.length!==2)return n.error(`Expected one argument.`);let i=Gt[r],a=[];for(let e=1;e4?`Invalid rgba value ${JSON.stringify(t)}: expected an array containing either three or four numeric values.`:wt(t[0],t[1],t[2],t[3]),!n))return new V(t[0]/255,t[1]/255,t[2]/255,t[3])}throw new H(n||`Could not parse color from value '${typeof t==`string`?t:JSON.stringify(t)}'`,this.key)}case`padding`:{let t;for(let n of this.args){t=n.evaluate(e);let r=gt.parse(t);if(r)return r}throw new H(`Could not parse padding from value '${typeof t==`string`?t:JSON.stringify(t)}'`,this.key)}case`numberArray`:{let t;for(let n of this.args){t=n.evaluate(e);let r=_t.parse(t);if(r)return r}throw new H(`Could not parse numberArray from value '${typeof t==`string`?t:JSON.stringify(t)}'`,this.key)}case`colorArray`:{let t;for(let n of this.args){t=n.evaluate(e);let r=vt.parse(t);if(r)return r}throw new H(`Could not parse colorArray from value '${typeof t==`string`?t:JSON.stringify(t)}'`,this.key)}case`variableAnchorOffsetCollection`:{let t;for(let n of this.args){t=n.evaluate(e);let r=bt.parse(t);if(r)return r}throw new H(`Could not parse variableAnchorOffsetCollection from value '${typeof t==`string`?t:JSON.stringify(t)}'`,this.key)}case`number`:{let t=null;for(let n of this.args){if(t=n.evaluate(e),t===null)return 0;let r=Number(t);if(!isNaN(r))return r}throw new H(`Could not convert ${JSON.stringify(t)} to number.`,this.key)}case`formatted`:return ht.fromString(Et(this.args[0].evaluate(e)));case`resolvedImage`:return xt.fromString(Et(this.args[0].evaluate(e)));case`projectionDefinition`:{let t=this.args[0].evaluate(e);if(St.parse(t))return t;throw new H(`Could not parse projectionDefinition from value '${typeof t==`string`?t:JSON.stringify(t)}'`,this.key)}default:return Et(this.args[0].evaluate(e))}}eachChild(e){this.args.forEach(e)}outputDefined(){return this.args.every(e=>e.outputDefined())}},qt=class e{constructor(e,t){this.type=t.type,this.bindings=[].concat(e),this.result=t}evaluate(e){return this.result.evaluate(e)}eachChild(e){for(let t of this.bindings)e(t[1]);e(this.result)}static parse(t,n){if(t.length<4)return n.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);let r=[];for(let e=1;e=n.length)throw new H(`Array index out of bounds: ${t} > ${n.length-1}.`,this.key);if(t!==Math.floor(t))throw new H(`Array index must be an integer, but found ${t} instead.`,this.key);return n[t]}eachChild(e){e(this.index),e(this.input)}outputDefined(){return!1}},Xt=class e{constructor(e,t,n){this.needle=e,this.haystack=t,this.key=n,this.type=L}static parse(t,n){if(t.length!==3)return n.error(`Expected 2 arguments, but found ${t.length-1} instead.`);let r=n.parse(t[1],1,R),i=n.parse(t[2],2,R);return!r||!i?null:Le(r.type,[L,I,F,Se,R])?new e(r,i,n.key):n.error(`Expected first argument to be of type boolean, string, number or null, but found ${z(r.type)} instead`)}evaluate(e){let t=this.needle.evaluate(e),n=this.haystack.evaluate(e);if(!n)return!1;if(!Re(t,[`boolean`,`string`,`number`,`null`]))throw new H(`Expected first argument to be of type boolean, string, number or null, but found ${z(U(t))} instead.`,this.key);if(!Re(n,[`string`,`array`]))throw new H(`Expected second argument to be of type array or string, but found ${z(U(n))} instead.`,this.key);return n.indexOf(t)>=0}eachChild(e){e(this.needle),e(this.haystack)}outputDefined(){return!0}},Zt=class e{constructor(e,t,n,r){this.needle=e,this.haystack=t,this.key=n,this.fromIndex=r,this.type=F}static parse(t,n){if(t.length<=2||t.length>=5)return n.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);let r=n.parse(t[1],1,R),i=n.parse(t[2],2,R);if(!r||!i)return null;if(!Le(r.type,[L,I,F,Se,R]))return n.error(`Expected first argument to be of type boolean, string, number or null, but found ${z(r.type)} instead`);if(t.length===4){let a=n.parse(t[3],3,F);return a?new e(r,i,n.key,a):null}return new e(r,i,n.key)}evaluate(e){let t=this.needle.evaluate(e),n=this.haystack.evaluate(e);if(!Re(t,[`boolean`,`string`,`number`,`null`]))throw new H(`Expected first argument to be of type boolean, string, number or null, but found ${z(U(t))} instead.`,this.key);let r;if(this.fromIndex&&(r=this.fromIndex.evaluate(e)),Re(n,[`string`])){let e=n.indexOf(t,r);return e===-1?-1:[...n.slice(0,e)].length}if(Re(n,[`array`]))return n.indexOf(t,r);throw new H(`Expected second argument to be of type array or string, but found ${z(U(n))} instead.`,this.key)}eachChild(e){e(this.needle),e(this.haystack),this.fromIndex&&e(this.fromIndex)}outputDefined(){return!1}},Qt=class e{constructor(e,t,n,r,i,a){this.inputType=e,this.type=t,this.input=n,this.cases=r,this.outputs=i,this.otherwise=a}static parse(t,n){if(t.length<5)return n.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return n.error(`Expected an even number of arguments.`);let r,i;n.expectedType&&n.expectedType.kind!==`value`&&(i=n.expectedType);let a={},o=[];for(let e=2;e2**53-1)return l.error(`Branch labels must be integers no larger than ${2**53-1}.`);if(typeof e==`number`&&Math.floor(e)!==e)return l.error(`Numeric branch labels must be integer values.`);if(!r)r=U(e);else if(l.checkSubtype(r,U(e)))return null;if(a[String(e)]!==void 0)return l.error(`Branch labels must be unique.`);a[String(e)]=o.length}let u=n.parse(c,e,i);if(!u)return null;i||=u.type,o.push(u)}let s=n.parse(t[1],1,R);if(!s)return null;let c=n.parse(t[t.length-1],t.length-1,i);return!c||s.type.kind!==`value`&&n.concat(1).checkSubtype(r,s.type)?null:new e(r,i,s,a,o,c)}evaluate(e){let t=this.input.evaluate(e);return(U(t)===this.inputType&&this.outputs[this.cases[t]]||this.otherwise).evaluate(e)}eachChild(e){e(this.input),this.outputs.forEach(e),e(this.otherwise)}outputDefined(){return this.outputs.every(e=>e.outputDefined())&&this.otherwise.outputDefined()}},$t=class e{constructor(e,t,n){this.type=e,this.branches=t,this.otherwise=n}static parse(t,n){if(t.length<4)return n.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return n.error(`Expected an odd number of arguments.`);let r;n.expectedType&&n.expectedType.kind!==`value`&&(r=n.expectedType);let i=[];for(let e=1;et.outputDefined())&&this.otherwise.outputDefined()}},en=class e{constructor(e,t,n,r,i){this.type=e,this.input=t,this.beginIndex=n,this.key=r,this.endIndex=i}static parse(t,n){if(t.length<=2||t.length>=5)return n.error(`Expected 2 or 3 arguments, but found ${t.length-1} instead.`);let r=n.parse(t[1],1,R),i=n.parse(t[2],2,F);if(!r||!i)return null;if(!Le(r.type,[Pe(R),I,R]))return n.error(`Expected first argument to be of type array or string, but found ${z(r.type)} instead`);if(t.length===4){let a=n.parse(t[3],3,F);return a?new e(r.type,r,i,n.key,a):null}return new e(r.type,r,i,n.key)}evaluate(e){let t=this.input.evaluate(e),n=this.beginIndex.evaluate(e),r;if(this.endIndex&&(r=this.endIndex.evaluate(e)),Re(t,[`string`]))return[...t].slice(n,r).join(``);if(Re(t,[`array`]))return t.slice(n,r);throw new H(`Expected first argument to be of type array or string, but found ${z(U(t))} instead.`,this.key)}eachChild(e){e(this.input),e(this.beginIndex),this.endIndex&&e(this.endIndex)}outputDefined(){return!1}},tn=class e{constructor(e,t){this.type=e,this.args=t}static parse(t,n){if(t.length<2)return n.error(`Expected at least one argument.`);let r=null,i=n.expectedType;i&&i.kind!==`value`&&(r=i);let a=[];for(let e of t.slice(1)){let t=n.parse(e,1+a.length,r,void 0,{typeAnnotation:`omit`});if(!t)return null;r||=t.type,a.push(t)}if(!r)throw Error(`No output type`);return i&&a.some(e=>Ie(i,e.type))?new e(R,a):new e(r,a)}evaluate(e){let t=null,n=0,r;for(let i of this.args)if(n++,t=i.evaluate(e),t&&t instanceof xt&&!t.available&&(r||=t.name,t=null,n===this.args.length&&(t=r)),t!==null)break;return t}eachChild(e){this.args.forEach(e)}outputDefined(){return this.args.every(e=>e.outputDefined())}};function nn(e,t){return e===`==`||e===`!=`?t.kind===`boolean`||t.kind===`string`||t.kind===`number`||t.kind===`null`||t.kind===`value`:t.kind===`string`||t.kind===`number`||t.kind===`value`}function rn(e,t,n){return t===n}function an(e,t,n){return t!==n}function on(e,t,n){return tn}function cn(e,t,n){return t<=n}function ln(e,t,n){return t>=n}function un(e,t,n,r){return r.compare(t,n)===0}function dn(e,t,n,r){return!un(e,t,n,r)}function fn(e,t,n,r){return r.compare(t,n)<0}function pn(e,t,n,r){return r.compare(t,n)>0}function mn(e,t,n,r){return r.compare(t,n)<=0}function hn(e,t,n,r){return r.compare(t,n)>=0}function gn(e,t,n){let r=e!==`==`&&e!==`!=`;return class i{constructor(e,t,n,r){this.lhs=e,this.rhs=t,this.key=n,this.collator=r,this.type=L,this.hasUntypedArgument=e.type.kind===`value`||t.type.kind===`value`}static parse(e,t){if(e.length!==3&&e.length!==4)return t.error(`Expected two or three arguments.`);let n=e[0],a=t.parse(e[1],1,R);if(!a)return null;if(!nn(n,a.type))return t.concat(1).error(`"${n}" comparisons are not supported for type '${z(a.type)}'.`);let o=t.parse(e[2],2,R);if(!o)return null;if(!nn(n,o.type))return t.concat(2).error(`"${n}" comparisons are not supported for type '${z(o.type)}'.`);if(a.type.kind!==o.type.kind&&a.type.kind!==`value`&&o.type.kind!==`value`)return t.error(`Cannot compare types '${z(a.type)}' and '${z(o.type)}'.`);r&&(a.type.kind===`value`&&o.type.kind!==`value`?a=new Wt(o.type,[a],t.key):a.type.kind!==`value`&&o.type.kind===`value`&&(o=new Wt(a.type,[o],t.key)));let s=null;if(e.length===4){if(a.type.kind!==`string`&&o.type.kind!==`string`&&a.type.kind!==`value`&&o.type.kind!==`value`)return t.error(`Cannot use collator to compare non-string types.`);if(s=t.parse(e[3],3,De),!s)return null}return new i(a,o,t.key,s)}evaluate(i){let a=this.lhs.evaluate(i),o=this.rhs.evaluate(i);if(r&&this.hasUntypedArgument){let t=U(a),n=U(o);if(t.kind!==n.kind||t.kind!==`string`&&t.kind!==`number`)throw new H(`Expected arguments for "${e}" to be (string, string) or (number, number), but found (${t.kind}, ${n.kind}) instead.`,this.key)}if(this.collator&&!r&&this.hasUntypedArgument){let e=U(a),n=U(o);if(e.kind!==`string`||n.kind!==`string`)return t(i,a,o)}return this.collator?n(i,a,o,this.collator.evaluate(i)):t(i,a,o)}eachChild(e){e(this.lhs),e(this.rhs),this.collator&&e(this.collator)}outputDefined(){return!0}}}const _n=gn(`==`,rn,un),vn=gn(`!=`,an,dn),yn=gn(`<`,on,fn),bn=gn(`>`,sn,pn),xn=gn(`<=`,cn,mn),Sn=gn(`>=`,ln,hn);var Cn=class e{constructor(e,t,n){this.type=De,this.locale=n,this.caseSensitive=e,this.diacriticSensitive=t}static parse(t,n){if(t.length!==2)return n.error(`Expected one argument.`);let r=t[1];if(typeof r!=`object`||Array.isArray(r))return n.error(`Collator options argument must be an object.`);let i=n.parse(r[`case-sensitive`]!==void 0&&r[`case-sensitive`],1,L);if(!i)return null;let a=n.parse(r[`diacritic-sensitive`]!==void 0&&r[`diacritic-sensitive`],1,L);if(!a)return null;let o=null;return r.locale&&(o=n.parse(r.locale,1,I),!o)?null:new e(i,a,o)}evaluate(e){return new Ct(this.caseSensitive.evaluate(e),this.diacriticSensitive.evaluate(e),this.locale?this.locale.evaluate(e):null)}eachChild(e){e(this.caseSensitive),e(this.diacriticSensitive),this.locale&&e(this.locale)}outputDefined(){return!1}},wn=class e{constructor(e,t,n,r,i,a){this.type=I,this.number=e,this.locale=t,this.currency=n,this.unit=r,this.minFractionDigits=i,this.maxFractionDigits=a}static parse(t,n){if(t.length!==3)return n.error(`Expected two arguments.`);let r=n.parse(t[1],1,F);if(!r)return null;let i=t[2];if(typeof i!=`object`||Array.isArray(i))return n.error(`NumberFormat options argument must be an object.`);let a=null;if(i.locale&&(a=n.parse(i.locale,1,I),!a))return null;let o=null;if(i.currency&&(o=n.parse(i.currency,1,I),!o))return null;let s=null;if(i.unit&&(s=n.parse(i.unit,1,I),!s))return null;if(o&&s)return n.error("NumberFormat options `currency` and `unit` are mutually exclusive");let c=null;if(i[`min-fraction-digits`]&&(c=n.parse(i[`min-fraction-digits`],1,F),!c))return null;let l=null;return i[`max-fraction-digits`]&&(l=n.parse(i[`max-fraction-digits`],1,F),!l)?null:new e(r,a,o,s,c,l)}evaluate(e){return new Intl.NumberFormat(this.locale?this.locale.evaluate(e):[],{style:this.currency?`currency`:this.unit?`unit`:`decimal`,currency:this.currency?this.currency.evaluate(e):void 0,unit:this.unit?this.unit.evaluate(e):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(e):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(e):void 0}).format(this.number.evaluate(e))}eachChild(e){e(this.number),this.locale&&e(this.locale),this.currency&&e(this.currency),this.unit&&e(this.unit),this.minFractionDigits&&e(this.minFractionDigits),this.maxFractionDigits&&e(this.maxFractionDigits)}outputDefined(){return!1}},Tn=class e{constructor(e){this.type=Me,this.input=e}static parse(t,n){if(t.length!==2)return n.error(`Expected two arguments.`);let r=n.parse(t[1],1,I);return r?new e(r):n.error(`No image name provided.`)}evaluate(e){let t=this.input.evaluate(e),n=xt.fromString(t);return n&&e.availableImages&&(n.available=e.availableImages.indexOf(t)>-1),n}eachChild(e){e(this.input)}outputDefined(){return!1}},En=class e{constructor(e,t){this.input=e,this.key=t,this.type=F}static parse(t,n){if(t.length!==2)return n.error(`Expected 1 argument, but found ${t.length-1} instead.`);let r=n.parse(t[1],1);return r?r.type.kind!==`array`&&r.type.kind!==`string`&&r.type.kind!==`value`?n.error(`Expected argument of type string or array, but found ${z(r.type)} instead.`):new e(r,n.key):null}evaluate(e){let t=this.input.evaluate(e);if(typeof t==`string`)return[...t].length;if(Array.isArray(t))return t.length;throw new H(`Expected value to be of type string or array, but found ${z(U(t))} instead.`,this.key)}eachChild(e){e(this.input)}outputDefined(){return!1}};const Dn=8192;function On(e,t){let n=An(e[0]),r=Mn(e[1]),i=2**t.z;return[Math.round(n*i*Dn),Math.round(r*i*Dn)]}function kn(e,t){let n=2**t.z,r=(e[0]/Dn+t.x)/n,i=(e[1]/Dn+t.y)/n;return[jn(r),Nn(i)]}function An(e){return(180+e)/360}function jn(e){return e*360-180}function Mn(e){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+e*Math.PI/360)))/360}function Nn(e){return 360/Math.PI*Math.atan(Math.exp((180-e*360)*Math.PI/180))-90}function Pn(e,t){e[0]=Math.min(e[0],t[0]),e[1]=Math.min(e[1],t[1]),e[2]=Math.max(e[2],t[0]),e[3]=Math.max(e[3],t[1])}function Fn(e,t){return!(e[0]<=t[0]||e[2]>=t[2]||e[1]<=t[1]||e[3]>=t[3])}function In(e,t,n){return t[1]>e[1]!=n[1]>e[1]&&e[0]<(n[0]-t[0])*(e[1]-t[1])/(n[1]-t[1])+t[0]}function Ln(e,t,n){let r=e[0]-t[0],i=e[1]-t[1],a=e[0]-n[0],o=e[1]-n[1];return r*o-a*i===0&&r*a<=0&&i*o<=0}function Rn(e,t,n,r){let i=[t[0]-e[0],t[1]-e[1]];return Wn([r[0]-n[0],r[1]-n[1]],i)!==0&&!!(Gn(e,t,n,r)&&Gn(n,r,e,t))}function zn(e,t,n){for(let r of n)for(let n=0;n0&&d<0||u<0&&d>0}function Kn(e,t,n){let r=[];for(let i=0;in[2]){let t=r*.5,i=e[0]-n[0]>t?-r:n[0]-e[0]>t?r:0;i===0&&(i=e[0]-n[2]>t?-r:n[2]-e[0]>t?r:0),e[0]+=i}Pn(t,e)}function Yn(e){e[0]=e[1]=1/0,e[2]=e[3]=-1/0}function Xn(e,t,n,r){let i=2**r.z*Dn,a=[r.x*Dn,r.y*Dn],o=[];for(let r of e)for(let e of r){let r=[e.x+a[0],e.y+a[1]];Jn(r,t,n,i),o.push(r)}return o}function Zn(e,t,n,r){let i=2**r.z*Dn,a=[r.x*Dn,r.y*Dn],o=[];for(let n of e){let e=[];for(let r of n){let n=[r.x+a[0],r.y+a[1]];Pn(t,n),e.push(n)}o.push(e)}if(t[2]-t[0]<=i/2){Yn(t);for(let e of o)for(let r of e)Jn(r,t,n,i)}return o}function Qn(e,t){let n=[1/0,1/0,-1/0,-1/0],r=[1/0,1/0,-1/0,-1/0],i=e.canonicalID();if(t.type===`Polygon`){let a=Kn(t.coordinates,r,i),o=Xn(e.geometry(),n,r,i);if(!Fn(n,r))return!1;for(let e of o)if(!Bn(e,a))return!1}if(t.type===`MultiPolygon`){let a=qn(t.coordinates,r,i),o=Xn(e.geometry(),n,r,i);if(!Fn(n,r))return!1;for(let e of o)if(!Vn(e,a))return!1}return!0}function $n(e,t){let n=[1/0,1/0,-1/0,-1/0],r=[1/0,1/0,-1/0,-1/0],i=e.canonicalID();if(t.type===`Polygon`){let a=Kn(t.coordinates,r,i),o=Zn(e.geometry(),n,r,i);if(!Fn(n,r))return!1;for(let e of o)if(!Hn(e,a))return!1}if(t.type===`MultiPolygon`){let a=qn(t.coordinates,r,i),o=Zn(e.geometry(),n,r,i);if(!Fn(n,r))return!1;for(let e of o)if(!Un(e,a))return!1}return!0}var er=class e{constructor(e,t){this.type=L,this.geojson=e,this.geometries=t}static parse(t,n){if(t.length!==2)return n.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Tt(t[1])){let n=t[1];if(n.type===`FeatureCollection`){let t=[];for(let e of n.features){let{type:n,coordinates:r}=e.geometry;n===`Polygon`&&t.push(r),n===`MultiPolygon`&&t.push(...r)}if(t.length)return new e(n,{type:`MultiPolygon`,coordinates:t})}else if(n.type===`Feature`){let t=n.geometry.type;if(t===`Polygon`||t===`MultiPolygon`)return new e(n,n.geometry)}else if(n.type===`Polygon`||n.type===`MultiPolygon`)return new e(n,n)}return n.error(`'within' expression requires valid geojson object that contains polygon geometry type.`)}evaluate(e){if(e.geometry()!=null&&e.canonicalID()!=null){if(e.geometryType()===`Point`)return Qn(e,this.geometries);if(e.geometryType()===`LineString`)return $n(e,this.geometries)}return!1}eachChild(){}outputDefined(){return!0}},tr=class{constructor(e=[],t=(e,t)=>et)){if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let e=(this.length>>1)-1;e>=0;e--)this._down(e)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(this.length===0)return;let e=this.data[0],t=this.data.pop();return--this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){let{data:t,compare:n}=this,r=t[e];for(;e>0;){let i=e-1>>1,a=t[i];if(n(r,a)>=0)break;t[e]=a,e=i}t[e]=r}_down(e){let{data:t,compare:n}=this,r=this.length>>1,i=t[e];for(;e=0)break;t[e]=t[r],e=r}t[e]=i}};const nr=Math.PI/180;var rr=class{constructor(e){let t=nr*6378.137*1e3,n=Math.cos(e*nr),r=1/(1-.0066943799901413165*(1-n*n)),i=Math.sqrt(r);this.kx=t*i*n,this.ky=t*i*r*.9933056200098587}distance(e,t){let n=this.wrap(e[0]-t[0])*this.kx,r=(e[1]-t[1])*this.ky;return Math.sqrt(n*n+r*r)}pointOnLine(e,t){let n=1/0,r,i,a,o;for(let s=0;s1?(c=e[s+1][0],l=e[s+1][1]):f>0&&(c+=u/this.kx*f,l+=d/this.ky*f)),u=this.wrap(t[0]-c)*this.kx,d=(t[1]-l)*this.ky;let p=u*u+d*d;p180;)e-=360;return e}};function ir(e,t){return t[0]-e[0]}function ar(e){return e[1]-e[0]+1}function or(e,t){return e[1]>=e[0]&&e[1]e[1])return[null,null];let n=ar(e);if(t){if(n===2)return[e,null];let t=Math.floor(n/2);return[[e[0],e[0]+t],[e[0]+t,e[1]]]}if(n===1)return[e,null];let r=Math.floor(n/2)-1;return[[e[0],e[0]+r],[e[0]+r+1,e[1]]]}function cr(e,t){if(!or(t,e.length))return[1/0,1/0,-1/0,-1/0];let n=[1/0,1/0,-1/0,-1/0];for(let r=t[0];r<=t[1];++r)Pn(n,e[r]);return n}function lr(e){let t=[1/0,1/0,-1/0,-1/0];for(let n of e)for(let e of n)Pn(t,e);return t}function ur(e){return e[0]!==-1/0&&e[1]!==-1/0&&e[2]!==1/0&&e[3]!==1/0}function dr(e,t,n){if(!ur(e)||!ur(t))return NaN;let r=0,i=0;return e[2]t[2]&&(r=e[0]-t[2]),e[1]>t[3]&&(i=e[1]-t[3]),e[3]=r)return r;if(Fn(i,a)){if(vr(e,t))return 0}else if(vr(t,e))return 0;let o=1/0;for(let r of e)for(let e=0,i=r.length,a=i-1;e0;){let i=o.pop();if(i[0]>=a)continue;let c=i[1],l=t?50:100;if(ar(c)<=l){if(!or(c,e.length))return NaN;if(t){let t=_r(e,c,n,r);if(isNaN(t)||t===0)return t;a=Math.min(a,t)}else for(let t=c[0];t<=c[1];++t){let i=gr(e[t],n,r);if(a=Math.min(a,i),a===0)return 0}}else{let n=sr(c,t);br(o,a,r,e,s,n[0]),br(o,a,r,e,s,n[1])}}return a}function Cr(e,t,n,r,i,a=1/0){let o=Math.min(a,i.distance(e[0],n[0]));if(o===0)return o;let s=new tr([[0,[0,e.length-1],[0,n.length-1]]],ir);for(;s.length>0;){let a=s.pop();if(a[0]>=o)continue;let c=a[1],l=a[2],u=t?50:100,d=r?50:100;if(ar(c)<=u&&ar(l)<=d){if(!or(c,e.length)&&or(l,n.length))return NaN;let a;if(t&&r)a=mr(e,c,n,l,i),o=Math.min(o,a);else if(t&&!r){let t=e.slice(c[0],c[1]+1);for(let e=l[0];e<=l[1];++e)if(a=fr(n[e],t,i),o=Math.min(o,a),o===0)return o}else if(!t&&r){let t=n.slice(l[0],l[1]+1);for(let n=c[0];n<=c[1];++n)if(a=fr(e[n],t,i),o=Math.min(o,a),o===0)return o}else a=hr(e,c,n,l,i),o=Math.min(o,a)}else{let a=sr(c,t),u=sr(l,r);xr(s,o,i,e,n,a[0],u[0]),xr(s,o,i,e,n,a[0],u[1]),xr(s,o,i,e,n,a[1],u[0]),xr(s,o,i,e,n,a[1],u[1])}}return o}function wr(e,t){let n=e.geometry(),r=n.flat().map(t=>kn([t.x,t.y],e.canonical));if(n.length===0)return NaN;let i=new rr(r[0][1]),a=1/0;for(let e of t){switch(e.type){case`Point`:a=Math.min(a,Cr(r,!1,[e.coordinates],!1,i,a));break;case`LineString`:a=Math.min(a,Cr(r,!1,e.coordinates,!0,i,a));break;case`Polygon`:a=Math.min(a,Sr(r,!1,e.coordinates,i,a))}if(a===0)return a}return a}function Tr(e,t){let n=e.geometry(),r=n.flat().map(t=>kn([t.x,t.y],e.canonical));if(n.length===0)return NaN;let i=new rr(r[0][1]),a=1/0;for(let e of t){switch(e.type){case`Point`:a=Math.min(a,Cr(r,!0,[e.coordinates],!1,i,a));break;case`LineString`:a=Math.min(a,Cr(r,!0,e.coordinates,!0,i,a));break;case`Polygon`:a=Math.min(a,Sr(r,!0,e.coordinates,i,a))}if(a===0)return a}return a}function Er(e,t){let n=e.geometry();if(n.length===0||n[0].length===0)return NaN;let r=Bt(n,0).map(t=>t.map(t=>t.map(t=>kn([t.x,t.y],e.canonical)))),i=new rr(r[0][0][0][1]),a=1/0;for(let e of t)for(let t of r){switch(e.type){case`Point`:a=Math.min(a,Sr([e.coordinates],!1,t,i,a));break;case`LineString`:a=Math.min(a,Sr(e.coordinates,!0,t,i,a));break;case`Polygon`:a=Math.min(a,yr(t,e.coordinates,i,a))}if(a===0)return a}return a}function Dr(e){return e.type===`MultiPolygon`?e.coordinates.map(e=>({type:`Polygon`,coordinates:e})):e.type===`MultiLineString`?e.coordinates.map(e=>({type:`LineString`,coordinates:e})):e.type===`MultiPoint`?e.coordinates.map(e=>({type:`Point`,coordinates:e})):[e]}var Or=class e{constructor(e,t){this.type=F,this.geojson=e,this.geometries=t}static parse(t,n){if(t.length!==2)return n.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Tt(t[1])){let n=t[1];if(n.type===`FeatureCollection`)return new e(n,n.features.map(e=>Dr(e.geometry)).flat());if(n.type===`Feature`)return new e(n,Dr(n.geometry));if(`type`in n&&`coordinates`in n)return new e(n,Dr(n))}return n.error(`'distance' expression requires valid geojson object that contains polygon geometry type.`)}evaluate(e){if(e.geometry()!=null&&e.canonicalID()!=null){if(e.geometryType()===`Point`)return wr(e,this.geometries);if(e.geometryType()===`LineString`)return Tr(e,this.geometries);if(e.geometryType()===`Polygon`)return Er(e,this.geometries)}return NaN}eachChild(){}outputDefined(){return!0}},kr=class e{constructor(e){let t=null;for(let n of e)if(!t)t=n.type;else if(t===n.type)continue;else{t=R;break}this.type=Pe(t??R,e.length),this.arr=e}static parse(t,n){if(t.length!==2)return n.error(`'semiliteral' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!Tt(t[1]))return n.error(`invalid value of type "${typeof t[1]}"`);let r=t[1],i=U(r);if(i.kind===`array`){let t=r,i=n.concat(1),a=[];for(let e=0;et.evaluate(e))}eachChild(e){this.arr.forEach(e)}outputDefined(){return this.arr.every(e=>e.outputDefined())}},Ar=class e{constructor(e){this.key=e,this.type=R}static parse(t,n){if(t.length!==2)return n.error(`Expected 1 argument, but found ${t.length-1} instead.`);let r=t[1];return r==null?n.error(`Global state property must be defined.`):typeof r==`string`?new e(r):n.error(`Global state property must be string, but found ${typeof t[1]} instead.`)}evaluate(e){let t=e.globals?.globalState;return!t||Object.keys(t).length===0?null:rt(t,this.key)??null}eachChild(){}outputDefined(){return!1}};const jr={"==":_n,"!=":vn,">":bn,"<":yn,">=":Sn,"<=":xn,array:Wt,at:Yt,boolean:Wt,case:$t,coalesce:tn,collator:Cn,format:It,image:Tn,in:Xt,"index-of":Zt,interpolate:Nt,"interpolate-hcl":Nt,"interpolate-lab":Nt,length:En,let:qt,literal:Dt,match:Qt,number:Wt,"number-format":wn,object:Wt,semiliteral:kr,slice:en,step:jt,string:Wt,"to-boolean":Kt,"to-color":Kt,"to-number":Kt,"to-string":Kt,var:Jt,within:er,distance:Or,"global-state":Ar};var Mr=class extends Error{constructor(e,t){super(t),this.message=t,this.key=e}},Nr=class e{constructor(e,t=[]){this.parent=e,this.bindings={};for(let[e,n]of t)this.bindings[e]=n}concat(t){return new e(this,t)}get(e){if(this.bindings[e])return this.bindings[e];if(this.parent)return this.parent.get(e);throw Error(`${e} not found in scope.`)}has(e){return this.bindings[e]?!0:this.parent?this.parent.has(e):!1}},Pr=class e{constructor(e,t,n=[],r,i=new Nr,a=[]){this.registry=e,this.path=n,this.key=n.map(e=>`[${e}]`).join(``),this.scope=i,this.errors=a,this.expectedType=r,this._isConstant=t}parse(e,t,n,r,i={}){return t==null?this._parse(e,i):this.concat(t,n,r)._parse(e,i)}_parse(e,t){(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`)&&(e=[`literal`,e]);let n=this.key;function r(e,t,r){return r===`assert`?new Wt(t,[e],n):r===`coerce`?new Kt(t,[e],n):e}if(Array.isArray(e)){if(e.length===0)return this.error(`Expected an array with at least one element. If you wanted a literal array, use ["literal", []].`);let n=e[0];if(typeof n!=`string`)return this.error(`Expression name must be a string, but found ${typeof n} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;let i=this.registry[n];if(i){let n=i.parse(e,this);if(!n)return null;if(this.expectedType){let e=this.expectedType,i=n.type;if((e.kind===`string`||e.kind===`number`||e.kind===`boolean`||e.kind===`object`||e.kind===`array`)&&i.kind===`value`)n=r(n,e,t.typeAnnotation||`assert`);else if(e.kind===`projectionDefinition`&&[`string`,`array`,`value`].includes(i.kind)||[`color`,`formatted`,`resolvedImage`].includes(e.kind)&&[`value`,`string`].includes(i.kind)||[`padding`,`numberArray`].includes(e.kind)&&[`value`,`number`,`array`].includes(i.kind)||e.kind===`colorArray`&&[`value`,`string`,`array`].includes(i.kind)||e.kind===`variableAnchorOffsetCollection`&&[`value`,`array`].includes(i.kind))n=r(n,e,t.typeAnnotation||`coerce`);else if(this.checkSubtype(e,i))return null}if(!(n instanceof Dt)&&n.type.kind!==`resolvedImage`&&this._isConstant(n)){let e=new kt;try{n=new Dt(n.type,n.evaluate(e))}catch(e){return this.error(e.message),null}}return n}return this.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0)}return e===void 0?this.error(`'undefined' value invalid. Use null instead.`):typeof e==`object`?this.error(`Bare objects invalid. Use ["literal", {...}] instead.`):this.error(`Expected an array, but found ${typeof e} instead.`)}concat(t,n,r){let i=typeof t==`number`?this.path.concat(t):this.path,a=r?this.scope.concat(r):this.scope;return new e(this.registry,this._isConstant,i,n||null,a,this.errors)}error(e,...t){let n=`${this.key}${t.map(e=>`[${e}]`).join(``)}`;this.errors.push(new Mr(n,e))}checkSubtype(e,t){let n=Ie(e,t);return n&&this.error(n),n}},Fr=class e{constructor(e,t,n,r,i){this.name=e,this.type=t,this._evaluate=n,this.args=r,this.key=i}evaluate(e){return this._evaluate(e,this.args,this.key)}eachChild(e){this.args.forEach(e)}outputDefined(){return!1}static parse(t,n){let r=t[0],i=e.definitions[r];if(!i)return n.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);let a=Array.isArray(i)?i[0]:i.type,o=Array.isArray(i)?[[i[1],i[2]]]:i.overloads,s=o.filter(([e])=>!Array.isArray(e)||e.length===t.length-1),c=null;for(let[i,o]of s){c=new Pr(n.registry,Hr,n.path,null,n.scope);let s=[],l=!1;for(let e=1;eVr(e)).join(` | `),r=[];for(let e=1;e>1;if(t[i]===e)return!0;t[i]>e?r=i-1:n=i+1}return!1}function Br(e){return{type:e}}Fr.register(jr,{error:[Ee,[I],(e,[t],n)=>{throw new H(t.evaluate(e),n)}],typeof:[I,[R],(e,[t])=>z(U(t.evaluate(e)))],"to-rgba":[Pe(F,4),[Ce],(e,[t])=>{let[n,r,i,a]=t.evaluate(e).rgb;return[n*255,r*255,i*255,a]}],rgb:[Ce,[F,F,F],Ir],rgba:[Ce,[F,F,F,F],Ir],has:{type:L,overloads:[[[I],(e,[t])=>Lr(t.evaluate(e),e.properties())],[[I,Te],(e,[t,n])=>Lr(t.evaluate(e),n.evaluate(e))]]},get:{type:R,overloads:[[[I],(e,[t])=>Rr(t.evaluate(e),e.properties())],[[I,Te],(e,[t,n])=>Rr(t.evaluate(e),n.evaluate(e))]]},"feature-state":[R,[I],(e,[t])=>Rr(t.evaluate(e),e.featureState||{})],properties:[Te,[],e=>e.properties()],"geometry-type":[I,[],e=>e.geometryType()],id:[R,[],e=>e.id()],zoom:[F,[],e=>e.globals.zoom],"heatmap-density":[F,[],e=>e.globals.heatmapDensity||0],elevation:[F,[],e=>e.globals.elevation||0],"line-progress":[F,[],e=>e.globals.lineProgress||0],accumulated:[R,[],e=>e.globals.accumulated===void 0?null:e.globals.accumulated],"+":[F,Br(F),(e,t)=>{let n=0;for(let r of t)n+=r.evaluate(e);return n}],"*":[F,Br(F),(e,t)=>{let n=1;for(let r of t)n*=r.evaluate(e);return n}],"-":{type:F,overloads:[[[F,F],(e,[t,n])=>t.evaluate(e)-n.evaluate(e)],[[F],(e,[t])=>-t.evaluate(e)]]},"/":[F,[F,F],(e,[t,n])=>t.evaluate(e)/n.evaluate(e)],"%":[F,[F,F],(e,[t,n])=>t.evaluate(e)%n.evaluate(e)],ln2:[F,[],()=>Math.LN2],pi:[F,[],()=>Math.PI],e:[F,[],()=>Math.E],"^":[F,[F,F],(e,[t,n])=>t.evaluate(e)**+n.evaluate(e)],sqrt:[F,[F],(e,[t])=>Math.sqrt(t.evaluate(e))],log10:[F,[F],(e,[t])=>Math.log(t.evaluate(e))/Math.LN10],ln:[F,[F],(e,[t])=>Math.log(t.evaluate(e))],log2:[F,[F],(e,[t])=>Math.log(t.evaluate(e))/Math.LN2],sin:[F,[F],(e,[t])=>Math.sin(t.evaluate(e))],cos:[F,[F],(e,[t])=>Math.cos(t.evaluate(e))],tan:[F,[F],(e,[t])=>Math.tan(t.evaluate(e))],asin:[F,[F],(e,[t])=>Math.asin(t.evaluate(e))],acos:[F,[F],(e,[t])=>Math.acos(t.evaluate(e))],atan:[F,[F],(e,[t])=>Math.atan(t.evaluate(e))],min:[F,Br(F),(e,t)=>Math.min(...t.map(t=>t.evaluate(e)))],max:[F,Br(F),(e,t)=>Math.max(...t.map(t=>t.evaluate(e)))],abs:[F,[F],(e,[t])=>Math.abs(t.evaluate(e))],round:[F,[F],(e,[t])=>{let n=t.evaluate(e);return n<0?-Math.round(-n):Math.round(n)}],floor:[F,[F],(e,[t])=>Math.floor(t.evaluate(e))],ceil:[F,[F],(e,[t])=>Math.ceil(t.evaluate(e))],"filter-==":[L,[I,R],(e,[t,n])=>e.properties()[t.value]===n.value],"filter-id-==":[L,[R],(e,[t])=>e.id()===t.value],"filter-type-==":[L,[I],(e,[t])=>e.geometryType()===t.value],"filter-<":[L,[I,R],(e,[t,n])=>{let r=e.properties()[t.value],i=n.value;return typeof r==typeof i&&r{let n=e.id(),r=t.value;return typeof n==typeof r&&n":[L,[I,R],(e,[t,n])=>{let r=e.properties()[t.value],i=n.value;return typeof r==typeof i&&r>i}],"filter-id->":[L,[R],(e,[t])=>{let n=e.id(),r=t.value;return typeof n==typeof r&&n>r}],"filter-<=":[L,[I,R],(e,[t,n])=>{let r=e.properties()[t.value],i=n.value;return typeof r==typeof i&&r<=i}],"filter-id-<=":[L,[R],(e,[t])=>{let n=e.id(),r=t.value;return typeof n==typeof r&&n<=r}],"filter->=":[L,[I,R],(e,[t,n])=>{let r=e.properties()[t.value],i=n.value;return typeof r==typeof i&&r>=i}],"filter-id->=":[L,[R],(e,[t])=>{let n=e.id(),r=t.value;return typeof n==typeof r&&n>=r}],"filter-has":[L,[R],(e,[t])=>{let n=t.value,r=e.properties();return n in r&&r[n]!==void 0}],"filter-has-id":[L,[],e=>e.id()!==null&&e.id()!==void 0],"filter-type-in":[L,[Pe(I)],(e,[t])=>t.value.indexOf(e.geometryType())>=0],"filter-id-in":[L,[Pe(R)],(e,[t])=>t.value.indexOf(e.id())>=0],"filter-in-small":[L,[I,Pe(R)],(e,[t,n])=>n.value.indexOf(e.properties()[t.value])>=0],"filter-in-large":[L,[I,Pe(R)],(e,[t,n])=>zr(e.properties()[t.value],n.value,0,n.value.length-1)],all:{type:L,overloads:[[[L,L],(e,[t,n])=>t.evaluate(e)&&n.evaluate(e)],[Br(L),(e,t)=>{for(let n of t)if(!n.evaluate(e))return!1;return!0}]]},any:{type:L,overloads:[[[L,L],(e,[t,n])=>t.evaluate(e)||n.evaluate(e)],[Br(L),(e,t)=>{for(let n of t)if(n.evaluate(e))return!0;return!1}]]},"!":[L,[L],(e,[t])=>!t.evaluate(e)],"is-supported-script":[L,[I],(e,[t])=>{let n=e.globals&&e.globals.isSupportedScript;return!n||n(t.evaluate(e))}],upcase:[I,[I],(e,[t])=>t.evaluate(e).toUpperCase()],downcase:[I,[I],(e,[t])=>t.evaluate(e).toLowerCase()],concat:[I,Br(R),(e,t)=>t.map(t=>Et(t.evaluate(e))).join(``)],split:[Pe(I),[I,I],(e,[t,n])=>t.evaluate(e).split(n.evaluate(e))],join:[I,[Pe(I),I],(e,[t,n])=>t.evaluate(e).join(n.evaluate(e))],"resolved-locale":[I,[De],(e,[t])=>t.evaluate(e).resolvedLocale()]});function Vr(e){return Array.isArray(e)?`(${e.map(z).join(`, `)})`:`(${z(e.type)}...)`}function Hr(e){if(e instanceof Jt)return Hr(e.boundExpression);if(e instanceof Fr&&e.name===`error`||e instanceof Cn||e instanceof er||e instanceof Or||e instanceof Ar)return!1;let t=e instanceof Kt||e instanceof Wt,n=!0;return e.eachChild(e=>{n&&=t?Hr(e):e instanceof Dt}),n?Ur(e)&&Gr(e,[`zoom`,`heatmap-density`,`elevation`,`line-progress`,`accumulated`,`is-supported-script`]):!1}function Ur(e){if(e instanceof Fr&&(e.name===`get`&&e.args.length===1||e.name===`feature-state`||e.name===`has`&&e.args.length===1||e.name===`properties`||e.name===`geometry-type`||e.name===`id`||/^filter-/.test(e.name))||e instanceof er||e instanceof Or)return!1;let t=!0;return e.eachChild(e=>{t&&!Ur(e)&&(t=!1)}),t}function Wr(e){if(e instanceof Fr&&e.name===`feature-state`)return!1;let t=!0;return e.eachChild(e=>{t&&!Wr(e)&&(t=!1)}),t}function Gr(e,t){if(e instanceof Fr&&t.indexOf(e.name)>=0)return!1;let n=!0;return e.eachChild(e=>{n&&!Gr(e,t)&&(n=!1)}),n}function Kr(e){return e[`property-type`]===`data-driven`||e[`property-type`]===`cross-faded-data-driven`}function qr(e){return!!e.expression&&e.expression.parameters.indexOf(`zoom`)>-1}function Jr(e){return!!e.expression&&e.expression.interpolated}const Yr=/^(.*)-transition$/;function Xr(e,...t){for(let n of t)for(let t in n)e[t]=n[t];return e}function W(e){return e instanceof Number?`number`:e instanceof String?`string`:e instanceof Boolean?`boolean`:Array.isArray(e)?`array`:e===null?`null`:typeof e}function Zr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&U(e)===Te}function Qr(e){return e}function $r(e){switch(e.type){case`color`:return V.parse;case`padding`:return gt.parse;case`numberArray`:return _t.parse;case`colorArray`:return vt.parse;default:return null}}function ei(e){switch(e){case`exponential`:return ai;case`interval`:return ii;case`categorical`:return ri;case`identity`:return oi;default:throw Error(`Unknown function type "${e}"`)}}function ti(e,t){let n=e.stops&&typeof e.stops[0][0]==`object`,r=n||e.property!==void 0,i=n||!r,a=e.type||(Jr(t)?`exponential`:`interval`),o=$r(t);if(o&&(e=Xr({},e),e.stops&&(e.stops=e.stops.map(e=>[e[0],o(e[1])])),e.default?e.default=o(e.default):e.default=o(t.default)),e.colorSpace&&!ft(e.colorSpace))throw Error(`Unknown color space: "${e.colorSpace}"`);let s=ei(a),c,l;if(a===`categorical`){c=Object.create(null);for(let t of e.stops)c[t[0]]=t[1];l=typeof e.stops[0][0]}if(n){let n={},r=[];for(let t=0;te[0]),evaluate({zoom:n},r){return ai({stops:i,base:e.base},t,n).evaluate(n,r)}}}if(i){let n=a===`exponential`?{name:`exponential`,base:e.base===void 0?1:e.base}:null;return{kind:`camera`,interpolationType:n,interpolationFactor:Nt.interpolationFactor.bind(void 0,n),zoomStops:e.stops.map(e=>e[0]),evaluate:({zoom:n})=>s(e,t,n,c,l)}}return{kind:`source`,evaluate(n,r){let i=r&&r.properties?r.properties[e.property]:void 0;return i===void 0?ni(e.default,t.default):s(e,t,i,c,l)}}}function ni(e,t,n){if(e!==void 0)return e;if(t!==void 0)return t;if(n!==void 0)return n}function ri(e,t,n,r,i){return ni(typeof n===i?r[n]:void 0,e.default,t.default)}function ii(e,t,n){if(W(n)!==`number`)return ni(e.default,t.default);let r=e.stops.length;if(r===1||n<=e.stops[0][0])return e.stops[0][1];if(n>=e.stops[r-1][0])return e.stops[r-1][1];let i=At(e.stops.map(e=>e[0]),n,``);return e.stops[i][1]}function ai(e,t,n){let r=e.base===void 0?1:e.base;if(W(n)!==`number`)return ni(e.default,t.default);let i=e.stops.length;if(i===1||n<=e.stops[0][0])return e.stops[0][1];if(n>=e.stops[i-1][0])return e.stops[i-1][1];let a=At(e.stops.map(e=>e[0]),n,``),o=si(n,r,e.stops[a][0],e.stops[a+1][0]),s=e.stops[a][1],c=e.stops[a+1][1],l=Ft[t.type]||Qr;return typeof s.evaluate==`function`?{evaluate(...t){let n=s.evaluate.apply(void 0,t),r=c.evaluate.apply(void 0,t);if(n!==void 0&&r!==void 0)return l(n,r,o,e.colorSpace)}}:l(s,c,o,e.colorSpace)}function oi(e,t,n){switch(t.type){case`color`:n=V.parse(n);break;case`formatted`:n=ht.fromString(n.toString());break;case`resolvedImage`:n=xt.fromString(n.toString());break;case`padding`:n=gt.parse(n);break;case`colorArray`:n=vt.parse(n);break;case`numberArray`:n=_t.parse(n);break;default:W(n)!==t.type&&(t.type!==`enum`||!t.values[n])&&(n=void 0)}return ni(n,e.default,t.default)}function si(e,t,n,r){let i=r-n,a=e-n;return i===0?0:t===1?a/i:(t**+a-1)/(t**+i-1)}function ci(e){return{result:`success`,value:e}}function li(e){return{result:`error`,value:e}}var ui=class{constructor(e,t,n,r){this.expression=e,this._warningHistory={},this._evaluator=new kt,this._defaultValue=n?wi(n):null,this._enumValues=n&&n.type===`enum`?n.values:null,this._globalState=r,this._rootKey=t}evaluateWithoutErrorHandling(e,t,n,r,i,a){return this._globalState&&(e=Ti(e,this._globalState)),this._evaluator.globals=e,this._evaluator.feature=t,this._evaluator.featureState=n,this._evaluator.canonical=r,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=a,this.expression.evaluate(this._evaluator)}evaluate(e,t,n,r,i,a){this._globalState&&(e=Ti(e,this._globalState)),this._evaluator.globals=e,this._evaluator.feature=t||null,this._evaluator.featureState=n||null,this._evaluator.canonical=r,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=a||null;try{let e=this.expression.evaluate(this._evaluator);if(e==null||typeof e==`number`&&e!==e)return this._defaultValue;if(this._enumValues&&!(e in this._enumValues))throw new H(`Expected value to be one of ${Object.keys(this._enumValues).map(e=>JSON.stringify(e)).join(`, `)}, but found ${JSON.stringify(e)} instead.`,``);return e}catch(e){let t=e instanceof H?e.path:``,n=`${t}|${e.message}`;return this._warningHistory[n]||(this._warningHistory[n]=!0,typeof console<`u`&&console.warn(di(this._rootKey,t,e.message,this._defaultValue))),this._defaultValue}}};function di(e,t,n,r){return`${e}${t}: ${n}${r==null?``:` Falling back to ${String(r)}.`}`}function fi(e){if(!e)throw Error(`rootKey must identify the location of the expression in the style JSON, e.g. "layers[3].paint.line-width".`)}function pi(e){return Array.isArray(e)&&e.length>0&&typeof e[0]==`string`&&e[0]in jr}function mi(e,t,n,r){fi(t);let i=new Pr(jr,Hr,[],n?Ci(n):void 0),a=i.parse(e,void 0,void 0,void 0,n&&n.type===`string`?{typeAnnotation:`coerce`}:void 0);return a?ci(new ui(a,t,n,r)):li(i.errors)}var hi=class{constructor(e,t,n){this.kind=e,this._styleExpression=t,this.isStateDependent=e!==`constant`&&!Wr(t.expression),this.globalStateRefs=Si(t.expression),this._globalState=n}evaluateWithoutErrorHandling(e,t,n,r,i,a){return this._globalState&&(e=Ti(e,this._globalState)),this._styleExpression.evaluateWithoutErrorHandling(e,t,n,r,i,a)}evaluate(e,t,n,r,i,a){return this._globalState&&(e=Ti(e,this._globalState)),this._styleExpression.evaluate(e,t,n,r,i,a)}},gi=class{constructor(e,t,n,r,i){this.kind=e,this.zoomStops=n,this._styleExpression=t,this.isStateDependent=e!==`camera`&&!Wr(t.expression),this.globalStateRefs=Si(t.expression),this.interpolationType=r,this._globalState=i}evaluateWithoutErrorHandling(e,t,n,r,i,a){return this._globalState&&(e=Ti(e,this._globalState)),this._styleExpression.evaluateWithoutErrorHandling(e,t,n,r,i,a)}evaluate(e,t,n,r,i,a){return this._globalState&&(e=Ti(e,this._globalState)),this._styleExpression.evaluate(e,t,n,r,i,a)}interpolationFactor(e,t,n){return this.interpolationType?Nt.interpolationFactor(this.interpolationType,e,t,n):0}};function _i(e){return e._styleExpression!==void 0}function vi(e,t,n,r){let i=mi(e,t,n,r);if(i.result===`error`)return i;let a=i.value.expression,o=Ur(a);if(!o&&!Kr(n))return li([new Mr(``,`data expressions not supported`)]);let s=Gr(a,[`zoom`]);if(!s&&!qr(n))return li([new Mr(``,`zoom expressions not supported`)]);let c=xi(a);if(!c&&!s)return li([new Mr(``,`"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.`)]);if(c instanceof Mr)return li([c]);if(c instanceof Nt&&!Jr(n))return li([new Mr(``,`"interpolate" expressions cannot be used with this property`)]);if(!c)return ci(o?new hi(`constant`,i.value,r):new hi(`source`,i.value,r));let l=c instanceof Nt?c.interpolation:void 0;return ci(o?new gi(`camera`,i.value,c.labels,l,r):new gi(`composite`,i.value,c.labels,l,r))}var yi=class e{constructor(e,t,n){this.isStateDependent=!1,this.globalStateRefs=/* @__PURE__ */ new Set,this._globalState=null,fi(t),this._parameters=e,this._specification=n,this._rootKey=t,this._defaultValue=wi(n),this._warningHistory={};let r=ti(this._parameters,this._specification);this.kind=r.kind,this.interpolationFactor=r.interpolationFactor,this.zoomStops=r.zoomStops,this.interpolationType=r.interpolationType,this._innerEvaluate=r.evaluate}evaluate(e,t){try{return this._innerEvaluate(e,t)}catch(e){let t=e instanceof Error?e.message:String(e),n=`|${t}`;return this._warningHistory[n]||(this._warningHistory[n]=!0,typeof console<`u`&&console.warn(di(this._rootKey,``,t,this._defaultValue))),this._defaultValue}}static deserialize(t){return new e(t._parameters,t._rootKey,t._specification)}static serialize(e){return{_parameters:e._parameters,_specification:e._specification,_rootKey:e._rootKey}}};function bi(e,t,n,r){if(Zr(e))return new yi(e,t,n);if(pi(e)){let i=vi(e,t,n,r);if(i.result===`error`)throw Error(i.value.map(e=>`${e.key}: ${e.message}`).join(`, `));return i.value}{let t=e;return n.type===`color`&&typeof e==`string`?t=V.parse(e):n.type===`padding`&&(typeof e==`number`||Array.isArray(e))?t=gt.parse(e):n.type===`numberArray`&&(typeof e==`number`||Array.isArray(e))?t=_t.parse(e):n.type===`colorArray`&&(typeof e==`string`||Array.isArray(e))?t=vt.parse(e):n.type===`variableAnchorOffsetCollection`&&Array.isArray(e)?t=bt.parse(e):n.type===`projectionDefinition`&&typeof e==`string`&&(t=St.parse(e)),{globalStateRefs:/* @__PURE__ */ new Set,_globalState:null,kind:`constant`,evaluate:()=>t}}}function xi(e){let t=null;if(e instanceof qt)t=xi(e.result);else if(e instanceof tn){for(let n of e.args)if(t=xi(n),t)break}else(e instanceof jt||e instanceof Nt)&&e.input instanceof Fr&&e.input.name===`zoom`&&(t=e);return t instanceof Mr||e.eachChild(e=>{let n=xi(e);n instanceof Mr?t=n:!t&&n?t=new Mr(``,`"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.`):t&&n&&t!==n&&(t=new Mr(``,`Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.`))}),t}function Si(e,t=/* @__PURE__ */ new Set){return e instanceof Ar&&t.add(e.key),e.eachChild(e=>{Si(e,t)}),t}function Ci(e){let t={color:Ce,string:I,number:F,enum:I,boolean:L,formatted:Oe,padding:ke,numberArray:je,colorArray:Ae,projectionDefinition:we,resolvedImage:Me,variableAnchorOffsetCollection:Ne};return e.type===`array`?Pe(t[e.value]||R,e.length):t[e.type]}function wi(e){if(e.type===`color`&&Zr(e.default))return new V(0,0,0,0);switch(e.type){case`color`:return V.parse(e.default)||null;case`padding`:return gt.parse(e.default)||null;case`numberArray`:return _t.parse(e.default)||null;case`colorArray`:return vt.parse(e.default)||null;case`variableAnchorOffsetCollection`:return bt.parse(e.default)||null;case`projectionDefinition`:return St.parse(e.default)||null;default:return e.default===void 0?null:e.default}}function Ti(e,t){let{zoom:n,heatmapDensity:r,elevation:i,lineProgress:a,isSupportedScript:o,accumulated:s}=e??{};return{zoom:n,heatmapDensity:r,elevation:i,lineProgress:a,isSupportedScript:o,accumulated:s,globalState:t}}function Ei(e){let t=!1;for(let n of e){let e=Di(n);if(e===`expression`)return`expression`;e===`legacy`&&(t=!0)}return t?`legacy`:`neutral`}function Di(e){if(typeof e==`boolean`)return`neutral`;if(!Array.isArray(e)||e.length===0)return`legacy`;switch(e[0]){case`has`:return e.length<2||e[1]===`$id`||e[1]===`$type`?`legacy`:e.length===2?`neutral`:`expression`;case`in`:return e.length>=3&&(typeof e[1]!=`string`||Array.isArray(e[2]))?`expression`:`legacy`;case`!in`:case`!has`:return`legacy`;case`==`:case`!=`:case`>`:case`>=`:case`<`:case`<=`:return e.length!==3||Array.isArray(e[1])||Array.isArray(e[2])?`expression`:`legacy`;case`none`:return`legacy`;case`any`:case`all`:return Ei(e.slice(1));default:return`expression`}}function Oi(e){return Di(e)!==`legacy`}function ki(e){return e===`$type`?[`geometry-type`]:e===`$id`?[`id`]:[`get`,e]}function Ai(e){switch(e[0]){case`==`:case`!=`:case`<`:case`<=`:case`>`:case`>=`:return e.length!==3||typeof e[1]!=`string`?null:[e[0],ki(e[1]),e[2]];case`in`:case`!in`:{if(e.length<2||typeof e[1]!=`string`)return null;let t=[`in`,ki(e[1]),[`literal`,e.slice(2)]];return e[0]===`!in`?[`!`,t]:t}case`has`:case`!has`:{if(e.length!==2||typeof e[1]!=`string`||e[1]===`$type`||e[1]===`$id`)return null;let t=[`has`,e[1]];return e[0]===`!has`?[`!`,t]:t}default:return null}}function ji(e){if((e[0]===`<`||e[0]===`<=`||e[0]===`>`||e[0]===`>=`)&&e[1]===`$type`)return`"$type" cannot be use with operator "${e[0]}"`;let t=Ai(e);return t?`Mixing deprecated filter syntax with expression syntax is not supported. Replace ${JSON.stringify(e)} with ${JSON.stringify(t)}.`:`Mixing deprecated filter syntax with expression syntax is not supported. Convert ${JSON.stringify(e)} to expression syntax.`}function Mi(e,t,n){let r=n[e];return Array.isArray(r)?Oi(r)?Ni(r,t.concat(e)):{path:t.concat(e),legacyFilter:r}:null}function Ni(e,t=[]){if(!Array.isArray(e)||e.length<1)return null;switch(e[0]){case`all`:case`any`:case`none`:for(let n=1;n`u`)return;let r=n.path.map(e=>`[${e}]`).join(``);console.warn(`${t}${r}: ${ji(n.legacyFilter)}`)}const Fi={type:`boolean`,default:!1,transition:!1,"property-type":`data-driven`,expression:{interpolated:!1,parameters:[`zoom`,`feature`]}};function Ii(e,t,n){if(e==null)return{filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>/* @__PURE__ */ new Set};Oi(e)?Pi(e,t):e=zi(e);let r=mi(e,t,Fi,n);if(r.result===`error`)throw Error(r.value.map(e=>`${e.key}: ${e.message}`).join(`, `));return{filter:(e,t,n)=>r.value.evaluate(e,t,{},n),needGeometry:Ri(e),getGlobalStateRefs:()=>Si(r.value.expression)}}function Li(e,t){return et)}function Ri(e){if(!Array.isArray(e))return!1;if(e[0]===`within`||e[0]===`distance`)return!0;for(let t=1;t`||t===`<=`||t===`>=`?Bi(e[1],e[2],t):t===`any`?Vi(e.slice(1)):t===`all`?[`all`].concat(e.slice(1).map(zi)):t===`none`?[`all`].concat(e.slice(1).map(zi).map(Wi)):t===`in`?Hi(e[1],e.slice(2)):t===`!in`?Wi(Hi(e[1],e.slice(2))):t===`has`?Ui(e[1]):t!==`!has`||Wi(Ui(e[1]))}function Bi(e,t,n){switch(e){case`$type`:return[`filter-type-${n}`,t];case`$id`:return[`filter-id-${n}`,t];default:return[`filter-${n}`,e,t]}}function Vi(e){return[`any`].concat(e.map(zi))}function Hi(e,t){if(t.length===0)return!1;switch(e){case`$type`:return[`filter-type-in`,[`literal`,t]];case`$id`:return[`filter-id-in`,[`literal`,t]];default:return t.length>200&&!t.some(e=>typeof e!=typeof t[0])?[`filter-in-large`,e,[`literal`,t.sort(Li)]]:[`filter-in-small`,e,[`literal`,t]]}}function Ui(e){switch(e){case`$type`:return!0;case`$id`:return[`filter-has-id`];default:return[`filter-has`,e]}}function Wi(e){return[`!`,e]}function Gi(e){let t=typeof e;if(t===`number`||t===`boolean`||t===`string`||e==null)return JSON.stringify(e);if(Array.isArray(e)){let t=`[`;for(let n of e)t+=`${Gi(n)},`;return`${t}]`}let n=Object.keys(e).sort(),r=`{`;for(let t=0;tr.maximum?[new P(t,n,`${n} is greater than the maximum value ${r.maximum}`)]:[]:[new P(t,n,`number expected, ${i} found`)]}function ea(e){let t=e.valueSpec,n=Yi(e.value.type),r,i={},a,o,s=n!==`categorical`&&e.value.property===void 0,c=!s,l=W(e.value.stops)===`array`&&W(e.value.stops[0])===`array`&&W(e.value.stops[0][0])===`object`,u=Zi({key:e.key,value:e.value,valueSpec:e.styleSpec.function,validateSpec:e.validateSpec,style:e.style,styleSpec:e.styleSpec,objectElementValidators:{stops:d,default:m}});return n===`identity`&&s&&u.push(new P(e.key,e.value,`missing required property "property"`)),n!==`identity`&&!e.value.stops&&u.push(new P(e.key,e.value,`missing required property "stops"`)),n===`exponential`&&e.valueSpec.expression&&!Jr(e.valueSpec)&&u.push(new P(e.key,e.value,`exponential functions not supported`)),e.styleSpec.$version>=8&&(c&&!Kr(e.valueSpec)?u.push(new P(e.key,e.value,`property functions not supported`)):s&&!qr(e.valueSpec)&&u.push(new P(e.key,e.value,`zoom functions not supported`))),(n===`categorical`||l)&&e.value.property===void 0&&u.push(new P(e.key,e.value,`"property" property is required`)),u;function d(e){if(n===`identity`)return[new P(e.key,e.value,`identity function may not have a "stops" property`)];let t=[],r=e.value;return t=t.concat(Qi({key:e.key,value:r,valueSpec:e.valueSpec,validateSpec:e.validateSpec,style:e.style,styleSpec:e.styleSpec,arrayElementValidator:f})),W(r)===`array`&&r.length===0&&t.push(new P(e.key,r,`array must have at least one stop`)),t}function f(e){let n=[],r=e.value,s=e.key;if(W(r)!==`array`)return[new P(s,r,`array expected, ${W(r)} found`)];if(r.length!==2)return[new P(s,r,`array length 2 expected, length ${r.length} found`)];if(l){if(W(r[0])!==`object`)return[new P(s,r,`object expected, ${W(r[0])} found`)];if(r[0].zoom===void 0)return[new P(s,r,`object stop key must have zoom`)];if(r[0].value===void 0)return[new P(s,r,`object stop key must have value`)];if(o&&o>Yi(r[0].zoom))return[new P(s,r[0].zoom,`stop zoom values must appear in ascending order`)];Yi(r[0].zoom)!==o&&(o=Yi(r[0].zoom),a=void 0,i={}),n=n.concat(Zi({key:`${s}[0]`,value:r[0],valueSpec:{zoom:{}},validateSpec:e.validateSpec,style:e.style,styleSpec:e.styleSpec,objectElementValidators:{zoom:$i,value:p}}))}else n=n.concat(p({key:`${s}[0]`,value:r[0],valueSpec:{},validateSpec:e.validateSpec,style:e.style,styleSpec:e.styleSpec},r));return pi(Xi(r[1]))?n.concat([new P(`${s}[1]`,r[1],`expressions are not allowed in function stops.`)]):n.concat(e.validateSpec({key:`${s}[1]`,value:r[1],valueSpec:t,validateSpec:e.validateSpec,style:e.style,styleSpec:e.styleSpec}))}function p(e,o){let s=W(e.value),c=Yi(e.value),l=e.value===null?o:e.value;if(!r)r=s;else if(s!==r)return[new P(e.key,l,`${s} stop domain type must match previous stop domain type ${r}`)];if(s!==`number`&&s!==`string`&&s!==`boolean`)return[new P(e.key,l,`stop domain value must be a number, string, or boolean`)];if(s!==`number`&&n!==`categorical`){let r=`number expected, ${s} found`;return Kr(t)&&n===void 0&&(r+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new P(e.key,l,r)]}return n===`categorical`&&s===`number`&&(!isFinite(c)||Math.floor(c)!==c)?[new P(e.key,l,`integer expected, found ${c}`)]:n!==`categorical`&&s===`number`&&a!==void 0&&cnew P(`${e.key}${t.key}`,e.value,t.message));let n=t.value.expression||t.value._styleExpression.expression;if(e.expressionContext===`property`&&e.propertyKey===`text-font`&&!n.outputDefined())return[new P(e.key,e.value,`Invalid data expression for "${e.propertyKey}". Output values must be contained as literals within the expression.`)];if(e.expressionContext===`property`&&e.propertyType===`layout`&&!Wr(n))return[new P(e.key,e.value,`"feature-state" data expressions are not supported with layout properties.`)];if(e.expressionContext===`filter`&&!Wr(n))return[new P(e.key,e.value,`"feature-state" data expressions are not supported with filters.`)];if(e.expressionContext&&e.expressionContext.indexOf(`cluster`)===0){if(!Gr(n,[`zoom`,`feature-state`]))return[new P(e.key,e.value,`"zoom" and "feature-state" expressions are not supported with cluster properties.`)];if(e.expressionContext===`cluster-initial`&&!Ur(n))return[new P(e.key,e.value,`Feature data expressions are not supported with initial expression part of cluster properties.`)]}return[]}function na(e){let t=e.value,n=e.key,r=W(t);return r===`boolean`?[]:[new P(n,t,`boolean expected, ${r} found`)]}function ra(e){let t=e.key,n=e.value,r=W(n);return r===`string`?V.parse(String(n))?[]:[new P(t,n,`color expected, "${n}" found`)]:[new P(t,n,`color expected, ${r} found`)]}function ia(e){let t=e.key,n=e.value,r=e.valueSpec,i=[];return Array.isArray(r.values)?r.values.indexOf(Yi(n))===-1&&i.push(new P(t,n,`expected one of [${r.values.join(`, `)}], ${JSON.stringify(n)} found`)):Object.keys(r.values).indexOf(Yi(n))===-1&&i.push(new P(t,n,`expected one of [${Object.keys(r.values).join(`, `)}], ${JSON.stringify(n)} found`)),i}function aa(e,t){let n=e;for(let e of t)n=n[e];return n}function oa(e,t){let n=Ni(t);return n?[new P(`${e.key}${n.path.map(e=>`[${e}]`).join(``)}`,aa(e.value,n.path),ji(n.legacyFilter),null,`warning`)]:[]}function sa(e){let t=Xi(e.value);return Oi(t)?[...oa(e,t),...ta(Xr({},e,{expressionContext:`filter`,valueSpec:{value:`boolean`}}))]:ca(e)}function ca(e){let t=e.value,n=e.key;if(W(t)!==`array`)return[new P(n,t,`array expected, ${W(t)} found`)];let r=e.styleSpec,i,a=[];if(t.length<1)return[new P(n,t,`filter array must have at least 1 element`)];switch(a=a.concat(ia({key:`${n}[0]`,value:t[0],valueSpec:r.filter_operator,style:e.style,styleSpec:e.styleSpec})),Yi(t[0])){case`<`:case`<=`:case`>`:case`>=`:t.length>=2&&Yi(t[1])===`$type`&&a.push(new P(n,t,`"$type" cannot be use with operator "${t[0]}"`));case`==`:case`!=`:t.length!==3&&a.push(new P(n,t,`filter array for operator "${t[0]}" must have 3 elements`));case`in`:case`!in`:t.length>=2&&(i=W(t[1]),i!==`string`&&a.push(new P(`${n}[1]`,t[1],`string expected, ${i} found`)));for(let o=2;o{e in n&&t.push(new P(r,n[e],`"${e}" is prohibited for ref layers`))});let e;i.layers.forEach(t=>{Yi(t.id)===s&&(e=t)}),e?e.ref?t.push(new P(r,n.ref,`ref cannot reference another ref layer`)):o=Yi(e.type):t.push(new P(r,n.ref,`ref layer "${s}" not found`))}else if(o!==`background`){if(!n.source)t.push(new P(r,n,`missing required property "source"`));else{let e=i.sources&&i.sources[n.source],a=e&&Yi(e.type);e?a===`vector`&&o===`raster`?t.push(new P(r,n.source,`layer "${n.id}" requires a raster source`)):a!==`raster-dem`&&o===`hillshade`||a!==`raster-dem`&&o===`color-relief`?t.push(new P(r,n.source,`layer "${n.id}" requires a raster-dem source`)):a===`raster`&&o!==`raster`?t.push(new P(r,n.source,`layer "${n.id}" requires a vector source`)):a===`vector`&&!n[`source-layer`]?t.push(new P(r,n,`layer "${n.id}" must specify a "source-layer"`)):a===`raster-dem`&&o!==`hillshade`&&o!==`color-relief`?t.push(new P(r,n.source,`raster-dem source can only be used with layer type 'hillshade' or 'color-relief'.`)):o===`line`&&n.paint&&n.paint[`line-gradient`]&&(a!==`geojson`||!e.lineMetrics)&&t.push(new P(r,n,`layer "${n.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):t.push(new P(r,n.source,`source "${n.source}" not found`))}}return o===`raster`&&n.paint?.resampling&&n.paint?.[`raster-resampling`]&&t.push(new P(r,n.paint,`layer "${n.id}" redundantly specifies "resampling" and "raster-resampling" paint properties, but only one is allowed. It is advised to use "resampling".`)),t=t.concat(Zi({key:r,value:n,valueSpec:a.layer,style:e.style,styleSpec:e.styleSpec,validateSpec:e.validateSpec,objectElementValidators:{"*"(){return[]},type(){return e.validateSpec({key:`${r}.type`,value:n.type,valueSpec:a.layer.type,style:e.style,styleSpec:e.styleSpec,validateSpec:e.validateSpec,object:n,objectKey:`type`})},filter:sa,layout(e){return Zi({layer:n,key:e.key,value:e.value,style:e.style,styleSpec:e.styleSpec,validateSpec:e.validateSpec,objectElementValidators:{"*"(e){return da(Xr({layerType:o},e))}}})},paint(e){return Zi({layer:n,key:e.key,value:e.value,style:e.style,styleSpec:e.styleSpec,validateSpec:e.validateSpec,objectElementValidators:{"*"(e){return ua(Xr({layerType:o},e))}}})}}})),t}function pa(e){let t=e.value,n=e.key,r=W(t);return r===`string`?[]:[new P(n,t,`string expected, ${r} found`)]}function ma(e){let t=e.sourceName??``,n=e.value,r=e.styleSpec,i=r.source_raster_dem,a=e.style,o=[],s=W(n);if(n===void 0)return o;if(s!==`object`)return o.push(new P(`source_raster_dem`,n,`object expected, ${s} found`)),o;let c=Yi(n.encoding)===`custom`,l=[`redFactor`,`greenFactor`,`blueFactor`,`baseShift`],u=e.value.encoding?`"${e.value.encoding}"`:`Default`;for(let s in n)!c&&l.includes(s)?o.push(new P(s,n[s],`In "${t}": "${s}" is only valid when "encoding" is set to "custom". ${u} encoding found`)):i[s]?o=o.concat(e.validateSpec({key:s,value:n[s],valueSpec:i[s],validateSpec:e.validateSpec,style:a,styleSpec:r})):o.push(new P(s,n[s],`unknown property "${s}"`));return o}const ha={promoteId:_a};function ga(e){let t=e.value,n=e.key,r=e.styleSpec,i=e.style,a=e.validateSpec;if(!t.type)return[new P(n,t,`"type" is required`)];let o=Yi(t.type),s;switch(o){case`vector`:case`raster`:return s=Zi({key:n,value:t,valueSpec:r[`source_${o.replace(`-`,`_`)}`],style:e.style,styleSpec:r,objectElementValidators:ha,validateSpec:a}),s;case`raster-dem`:return s=ma({sourceName:n,value:t,style:e.style,styleSpec:r,validateSpec:a}),s;case`geojson`:if(s=Zi({key:n,value:t,valueSpec:r.source_geojson,style:i,styleSpec:r,validateSpec:a,objectElementValidators:ha}),t.cluster)for(let e in t.clusterProperties){let[r,i]=t.clusterProperties[e],o=typeof r==`string`?[r,[`accumulated`],[`get`,e]]:r;s.push(...ta({key:`${n}.${e}.map`,value:i,validateSpec:a,expressionContext:`cluster-map`})),s.push(...ta({key:`${n}.${e}.reduce`,value:o,validateSpec:a,expressionContext:`cluster-reduce`}))}return s;case`video`:return Zi({key:n,value:t,valueSpec:r.source_video,style:i,validateSpec:a,styleSpec:r});case`image`:return Zi({key:n,value:t,valueSpec:r.source_image,style:i,validateSpec:a,styleSpec:r});case`canvas`:return[new P(n,null,`Please use runtime APIs to add canvas sources, rather than including them in stylesheets.`,`source.canvas`)];default:return ia({key:`${n}.type`,value:t.type,valueSpec:{values:[`vector`,`raster`,`raster-dem`,`geojson`,`video`,`image`]},style:i,validateSpec:a,styleSpec:r})}}function _a({key:e,value:t}){if(W(t)===`string`)return pa({key:e,value:t});{let n=[];for(let r in t)n.push(...pa({key:`${e}.${r}`,value:t[r]}));return n}}function va(e){let t=e.value,n=e.styleSpec,r=n.light,i=e.style,a=[],o=W(t);if(t===void 0)return a;if(o!==`object`)return a=a.concat([new P(`light`,t,`object expected, ${o} found`)]),a;for(let o in t){let s=o.match(Yr);a=s&&r[s[1]]&&r[s[1]].transition?a.concat(e.validateSpec({key:o,value:t[o],valueSpec:n.transition,validateSpec:e.validateSpec,style:i,styleSpec:n})):r[o]?a.concat(e.validateSpec({key:o,value:t[o],valueSpec:r[o],validateSpec:e.validateSpec,style:i,styleSpec:n})):a.concat([new P(o,t[o],`unknown property "${o}"`)])}return a}function ya(e){let t=e.value,n=e.styleSpec,r=n.sky,i=e.style,a=W(t);if(t===void 0)return[];if(a!==`object`)return[new P(`sky`,t,`object expected, ${a} found`)];let o=[];for(let a in t){let s=a.match(Yr);o=s&&r[s[1]]&&r[s[1]].transition?o.concat(e.validateSpec({key:a,value:t[a],valueSpec:n.transition,style:i,styleSpec:n})):r[a]?o.concat(e.validateSpec({key:a,value:t[a],valueSpec:r[a],style:i,styleSpec:n})):o.concat([new P(a,t[a],`unknown property "${a}"`)])}return o}function ba(e){let t=e.value,n=e.styleSpec,r=n.terrain,i=e.style,a=[],o=W(t);if(t===void 0)return a;if(o!==`object`)return a=a.concat([new P(`terrain`,t,`object expected, ${o} found`)]),a;for(let o in t)a=r[o]?a.concat(e.validateSpec({key:o,value:t[o],valueSpec:r[o],validateSpec:e.validateSpec,style:i,styleSpec:n})):a.concat([new P(o,t[o],`unknown property "${o}"`)]);return a}function xa(e){return pa(e).length===0?[]:ta(e)}function Sa(e){return pa(e).length===0?[]:ta(e)}function Ca(e){let t=e.key,n=e.value;if(W(n)===`array`){if(n.length<1||n.length>4)return[new P(t,n,`padding requires 1 to 4 values; ${n.length} values found`)];let r={type:`number`},i=[];for(let a=0;a[new P(e,t,`invalid unicode range, expected a value such as "U+26", "U+0-10FFFF" or "U+4??"`)],i=n.match(Fa);if(!i)return r();let[,a,o,s]=i;if(s!==void 0)return s.length>6?r():[];let c=parseInt(a,16),l=o===void 0?c:parseInt(o,16);return c>Pa||l>Pa?[new P(e,t,`unicode range is out of bounds, the maximum code point is U+10FFFF`)]:c>l?[new P(e,t,`unicode range start must not be greater than its end, but ${n} is`)]:[]}function La(e){let t=e.key??`font-faces`,n=e.value,r=e.validateSpec,i=e.styleSpec??be,a=e.style;if(!Ma(n))return[new P(t,n,`object expected, ${W(n)} found`)];let o=[];for(let e in n){let s=n[e],c=W(s);if(c===`string`)o.push(...pa({key:`${t}.${e}`,value:s}));else if(c===`array`){let n={url:{type:`string`,required:!0},"unicode-range":{type:`array`,value:`string`}};for(let[c,l]of s.entries()){let s=`${t}.${e}[${c}]`;o.push(...Zi({key:s,value:l,valueSpec:n,styleSpec:i,style:a,validateSpec:r}));let u=Ma(l)?l[`unicode-range`]:void 0;if(W(u)===`array`)for(let[e,t]of u.entries())o.push(...Ia(`${s}.unicode-range[${e}]`,t))}}else o.push(new P(`${t}.${e}`,s,`string or array expected, ${c} found`))}return o}const Ra={"*"(){return[]},array:Qi,boolean:na,number:$i,color:ra,constants:Ji,enum:ia,filter:sa,function:ea,layer:fa,object:Zi,source:ga,light:va,sky:ya,terrain:ba,projection:Oa,projectionDefinition:ka,string:pa,formatted:xa,resolvedImage:Sa,padding:Ca,numberArray:wa,colorArray:Ta,variableAnchorOffsetCollection:Ea,sprite:Da,state:Na,fontFaces:La};function za(e){let t=e.value,n=e.valueSpec,r=e.styleSpec;return e.validateSpec=za,n.expression&&Zr(Yi(t))?ea(e):n.expression&&pi(Xi(t))?ta(e):n.type&&Ra[n.type]?Ra[n.type](e):Zi(Xr({},e,{valueSpec:n.type?r[n.type]:n}))}function Ba(e){let t=e.value,n=e.key,r=pa(e);return r.length||(t.indexOf(`{fontstack}`)===-1&&r.push(new P(n,t,`"glyphs" url must include a "{fontstack}" token`)),t.indexOf(`{range}`)===-1&&r.push(new P(n,t,`"glyphs" url must include a "{range}" token`))),r}function Va(e,t=N){let n=[];return n=n.concat(za({key:``,value:e,valueSpec:t.$root,styleSpec:t,style:e,validateSpec:za,objectElementValidators:{glyphs:Ba,"*"(){return[]}}})),e.constants&&(n=n.concat(Ji({key:`constants`,value:e.constants,style:e,styleSpec:t,validateSpec:za}))),Ua(n)}Va.source=Wa(Ha(ga)),Va.sprite=Wa(Ha(Da)),Va.glyphs=Wa(Ha(Ba)),Va.fontFaces=Wa(Ha(La)),Va.light=Wa(Ha(va)),Va.sky=Wa(Ha(ya)),Va.terrain=Wa(Ha(ba)),Va.state=Wa(Ha(Na)),Va.layer=Wa(Ha(fa)),Va.filter=Wa(Ha(sa)),Va.paintProperty=Wa(Ha(ua)),Va.layoutProperty=Wa(Ha(da));function Ha(e){return function(t){return e(Object.assign({},t,{validateSpec:za}))}}function Ua(e){return[].concat(e).sort((e,t)=>e.line-t.line)}function Wa(e){return function(...t){return Ua(e.apply(this,t))}}const Ga={type:`enum`,"property-type":`data-constant`,expression:{interpolated:!1,parameters:[`global-state`]},values:{visible:{},none:{}},transition:!1,default:`visible`};var Ka=class{constructor(e,t,n){this._rootKey=t,this._globalState=n,this.setValue(e)}evaluate(){return this._literalValue??this._compiledValue.evaluate({})}setValue(e){if(e==null||e===`visible`||e===`none`){this._literalValue=e===`none`?`none`:`visible`,this._compiledValue=void 0,this._globalStateRefs=/* @__PURE__ */ new Set;return}let t=mi(e,this._rootKey,Ga,this._globalState);if(t.result===`error`)throw this._literalValue=`visible`,this._compiledValue=void 0,Error(t.value.map(e=>`${e.key}: ${e.message}`).join(`, `));this._literalValue=void 0,this._compiledValue=t.value,this._globalStateRefs=Si(t.value.expression)}getGlobalStateRefs(){return this._globalStateRefs}};function qa(e,t,n){return new Ka(e,t,n)}const Ja={MAX_PARALLEL_IMAGE_REQUESTS:16,MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:8,MAX_TILE_CACHE_ZOOM_LEVELS:5,REGISTERED_PROTOCOLS:{},WORKER_URL:``};function Ya(e){return Ja.REGISTERED_PROTOCOLS[e.substring(0,e.indexOf(`://`))]}function Xa(e,t){Ja.REGISTERED_PROTOCOLS[e]=t}function Za(e){delete Ja.REGISTERED_PROTOCOLS[e]}const Qa=`global-dispatcher`;var $a=class extends Error{constructor(e,t,n,r){super(`AJAXError: ${t} (${e}): ${n}`),this.status=e,this.statusText=t,this.url=n,this.body=r}};function eo(){if(te(self))return self.worker?.referrer;if(window.location.protocol===`blob:`)try{return window.parent.location.href}catch{}return window.location.href}const to=e=>e.startsWith(`file:`)||eo()?.startsWith(`file:`)&&!/^\w+:/.test(e);async function no(e,t){let n=new Request(e.url,{method:e.method||`GET`,body:e.body,credentials:e.credentials,headers:e.headers,cache:e.cache,referrer:eo(),referrerPolicy:e.referrerPolicy,signal:t.signal});e.type===`json`&&!n.headers.has(`Accept`)&&n.headers.set(`Accept`,`application/json`);let r;try{r=await fetch(n)}catch(t){throw _e(t)?t:new $a(0,y(t).message,e.url,new Blob)}if(!r.ok){let t=await r.blob();throw new $a(r.status,r.statusText,e.url,t)}let i;i=e.type===`arrayBuffer`||e.type===`image`?r.arrayBuffer():e.type===`json`?r.json():r.text();let a=await i;return ve(t.signal),{data:a,cacheControl:r.headers.get(`Cache-Control`),expires:r.headers.get(`Expires`),etag:r.headers.get(`ETag`)}}function ro(e,t){return new Promise((n,r)=>{let i=new XMLHttpRequest;i.open(e.method||`GET`,e.url,!0),(e.type===`arrayBuffer`||e.type===`image`)&&(i.responseType=`arraybuffer`);for(let t in e.headers)i.setRequestHeader(t,e.headers[t]);e.type===`json`&&(i.responseType=`text`,e.headers?.Accept||i.setRequestHeader(`Accept`,`application/json`)),i.withCredentials=e.credentials===`include`,i.onerror=()=>{r(Error(i.statusText))},i.onload=()=>{if(!t.signal.aborted){if((i.status>=200&&i.status<300||i.status===0)&&i.response!==null){let t=i.response;if(e.type===`json`)try{t=JSON.parse(i.response)}catch(e){r(e);return}n({data:t,cacheControl:i.getResponseHeader(`Cache-Control`),expires:i.getResponseHeader(`Expires`),etag:i.getResponseHeader(`ETag`)})}else{let t=new Blob([i.response],{type:i.getResponseHeader(`Content-Type`)});r(new $a(i.status,i.statusText,e.url,t))}}},t.signal.addEventListener(`abort`,()=>{i.abort(),r(new ge(t.signal.reason))}),i.send(e.body)})}const io=async function(e,t){if(e.url.includes(`://`)&&!/^https?:|^file:/.test(e.url)){let n=Ya(e.url);if(n){let r=await n(e,t);return!r.data&&e.type===`arrayBuffer`?w(r,{data:/* @__PURE__ */ new ArrayBuffer(0)}):r}if(te(self)&&self.worker?.actor)return self.worker.actor.sendAsync({type:`GR`,data:e,targetMapId:Qa},t)}if(!to(e.url)){if(fetch&&Request&&AbortController&&Object.hasOwn(Request.prototype,`signal`))return no(e,t);if(te(self)&&self.worker?.actor)return self.worker.actor.sendAsync({type:`GR`,data:e,mustQueue:!0,targetMapId:Qa},t)}return ro(e,t)},ao=(e,t)=>io(w(e,{type:`json`}),t),oo=(e,t)=>io(w(e,{type:`arrayBuffer`}),t),so={};function G(e,t,n={}){if(so[e])throw Error(`${e} is already registered.`);Object.defineProperty(t,"_classRegistryKey",{value:e,writeable:!1}),so[e]={klass:t,omit:n.omit||[],shallow:n.shallow||[]}}G(`Object`,Object),G(`Set`,Set),G(`TransferableGridIndex`,ye),G(`Color`,V),G(`Error`,Error),G(`AJAXError`,$a),G(`ResolvedImage`,xt),G(`StylePropertyFunction`,yi),G(`StyleExpression`,ui,{omit:[`_evaluator`]}),G(`ZoomDependentExpression`,gi),G(`ZoomConstantExpression`,hi),G(`CompoundExpression`,Fr,{omit:[`_evaluate`]});for(let e in jr)jr[e]._classRegistryKey||G(`Expression_${e}`,jr[e]);function co(e){return e&&typeof ArrayBuffer<`u`&&(e instanceof ArrayBuffer||e.constructor?.name===`ArrayBuffer`)}function lo(e){let t=e.constructor;return e.$name||t._classRegistryKey}function uo(e){if(typeof e!=`object`||!e)return!1;let t=lo(e);return t&&t!==`Object`}function fo(e){return!uo(e)&&(e==null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`||e instanceof Boolean||e instanceof Number||e instanceof String||e instanceof Date||e instanceof RegExp||e instanceof Blob||e instanceof Error||co(e)||ne(e)||ArrayBuffer.isView(e)||e instanceof ImageData)}function po(e,t){if(fo(e))return(co(e)||ne(e))&&t&&t.push(e),ArrayBuffer.isView(e)&&t&&t.push(e.buffer),e instanceof ImageData&&t&&t.push(e.data.buffer),e;if(Array.isArray(e)){let n=[];for(let r of e)n.push(po(r,t));return n}if(typeof e!=`object`)throw Error(`can't serialize object of type ${typeof e}`);let n=lo(e);if(!n)throw Error(`can't serialize object of unregistered class ${e.constructor.name}`);if(!so[n])throw Error(`${n} is not registered.`);let{klass:r}=so[n],i=r.serialize?r.serialize(e,t):{};if(!r.serialize){for(let r in e){if(!e.hasOwnProperty(r)||so[n].omit.includes(r))continue;let a=e[r];a!==void 0&&(i[r]=so[n].shallow.includes(r)?a:po(a,t))}e instanceof Error&&(i.message=e.message)}else if(i===t?.[t.length-1])throw Error(`statically serialized object won't survive transfer of $name property`);if(i.$name)throw Error(`$name property is reserved for worker serialization logic.`);return n!==`Object`&&(i.$name=n),i}function mo(e){if(fo(e))return e;if(Array.isArray(e))return e.map(mo);if(typeof e!=`object`)throw Error(`can't deserialize object of type ${typeof e}`);let t=lo(e)||`Object`;if(!so[t])throw Error(`can't deserialize unregistered class ${t}`);let{klass:n}=so[t];if(!n)throw Error(`can't deserialize unregistered class ${t}`);if(n.deserialize)return n.deserialize(e);let r=Object.create(n.prototype);for(let n of Object.keys(e)){if(n===`$name`)continue;let i=e[n];r[n]=so[t].shallow.includes(n)?i:mo(i)}return r}var ho=class{constructor(e){this._methodToThrottle=e,this._triggered=!1,this._channel=new MessageChannel,this._channel.port2.onmessage=()=>this._invoke()}trigger(){this._triggered||(this._triggered=!0,this._channel?.port1.postMessage(!0),setTimeout(()=>this._invoke(),0))}_invoke(){this._triggered&&(this._triggered=!1,this._methodToThrottle())}remove(){delete this._channel,this._methodToThrottle=()=>{}}};const go={once:!0};var _o=class{constructor(e,t){this.target=e,this.mapId=t,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new ho(()=>this.process()),this.subscription=le(this.target,`message`,e=>this.receive(e),!1),this.globalScope=te(self)?e:window}registerMessageHandler(e,t){this.messageHandlers[e]=t}unregisterMessageHandler(e){delete this.messageHandlers[e]}sendAsync(e,t){return new Promise((n,r)=>{let i=Math.round(Math.random()*0xde0b6b3a7640000).toString(36).substring(0,10),a=t?le(t.signal,`abort`,()=>{a?.unsubscribe(),delete this.resolveRejects[i];let n={id:i,type:``,origin:location.origin,targetMapId:e.targetMapId,sourceMapId:this.mapId};this.target.postMessage(n),r(new ge(t.signal.reason))},go):null;this.resolveRejects[i]={resolve:e=>{a?.unsubscribe(),n(e)},reject:e=>{a?.unsubscribe(),r(e)}};let o=[],s={...e,id:i,sourceMapId:this.mapId,origin:location.origin,data:po(e.data,o)};this.target.postMessage(s,{transfer:o})})}receive(e){let t=e.data,n=t.id,r=[`file://`,`resource://android`,`null`],i=[t.origin,location.origin],a=t.origin===location.origin,o=i.some(e=>r.includes(e));if((a||o)&&!(t.targetMapId&&this.mapId!==t.targetMapId)){if(t.type===``){delete this.tasks[n];let e=this.abortControllers[n];delete this.abortControllers[n],e&&e.abort()}else te(self)||t.mustQueue?(this.tasks[n]=t,this.taskQueue.push(n),this.invoker.trigger()):this.processTask(n,t)}}process(){if(this.taskQueue.length===0)return;let e=this.taskQueue.shift(),t=this.tasks[e];delete this.tasks[e],this.taskQueue.length>0&&this.invoker.trigger(),t&&this.processTask(e,t)}async processTask(e,t){if(t.type===``){let n=this.resolveRejects[e];if(delete this.resolveRejects[e],!n)return;t.error?n.reject(y(mo(t.error))):n.resolve(mo(t.data));return}if(!this.messageHandlers[t.type]){this.completeTask(e,null,null);return}let n=mo(t.data),r=new AbortController;this.abortControllers[e]=r;try{let i=await this.messageHandlers[t.type](t.sourceMapId,n,r);this.completeTask(e,null,i)}catch(t){this.completeTask(e,y(t))}}completeTask(e,t,n){let r=[];delete this.abortControllers[e];let i={id:e,type:``,sourceMapId:this.mapId,origin:location.origin,error:t?po(t):null,data:po(n,r)};this.target.postMessage(i,{transfer:r})}remove(){this.invoker.remove(),this.subscription.unsubscribe()}};const vo=Va;new Set(Object.keys(N).filter(e=>e.startsWith(`source_`)).map(e=>e.slice(7).replaceAll(`_`,`-`)));function yo(e,t){let n=!1;for(let r of t)r.severity===`warning`?j(r.message):(e.fire(new me(Error(r.message))),n=!0);return n}function bo(e,t,n,r){return r?.validate!==!1&&yo(e,t({styleSpec:N,...n}))}var xo=class{constructor(){this.first=!0}update(e,t){let n=Math.floor(e);return this.first?(this.first=!1,this.lastIntegerZoom=n,this.lastIntegerZoomTime=0,this.lastZoom=e,this.lastFloorZoom=n,!0):(this.lastFloorZoom>n?(this.lastIntegerZoom=n+1,this.lastIntegerZoomTime=t):this.lastFloorZoomthis.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:t+(1-t)*n}:{fromScale:.5,toScale:1,t:1-(1-n)*t}}},So=class{constructor(e,t,n,r){this.property=e,this.value=t,this.expression=bi(t===void 0?e.specification.default:t,n,e.specification,r)}isDataDriven(){return this.expression.kind===`source`||this.expression.kind===`composite`}getGlobalStateRefs(){return this.expression.globalStateRefs||/* @__PURE__ */ new Set}readsGlobalState(e){let t=this.getGlobalStateRefs();return e.some(e=>t.has(e))}possiblyEvaluate(e,t,n){return this.property.possiblyEvaluate(this,e,t,n)}},Co=class{constructor(e,t,n){this.property=e,this.value=new So(e,void 0,t,n)}transitioned(e,t){return t.value===this.value?t:new To(this.property,this.value,t,w({},e.transition,this.transition),e.now)}untransitioned(){return new To(this.property,this.value,null,{},0)}},wo=class{constructor(e,t,n){this._properties=e,this._values=Object.create(e.defaultTransitionablePropertyValues),this._globalState=n,this._rootKey=t}_propertyRootKey(e){return`${this._rootKey}.${String(e)}`}hasProperty(e){return e in this._properties.defaultTransitionablePropertyValues}getValue(e){return k(this._values[e].value.value)}setValue(e,t){Object.hasOwn(this._values,e)||(this._values[e]=new Co(this._values[e].property,this._propertyRootKey(e),this._globalState)),this._values[e].value=new So(this._values[e].property,t===null?void 0:k(t),this._propertyRootKey(e),this._globalState)}setValues(e){for(let t in e){let n=e[t];t.endsWith(`-transition`)?this.setTransition(t.slice(0,-11),n):O(this._values[t].value.value,n)||this.setValue(t,n)}}getTransition(e){return k(this._values[e].transition)}setTransition(e,t){Object.hasOwn(this._values,e)||(this._values[e]=new Co(this._values[e].property,this._propertyRootKey(e),this._globalState)),this._values[e].transition=k(t)||void 0}retainPriorGlobalState(e,t,n){for(let r of Object.keys(n._values))for(let i=n._values[r];i;i=i.prior){let{value:n}=i;n.property.specification.transition&&!n.isDataDriven()&&n.expression._globalState===this._globalState&&n.readsGlobalState(e)&&(i.value=new So(n.property,n.value,this._propertyRootKey(r),t))}}applyGlobalStateChange(e,t,n,r){this.retainPriorGlobalState(e,t,n);let i=!1;for(let t of Object.keys(this._values)){let{value:n}=this._values[t];n.readsGlobalState(e)&&(this.setValue(t,n.value),i=!0)}return i?this.transitioned(r,n):n}serialize(){let e={};for(let t of Object.keys(this._values)){let n=this.getValue(t);n!==void 0&&(e[t]=n);let r=this.getTransition(t);r!==void 0&&(e[`${t}-transition`]=r)}return e}transitioned(e,t){let n=new Eo(this._properties);for(let r of Object.keys(this._values))n._values[r]=this._values[r].transitioned(e,t._values[r]);return n}untransitioned(){let e=new Eo(this._properties);for(let t of Object.keys(this._values))e._values[t]=this._values[t].untransitioned();return e}},To=class{constructor(e,t,n,r,i){this.property=e,this.value=t,this.begin=i+r.delay||0,this.end=this.begin+r.duration||0,e.specification.transition&&(r.delay||r.duration)&&(this.prior=n)}possiblyEvaluate(e,t,n){let r=e.now||0,i=this.value.possiblyEvaluate(e,t,n),a=this.prior;if(!a)return i;if(r>this.end||this.value.isDataDriven())return this.prior=null,i;if(rr.zoomHistory.lastIntegerZoom?{from:e,to:t}:{from:n,to:t}}interpolate(e){return e}},No=class{constructor(e,t){this.specification=e,this.name=t}possiblyEvaluate(e,t,n,r){if(e.value!==void 0){if(e.expression.kind===`constant`){let i=e.expression.evaluate(t,null,{},n,r);return this._calculate(i,i,i,t)}return this._calculate(e.expression.evaluate(new K(Math.floor(t.zoom-1),t)),e.expression.evaluate(new K(Math.floor(t.zoom),t)),e.expression.evaluate(new K(Math.floor(t.zoom+1),t)),t)}}_calculate(e,t,n,r){return r.zoom>r.zoomHistory.lastIntegerZoom?{from:e,to:t}:{from:n,to:t}}interpolate(e){return e}},Po=class{constructor(e,t){this.specification=e,this.name=t}possiblyEvaluate(e,t,n,r){return!!e.expression.evaluate(t,null,{},n,r)}interpolate(){return!1}},Fo=class{constructor(e){this.properties=e,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(let t in e){let n=e[t];n.specification.overridable&&this.overridableProperties.push(t);let r=this.defaultPropertyValues[t]=new So(n,void 0,n.name,void 0),i=this.defaultTransitionablePropertyValues[t]=new Co(n,n.name,void 0);this.defaultTransitioningPropertyValues[t]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[t]=r.possiblyEvaluate({})}}};G(`DataDrivenProperty`,J),G(`DataConstantProperty`,q),G(`CrossFadedDataDrivenProperty`,Mo),G(`CrossFadedProperty`,No),G(`ColorRampProperty`,Po);const Io=` is a PAINT property not a LAYOUT property. Use get/setPaintProperty instead?`,Lo=` is a LAYOUT property not a PAINT property. Use get/setLayoutProperty instead?`;var Ro=class extends he{constructor(e,t,n){if(super(),this.id=e.id,this.type=e.type,this._globalState=n,this._featureFilter={filter:()=>!0,needGeometry:!1,getGlobalStateRefs:()=>/* @__PURE__ */ new Set},this._visibilityExpression=qa(this.visibility,`layers[${this.id}].layout.visibility`,n),e.type!==`custom`&&(this.metadata=e.metadata,this.minzoom=e.minzoom,this.maxzoom=e.maxzoom,e.type!==`background`&&(this.source=e.source,this.sourceLayer=e[`source-layer`],this.filter=e.filter,this._featureFilter=Ii(e.filter,`layers[${this.id}].filter`,n)),t.layout&&(this._unevaluatedLayout=new Do(t.layout,`layers[${this.id}].layout`,n)),t.paint)){this._transitionablePaint=new wo(t.paint,`layers[${this.id}].paint`,n);for(let t in e.paint)this.setPaintProperty(t,e.paint[t],{validate:!1});for(let t in e.layout)this.setLayoutProperty(t,e.layout[t],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new ko(t.paint)}}setFilter(e){this.filter=e,this._featureFilter=Ii(e,`layers[${this.id}].filter`,this._globalState)}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(e){if(e===`visibility`)return this.visibility;if(this._transitionablePaint?.hasProperty(e))throw Error(e+Io);if(!this._unevaluatedLayout)throw Error(`Cannot get layout property "${e}" on layer type "${this.type}" which has no layout properties.`);return this._unevaluatedLayout.getValue(e)}getLayoutAffectingGlobalStateRefs(){let e=/* @__PURE__ */ new Set;for(let t of this._visibilityExpression.getGlobalStateRefs())e.add(t);if(this._unevaluatedLayout)for(let t in this._unevaluatedLayout._values){let n=this._unevaluatedLayout._values[t];for(let t of n.getGlobalStateRefs())e.add(t)}for(let t of this._featureFilter.getGlobalStateRefs())e.add(t);return e}getPaintAffectingGlobalStateRefs(){let e=new globalThis.Map;if(this._transitionablePaint)for(let t in this._transitionablePaint._values){let n=this._transitionablePaint._values[t].value;for(let r of n.getGlobalStateRefs()){let i=e.get(r)??[];i.push({name:t,value:n.value}),e.set(r,i)}}return e}getVisibilityAffectingGlobalStateRefs(){return this._visibilityExpression.getGlobalStateRefs()}setLayoutProperty(e,t,n={}){e===`visibility`?(this.visibility=t,this._visibilityExpression.setValue(t),this.recalculateVisibility()):this._transitionablePaint?.hasProperty(e)?this.fire(new me(/* @__PURE__ */ Error(e+Io))):t!=null&&this._validate(vo.layoutProperty,`layers.${this.id}.layout.${e}`,e,t,n)||this._unevaluatedLayout.setValue(e,t)}getPaintProperty(e){if(e.endsWith(`-transition`)){let t=e.slice(0,-11);if(t===`visibility`||this._unevaluatedLayout?.hasProperty(t))throw Error(e+Lo);return this._transitionablePaint.getTransition(t)}if(e===`visibility`||this._unevaluatedLayout?.hasProperty(e))throw Error(e+Lo);return this._transitionablePaint.getValue(e)}setPaintProperty(e,t,n={}){if(e===`visibility`||this._unevaluatedLayout?.hasProperty(e))return this.fire(new me(/* @__PURE__ */ Error(e+Lo))),!1;if(t!=null&&this._validate(vo.paintProperty,`layers.${this.id}.paint.${e}`,e,t,n))return!1;if(e.endsWith(`-transition`))return this._transitionablePaint.setTransition(e.slice(0,-11),t||void 0),!1;{let n=this._transitionablePaint._values[e],r=n.property.specification[`property-type`]===`cross-faded-data-driven`,i=n.value.isDataDriven(),a=n.value;this._transitionablePaint.setValue(e,t),this._handleSpecialPaintPropertyUpdate(e);let o=this._transitionablePaint._values[e].value;return o.isDataDriven()||i||r||this._handleOverridablePaintPropertyUpdate(e,a,o)}}_handleSpecialPaintPropertyUpdate(e){}_handleOverridablePaintPropertyUpdate(e,t,n){return!1}isHidden(e=this.minzoom,t=!1){return this.minzoom&&e<(t?Math.floor(this.minzoom):this.minzoom)||this.maxzoom&&e>=this.maxzoom?!0:this._evaluatedVisibility===`none`}updateTransitions(e){this._transitioningPaint=this._transitionablePaint.transitioned(e,this._transitioningPaint)}retainPriorGlobalState(e,t){this._transitionablePaint?.retainPriorGlobalState(e,t,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculateVisibility(){this._evaluatedVisibility=this._visibilityExpression.evaluate()}recalculate(e,t){e.getCrossfadeParameters&&(this._crossfadeParameters=e.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(e,void 0,t)),this.paint=this._transitioningPaint.possiblyEvaluate(e,void 0,t)}serialize(){let e={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout?.serialize(),paint:this._transitionablePaint?.serialize()};return this.visibility&&(e.layout||={},e.layout.visibility=this.visibility),D(e,(e,t)=>e!==void 0&&!(t===`layout`&&!Object.keys(e).length)&&!(t===`paint`&&!Object.keys(e).length))}_validate(e,t,n,r,i={}){return bo(this,e,{key:t,layerType:this.type,objectKey:n,value:r},i)}is3D(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}resize(){}isStateDependent(){for(let e in this.paint._values){let t=this.paint.get(e);if(t instanceof Oo&&Kr(t.property.specification)&&(t.value.kind===`source`||t.value.kind===`composite`)&&t.value.isStateDependent)return!0}return!1}};const zo={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};var Bo=class{constructor(e,t){this._structArray=e,this._pos1=t*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}},Vo=class{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0)}static serialize(e,t){return e._trim(),t&&(e.isTransferred=!0,t.push(e.arrayBuffer)),{length:e.length,arrayBuffer:e.arrayBuffer}}static deserialize(e){let t=Object.create(this.prototype);return t.arrayBuffer=e.arrayBuffer,t.length=e.length,t.capacity=e.arrayBuffer.byteLength/t.bytesPerElement,t._refreshViews(),t}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())}clear(){this.length=0}resize(e){this.reserve(e),this.length=e}reserve(e){if(e>this.capacity){this.capacity=Math.max(e,Math.floor(this.capacity*5),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);let t=this.uint8;this._refreshViews(),t&&this.uint8.set(t)}}_refreshViews(){throw Error(`_refreshViews() must be implemented by each concrete StructArray layout`)}freeBufferAfterUpload(){this.arrayBuffer=/* @__PURE__ */ new ArrayBuffer(0),this._refreshViews()}};function Ho(e,t=1){let n=0,r=0;return{members:e.map(e=>{let i=Uo(e.type),a=n=Wo(n,Math.max(t,i)),o=e.components||1;return r=Math.max(r,i),n+=i*o,{name:e.name,type:e.type,components:o,offset:a}}),size:Wo(n,Math.max(r,t)),alignment:t}}function Uo(e){return zo[e].BYTES_PER_ELEMENT}function Wo(e,t){return Math.ceil(e/t)*t}var Go=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,t){let n=this.length;return this.resize(n+1),this.emplace(n,e,t)}emplace(e,t,n){let r=e*2;return this.int16[r+0]=t,this.int16[r+1]=n,e}};Go.prototype.bytesPerElement=4,G(`StructArrayLayout2i4`,Go);var Ko=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,t,n){let r=this.length;return this.resize(r+1),this.emplace(r,e,t,n)}emplace(e,t,n,r){let i=e*3;return this.int16[i+0]=t,this.int16[i+1]=n,this.int16[i+2]=r,e}};Ko.prototype.bytesPerElement=6,G(`StructArrayLayout3i6`,Ko);var qo=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,t,n,r){let i=this.length;return this.resize(i+1),this.emplace(i,e,t,n,r)}emplace(e,t,n,r,i){let a=e*4;return this.int16[a+0]=t,this.int16[a+1]=n,this.int16[a+2]=r,this.int16[a+3]=i,e}};qo.prototype.bytesPerElement=8,G(`StructArrayLayout4i8`,qo);var Jo=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,t,n,r,i,a){let o=this.length;return this.resize(o+1),this.emplace(o,e,t,n,r,i,a)}emplace(e,t,n,r,i,a,o){let s=e*6;return this.int16[s+0]=t,this.int16[s+1]=n,this.int16[s+2]=r,this.int16[s+3]=i,this.int16[s+4]=a,this.int16[s+5]=o,e}};Jo.prototype.bytesPerElement=12,G(`StructArrayLayout2i4i12`,Jo);var Yo=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.int8=new Int8Array(this.arrayBuffer)}emplaceBack(e,t,n,r,i,a,o,s){let c=this.length;return this.resize(c+1),this.emplace(c,e,t,n,r,i,a,o,s)}emplace(e,t,n,r,i,a,o,s,c){let l=e*5,u=e*10;return this.int16[l+0]=t,this.int16[l+1]=n,this.uint8[u+4]=r,this.uint8[u+5]=i,this.uint8[u+6]=a,this.uint8[u+7]=o,this.int8[u+8]=s,this.int8[u+9]=c,e}};Yo.prototype.bytesPerElement=10,G(`StructArrayLayout2i4ub2b10`,Yo);var Xo=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,t){let n=this.length;return this.resize(n+1),this.emplace(n,e,t)}emplace(e,t,n){let r=e*2;return this.float32[r+0]=t,this.float32[r+1]=n,e}};Xo.prototype.bytesPerElement=8,G(`StructArrayLayout2f8`,Xo);var Zo=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,t,n,r,i,a,o,s,c,l){let u=this.length;return this.resize(u+1),this.emplace(u,e,t,n,r,i,a,o,s,c,l)}emplace(e,t,n,r,i,a,o,s,c,l,u){let d=e*10;return this.uint16[d+0]=t,this.uint16[d+1]=n,this.uint16[d+2]=r,this.uint16[d+3]=i,this.uint16[d+4]=a,this.uint16[d+5]=o,this.uint16[d+6]=s,this.uint16[d+7]=c,this.uint16[d+8]=l,this.uint16[d+9]=u,e}};Zo.prototype.bytesPerElement=20,G(`StructArrayLayout10ui20`,Zo);var Qo=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,t,n,r,i,a,o,s){let c=this.length;return this.resize(c+1),this.emplace(c,e,t,n,r,i,a,o,s)}emplace(e,t,n,r,i,a,o,s,c){let l=e*8;return this.uint16[l+0]=t,this.uint16[l+1]=n,this.uint16[l+2]=r,this.uint16[l+3]=i,this.uint16[l+4]=a,this.uint16[l+5]=o,this.uint16[l+6]=s,this.uint16[l+7]=c,e}};Qo.prototype.bytesPerElement=16,G(`StructArrayLayout8ui16`,Qo);var $o=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=this.length;return this.resize(p+1),this.emplace(p,e,t,n,r,i,a,o,s,c,l,u,d,f)}emplace(e,t,n,r,i,a,o,s,c,l,u,d,f,p){let m=e*14,h=e*7;return this.int16[m+0]=t,this.int16[m+1]=n,this.int16[m+2]=r,this.int16[m+3]=i,this.uint16[m+4]=a,this.uint16[m+5]=o,this.uint16[m+6]=s,this.uint16[m+7]=c,this.int16[m+8]=l,this.int16[m+9]=u,this.int16[m+10]=d,this.int16[m+11]=f,this.float32[h+6]=p,e}};$o.prototype.bytesPerElement=28,G(`StructArrayLayout4i4ui4i1f28`,$o);var es=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,t,n){let r=this.length;return this.resize(r+1),this.emplace(r,e,t,n)}emplace(e,t,n,r){let i=e*3;return this.float32[i+0]=t,this.float32[i+1]=n,this.float32[i+2]=r,e}};es.prototype.bytesPerElement=12,G(`StructArrayLayout3f12`,es);var ts=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(e){let t=this.length;return this.resize(t+1),this.emplace(t,e)}emplace(e,t){let n=e*1;return this.uint32[n+0]=t,e}};ts.prototype.bytesPerElement=4,G(`StructArrayLayout1ul4`,ts);var ns=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,t,n,r,i,a,o,s,c){let l=this.length;return this.resize(l+1),this.emplace(l,e,t,n,r,i,a,o,s,c)}emplace(e,t,n,r,i,a,o,s,c,l){let u=e*10,d=e*5;return this.int16[u+0]=t,this.int16[u+1]=n,this.int16[u+2]=r,this.int16[u+3]=i,this.int16[u+4]=a,this.int16[u+5]=o,this.uint32[d+3]=s,this.uint16[u+8]=c,this.uint16[u+9]=l,e}};ns.prototype.bytesPerElement=20,G(`StructArrayLayout6i1ul2ui20`,ns);var rs=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,t,n,r,i,a){let o=this.length;return this.resize(o+1),this.emplace(o,e,t,n,r,i,a)}emplace(e,t,n,r,i,a,o){let s=e*6;return this.int16[s+0]=t,this.int16[s+1]=n,this.int16[s+2]=r,this.int16[s+3]=i,this.int16[s+4]=a,this.int16[s+5]=o,e}};rs.prototype.bytesPerElement=12,G(`StructArrayLayout2i2i2i12`,rs);var is=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,t,n,r,i){let a=this.length;return this.resize(a+1),this.emplace(a,e,t,n,r,i)}emplace(e,t,n,r,i,a){let o=e*4,s=e*8;return this.float32[o+0]=t,this.float32[o+1]=n,this.float32[o+2]=r,this.int16[s+6]=i,this.int16[s+7]=a,e}};is.prototype.bytesPerElement=16,G(`StructArrayLayout2f1f2i16`,is);var as=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(e,t,n,r,i,a){let o=this.length;return this.resize(o+1),this.emplace(o,e,t,n,r,i,a)}emplace(e,t,n,r,i,a,o){let s=e*16,c=e*4,l=e*8;return this.uint8[s+0]=t,this.uint8[s+1]=n,this.float32[c+1]=r,this.float32[c+2]=i,this.int16[l+6]=a,this.int16[l+7]=o,e}};as.prototype.bytesPerElement=16,G(`StructArrayLayout2ub2f2i16`,as);var os=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,t,n){let r=this.length;return this.resize(r+1),this.emplace(r,e,t,n)}emplace(e,t,n,r){let i=e*3;return this.uint16[i+0]=t,this.uint16[i+1]=n,this.uint16[i+2]=r,e}};os.prototype.bytesPerElement=6,G(`StructArrayLayout3ui6`,os);var ss=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=this.length;return this.resize(v+1),this.emplace(v,e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_)}emplace(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){let y=e*26,b=e*13,x=e*52;return this.int16[y+0]=t,this.int16[y+1]=n,this.uint16[y+2]=r,this.uint16[y+3]=i,this.uint32[b+2]=a,this.uint32[b+3]=o,this.uint32[b+4]=s,this.uint16[y+10]=c,this.uint16[y+11]=l,this.uint16[y+12]=u,this.float32[b+7]=d,this.float32[b+8]=f,this.uint8[x+36]=p,this.uint8[x+37]=m,this.uint8[x+38]=h,this.uint32[b+10]=g,this.int16[y+22]=_,this.float32[b+12]=v,e}};ss.prototype.bytesPerElement=52,G(`StructArrayLayout2i2ui3ul3ui2f3ub1ul1i1f52`,ss);var cs=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O){let k=this.length;return this.resize(k+1),this.emplace(k,e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O)}emplace(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k){let A=e*34,j=e*17;return this.int16[A+0]=t,this.int16[A+1]=n,this.int16[A+2]=r,this.int16[A+3]=i,this.int16[A+4]=a,this.int16[A+5]=o,this.int16[A+6]=s,this.int16[A+7]=c,this.uint16[A+8]=l,this.uint16[A+9]=u,this.uint16[A+10]=d,this.uint16[A+11]=f,this.uint16[A+12]=p,this.uint16[A+13]=m,this.uint16[A+14]=h,this.uint16[A+15]=g,this.uint16[A+16]=_,this.uint16[A+17]=v,this.uint16[A+18]=y,this.uint16[A+19]=b,this.uint16[A+20]=x,this.uint16[A+21]=S,this.uint16[A+22]=C,this.uint32[j+12]=w,this.float32[j+13]=T,this.float32[j+14]=E,this.uint16[A+30]=D,this.uint16[A+31]=O,this.float32[j+16]=k,e}};cs.prototype.bytesPerElement=68,G(`StructArrayLayout8i15ui1ul2f2ui1f68`,cs);var ls=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e){let t=this.length;return this.resize(t+1),this.emplace(t,e)}emplace(e,t){let n=e*1;return this.float32[n+0]=t,e}};ls.prototype.bytesPerElement=4,G(`StructArrayLayout1f4`,ls);var us=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,t,n){let r=this.length;return this.resize(r+1),this.emplace(r,e,t,n)}emplace(e,t,n,r){let i=e*6,a=e*3;return this.uint16[i+0]=t,this.float32[a+1]=n,this.float32[a+2]=r,e}};us.prototype.bytesPerElement=12,G(`StructArrayLayout1ui2f12`,us);var ds=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,t,n){let r=this.length;return this.resize(r+1),this.emplace(r,e,t,n)}emplace(e,t,n,r){let i=e*2,a=e*4;return this.uint32[i+0]=t,this.uint16[a+2]=n,this.uint16[a+3]=r,e}};ds.prototype.bytesPerElement=8,G(`StructArrayLayout1ul2ui8`,ds);var fs=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e,t){let n=this.length;return this.resize(n+1),this.emplace(n,e,t)}emplace(e,t,n){let r=e*2;return this.uint16[r+0]=t,this.uint16[r+1]=n,e}};fs.prototype.bytesPerElement=4,G(`StructArrayLayout2ui4`,fs);var ps=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(e){let t=this.length;return this.resize(t+1),this.emplace(t,e)}emplace(e,t){let n=e*1;return this.uint16[n+0]=t,e}};ps.prototype.bytesPerElement=2,G(`StructArrayLayout1ui2`,ps);var ms=class extends Vo{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(e,t,n,r){let i=this.length;return this.resize(i+1),this.emplace(i,e,t,n,r)}emplace(e,t,n,r,i){let a=e*4;return this.float32[a+0]=t,this.float32[a+1]=n,this.float32[a+2]=r,this.float32[a+3]=i,e}};ms.prototype.bytesPerElement=16,G(`StructArrayLayout4f16`,ms);var hs=class extends Bo{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new l(this.anchorPointX,this.anchorPointY)}};hs.prototype.size=20;var gs=class extends ns{get(e){return new hs(this,e)}};G(`CollisionBoxArray`,gs);var _s=class extends Bo{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(e){this._structArray.uint8[this._pos1+37]=e}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(e){this._structArray.uint8[this._pos1+38]=e}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(e){this._structArray.uint32[this._pos4+10]=e}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}get heightOffset(){return this._structArray.float32[this._pos4+12]}};_s.prototype.size=52;var vs=class extends ss{get(e){return new _s(this,e)}};G(`PlacedSymbolArray`,vs);var ys=class extends Bo{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(e){this._structArray.uint32[this._pos4+12]=e}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}get heightOffset(){return this._structArray.float32[this._pos4+16]}};ys.prototype.size=68;var bs=class extends cs{get(e){return new ys(this,e)}};G(`SymbolInstanceArray`,bs);var xs=class extends ls{getoffsetX(e){return this.float32[e*1+0]}};G(`GlyphOffsetArray`,xs);var Ss=class extends Ko{getx(e){return this.int16[e*3+0]}gety(e){return this.int16[e*3+1]}gettileUnitDistanceFromAnchor(e){return this.int16[e*3+2]}};G(`SymbolLineVertexArray`,Ss);var Cs=class extends Bo{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}};Cs.prototype.size=12;var ws=class extends us{get(e){return new Cs(this,e)}};G(`TextAnchorOffsetArray`,ws);var Ts=class extends Bo{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}};Ts.prototype.size=8;var Es=class extends ds{get(e){return new Ts(this,e)}};G(`FeatureIndexArray`,Es);var Ds=class extends Go{},Os=class extends Go{},ks=class extends Go{},As=class extends Jo{},js=class extends Yo{},Ms=class extends Xo{},Ns=class extends Zo{},Ps=class extends Qo{},Fs=class extends $o{},Is=class extends es{},Ls=class extends ts{},Rs=class extends rs{},zs=class extends as{},Bs=class extends os{},Vs=class extends fs{};const Hs=Ho([{name:`a_pos`,components:2,type:`Int16`}],4),Us=Hs.members;Hs.size,Hs.alignment;var Ws=class e{constructor(e=[]){this._forceNewSegmentOnNextPrepare=!1,this.segments=e}prepareSegment(t,n,r,i){let a=this.segments[this.segments.length-1];return t>e.MAX_VERTEX_ARRAY_LENGTH&&j(`Max vertices per segment is ${e.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${e.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!a||a.vertexLength+t>e.MAX_VERTEX_ARRAY_LENGTH||a.sortKey!==i?this.createNewSegment(n,r,i):a}createNewSegment(e,t,n){let r={vertexOffset:e.length,primitiveOffset:t.length,vertexLength:0,primitiveLength:0,vaos:{}};return n!==void 0&&(r.sortKey=n),this._forceNewSegmentOnNextPrepare=!1,this.segments.push(r),r}getOrCreateLatestSegment(e,t,n){return this.prepareSegment(0,e,t,n)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=!0}get(){return this.segments}destroy(){for(let e of this.segments)for(let t in e.vaos)e.vaos[t].destroy()}static simpleSegment(t,n,r,i){return new e([{vertexOffset:t,primitiveOffset:n,vertexLength:r,primitiveLength:i,vaos:{},sortKey:0}])}};Ws.MAX_VERTEX_ARRAY_LENGTH=2**16-1,G(`SegmentVector`,Ws);function Gs(e,t){return e=S(Math.floor(e),0,255),t=S(Math.floor(t),0,255),256*e+t}const Ks=Ho([{name:`a_pattern_from`,components:4,type:`Uint16`},{name:`a_pattern_to`,components:4,type:`Uint16`},{name:`a_pixel_ratio_from`,components:1,type:`Uint16`},{name:`a_pixel_ratio_to`,components:1,type:`Uint16`}]),qs=Ho([{name:`a_dasharray_from`,components:4,type:`Uint16`},{name:`a_dasharray_to`,components:4,type:`Uint16`}]);var Js=/* @__PURE__ */ o(((e,t)=>{function n(e,t){for(var n=e.length&3,r=e.length-n,i=t,a,o=3432918353,s=461845907,c,l=0;l>>16)*o&65535)<<16)|0,c=c<<15|c>>>17,c=(c&65535)*s+(((c>>>16)*s&65535)<<16)|0,i^=c,i=i<<13|i>>>19,a=(i&65535)*5+(((i>>>16)*5&65535)<<16)|0,i=(a&65535)+27492+(((a>>>16)+58964&65535)<<16);switch(c=0,n){case 3:c^=(e.charCodeAt(l+2)&255)<<16;case 2:c^=(e.charCodeAt(l+1)&255)<<8;case 1:c^=e.charCodeAt(l)&255,c=(c&65535)*o+(((c>>>16)*o&65535)<<16)|0,c=c<<15|c>>>17,c=(c&65535)*s+(((c>>>16)*s&65535)<<16)|0,i^=c}return i^=e.length,i^=i>>>16,i=(i&65535)*2246822507+(((i>>>16)*2246822507&65535)<<16)|0,i^=i>>>13,i=(i&65535)*3266489909+(((i>>>16)*3266489909&65535)<<16)|0,i^=i>>>16,i>>>0}t!==void 0&&(t.exports=n)})),Ys=/* @__PURE__ */ o(((e,t)=>{function n(e,t){for(var n=e.length,r=t^n,i=0,a;n>=4;)a=e.charCodeAt(i)&255|(e.charCodeAt(++i)&255)<<8|(e.charCodeAt(++i)&255)<<16|(e.charCodeAt(++i)&255)<<24,a=(a&65535)*1540483477+(((a>>>16)*1540483477&65535)<<16),a^=a>>>24,a=(a&65535)*1540483477+(((a>>>16)*1540483477&65535)<<16),r=(r&65535)*1540483477+(((r>>>16)*1540483477&65535)<<16)^a,n-=4,++i;switch(n){case 3:r^=(e.charCodeAt(i+2)&255)<<16;case 2:r^=(e.charCodeAt(i+1)&255)<<8;case 1:r^=e.charCodeAt(i)&255,r=(r&65535)*1540483477+(((r>>>16)*1540483477&65535)<<16)}return r^=r>>>13,r=(r&65535)*1540483477+(((r>>>16)*1540483477&65535)<<16),r^=r>>>15,r>>>0}t.exports=n})),Xs=/* @__PURE__ */ c((/* @__PURE__ */ o(((e,t)=>{var n=Js(),r=Ys();t.exports=n,t.exports.murmur3=n,t.exports.murmur2=r})))(),1),Zs=class e{constructor(){this.ids=[],this.positions=[],this.indexed=!1}add(e,t,n,r){this.ids.push(Qs(e)),this.positions.push(t,n,r)}getPositions(e){if(!this.indexed)throw Error(`Trying to get index, but feature positions are not indexed`);let t=Qs(e),n=0,r=this.ids.length-1;for(;n>1;this.ids[e]>=t?r=e:n=e+1}let i=[];for(;this.ids[n]===t;){let e=this.positions[3*n],t=this.positions[3*n+1],r=this.positions[3*n+2];i.push({index:e,start:t,end:r}),n++}return i}static serialize(e,t){let n=new Float64Array(e.ids),r=new Uint32Array(e.positions);return $s(n,r,0,n.length-1),t&&t.push(n.buffer,r.buffer),{ids:n,positions:r}}static deserialize(t){let n=new e;return n.ids=t.ids,n.positions=t.positions,n.indexed=!0,n}};function Qs(e){let t=+e;return!isNaN(t)&&t<=2**53-1?t:(0,Xs.default)(String(e))}function $s(e,t,n,r){for(;n>1],a=n-1,o=r+1;for(;;){do a++;while(e[a]i);if(a>=o)break;ec(e,a,o),ec(t,3*a,3*o),ec(t,3*a+1,3*o+1),ec(t,3*a+2,3*o+2)}o-n`u_${e}`),this.type=n}setUniform(e,t,n){e.set(n.constantOr(this.value))}getBinding(e,t,n){return this.type===`color`?new ic(e,t):new nc(e,t)}},sc=class{constructor(e,t){this.uniformNames=t.map(e=>`u_${e}`),this.patternFrom=null,this.patternTo=null,this.dashFrom=null,this.dashTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1}setConstantPatternPositions(e,t){this.pixelRatioFrom=t.pixelRatio,this.pixelRatioTo=e.pixelRatio,this.patternFrom=t.tlbr,this.patternTo=e.tlbr}setConstantDashPositions(e,t){this.dashTo=[0,e.y,e.height,e.width],this.dashFrom=[0,t.y,t.height,t.width]}setUniform(e,t,n,r){let i=null;r===`u_pattern_to`?i=this.patternTo:r===`u_pattern_from`?i=this.patternFrom:r===`u_dasharray_to`?i=this.dashTo:r===`u_dasharray_from`?i=this.dashFrom:r===`u_pixel_ratio_to`?i=this.pixelRatioTo:r===`u_pixel_ratio_from`&&(i=this.pixelRatioFrom),i!==null&&e.set(i)}getBinding(e,t,n){return n.startsWith(`u_pattern`)||n.startsWith(`u_dasharray_`)?new rc(e,t):new nc(e,t)}},cc=class{constructor(e,t,n,r){this.expression=e,this.type=n,this.maxValue=0,this.paintVertexAttributes=t.map(e=>({name:`a_${e}`,type:`Float32`,components:n===`color`?2:1,offset:0})),this.paintVertexArray=new r}populatePaintArray(e,t,n){let r=this.paintVertexArray.length,i=this.expression.evaluate(new K(0,n),t,{},n.canonical,[],n.formattedSection);this.paintVertexArray.resize(e),this._setPaintValue(r,e,i)}updatePaintArray(e,t,n,r,i){let a=this.expression.evaluate(new K(0,i),n,r);this._setPaintValue(e,t,a)}_setPaintValue(e,t,n){if(this.type===`color`){let r=ac(n);for(let n=e;n`u_${e}_t`),this.type=n,this.useIntegerZoom=r,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=t.map(e=>({name:`a_${e}`,type:`Float32`,components:n===`color`?4:2,offset:0})),this.paintVertexArray=new a}populatePaintArray(e,t,n){let r=this.expression.evaluate(new K(this.zoom,n),t,{},n.canonical,[],n.formattedSection),i=this.expression.evaluate(new K(this.zoom+1,n),t,{},n.canonical,[],n.formattedSection),a=this.paintVertexArray.length;this.paintVertexArray.resize(e),this._setPaintValue(a,e,r,i)}updatePaintArray(e,t,n,r,i){let a=this.expression.evaluate(new K(this.zoom,i),n,r),o=this.expression.evaluate(new K(this.zoom+1,i),n,r);this._setPaintValue(e,t,a,o)}_setPaintValue(e,t,n,r){if(this.type===`color`){let i=ac(n),a=ac(r);for(let n=e;n`#define HAS_UNIFORM_${e}`))}return e}getBinderAttributes(){let e=[];for(let t in this.binders){let n=this.binders[t];if(n instanceof cc||n instanceof lc)for(let t of n.paintVertexAttributes)e.push(t.name);else if(n instanceof uc){let t=n.getVertexAttributes();for(let n of t)e.push(n.name)}}return e}getBinderUniforms(){let e=[];for(let t in this.binders){let n=this.binders[t];if(n instanceof oc||n instanceof sc||n instanceof lc)for(let t of n.uniformNames)e.push(t)}return e}getPaintVertexBuffers(){return this._buffers}getUniforms(e,t){let n=[];for(let r in this.binders){let i=this.binders[r];if(i instanceof oc||i instanceof sc||i instanceof lc){for(let a of i.uniformNames)if(t[a]){let o=i.getBinding(e,t[a],a);n.push({name:a,property:r,binding:o})}}}return n}setUniforms(e,t,n,r){for(let{name:e,property:i,binding:a}of t)this.binders[i].setUniform(a,r,n.get(i),e)}updatePaintBuffers(e){this._buffers=[];for(let t in this.binders){let n=this.binders[t];if(e&&n instanceof uc){let t=e.fromScale===2?n.zoomInPaintVertexBuffer:n.zoomOutPaintVertexBuffer;t&&this._buffers.push(t)}else(n instanceof cc||n instanceof lc)&&n.paintVertexBuffer&&this._buffers.push(n.paintVertexBuffer)}}upload(e){for(let t in this.binders){let n=this.binders[t];(n instanceof cc||n instanceof lc||n instanceof uc)&&n.upload(e)}this.updatePaintBuffers()}destroy(){for(let e in this.binders){let t=this.binders[e];(t instanceof cc||t instanceof lc||t instanceof uc)&&t.destroy()}}},mc=class{constructor(e,t,n=()=>!0){this.programConfigurations={};for(let r of e)this.programConfigurations[r.id]=new pc(r,t,n);this.needsUpload=!1,this._featureMap=new Zs,this._bufferOffset=0}populatePaintArrays(e,t,n,r){for(let n in this.programConfigurations)this.programConfigurations[n].populatePaintArrays(e,t,r);t.id!==void 0&&this._featureMap.add(t.id,n,this._bufferOffset,e),this._bufferOffset=e,this.needsUpload=!0}updatePaintArrays(e,t,n,r){for(let i of n)this.needsUpload=this.programConfigurations[i.id].updatePaintArrays(e,this._featureMap,t,i,r)||this.needsUpload}get(e){return this.programConfigurations[e]}upload(e){if(this.needsUpload){for(let t in this.programConfigurations)this.programConfigurations[t].upload(e);this.needsUpload=!1}}destroy(){for(let e in this.programConfigurations)this.programConfigurations[e].destroy()}};function hc(e,t){return{"text-opacity":[`opacity`],"icon-opacity":[`opacity`],"text-color":[`fill_color`],"icon-color":[`fill_color`],"text-halo-color":[`halo_color`],"icon-halo-color":[`halo_color`],"text-halo-blur":[`halo_blur`],"icon-halo-blur":[`halo_blur`],"text-halo-width":[`halo_width`],"icon-halo-width":[`halo_width`],"line-gap-width":[`gapwidth`],"line-dasharray":[`dasharray_to`,`dasharray_from`],"line-pattern":[`pattern_to`,`pattern_from`,`pixel_ratio_to`,`pixel_ratio_from`],"fill-pattern":[`pattern_to`,`pattern_from`,`pixel_ratio_to`,`pixel_ratio_from`],"fill-extrusion-pattern":[`pattern_to`,`pattern_from`,`pixel_ratio_to`,`pixel_ratio_from`]}[e]||[e.replace(`${t}-`,``).replace(/-/g,`_`)]}function gc(e){return{"line-pattern":{source:Ns,composite:Ns},"fill-pattern":{source:Ns,composite:Ns},"fill-extrusion-pattern":{source:Ns,composite:Ns},"line-dasharray":{source:Ps,composite:Ps}}[e]}function _c(e,t,n){let r={color:{source:Xo,composite:ms},number:{source:ls,composite:Xo}};return gc(e)?.[n]||r[t][n]}G(`ConstantBinder`,oc),G(`CrossFadedConstantBinder`,sc),G(`SourceExpressionBinder`,cc),G(`CrossFadedPatternBinder`,dc),G(`CrossFadedDasharrayBinder`,fc),G(`CompositeExpressionBinder`,lc),G(`ProgramConfiguration`,pc,{omit:[`_buffers`]}),G(`ProgramConfigurationSet`,mc);const vc=2**14-1,yc=-vc-1;function bc(e){let t=v/e.extent,n=e.loadGeometry();for(let e of n)for(let n of e){let e=Math.round(n.x*t),r=Math.round(n.y*t);n.x=S(e,yc,vc),n.y=S(r,yc,vc),(en.x+1||rn.y+1)&&j(`Geometry exceeds allowed extent, reduce your vector tile buffer size`)}return n}function xc(e,t){return{type:e.type,id:e.id,properties:e.properties,geometry:t?bc(e):[]}}var Sc=class e{constructor(){this.minX=1/0,this.maxX=-1/0,this.minY=1/0,this.maxY=-1/0}extend(e){return this.minX=Math.min(this.minX,e.x),this.minY=Math.min(this.minY,e.y),this.maxX=Math.max(this.maxX,e.x),this.maxY=Math.max(this.maxY,e.y),this}expandBy(e){return this.minX-=e,this.minY-=e,this.maxX+=e,this.maxY+=e,(this.minX>this.maxX||this.minY>this.maxY)&&(this.minX=1/0,this.maxX=-1/0,this.minY=1/0,this.maxY=-1/0),this}shrinkBy(e){return this.expandBy(-e)}map(t){let n=new e;return n.extend(t(new l(this.minX,this.minY))),n.extend(t(new l(this.maxX,this.minY))),n.extend(t(new l(this.minX,this.maxY))),n.extend(t(new l(this.maxX,this.maxY))),n}static fromPoints(t){let n=new e;for(let e of t)n.extend(e);return n}contains(e){return e.x>=this.minX&&e.x<=this.maxX&&e.y>=this.minY&&e.y<=this.maxY}empty(){return this.minX>this.maxX}width(){return this.maxX-this.minX}height(){return this.maxY-this.minY}covers(e){return!this.empty()&&!e.empty()&&e.minX>=this.minX&&e.maxX<=this.maxX&&e.minY>=this.minY&&e.maxY<=this.maxY}intersects(e){return!this.empty()&&!e.empty()&&e.minX<=this.maxX&&e.maxX>=this.minX&&e.minY<=this.maxY&&e.maxY>=this.minY}};Sc.fromPoints([new l(0,0),new l(v,v)]);function Cc(e,t){return e.x===t.x&&(e.x<0||e.x>8192)||e.y===t.y&&(e.y<0||e.y>8192)}function wc(e){return e.every(e=>e.x<0)||e.every(e=>e.x>8192)||e.every(e=>e.y<0)||e.every(e=>e.y>8192)}function Tc(e){return e.x<0||e.x>=8192||e.y<0||e.y>=8192}const Ec=-32768;function Dc(e,t,n,r,i){e.emplaceBack(Ec+t*8+r,Ec+n*8+i)}var Oc=class{constructor(e){this.zoom=e.zoom,this.overscaling=e.overscaling,this.layers=e.layers,this.layerIds=this.layers.map(e=>e.id),this.index=e.index,this.hasDependencies=!1,this.layoutVertexArray=new Os,this.indexArray=new Bs,this.segments=new Ws,this.programConfigurations=new mc(e.layers,e.zoom),this.stateDependentLayerIds=this.layers.filter(e=>e.isStateDependent()).map(e=>e.id)}populate(e,t,n){let r=this.layers[0],i=[],a=null,o=!1,s=r.type===`heatmap`;if(r.type===`circle`){let e=r;a=e.layout.get(`circle-sort-key`),o=!a.isConstant(),s||=e.paint.get(`circle-pitch-alignment`)===`map`}let c=s?t.subdivisionGranularity.circle:1,l=new K(this.zoom),u=this.layers[0]._featureFilter.needGeometry;for(let{feature:t,id:r,index:s,sourceLayerIndex:c}of e){let e=xc(t,u);if(!this.layers[0]._featureFilter.filter(l,e,n))continue;let d=o?a.evaluate(e,{},n):void 0,f={id:r,properties:t.properties,type:t.type,sourceLayerIndex:c,index:s,geometry:u?e.geometry:bc(t),patterns:{},sortKey:d};i.push(f)}o&&i.sort((e,t)=>e.sortKey-t.sortKey);for(let r of i){let{geometry:i,index:a,sourceLayerIndex:o}=r,s=e[a].feature;this.addFeature(r,i,a,n,c),t.featureIndex.insert(s,i,a,o,this.index)}}update(e,t,n){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(e,t,this.stateDependentLayers,{imagePositions:n})}addFeatures(e){}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(e){this.uploaded||(this.layoutVertexBuffer=e.createVertexBuffer(this.layoutVertexArray,Us),this.indexBuffer=e.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(e),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(e,t,n,r,i=1){let a;switch(i){case 1:a=[0,7];break;case 3:a=[0,2,5,7];break;case 5:a=[0,1,3,4,6,7];break;case 7:a=[0,1,2,3,4,5,6,7];break;default:throw Error(`Invalid circle bucket granularity: ${i}; valid values are 1, 3, 5, 7.`)}let o=a.length;for(let n of t)for(let t of n){let n=t.x,r=t.y;if(Tc(t))continue;let i=this.segments.prepareSegment(o*o,this.layoutVertexArray,this.indexArray,e.sortKey),s=i.vertexLength;for(let e=0;e=3){for(let t of r)if(zc(e,t))return!0}if(Nc(e,r,n))return!0}return!1}function Nc(e,t,n){if(e.length>1){if(Pc(e,t))return!0;for(let r of t)if(Ic(r,e,n))return!0}for(let r of e)if(Ic(r,t,n))return!0;return!1}function Pc(e,t){if(e.length===0||t.length===0)return!1;for(let n=0;n1?e.distSqr(n):e.distSqr(n.sub(t)._mult(i)._add(t))}function Rc(e,t){let n=!1,r,i,a;for(let o of e){r=o;for(let e=0,o=r.length-1;et.y!=a.y>t.y&&t.x<(a.x-i.x)*(t.y-i.y)/(a.y-i.y)+i.x&&(n=!n)}return n}function zc(e,t){let n=!1;for(let r=0,i=e.length-1;rt.y!=o.y>t.y&&t.x<(o.x-a.x)*(t.y-a.y)/(o.y-a.y)+a.x&&(n=!n)}return n}function Bc(e,t,n,r,i){for(let a of e)if(t<=a.x&&n<=a.y&&r>=a.x&&i>=a.y)return!0;let a=[new l(t,n),new l(t,i),new l(r,i),new l(r,n)];if(e.length>2){for(let t of a)if(zc(e,t))return!0}for(let t=0;ti.x&&t.x>i.x||e.yi.y&&t.y>i.y)return!1;let a=ee(e,t,n[0]);return a!==ee(e,t,n[1])||a!==ee(e,t,n[2])||a!==ee(e,t,n[3])}function Hc(e,t,n){let r=t.paint.get(e).value;return r.kind===`constant`?r.value:n.programConfigurations.get(t.id).getMaxValue(e)}function Uc(e){return Math.sqrt(e[0]*e[0]+e[1]*e[1])}function Wc(e,t,n,r,i){if(!t[0]&&!t[1])return e;let a=l.convert(t)._mult(i);n===`viewport`&&a._rotate(-r);let o=[];for(let t of e)o.push(t.sub(a));return o}function Gc(e){let t=[];for(let n=0;nQc(e,t,n,r))}let el;const tl=()=>el||=new Fo({"circle-sort-key":new J(N.layout_circle[`circle-sort-key`],`circle-sort-key`)});let nl;const rl=()=>nl||=new Fo({"circle-radius":new J(N.paint_circle[`circle-radius`],`circle-radius`),"circle-color":new J(N.paint_circle[`circle-color`],`circle-color`),"circle-blur":new J(N.paint_circle[`circle-blur`],`circle-blur`),"circle-opacity":new J(N.paint_circle[`circle-opacity`],`circle-opacity`),"circle-translate":new q(N.paint_circle[`circle-translate`],`circle-translate`),"circle-translate-anchor":new q(N.paint_circle[`circle-translate-anchor`],`circle-translate-anchor`),"circle-pitch-scale":new q(N.paint_circle[`circle-pitch-scale`],`circle-pitch-scale`),"circle-pitch-alignment":new q(N.paint_circle[`circle-pitch-alignment`],`circle-pitch-alignment`),"circle-stroke-width":new J(N.paint_circle[`circle-stroke-width`],`circle-stroke-width`),"circle-stroke-color":new J(N.paint_circle[`circle-stroke-color`],`circle-stroke-color`),"circle-stroke-opacity":new J(N.paint_circle[`circle-stroke-opacity`],`circle-stroke-opacity`)});var il={get paint(){return rl()},get layout(){return tl()}},al=class extends Ro{constructor(e,t){super(e,il,t)}createBucket(e){return new Oc(e)}queryRadius(e){let t=e;return Hc(`circle-radius`,this,t)+Hc(`circle-stroke-width`,this,t)+Uc(this.paint.get(`circle-translate`))}queryIntersectsFeature({queryGeometry:e,feature:t,featureState:n,geometry:r,transform:i,pixelsToTileUnits:a,unwrappedTileID:o,getElevation:s}){let c=Wc(e,this.paint.get(`circle-translate`),this.paint.get(`circle-translate-anchor`),-i.bearingInRadians,a),l=this.paint.get(`circle-radius`).evaluate(t,n)+this.paint.get(`circle-stroke-width`).evaluate(t,n),u=this.paint.get(`circle-pitch-scale`),d=this.paint.get(`circle-pitch-alignment`),f,p;return d===`map`?(f=c,p=l*a):(f=$c(c,i,o,s),p=l),Zc({queryGeometry:f,size:p,transform:i,unwrappedTileID:o,getElevation:s,pitchAlignment:d,pitchScale:u},r)}},ol=class extends Oc{};G(`HeatmapBucket`,ol,{omit:[`layers`]});let sl;const cl=()=>sl||=new Fo({"heatmap-radius":new J(N.paint_heatmap[`heatmap-radius`],`heatmap-radius`),"heatmap-weight":new J(N.paint_heatmap[`heatmap-weight`],`heatmap-weight`),"heatmap-intensity":new q(N.paint_heatmap[`heatmap-intensity`],`heatmap-intensity`),"heatmap-color":new Po(N.paint_heatmap[`heatmap-color`],`heatmap-color`),"heatmap-opacity":new q(N.paint_heatmap[`heatmap-opacity`],`heatmap-opacity`)});var ll={get paint(){return cl()}};function ul(e,{width:t,height:n},r,i){if(!i)i=new Uint8Array(t*n*r);else if(i instanceof Uint8ClampedArray)i=new Uint8Array(i.buffer);else if(i.length!==t*n*r)throw RangeError(`mismatched image size. expected: ${i.length} but got: ${t*n*r}`);return e.width=t,e.height=n,e.data=i,e}function dl(e,{width:t,height:n},r){if(t===e.width&&n===e.height)return;let i=ul({},{width:t,height:n},r);fl(e,i,{x:0,y:0},{x:0,y:0},{width:Math.min(e.width,t),height:Math.min(e.height,n)},r),e.width=t,e.height=n,e.data=i.data}function fl(e,t,n,r,i,a){if(i.width===0||i.height===0)return t;if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw RangeError(`out of range source coordinates for image copy`);if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw RangeError(`out of range destination coordinates for image copy`);let o=e.data,s=t.data;if(o===s)throw Error(`srcData equals dstData, so image is already copied`);for(let c=0;c{t[e.evaluationKey]=o;let s=e.expression.evaluate(t);i.setPixel(r/4/n,a/4,s)};if(e.clips)for(let t=0,i=0;tvl||=new Fo({"hillshade-illumination-direction":new q(N.paint_hillshade[`hillshade-illumination-direction`],`hillshade-illumination-direction`),"hillshade-illumination-altitude":new q(N.paint_hillshade[`hillshade-illumination-altitude`],`hillshade-illumination-altitude`),"hillshade-illumination-anchor":new q(N.paint_hillshade[`hillshade-illumination-anchor`],`hillshade-illumination-anchor`),"hillshade-exaggeration":new q(N.paint_hillshade[`hillshade-exaggeration`],`hillshade-exaggeration`),"hillshade-shadow-color":new q(N.paint_hillshade[`hillshade-shadow-color`],`hillshade-shadow-color`),"hillshade-highlight-color":new q(N.paint_hillshade[`hillshade-highlight-color`],`hillshade-highlight-color`),"hillshade-accent-color":new q(N.paint_hillshade[`hillshade-accent-color`],`hillshade-accent-color`),"hillshade-method":new q(N.paint_hillshade[`hillshade-method`],`hillshade-method`),resampling:new q(N.paint_hillshade.resampling,`resampling`)});var bl={get paint(){return yl()}},xl=class extends Ro{constructor(e,t){super(e,bl,t),this.recalculate({zoom:0,zoomHistory:{}},void 0)}getIlluminationProperties(){let e=this.paint.get(`hillshade-illumination-direction`).values,t=this.paint.get(`hillshade-illumination-altitude`).values,n=this.paint.get(`hillshade-highlight-color`).values,r=this.paint.get(`hillshade-shadow-color`).values,i=Math.max(e.length,t.length,n.length,r.length);e=e.concat(Array(i-e.length).fill(e.at(-1))),t=t.concat(Array(i-t.length).fill(t.at(-1))),n=n.concat(Array(i-n.length).fill(n.at(-1))),r=r.concat(Array(i-r.length).fill(r.at(-1)));let a=t.map(ue);return{directionRadians:e.map(ue),altitudeRadians:a,shadowColor:r,highlightColor:n}}hasOffscreenPass(){return this.paint.get(`hillshade-exaggeration`)!==0&&!this.isHidden()}};let Sl;const Cl=()=>Sl||=new Fo({"color-relief-opacity":new q(N[`paint_color-relief`][`color-relief-opacity`],`color-relief-opacity`),"color-relief-color":new Po(N[`paint_color-relief`][`color-relief-color`],`color-relief-color`),resampling:new q(N[`paint_color-relief`].resampling,`resampling`)});var wl={get paint(){return Cl()}};function Tl(e){return`data`in e}var El=class{constructor(e,t,n,r){this.context=e,this.format=n,this.texture=e.gl.createTexture(),this._ownedHandle=this.texture,this.update(t,r)}update(e,t,n){let{width:r,height:i}=e,a=(this.size?.[0]!==r||this.size[1]!==i)&&!n,{context:o}=this,{gl:s}=o;this.useMipmap=!!t?.useMipmap,a&&this.size&&this.format===s.RGBA&&(s.deleteTexture(this.texture),this.texture=s.createTexture(),this._ownedHandle=this.texture,this.magFilter=void 0,this.minFilter=void 0,this.wrap=void 0),s.bindTexture(s.TEXTURE_2D,this.texture),o.pixelStoreUnpackFlipY.set(!1),o.pixelStoreUnpack.set(1);let c=this.format===s.RGBA&&t?.premultiply!==!1;if(a){if(this.size=[r,i],this.format===s.RGBA&&r>0&&i>0){let t=this.useMipmap?Math.floor(Math.log2(Math.max(r,i)))+1:1;if(s.texStorage2D(s.TEXTURE_2D,t,s.RGBA8,r,i),Tl(e)){o.pixelStoreUnpackPremultiplyAlpha.set(!1);let{data:t}=e;c&&t&&(t=hl(t)),t&&s.texSubImage2D(s.TEXTURE_2D,0,0,0,r,i,s.RGBA,s.UNSIGNED_BYTE,t)}else o.pixelStoreUnpackPremultiplyAlpha.set(c),s.texSubImage2D(s.TEXTURE_2D,0,0,0,s.RGBA,s.UNSIGNED_BYTE,e)}else Tl(e)?(o.pixelStoreUnpackPremultiplyAlpha.set(!1),this._uploadRawData(e,c,r,i,s)):(o.pixelStoreUnpackPremultiplyAlpha.set(c),this._uploadDomImage(e,s))}else{let{x:t,y:a}=n||{x:0,y:0};Tl(e)?(o.pixelStoreUnpackPremultiplyAlpha.set(!1),this._updateRawData(e,c,t,a,r,i,s)):(o.pixelStoreUnpackPremultiplyAlpha.set(c),this._updateDomImage(e,t,a,s))}this.useMipmap&&!(Tl(e)&&e.data===null)&&s.generateMipmap(s.TEXTURE_2D),o.pixelStoreUnpackFlipY.setDefault(),o.pixelStoreUnpack.setDefault(),o.pixelStoreUnpackPremultiplyAlpha.setDefault()}_uploadDomImage(e,t){t.texImage2D(t.TEXTURE_2D,0,this.format,this.format,t.UNSIGNED_BYTE,e)}_uploadRawData(e,t,n,r,i){let{data:a}=e;t&&a&&(a=hl(a)),i.texImage2D(i.TEXTURE_2D,0,this.format,n,r,0,this.format,i.UNSIGNED_BYTE,a)}_updateDomImage(e,t,n,r){r.texSubImage2D(r.TEXTURE_2D,0,t,n,r.RGBA,r.UNSIGNED_BYTE,e)}_updateRawData(e,t,n,r,i,a,o){let{data:s}=e;t&&s&&(s=hl(s)),o.texSubImage2D(o.TEXTURE_2D,0,n,r,i,a,o.RGBA,o.UNSIGNED_BYTE,s)}bind(e,t,n){let{context:r}=this,{gl:i}=r;this.texture!==this._ownedHandle&&(this.texture=this._ownedHandle),i.bindTexture(i.TEXTURE_2D,this.texture),(n===i.LINEAR_MIPMAP_NEAREST||n===i.LINEAR_MIPMAP_LINEAR)&&!this.useMipmap&&(n=i.LINEAR);let a=n||e;e!==this.magFilter&&(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,e),this.magFilter=e),a!==this.minFilter&&(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,a),this.minFilter=a),t!==this.wrap&&(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,t),this.wrap=t)}generateMipmap(){if(!this.useMipmap)return;let{gl:e}=this.context;e.bindTexture(e.TEXTURE_2D,this.texture),e.generateMipmap(e.TEXTURE_2D)}destroy(){let{gl:e}=this.context;e.deleteTexture(this.texture),this.texture=null,this._ownedHandle=null}},Dl=class e{static{this.byteViewCache=/* @__PURE__ */ new WeakMap}constructor(t,n,r,i=1,a=1,o=1,s=0){if(this.uid=t,n.height!==n.width)throw RangeError(`DEM tiles must be square`);if(r&&![`mapbox`,`terrarium`,`custom`].includes(r)){j(`"${r}" is not a valid encoding type. Valid types include "mapbox", "terrarium" and "custom".`);return}this.stride=n.height;let c=this.dim=n.height-4;switch(this.data=new Uint32Array(n.data.buffer),e.byteViewCache.set(this,new Uint8Array(this.data.buffer)),r){case`terrarium`:this.redFactor=256,this.greenFactor=1,this.blueFactor=1/256,this.baseShift=32768;break;case`custom`:this.redFactor=i,this.greenFactor=a,this.blueFactor=o,this.baseShift=s;break;default:this.redFactor=6553.6,this.greenFactor=25.6,this.blueFactor=.1,this.baseShift=1e4}for(let e=-2;e=c)&&this.data.copyWithin(this._idx(0,e),t,t+c),this.data.fill(this.data[t],this._idx(-2,e),this._idx(0,e)),this.data.fill(this.data[t+c-1],this._idx(c,e),this._idx(c+1,e)+1)}let l=this._getByteView();this.min=2**53-1,this.max=-(2**53-1);for(let e=0;ethis.max&&(this.max=r),r=this.dim||r<-1||r>=this.dim)throw RangeError(`Out of range source coordinates for DEM data. x: ${e}, y: ${t}, dim: ${this.dim}`);let i=this._getByteView(),a=((r+2)*this.stride+n+2)*4,o=this.stride*4,s=e-n,c=t-r,l=this._unpackAtIndex(i,a),u=this._unpackAtIndex(i,a+4),d=this._unpackAtIndex(i,a+o),f=this._unpackAtIndex(i,a+o+4);return l*(1-s)*(1-c)+u*s*(1-c)+d*(1-s)*c+f*s*c}getUnpackVector(){return[this.redFactor,this.greenFactor,this.blueFactor,this.baseShift]}_idx(e,t){if(e<-2||e>=this.dim+2||t<-2||t>=this.dim+2)throw RangeError(`Out of range source coordinates for DEM data. x: ${e}, y: ${t}, dim: ${this.dim}`);return(t+2)*this.stride+(e+2)}unpack(e,t,n){return e*this.redFactor+t*this.greenFactor+n*this.blueFactor-this.baseShift}pack(e){return Ol(e,this.getUnpackVector())}getPixels(){return new ml({width:this.stride,height:this.stride},this._getByteView())}backfillBorder(e,t,n){if(this.dim!==e.dim)throw Error(`dem dimension mismatch`);let r=t*this.dim,i=t*this.dim+this.dim,a=n*this.dim,o=n*this.dim+this.dim;switch(t){case-1:r=i-2;break;case 1:i=r+2}switch(n){case-1:a=o-2;break;case 1:o=a+2}let s=-t*this.dim,c=-n*this.dim;for(let t=a;te!==0);if(o.length===0)return{r:0,g:0,b:0};let s=Math.min(...o),c=Math.round((e+a)/s),l=e=>e===0?0:Math.floor(c*s/e)%256;return{r:l(n),g:l(r),b:l(i)}}G(`DEMData`,Dl);var kl=class extends Ro{constructor(e,t){super(e,wl,t)}_createColorRamp(e){let t={elevationStops:[],colorStops:[]},n=this._transitionablePaint._values[`color-relief-color`].value.expression;if(n instanceof hi&&n._styleExpression.expression instanceof Nt){this.colorRampExpression=n;let e=n._styleExpression.expression;t.elevationStops=e.labels,t.colorStops=[];for(let n of t.elevationStops)t.colorStops.push(e.evaluate({globals:{elevation:n}}))}if(t.elevationStops.length<1&&(t.elevationStops=[0],t.colorStops=[V.transparent]),t.elevationStops.length<2&&(t.elevationStops.push(t.elevationStops[0]+1),t.colorStops.push(t.colorStops[0])),t.elevationStops.length<=e)return t;let r={elevationStops:[],colorStops:[]},i=(t.elevationStops.length-1)/(e-1);for(let e=0;e80*n){s=e[0],c=e[1];let t=s,r=c;for(let a=n;at&&(t=n),i>r&&(r=i)}l=Math.max(t-s,r-c),l=l===0?0:32767/l}return zl(a,o,s,c,l),o}function Ll(e,t,n,r,i){let a=null;if(i===Ou(e,t,n,r)>0)for(let i=t;i=t;i-=r)a=Tu(i/r|0,e[i],e[i+1],a);return a&&vu(a,a.next)&&(Eu(a),a=a.next),a}function Rl(e,t=e){let n=t===e,r=e,i;do i=!1,r!==r.next&&(Pl.size===0||!Pl.has(r))&&(vu(r,r.next)||_u(r.prev,r,r.next)===0)?((n||r===t)&&(t=r.prev),Fl=!0,Eu(r),r=r.prev,i=!0):(n||r!==t)&&(r=r.next,i=!n);while(i||r!==t);return t}function zl(e,t,n,r,i){i&&uu(e,n,r,i);let a=e,o=!1;for(;e.prev!==e.next;){let s=e.prev,c=e.next;if(_u(s,e,c)<0&&(i?Vl(e,n,r,i):Bl(e)))t.push(s.i,e.i,c.i),Eu(e),e=c,a=c;else if(e=c,e===a){if(Fl=!1,e=Rl(e),Fl){a=e;continue}if(!o){e=Hl(e,t),a=e,o=!0;continue}Ul(e,t,n,r,i);break}}}function Bl(e){let t=e.prev,n=e,r=e.next,i=t.x,a=n.x,o=r.x,s=t.y,c=n.y,l=r.y,u=Math.min(i,a,o),d=Math.min(s,c,l),f=Math.max(i,a,o),p=Math.max(s,c,l),m=r.next;for(;m!==t;){if(m.x>=u&&m.x<=f&&m.y>=d&&m.y<=p&&(i!==m.x||s!==m.y)&&hu(i,s,a,c,o,l,m.x,m.y)&&_u(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Vl(e,t,n,r){let i=e.prev,a=e,o=e.next,s=i.x,c=a.x,l=o.x,u=i.y,d=a.y,f=o.y,p=Math.min(s,c,l),m=Math.min(u,d,f),h=Math.max(s,c,l),g=Math.max(u,d,f),_=pu(p,m,t,n,r),v=pu(h,g,t,n,r),y=e.prevZ;for(;y&&y.z>=_;){if(y.x>=p&&y.x<=h&&y.y>=m&&y.y<=g&&y!==o&&(s!==y.x||u!==y.y)&&hu(s,u,c,d,l,f,y.x,y.y)&&_u(y.prev,y,y.next)>=0)return!1;y=y.prevZ}let b=e.nextZ;for(;b&&b.z<=v;){if(b.x>=p&&b.x<=h&&b.y>=m&&b.y<=g&&b!==o&&(s!==b.x||u!==b.y)&&hu(s,u,c,d,l,f,b.x,b.y)&&_u(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function Hl(e,t){let n=e,r=!1;do{let i=n.prev,a=n.next.next;yu(i,n,n.next,a,!1)&&Su(i,a)&&Su(a,i)&&(t.push(i.i,n.i,a.i),Eu(n),Eu(n.next),n=e=a,r=!0),n=n.next}while(n!==e);return r?Rl(n):n}function Ul(e,t,n,r,i){let a=e;do{let e=a.next.next;for(;e!==a.prev;){if(a.i!==e.i&&gu(a,e)){let o=wu(a,e);a=Rl(a,a.next),o=Rl(o,o.next),zl(a,t,n,r,i),zl(o,t,n,r,i);return}e=e.next}a=a.next}while(a!==e)}let Wl=!1;function Gl(e,t,n,r){let i=[];for(let n=0,a=t.length;na&&(a=t.x),t.yo&&(o=t.y),n=t}while(++s<16&&n!==t);Zl[e]=n;let c=e*4;Jl[c]=r,Jl[c+1]=i,Jl[c+2]=a,Jl[c+3]=o}while(n!==t)}function eu(e,t){let n=e.z*4;t.xJl[n+2]&&(Jl[n+2]=t.x),t.y>Jl[n+3]&&(Jl[n+3]=t.y)}function tu(e){let t=Zl[e];for(;t.prev.next!==t;)t=t.next;return Zl[e]=t,t}function nu(e){let t=Xl[e];for(;t.prev.next!==t;)t=t.next;return Xl[e]=t,t}function ru(e,t){let n=t,r=e.x,i=e.y,a=-1/0,o;if(vu(e,n))return n;for(let t=0,s=0;tJl[s+3]||Jl[s]>r||Jl[s+2]<=a)continue;let c=tu(t);n=nu(t);do{if(n.prev.next===n){if(vu(e,n.next))return n.next;if(i<=n.y&&i>=n.next.y&&n.next.y!==n.y){let e=n.x+(i-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(e<=r&&e>a&&(a=e,o=n.xr||Jl[f+3]u)continue;let p=tu(t);n=nu(t);do{if(n.prev.next===n&&r>=n.x&&n.x>=s&&r!==n.x&&hu(ir)&&(to.x||n.x===o.x&&iu(o,n)))&&(o=n,d=t)}n=n.next}while(n!==p)}return o}function iu(e,t){return _u(e.prev,e,t.prev)<0&&_u(t.next,e,e.next)<0}const au=[];let ou=[],su=/* @__PURE__ */ new Uint32Array,cu=/* @__PURE__ */ new Uint32Array;const lu=/* @__PURE__ */ new Uint32Array(256);function uu(e,t,n,r){let i=e,a=0;do i.z=pu(i.x,i.y,t,n,r),au[a++]=i,i=i.next;while(i!==e);du(a);let o=null;for(let e=0;e=0&&au[r].z>n;)au[r+1]=au[r],r--;au[r+1]=e}else{su.length>>a&255]++;let o=0;for(let e=0;e<256;e++){let t=lu[e];lu[e]=o,o+=t}for(let o=0;o>>a&255]++;r[s]=t[o],i[s]=e}}function pu(e,t,n,r,i){return e=(e-n)*i|0,t=(t-r)*i|0,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,e|t<<1}function mu(e){let t=e,n=e;do(t.x=(e-o)*(a-s)&&(e-o)*(r-s)>=(n-o)*(t-s)&&(n-o)*(a-s)>=(i-o)*(r-s)}function gu(e,t){let n=vu(e,t)&&_u(e.prev,e,e.next)>0&&_u(t.prev,t,t.next)>0;return e.next.i!==t.i&&(n||Su(e,t)&&Su(t,e)&&(_u(e.prev,e,t.prev)!==0||_u(e,t.prev,t)!==0))&&!xu(e,t)&&(n||Cu(e,t))}function _u(e,t,n){return(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y)}function vu(e,t){return e.x===t.x&&e.y===t.y}function yu(e,t,n,r,i=!0){let a=_u(e,t,n),o=_u(e,t,r),s=_u(n,r,e),c=_u(n,r,t);return(a>0&&o<0||a<0&&o>0)&&(s>0&&c<0||s<0&&c>0)?!0:i?!!(a===0&&bu(e,n,t)||o===0&&bu(e,r,t)||s===0&&bu(n,e,r)||c===0&&bu(n,t,r)):!1}function bu(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function xu(e,t){let n=Math.min(e.x,t.x),r=Math.max(e.x,t.x),i=Math.min(e.y,t.y),a=Math.max(e.y,t.y),o=e;do{let s=o.next;if(o.x>r&&s.x>r||o.xa&&s.y>a||o.y=0&&_u(e,e.prev,t)>=0:_u(e,t,e.prev)<0||_u(e,e.next,t)<0}function Cu(e,t){let n=e,r=!1,i=(e.x+t.x)/2,a=(e.y+t.y)/2;do{let e=n.next;n.y>a!=e.y>a&&i<(e.x-n.x)*(a-n.y)/(e.y-n.y)+n.x&&(r=!r),n=e}while(n!==e);return r}function wu(e,t){let n=Du(e.i,e.x,e.y),r=Du(t.i,t.x,t.y),i=e.next,a=t.prev;return e.next=t,t.prev=e,n.next=i,i.prev=n,r.next=n,n.prev=r,a.next=r,r.prev=a,r}function Tu(e,t,n,r){let i=Du(e,t,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function Eu(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ),Wl&&eu(e.prev,e.next)}function Du(e,t,n){return{i:e,x:t,y:n,prev:null,next:null,z:0,prevZ:null,nextZ:null}}function Ou(e,t,n,r){let i=0;for(let a=t,o=n-r;ae)throw Error(`Min granularity must not be greater than base granularity.`);this._baseZoomGranularity=e,this._minGranularity=t}getGranularityForZoomLevel(e){let t=1<32767||t>32767)throw Error(`Vertex coordinates are out of signed 16 bit integer range.`);let n=Math.round(e)|0,r=Math.round(t)|0,i=this._getKey(n,r),a=this._vertexDictionary.get(i);if(a!==void 0)return a;let o=this._vertexBuffer.length/2;return this._vertexDictionary.set(i,o),this._vertexBuffer.push(n,r),o}_subdivideTrianglesScanline(e,t){if(this._granularity<2)return zu(this._vertexBuffer,Ru(e,t));let n=[],r=e.length;for(let i=0;i=1||y<=0)||h&&(si)){l>=r&&l<=i&&a.push(n[(e+1)%3]);continue}if(!h&&v>0){let e=o+f*v,t=s+p*v;a.push(this._vertexToIndex(e,t))}let b=o+f*Math.max(v,0),x=o+f*Math.min(y,1);if(m||this._generateIntraEdgeVertices(a,o,s,c,l,b,x),!h&&y<1){let e=o+f*y,t=s+p*y;a.push(this._vertexToIndex(e,t))}(h||l>=r&&l<=i)&&a.push(n[(e+1)%3]),!h&&(l<=r||l>=i)&&this._generateInterEdgeVertices(a,o,s,c,l,u,d,x,r,i)}return a}_generateIntraEdgeVertices(e,t,n,r,i,a,o){let s=r-t,c=i-n,l=c===0,u=l?Math.min(t,r):Math.min(a,o),d=l?Math.max(t,r):Math.max(a,o),f=Math.floor(u/this._granularityCellSize)+1,p=Math.ceil(d/this._granularityCellSize)-1;if(l?t=f;r--){let i=r*this._granularityCellSize,a=n+c*(i-t)/s;e.push(this._vertexToIndex(i,a))}}_generateInterEdgeVertices(e,t,n,r,i,a,o,s,c,l){let u=i-n,d=a-r,f=o-i,p=(c-i)/f,m=(l-i)/f,h=Math.min(p,m),g=Math.max(p,m),_=r+d*h,v=Math.floor(Math.min(_,s)/this._granularityCellSize)+1,y=Math.ceil(Math.max(_,s)/this._granularityCellSize)-1,b=s<_,x=f===0;if(x&&(o===c||o===l))return;if(x||h>=1||g<=0){let e=t-a,r=n-o,i=(c-o)/r,u=(l-o)/r,d=a+e*Math.min(i,u);v=Math.floor(Math.min(d,s)/this._granularityCellSize)+1,y=Math.ceil(Math.max(d,s)/this._granularityCellSize)-1,b=s0?l:c;if(b)for(let t=v;t<=y;t++){let n=t*this._granularityCellSize;e.push(this._vertexToIndex(n,S))}else for(let t=y;t>=v;t--){let n=t*this._granularityCellSize;e.push(this._vertexToIndex(n,S))}}_generateOutline(e,t){let n=[],r=0;for(let i of e){let e=this._granularity<2?this._ringPathIndices(i,r,t):this._pointArrayToIndices(Fu(i,this._granularity,!0));r+=i.length;let a=[];for(let t=1;t=2&&Iu(e)&&r.push(r[0]),r}_handlePoles(e){let t=!1,n=!1;this._canonical&&(this._canonical.y===0&&(t=!0),this._canonical.y===(1<i==(a===-32768)?(e.push(n),e.push(t),e.push(this._vertexToIndex(r,a)),e.push(this._vertexToIndex(i,a)),e.push(n),e.push(this._vertexToIndex(r,a))):(e.push(t),e.push(n),e.push(this._vertexToIndex(r,a)),e.push(n),e.push(this._vertexToIndex(i,a)),e.push(this._vertexToIndex(r,a)))}_fillPoles(e,t,n){let r=this._vertexBuffer,i=v,a=e.length;for(let o=2;o=2&&this._canonical?.z===0&&(a=this._removeTrianglesOutsideTileX(a),o=o.map(e=>this._removeLinesOutsideTileX(e))),{verticesFlattened:this._vertexBuffer,indicesTriangles:a,indicesLineList:o}}_vertexOutsideTileX(e){let t=this._vertexBuffer[e*2];return t<0||t>8192}_removeTrianglesOutsideTileX(e){let t=[];for(let n=0;n0?(Math.floor(v/i)+1)*i:(Math.ceil(v/i)-1)*i,t=h>0?(Math.floor(y/i)+1)*i:(Math.ceil(y/i)-1)*i,n=Math.abs(v-e),r=Math.abs(y-t),o=Math.abs(v-u),s=Math.abs(y-d),c=f?n/g:1/0,b=p?r/_:1/0;if((o<=n||!f)&&(s<=r||!p))break;if(c0?(n.push(i),n.push(o),n.push(a)):(n.push(i),n.push(a),n.push(o))}return n}function Bu(e,t,n){if(t.length===0)throw Error(`Subdivision vertex ring is empty.`);let r=0,i=e[t[0]*2];for(let n=1;n=0?o-1:a-1,i=(s+1)%a,c=e[t[r]*2],l=e[t[r]*2+1],u=e[t[i]*2],d=e[t[i]*2+1],f=e[t[o]*2],p=e[t[o]*2+1],m=e[t[s]*2],h=e[t[s]*2+1],g=!1;if(cu)g=!1;else{let e=h-p,t=-(m-f),n=p((u-f)*e+(d-p)*t)*n&&(g=!0)}if(g){let e=t[r],i=t[o],c=t[s];e!==i&&e!==c&&i!==c&&n.push(c,i,e),o--,o<0&&(o=a-1)}else{let e=t[i],r=t[o],c=t[s];e!==r&&e!==c&&r!==c&&n.push(c,r,e),s++,s>=a&&(s=0)}if(r===i)break}}function Vu(e,t,n,r,i,a,o,s,c){let l=i.length/2,u=o&&s&&c;if(lWs.MAX_VERTEX_ARRAY_LENGTH&&(l=e.createNewSegment(t,n),c=s.count,h=!0,g=!0,_=!0,u=0);let y=Hu(o,r,a,s,f,h,l),b=Hu(o,r,a,s,p,g,l),x=Hu(o,r,a,s,m,_,l);n.emplaceBack(u+y-c,u+b-c,u+x-c),l.primitiveLength++}}function Wu(e,t,n,r,i,a){let o=[];for(let e=0;eWs.MAX_VERTEX_ARRAY_LENGTH&&(l=e.createNewSegment(t,n),c=s.count,m=!0,h=!0,u=0);let _=Hu(o,r,a,s,f,m,l),v=Hu(o,r,a,s,p,h,l);n.emplaceBack(u+_-c,u+v-c),l.primitiveLength++}}var Gu=class{constructor(e){this.zoom=e.zoom,this.overscaling=e.overscaling,this.layers=e.layers,this.layerIds=this.layers.map(e=>e.id),this.index=e.index,this.hasDependencies=!1,this.sdfPatterns={},this.patternFeatures=[],this.layoutVertexArray=new ks,this.indexArray=new Bs,this.indexArray2=new Vs,this.programConfigurations=new mc(e.layers,e.zoom),this.segments=new Ws,this.segments2=new Ws,this.stateDependentLayerIds=this.layers.filter(e=>e.isStateDependent()).map(e=>e.id)}populate(e,t,n){this.hasDependencies=Ml(`fill`,this.layers,t);let r=this.layers[0].layout.get(`fill-sort-key`),i=!r.isConstant(),a=[],o=new K(this.zoom),s=this.layers[0]._featureFilter.needGeometry;for(let{feature:c,id:l,index:u,sourceLayerIndex:d}of e){let e=xc(c,s);if(!this.layers[0]._featureFilter.filter(o,e,n))continue;let f=i?r.evaluate(e,{},n,t.availableImages):void 0,p={id:l,properties:c.properties,type:c.type,sourceLayerIndex:d,index:u,geometry:s?e.geometry:bc(c),patterns:{},sortKey:f};a.push(p)}i&&a.sort((e,t)=>e.sortKey-t.sortKey);for(let r of a){let{geometry:i,index:a,sourceLayerIndex:o}=r;if(this.hasDependencies){let e=Nl(`fill`,this.layers,r,{zoom:this.zoom},t);this.patternFeatures.push(e)}else this.addFeature(r,i,a,n,{},t.subdivisionGranularity);let s=e[a].feature;t.featureIndex.insert(s,i,a,o,this.index)}}update(e,t,n){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(e,t,this.stateDependentLayers,{imagePositions:n})}addFeatures({options:e,canonical:t,patternPositions:n,patternMap:r}){this.detectSdfPatterns(r);for(let r of this.patternFeatures)this.addFeature(r,r.geometry,r.index,t,n,e.subdivisionGranularity)}detectSdfPatterns(e){for(let t of this.patternFeatures)for(let n in t.patterns){let r=t.patterns[n];this.recordSdfPattern(n,e[r.min]),this.recordSdfPattern(n,e[r.mid]),this.recordSdfPattern(n,e[r.max])}for(let t of this.layers){let n=t.paint.get(`fill-pattern`).constantOr(null);n&&(this.recordSdfPattern(t.id,e[n.from.toString()]),this.recordSdfPattern(t.id,e[n.to.toString()]))}}recordSdfPattern(e,t){if(!t)return;let n=t.sdf===!0,r=this.sdfPatterns[e];r===void 0?this.sdfPatterns[e]=n:r!==n&&j(`Style sheet warning: Cannot mix SDF and non-SDF fill patterns in layer "${e}"`)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(e){this.uploaded||(this.layoutVertexBuffer=e.createVertexBuffer(this.layoutVertexArray,jl),this.indexBuffer=e.createIndexBuffer(this.indexArray),this.indexBuffer2=e.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(e),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy())}addFeature(e,t,n,r,i,a){for(let e of Bt(t,500)){let t=Pu(e,r,a.fill.getGranularityForZoomLevel(r.z)),n=this.layoutVertexArray;Vu((e,t)=>{n.emplaceBack(e,t)},this.segments,this.layoutVertexArray,this.indexArray,t.verticesFlattened,t.indicesTriangles,this.segments2,this.indexArray2,t.indicesLineList)}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,e,n,{imagePositions:i,canonical:r})}};G(`FillBucket`,Gu,{omit:[`layers`,`patternFeatures`]});let Ku;const qu=()=>Ku||=new Fo({"fill-sort-key":new J(N.layout_fill[`fill-sort-key`],`fill-sort-key`)});let Ju;const Yu=()=>Ju||=new Fo({"fill-antialias":new q(N.paint_fill[`fill-antialias`],`fill-antialias`),"fill-opacity":new J(N.paint_fill[`fill-opacity`],`fill-opacity`),"fill-layer-opacity":new q(N.paint_fill[`fill-layer-opacity`],`fill-layer-opacity`),"fill-color":new J(N.paint_fill[`fill-color`],`fill-color`),"fill-outline-color":new J(N.paint_fill[`fill-outline-color`],`fill-outline-color`),"fill-translate":new q(N.paint_fill[`fill-translate`],`fill-translate`),"fill-translate-anchor":new q(N.paint_fill[`fill-translate-anchor`],`fill-translate-anchor`),"fill-pattern":new Mo(N.paint_fill[`fill-pattern`],`fill-pattern`)});var Xu={get paint(){return Yu()},get layout(){return qu()}},Zu=class extends Ro{constructor(e,t){super(e,Xu,t)}recalculate(e,t){super.recalculate(e,t);let n=this.paint._values[`fill-outline-color`];n.value.kind===`constant`&&n.value.value===void 0&&(this.paint._values[`fill-outline-color`]=this.paint._values[`fill-color`])}createBucket(e){return new Gu(e)}queryRadius(){return Uc(this.paint.get(`fill-translate`))}queryIntersectsFeature({queryGeometry:e,geometry:t,transform:n,pixelsToTileUnits:r}){return jc(Wc(e,this.paint.get(`fill-translate`),this.paint.get(`fill-translate-anchor`),-n.bearingInRadians,r),t)}isTileClipped(){return!0}};const Qu=Ho([{name:`a_pos`,components:2,type:`Int16`},{name:`a_normal_ed`,components:4,type:`Int16`}],4),$u=Ho([{name:`a_centroid`,components:2,type:`Int16`}],4),ed=Qu.members;Qu.size,Qu.alignment;var td=class{constructor(e,t,n,r,i){for(this.properties=Object.create(null),this.extent=n,this.type=0,this.id=void 0,this._pbf=e,this._geometry=-1,this._keys=r,this._values=i;e.pos>3,a===0)continue}if(a--,i===1)o+=e.readSVarint(),s+=e.readSVarint(),r&&n.push(r),r=[new l(o,s)];else if(i===2)o+=e.readSVarint(),s+=e.readSVarint(),r&&r.push(new l(o,s));else if(i===7)r&&r.push(r[0].clone());else throw Error(`unknown command ${i}`)}return r&&n.push(r),n}bbox(){if(this._geometry<0)throw Error(`feature has no geometry`);let e=this._pbf;e.pos=this._geometry;let t=e.readVarint()+e.pos,n=1,r=0,i=0,a=0,o=1/0,s=-1/0,c=1/0,l=-1/0;for(;e.pos>3,r===0)continue}if(r--,n===1||n===2)i+=e.readSVarint(),a+=e.readSVarint(),is&&(s=i),al&&(l=a);else if(n!==7)throw Error(`unknown command ${n}`)}return[o,c,s,l]}toGeoJSON(e,t,n){let r=this.extent*2**n,i=this.extent*e,a=this.extent*t,o=this.loadGeometry();function s(e){return[(e.x+i)*360/r-180,360/Math.PI*Math.atan(Math.exp((1-(e.y+a)*2/r)*Math.PI))-90]}function c(e){return e.map(s)}let l;if(this.type===1){let e=[];for(let t of o)e.push(t[0]);let t=c(e);l=e.length===1?{type:`Point`,coordinates:t[0]}:{type:`MultiPoint`,coordinates:t}}else if(this.type===2){let e=o.map(c);l=e.length===1?{type:`LineString`,coordinates:e[0]}:{type:`MultiLineString`,coordinates:e}}else if(this.type===3){let e=nd(o),t=[];for(let n of e)t.push(n.map(c));l=t.length===1?{type:`Polygon`,coordinates:t[0]}:{type:`MultiPolygon`,coordinates:t}}else throw Error(`unknown feature type`);let u={type:`Feature`,geometry:l,properties:this.properties};return this.id!=null&&(u.id=this.id),u}};td.types=[`Unknown`,`Point`,`LineString`,`Polygon`];function nd(e){let t=e.length;if(t<=1)return[e];let n=[],r,i;for(let a=0;a=this._features.length)throw Error(`feature index out of bounds`);this._pbf.pos=this._features[e];let t=this._pbf.readVarint()+this._pbf.pos;return new td(this._pbf,t,this.extent,this._keys,this._values)}};function ad(e){let t=null,n=e.readVarint()+e.pos;for(;e.pos90||this.lat<-90)throw Error(`Invalid LngLat latitude value: must be between -90 and 90`)}wrap(){return new e(C(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(e){let t=Math.PI/180,n=this.lat*t,r=e.lat*t,i=Math.sin(n)*Math.sin(r)+Math.cos(n)*Math.cos(r)*Math.cos((e.lng-this.lng)*t);return sd*Math.acos(Math.min(i,1))}static convert(t){if(t instanceof e)return t;if(Array.isArray(t)&&(t.length===2||t.length===3))return new e(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&typeof t==`object`&&t)return new e(Number(`lng`in t?t.lng:t.lon),Number(t.lat));throw Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}};const ld=6378137,ud={origin:[-Math.PI*ld,Math.PI*ld],extentAtZoom0:2*Math.PI*ld},dd=2*Math.PI*sd;function fd(e){return dd*Math.cos(e*Math.PI/180)}function pd(e){return(180+e)/360}function md(e){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+e*Math.PI/360)))/360}function hd(e,t){return e/fd(t)}function gd(e){return e*360-180}function _d(e){let t=180-e*360;return 360/Math.PI*Math.atan(Math.exp(t*Math.PI/180))-90}function vd(e,t){return e*fd(_d(t))}function yd(e){return 1/Math.cos(e*Math.PI/180)}var bd=class e{constructor(e,t,n=0){this.x=+e,this.y=+t,this.z=+n}static fromLngLat(t,n=0){let r=cd.convert(t);return new e(pd(r.lng),md(r.lat),hd(n,r.lat))}toLngLat(){return new cd(gd(this.x),_d(this.y))}toAltitude(){return vd(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/dd*yd(_d(this.y))}};const xd=new class{constructor(){this.name=`mercator`,this.wraps=!0,this.tileMatrixSet=ud}worldFromLngLat(e,t,n){return new bd(pd(e),md(t),n===void 0?0:hd(n,t))}lngLatFromWorld(e,t){return new cd(gd(e),_d(t))}hasLngLat(e,t){return!0}metersPerWorldUnit(e,t){return 1/(1/dd*yd(_d(t)))}worldZFromAltitude(e,t){return hd(e,t.lat)}};function Sd(e,t,n){let r=1/(1<kd(e,t))}function Td(e,t){let n=Cd(v/2,v/2,t),r=bd.fromLngLat(n).meterInMercatorCoordinateUnits(),i=(1<0;t.push(i?r._perp():null)}let n=e.length-1,r=n>1&&e[0].equals(e[n]),i=[null];for(let e=1;e<=n;e++){let a=t[e];if(!a){i.push(null);continue}let o=r&&e===1?t[n]:t[e-1],s=r&&e===n?t[1]:t[e+1];i.push({start:Od(a,o),end:Od(a,s)})}return i}function Od(e,t){if(!t)return e.unit();let n=e.mag(),r=t.mag();return e.x*t.x+e.y*t.y=2*r?e.unit():r>=2*n?t.unit():e.add(t)._unit()}function kd(e,t){if(!e||e.length<3)return e;let n=e[0].x===e[e.length-1].x&&e[0].y===e[e.length-1].y,r=n?e.length-1:e.length;if(r<3)return e;let i=[],a=Cc(e[r-1],e[0]);for(let n=0;n1&&t[0].x===t[t.length-1].x&&t[0].y===t[t.length-1].y;)t.pop();return t}function jd(e,t,n,r,i){let a=t.sub(n),o=r.sub(n),s=a.mag(),c=o.mag();if(s<1e-6||c<1e-6){e.push(n.clone());return}a._div(s),o._div(c);let l=a.x*o.x+a.y*o.y;if(Math.abs(l)>Math.cos(5*Math.PI/180)){e.push(n.clone());return}let u=.2,d=Math.min(i,s*u,c*u),f=n.add(a.mult(d)),p=n.add(o.mult(d)),m=Math.sqrt((1+l)/2),h=n.add(a.add(o)._unit()._mult(d/m)),g=f.sub(h).angleWith(p.sub(h)),_=Math.max(2,Math.ceil(Math.abs(g)/(Math.PI/6)-1e-6));for(let t=0;t<=_;t++)e.push(f.rotateAround(t/_*g,h))}const Md=8192;function Nd(e,t,n,r,i,a,o,s){e.emplaceBack(t,n,Math.floor(r*Md)*2+o,i*Md*2,a*Md*2,Math.round(s))}var Pd=class{constructor(e){this.zoom=e.zoom,this.overscaling=e.overscaling,this.layers=e.layers,this.layerIds=this.layers.map(e=>e.id),this.index=e.index,this.hasDependencies=!1,this.layoutVertexArray=new As,this.centroidVertexArray=new Ds,this.indexArray=new Bs,this.programConfigurations=new mc(e.layers,e.zoom),this.segments=new Ws,this.stateDependentLayerIds=this.layers.filter(e=>e.isStateDependent()).map(e=>e.id)}populate(e,t,n){this.features=[],this.hasDependencies=Ml(`fill-extrusion`,this.layers,t);let r=new K(this.zoom),i=this.layers[0],a=i.layout.get(`fill-extrusion-rounded-corner-distance`),o=a>0?Td(a,n):0,s=i._featureFilter.needGeometry;for(let{feature:a,id:c,index:l,sourceLayerIndex:u}of e){let e=xc(a,s);if(!i._featureFilter.filter(r,e,n))continue;let d={id:c,sourceLayerIndex:u,index:l,geometry:wd(s?e.geometry:bc(a),o),properties:a.properties,type:a.type,patterns:{}};this.hasDependencies?this.features.push(Nl(`fill-extrusion`,this.layers,d,{zoom:this.zoom},t)):this.addFeature(d,d.geometry,l,n,{},t.subdivisionGranularity),t.featureIndex.insert(a,d.geometry,l,u,this.index,!0)}}addFeatures({options:e,canonical:t,patternPositions:n}){for(let r of this.features){let{geometry:i}=r;this.addFeature(r,i,r.index,t,n,e.subdivisionGranularity)}}update(e,t,n){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(e,t,this.stateDependentLayers,{imagePositions:n})}isEmpty(){return this.layoutVertexArray.length===0&&this.centroidVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(e){this.uploaded||(this.layoutVertexBuffer=e.createVertexBuffer(this.layoutVertexArray,ed),this.centroidVertexBuffer=e.createVertexBuffer(this.centroidVertexArray,$u.members,!0),this.indexBuffer=e.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(e),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy())}addFeature(e,t,n,r,i,a){for(let n of Bt(t,500)){let t={x:0,y:0,sampleCount:0},i=this.layoutVertexArray.length;this.processPolygon(t,r,e,n,a);let o=this.layoutVertexArray.length-i,s=Math.floor(t.x/t.sampleCount),c=Math.floor(t.y/t.sampleCount);for(let e=0;e{Nd(l,e,t,0,0,1,1,0)},this.segments,this.layoutVertexArray,this.indexArray,c.verticesFlattened,c.indicesTriangles)}_generateSideFaces(e,t){let n=0,r=this.layers[0].layout.get(`fill-extrusion-rounded-corner-distance`)>0?Dd(e):null;for(let i=1;iWs.MAX_VERTEX_ARRAY_LENGTH&&(t.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));let s=a.sub(o)._perp()._unit(),{start:c,end:l}=r?r[i]:{start:s,end:s},u=o.dist(a);n+u>32768&&(n=0),Nd(this.layoutVertexArray,a.x,a.y,l.x,l.y,0,0,n),Nd(this.layoutVertexArray,a.x,a.y,l.x,l.y,0,1,n),n+=u,Nd(this.layoutVertexArray,o.x,o.y,c.x,c.y,0,0,n),Nd(this.layoutVertexArray,o.x,o.y,c.x,c.y,0,1,n);let d=t.segment.vertexLength;this.indexArray.emplaceBack(d,d+2,d+1),this.indexArray.emplaceBack(d+1,d+2,d+3),t.segment.vertexLength+=4,t.segment.primitiveLength+=2}}};function Fd(e,t){for(let n=0;nId||=new Fo({"fill-extrusion-rounded-corner-distance":new q(N[`layout_fill-extrusion`][`fill-extrusion-rounded-corner-distance`],`fill-extrusion-rounded-corner-distance`)});let Rd;const zd=()=>Rd||=new Fo({"fill-extrusion-opacity":new q(N[`paint_fill-extrusion`][`fill-extrusion-opacity`],`fill-extrusion-opacity`),"fill-extrusion-color":new J(N[`paint_fill-extrusion`][`fill-extrusion-color`],`fill-extrusion-color`),"fill-extrusion-translate":new q(N[`paint_fill-extrusion`][`fill-extrusion-translate`],`fill-extrusion-translate`),"fill-extrusion-translate-anchor":new q(N[`paint_fill-extrusion`][`fill-extrusion-translate-anchor`],`fill-extrusion-translate-anchor`),"fill-extrusion-pattern":new Mo(N[`paint_fill-extrusion`][`fill-extrusion-pattern`],`fill-extrusion-pattern`),"fill-extrusion-height":new J(N[`paint_fill-extrusion`][`fill-extrusion-height`],`fill-extrusion-height`),"fill-extrusion-base":new J(N[`paint_fill-extrusion`][`fill-extrusion-base`],`fill-extrusion-base`),"fill-extrusion-vertical-gradient":new q(N[`paint_fill-extrusion`][`fill-extrusion-vertical-gradient`],`fill-extrusion-vertical-gradient`)});var Bd={get paint(){return zd()},get layout(){return Ld()}},Vd=class extends Ro{constructor(e,t){super(e,Bd,t)}createBucket(e){return new Pd(e)}queryRadius(){return Uc(this.paint.get(`fill-extrusion-translate`))}is3D(){return!0}queryIntersectsFeature({queryGeometry:e,feature:t,featureState:n,geometry:r,transform:i,pixelsToTileUnits:a,pixelPosMatrix:o}){let s=Wc(e,this.paint.get(`fill-extrusion-translate`),this.paint.get(`fill-extrusion-translate-anchor`),-i.bearingInRadians,a),c=this.paint.get(`fill-extrusion-height`).evaluate(t,n),l=this.paint.get(`fill-extrusion-base`).evaluate(t,n),u=Kd(s,o,0),d=Gd(r,l,c,o),f=d[0],p=d[1];return Wd(f,p,u)}};function Hd(e,t){return e.x*t.x+e.y*t.y}function Ud(e,t){if(e.length===1){let n=0,r=t[n++],i;for(;!i||r.equals(i);)if(i=t[n++],!i)return 1/0;for(;n>1),s=n-t,c,l=e[t],u=e[t+1],d=e[n],f=e[n+1];for(let r=t+3;ra)c=r,a=t;else if(t===a){let e=Math.abs(r-o);er&&(e[c+2]=a,c-t>3&&i.push(t,c),n-c>3&&i.push(c,n))}function Yd(e,t,n,r,i,a){let o=i-n,s=a-r;if(o!==0||s!==0){let c=((e-n)*o+(t-r)*s)/(o*o+s*s);c>1?(n=i,r=a):c>0&&(n+=o*c,r+=s*c)}return o=e-n,s=t-r,o*o+s*s}function Xd(e,t,n,r){let i={type:t,geom:n},a={id:e??null,type:i.type,geometry:i.geom,tags:r,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};switch(i.type){case`Point`:case`MultiPoint`:Qd(a,i.geom);break;case`LineString`:Qd(a,i.geom.points);break;case`Polygon`:Qd(a,i.geom[0].points);break;case`MultiLineString`:for(let e of i.geom)Qd(a,e.points);break;case`MultiPolygon`:for(let e of i.geom)Qd(a,e[0].points)}return a}function Zd(e){let t=e;e.points.length>64&&(t.points=new Float64Array(e.points))}function Qd(e,t){for(let n=0;n1?1:n}unprojectX(e){return(e-.5)*360}unprojectY(e){let t=(180-e*360)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}},ef=class{projectX(e){return e}projectY(e){return e}unprojectX(e){return e}unprojectY(e){return e}};const tf=new $d,nf=new ef;function rf(e){return e===`unitSquare`?nf:tf}function af(e,t,n){let r=[];switch(e.type){case`FeatureCollection`:for(let i=0;ia?r.delete(o):r.set(o,{...t,id:o}))}function sf(e,t,n,r,i=0){if(!t.geometry)return;if(i>1024)throw Error(`GeometryCollection nesting exceeds supported depth: 1024`);if(t.geometry.type===`GeometryCollection`){lf(e,t,t.geometry,n,r,i+1);return}if(!t.geometry.coordinates?.length)return;let a=cf(t,n,r),o=(n.tolerance/((1<0&&(s+=r?(a*l-c*o)/2:Math.sqrt((c-a)**2+(l-o)**2)),a=c,o=l}let c=t.points.length-3;t.points[2]=1,n>0&&qd(t.points,0,c,n),t.points[c+2]=1,Zd(t),t.size=Math.abs(s),t.start=0,t.end=t.size}function _f(e,t,n,r,i){for(let a=0;ayf(e,t))}}function yf(e,t=tf){let n={type:`Feature`,geometry:bf(e,t),properties:e.tags};return e.id!=null&&(n.id=e.id),n}function bf(e,t){let{type:n,geometry:r}=e;switch(n){case`Point`:return{type:n,coordinates:Sf(r[0],r[1],t)};case`MultiPoint`:return{type:n,coordinates:xf(r,t)};case`LineString`:return{type:n,coordinates:xf(r.points,t)};case`MultiLineString`:case`Polygon`:return{type:n,coordinates:r.map(e=>xf(e.points,t))};case`MultiPolygon`:return{type:n,coordinates:r.map(e=>e.map(e=>xf(e.points,t)))}}}function xf(e,t=tf){let n=[];for(let r=0;r=n&&o=r)return null;let c=[];for(let t of e){let e=i===0?t.minX:t.minY,a=i===0?t.maxX:t.maxY;if(e>=n&&a=r))switch(t.type){case`Point`:case`MultiPoint`:wf(t,c,n,r,i);continue;case`LineString`:Tf(t,c,n,r,i,s);continue;case`MultiLineString`:Ef(t,c,n,r,i);continue;case`Polygon`:Df(t,c,n,r,i);continue;case`MultiPolygon`:Of(t,c,n,r,i);continue}}return c.length?c:null}function wf(e,t,n,r,i){let a=[];if(kf(e.geometry,a,n,r,i),!a.length)return;let o=a.length===3?`Point`:`MultiPoint`;t.push(Xd(e.id,o,a,e.tags))}function Tf(e,t,n,r,i,a){let o=[];if(Af(e.geometry,o,n,r,i,!1,a.lineMetrics),o.length){if(a.lineMetrics)for(let n of o)t.push(Xd(e.id,`LineString`,n,e.tags));else o.length>1?t.push(Xd(e.id,`MultiLineString`,o,e.tags)):t.push(Xd(e.id,`LineString`,o[0],e.tags))}}function Ef(e,t,n,r,i){let a=[];Mf(e.geometry,a,n,r,i,!1),a.length&&(a.length===1?t.push(Xd(e.id,`LineString`,a[0],e.tags)):t.push(Xd(e.id,`MultiLineString`,a,e.tags)))}function Df(e,t,n,r,i){let a=[];Mf(e.geometry,a,n,r,i,!0),a.length&&t.push(Xd(e.id,`Polygon`,a,e.tags))}function Of(e,t,n,r,i){let a=[];for(let t of e.geometry){let e=[];Mf(t,e,n,r,i,!0),e.length&&a.push(e)}a.length&&t.push(Xd(e.id,`MultiPolygon`,a,e.tags))}function kf(e,t,n,r,i){for(let a=0;a=n&&o<=r&&Nf(t,e[a],e[a+1],e[a+2])}}function Af(e,t,n,r,i,a,o){let s=jf(e),c=i===0?Pf:Ff,l=e.start,u,d;for(let f=0;f=n&&(d=c(s,p,m,g,_,n),o&&(s.start=l+u*d)):v>r?y<=r&&(d=c(s,p,m,g,_,r),o&&(s.start=l+u*d)):Nf(s.points,p,m,h),y=n&&(d=c(s,p,m,g,_,n),b=!0),y>r&&v<=r&&(d=c(s,p,m,g,_,r),b=!0),!a&&b&&(o&&(s.end=l+u*d),t.push(s),s=jf(e)),o&&(l+=u)}let f=e.points.length-3,p=e.points[f],m=e.points[f+1],h=e.points[f+2],g=i===0?p:m;g>=n&&g<=r&&Nf(s.points,p,m,h),f=s.points.length-3,a&&f>=3&&(s.points[f]!==s.points[0]||s.points[f+1]!==s.points[1])&&Nf(s.points,s.points[0],s.points[1],s.points[2]),s.points.length&&(Zd(s),t.push(s))}function jf(e){return{points:[],size:e.size,start:e.start,end:e.end}}function Mf(e,t,n,r,i,a){for(let o of e)Af(o,t,n,r,i,a,!1)}function Nf(e,t,n,r){e.push(t,n,r)}function Pf(e,t,n,r,i,a){let o=(a-t)/(r-t);return Nf(e.points,a,n+(i-n)*o,1),o}function Ff(e,t,n,r,i,a){let o=(a-n)/(i-n);return Nf(e.points,t+(r-t)*o,a,1),o}function If(e,t){if(!t.wrap)return e;let n=t.buffer/t.extent,r=e,i=Cf(e,1,-1-n,n,0,-1,2,t),a=Cf(e,1,1-n,2+n,0,-1,2,t);return!i&&!a||(r=Cf(e,1,-n,1+n,0,-1,2,t)||[],i&&(r=Lf(i,1).concat(r)),a&&(r=r.concat(Lf(a,-1)))),r}function Lf(e,t){let n=[];for(let r of e)switch(r.type){case`Point`:case`MultiPoint`:{let e=Rf(r.geometry,t);n.push(Xd(r.id,r.type,e,r.tags));continue}case`LineString`:{let e=zf(r.geometry,t);n.push(Xd(r.id,r.type,e,r.tags));continue}case`MultiLineString`:case`Polygon`:{let e=[];for(let n of r.geometry)e.push(zf(n,t));n.push(Xd(r.id,r.type,e,r.tags));continue}case`MultiPolygon`:{let e=[];for(let n of r.geometry){let r=[];for(let e of n)r.push(zf(e,t));e.push(r)}n.push(Xd(r.id,r.type,e,r.tags));continue}}return n}function Rf(e,t){let n=[];for(let r=0;re.id));e=e.filter(e=>!n.has(e.id))}if(i.add.size){let t=af({type:`FeatureCollection`,features:Array.from(i.add.values())},n,r);t=If(t,n),a=a.concat(t),e=e.concat(t)}}if(i.update.size){let t=/* @__PURE__ */ new Map,o=[];for(let n of e)i.update.has(n.id)?t.set(n.id,[...t.get(n.id)||[],n]):o.push(n);for(let[e,s]of i.update){let i=t.get(e);if(!i||i.length===0){if(!r?.has(e))continue;let t=Hf(e,s,n,r);a=a.concat(t),o=o.concat(t);continue}let c=Vf(i,s,n,r);a=a.concat(i,c),o=o.concat(c)}e=o}return{affected:a,source:e}}function Vf(e,t,n,r){let i=!!t.newGeometry,a=Wf(t);if(i){let i=e[0],o=a?Gf(i.tags,t):i.tags;return Uf(i.id,t.newGeometry,o,n,r)}if(a){let n=[];for(let r of e){let e={...r};e.tags=Gf(e.tags,t),n.push(e)}return n}return e}function Hf(e,t,n,r){let i=r.get(e),a=Wf(t)?Gf(i.properties,t):i.properties;return t.newGeometry?Uf(e,t.newGeometry,a,n,r):(r.set(e,{...i,properties:a}),[])}function Uf(e,t,n,r,i){return If(af({type:`FeatureCollection`,features:[{type:`Feature`,id:e,geometry:t,properties:n}]},{...r,promoteId:void 0,generateId:!1},i),r)}function Wf(e){return e.removeAllProperties||e.removeProperties?.length>0||e.addOrUpdateProperties?.length>0}function Gf(e,t){if(t.removeAllProperties)return{};let n={...e||{}};if(t.removeProperties)for(let e of t.removeProperties)delete n[e];if(t.addOrUpdateProperties)for(let{key:e,value:r}of t.addOrUpdateProperties)n[e]=r;return n}function Kf(e,t){return e?{removeAll:e.removeAll,remove:new Set(e.remove||[]),add:new Map(e.add?.map(e=>[t.promoteId?e.properties?.[t.promoteId]:e.id,e])),update:new Map(e.update?.map(e=>[e.id,e]))}:{remove:/* @__PURE__ */ new Set,add:/* @__PURE__ */ new Map,update:/* @__PURE__ */ new Map}}const qf=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Jf=/* @__PURE__ */ new Uint32Array(96);var Yf=class e{static from(t){if(!t||t.byteLength===void 0||t.buffer)throw Error(`Data must be an instance of ArrayBuffer or SharedArrayBuffer.`);let[n,r]=new Uint8Array(t,0,2);if(n!==219)throw Error(`Data does not appear to be in a KDBush format.`);let i=r>>4;if(i!==1)throw Error(`Got v${i} data when expected v1.`);let a=qf[r&15];if(!a)throw Error(`Unrecognized array type.`);let[o]=new Uint16Array(t,2,1),[s]=new Uint32Array(t,4,1);return new e(s,o,a,void 0,t)}constructor(e,t=64,n=Float64Array,r=ArrayBuffer,i){if(isNaN(e)||e<0)throw Error(`Unexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+t,2),65535),this.ArrayType=n,this.IndexArrayType=e<65536?Uint16Array:Uint32Array;let a=qf.indexOf(this.ArrayType),o=e*2*this.ArrayType.BYTES_PER_ELEMENT,s=e*this.IndexArrayType.BYTES_PER_ELEMENT,c=(8-s%8)%8;if(a<0)throw Error(`Unexpected typed array class: ${n}.`);if(i)this.data=i,this.ids=new this.IndexArrayType(i,8,e),this.coords=new n(i,8+s+c,e*2),this._pos=e*2,this._finished=!0;else{let i=this.data=new r(8+o+s+c);this.ids=new this.IndexArrayType(i,8,e),this.coords=new n(i,8+s+c,e*2),this._pos=0,this._finished=!1,new Uint8Array(i,0,2).set([219,16+a]),new Uint16Array(i,2,1)[0]=t,new Uint32Array(i,4,1)[0]=e}}add(e,t){let n=this._pos>>1;return this.ids[n]=n,this.coords[this._pos++]=e,this.coords[this._pos++]=t,n}finish(){let e=this._pos>>1;if(e!==this.numItems)throw Error(`Added ${e} items when expected ${this.numItems}.`);return Xf(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(e,t,n,r){if(!this._finished)throw Error(`Data not yet indexed - call index.finish().`);let{ids:i,coords:a,nodeSize:o}=this;Jf[0]=0,Jf[1]=i.length-1,Jf[2]=0;let s=3,c=[];for(;s>0;){let l=Jf[--s],u=Jf[--s],d=Jf[--s];if(u-d<=o){for(let o=d;o<=u;o++){let s=a[2*o],l=a[2*o+1];s>=e&&s<=n&&l>=t&&l<=r&&c.push(i[o])}continue}let f=d+u>>1,p=a[2*f],m=a[2*f+1];p>=e&&p<=n&&m>=t&&m<=r&&c.push(i[f]),(l===0?e<=p:t<=m)&&(Jf[s++]=d,Jf[s++]=f-1,Jf[s++]=1-l),(l===0?n>=p:r>=m)&&(Jf[s++]=f+1,Jf[s++]=u,Jf[s++]=1-l)}return c}within(e,t,n){let r=[];return this.withinInto(e,t,n,r),r}withinInto(e,t,n,r){if(!this._finished)throw Error(`Data not yet indexed - call index.finish().`);let{ids:i,coords:a,nodeSize:o}=this;Jf[0]=0,Jf[1]=i.length-1,Jf[2]=0;let s=3,c=0,l=n*n;for(;s>0;){let u=Jf[--s],d=Jf[--s],f=Jf[--s];if(d-f<=o){for(let n=f;n<=d;n++)ep(a[2*n],a[2*n+1],e,t)<=l&&(r[c++]=i[n]);continue}let p=f+d>>1,m=a[2*p],h=a[2*p+1];ep(m,h,e,t)<=l&&(r[c++]=i[p]),(u===0?e-n<=m:t-n<=h)&&(Jf[s++]=f,Jf[s++]=p-1,Jf[s++]=1-u),(u===0?e+n>=m:t+n>=h)&&(Jf[s++]=p+1,Jf[s++]=d,Jf[s++]=1-u)}return c}};function Xf(e,t,n,r,i,a){if(i-r<=n)return;let o=r+i>>1;Zf(e,t,o,r,i,a),Xf(e,t,n,r,o-1,1-a),Xf(e,t,n,o+1,i,1-a)}function Zf(e,t,n,r,i,a){for(;i>r;){if(i-r>600){let o=i-r+1,s=n-r+1,c=Math.log(o),l=.5*Math.exp(2*c/3),u=.5*Math.sqrt(c*l*(o-l)/o)*(s-o/2<0?-1:1);Zf(e,t,n,Math.max(r,Math.floor(n-s*l/o+u)),Math.min(i,Math.floor(n+(o-s)*l/o+u)),a)}let o=t[2*n+a],s=r,c=i;for(Qf(e,t,r,n),t[2*i+a]>o&&Qf(e,t,r,i);so;)c--}t[2*r+a]===o?Qf(e,t,r,c):(c++,Qf(e,t,c,i)),c<=n&&(r=c+1),n<=c&&(i=c-1)}}function Qf(e,t,n,r){$f(e,n,r),$f(t,2*n,2*r),$f(t,2*n+1,2*r+1)}function $f(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}function ep(e,t,n,r){let i=e-n,a=t-r;return i*i+a*a}const tp={minZoom:0,maxZoom:16,minPoints:2,radius:40,extent:512,nodeSize:64,log:!1,generateId:!1,reduce:null,map:e=>e,coordinates:`lngLat`,wrap:!0},np=1073741824;function rp(e){return(e-.5)*np}function ip(e){return e/np+.5}function ap(e){return Math.abs(rp(e))<2147483647}var op=class{constructor(e){this.options=sp(e),this.worldCoordinateHelper=rf(this.options.coordinates),this.trees=Array(this.options.maxZoom+1),this.stride=this.options.reduce?5:4,this.clusterProps=[],this.points=[]}load(e){let t=[];for(let n of e){if(!n.geometry)continue;let e=n.geometry.type===`MultiPoint`?n.geometry.coordinates:[n.geometry.coordinates];for(let[r,i]of e){let[e,a]=[this.worldCoordinateHelper.projectX(r),this.worldCoordinateHelper.projectY(i)];if(!this.options.wrap&&!dp([e,a]))continue;let o={id:n.id,type:`Point`,geometry:[e,a],tags:n.properties};t.push(o)}}this.createIndex(t)}initialize(e){let t=[];for(let n of e)if(n.type===`Point`){if(!this.options.wrap&&!dp(n.geometry))continue;t.push(n)}else if(n.type===`MultiPoint`)for(let e=0;e=n;e--){let n=Date.now(),r=this.cluster(u,e,d,f);this.isSameAsTree(u,f,r)||(u=this.createTree(d.slice(0,r*2),f.slice(0,r*a),r)),this.trees[e]=u,t&&console.log(`z%d: %d clusters in %dms`,e,u.numItems,Date.now()-n)}t&&console.timeEnd(`total time`)}getClusters(e,t){return(this.options.wrap?this.options.coordinates===`unitSquare`?this.getClustersAcrossEdge(e,t):this.getClustersInternal(e,t):this.getClustersInWorld(e,t)).map(e=>yf(e,this.worldCoordinateHelper))}getClustersInWorld(e,t){let n=this.options.coordinates!==`unitSquare`,r=this.worldCoordinateHelper.projectY(n?Math.max(-90,Math.min(90,e[1])):e[1]),i=this.worldCoordinateHelper.projectY(n?Math.max(-90,Math.min(90,e[3])):e[3]),a=Math.max(0,this.worldCoordinateHelper.projectX(e[0])),o=Math.min(1,this.worldCoordinateHelper.projectX(e[2]));return a>o?[]:this.getClustersInRange([a,Math.min(r,i),o,Math.max(r,i)],t)}getClustersAcrossEdge([e,t,n,r],i){if(n=1)return this.getClustersInRange([0,t,1,r],i);let a=Math.floor(e),o=e-a,s=n-a;return s<=1?this.getClustersInRange([o,t,s,r],i):this.getClustersInRange([o,t,1,r],i).concat(this.getClustersInRange([0,t,s-1,r],i))}getClustersInternal(e,t){let n=((e[0]+180)%360+360)%360-180,r=Math.max(-90,Math.min(90,e[1])),i=e[2]===180?180:((e[2]+180)%360+360)%360-180,a=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)n=-180,i=180;else if(n>i){let e=this.getClustersInternal([n,r,180,a],t),o=this.getClustersInternal([-180,r,i,a],t);return e.concat(o)}return this.getClustersInRange([this.worldCoordinateHelper.projectX(n),this.worldCoordinateHelper.projectY(a),this.worldCoordinateHelper.projectX(i),this.worldCoordinateHelper.projectY(r)],t)}getClustersInRange([e,t,n,r],i){let a=this.trees[this.limitZoom(i)],o=a.range(rp(e),rp(t),rp(n),rp(r)),s=a.flatCoords,c=a.flatData,l=[];for(let e of o){let t=this.stride*e;l.push(c[t+3]>1?cp(s,e,c,t,this.clusterProps):this.points[c[t+1]])}return l}getChildren(e){let t=this.getOriginId(e),n=this.getOriginZoom(e),r=/* @__PURE__ */ Error(`No cluster with the specified id: `+e),i=this.trees[n];if(!i)throw r;let a=i.flatCoords,o=i.flatData;if(t>=i.numItems)throw r;let s=this.options.radius/(this.options.extent*2**(n-1))*np,c=a[t*2],l=a[t*2+1],u=i.within(c,l,s),d=[];for(let t of u){let n=t*this.stride;o[n+2]===e&&d.push(o[n+3]>1?lp(a,t,o,n,this.clusterProps,this.worldCoordinateHelper):yf(this.points[o[n+1]],this.worldCoordinateHelper))}if(d.length===0)throw r;return d}getLeaves(e,t,n){t||=10,n||=0;let r=[];return this.appendLeaves(r,e,t,n,0),r}getTile(e,t,n){let r=this.trees[this.limitZoom(e)];if(!r)return null;let i=2**e;if(!this.options.wrap&&(t<0||t>=i||n<0||n>=i))return null;let{extent:a,radius:o}=this.options,s=o/a,c=rp((n-s)/i),l=rp((n+1+s)/i),u={transformed:!0,features:[],source:null,x:t,y:n,z:e};return this.addTileFeatures(r.range(rp((t-s)/i),c,rp((t+1+s)/i),l),r,t,n,i,u),this.options.wrap&&t===0&&this.addTileFeatures(r.range(rp(1-s/i),c,rp(1),l),r,i,n,i,u),this.options.wrap&&t===i-1&&this.addTileFeatures(r.range(rp(0),c,rp(s/i),l),r,-1,n,i,u),u}getClusterExpansionZoom(e){return this.getOriginZoom(e)}appendLeaves(e,t,n,r,i){let a=this.getChildren(t);for(let t of a){let a=t.properties;if(a?.cluster?i+a.point_count<=r?i+=a.point_count:i=this.appendLeaves(e,a.cluster_id,n,r,i):i1,l,u,d;if(c)l=up(s,e,this.clusterProps),u=ip(o[t*2]),d=ip(o[t*2+1]);else{let t=this.points[s[e+1]];l=t.tags,[u,d]=t.geometry}let f={type:1,geometry:[[Math.round(this.options.extent*(u*i-n)),Math.round(this.options.extent*(d*i-r))]],tags:l},p;p=c||this.options.generateId?s[e+1]:this.points[s[e+1]].id,p!==void 0&&(f.id=p),a.features.push(f)}}limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}cluster(e,t,n,r){let{radius:i,extent:a,reduce:o,minPoints:s,maxZoom:c}=this.options,l=i/(a*2**t)*np,u=c+1,d=e.flatCoords,f=e.flatData,p=this.stride,m=new Uint32Array(e.numItems),h=0;for(let i=0;it&&(y+=f[n+3])}if(y>v&&y>=s){let e=c*v,s=g*v,l,b=-1,x=(i<<5)+(t+1)+this.points.length;for(let n=0;n<_;n++){let r=m[n],i=r*p;if(f[i+0]<=t)continue;f[i+0]=t;let c=f[i+3];e+=d[r*2]*c,s+=d[r*2+1]*c,f[i+2]=x,o&&(l||(l=this.map(f,a,!0),b=this.clusterProps.length,this.clusterProps.push(l)),o(l,this.map(f,i)))}f[a+2]=x,n[h*2]=Math.round(e/y),n[h*2+1]=Math.round(s/y);let S=h*p;r[S+0]=u,r[S+1]=x,r[S+2]=-1,r[S+3]=y,o&&(r[S+4]=b),h++}else{n[h*2]=c,n[h*2+1]=g;for(let e=0;e1)for(let e=0;e<_;e++){let i=m[e],a=i*p;if(!(f[a+0]<=t)){f[a+0]=t,n[h*2]=d[i*2],n[h*2+1]=d[i*2+1];for(let e=0;e
>5}getOriginZoom(e){return(e-this.points.length)%32}map(e,t,n){if(e[t+3]>1){let r=this.clusterProps[e[t+4]];return n?Object.assign({},r):r}let r=this.points[e[t+1]].tags,i=this.options.map(r);return n&&i===r?Object.assign({},i):i}};function sp(e){let t=Object.assign(Object.create(tp),e);return t.minZoom=Math.min(t.minZoom,30),t.maxZoom=Math.min(t.maxZoom,30),t}function cp(e,t,n,r,i){return{id:n[r+1],type:`Point`,tags:up(n,r,i),geometry:[ip(e[t*2]),ip(e[t*2+1])]}}function lp(e,t,n,r,i,a){return{type:`Feature`,id:n[r+1],properties:up(n,r,i),geometry:{type:`Point`,coordinates:[a.unprojectX(ip(e[t*2])),a.unprojectY(ip(e[t*2+1]))]}}}function up(e,t,n){let r=e[t+3],i=r>=1e4?`${Math.round(r/1e3)}k`:r>=1e3?`${Math.round(r/100)/10}k`:r,a=e[t+4],o=a===-1?{}:Object.assign({},n[a]);return Object.assign(o,{cluster:!0,cluster_id:e[t+1],point_count:r,point_count_abbreviated:i})}function dp(e){return e[0]>=0&&e[0]<=1&&e[1]>=0&&e[1]<=1}const fp=`geojsonvt_clip_start`,pp=`geojsonvt_clip_end`;function mp(e,t,n,r,i){let a=t===i.maxZoom?0:i.tolerance/((1<0&&t.size<(i?o:r)){n.numPoints+=t.points.length/3;return}let s=[];for(let e=0;eo)&&(n.numSimplified++,s.push(t.points[e],t.points[e+1])),n.numPoints++;i&&xp(s,a),e.push(s)}function xp(e,t){let n=0;for(let t=0,r=e.length,i=r-2;t0===t)for(let t=0,n=e.length;t1&&(console.log(`invalidating tiles`),console.time(`invalidating`)),this.invalidateTiles(t),n.debug>1&&console.timeEnd(`invalidating`);let[r,i,a]=[0,0,0],o=this.clipToWorld(e),s=mp(o,r,i,a,n);s.source=o;let c=Dp(r,i,a);if(this.tiles[c]=s,this.tileCoords.push({z:r,x:i,y:a,id:c}),n.debug){let e=`z${r}`;this.stats[e]=(this.stats[e]||0)+1,this.total++}}getClusterExpansionZoom(e){return null}getChildren(e){return null}getLeaves(e,t,n){return null}getTile(e,t,n){let{extent:r,debug:i}=this.options,a=1<=a))return null;t=t+a&a-1;let o=Dp(e,t,n);if(this.tiles[o])return Sp(this.tiles[o],r);i>1&&console.log(`drilling down to z%d-%d-%d`,e,t,n);let s=e,c=t,l=n,u;for(;!u&&s>0;)s--,c>>=1,l>>=1,u=this.tiles[Dp(s,c,l)];return!u?.source||(i>1&&(console.log(`found parent tile z%d-%d-%d`,s,c,l),console.time(`drilling down`)),this.splitTile(u.source,s,c,l,e,t,n),i>1&&console.timeEnd(`drilling down`),!this.tiles[o])?null:Sp(this.tiles[o],r)}clipToWorld(e){let{wrap:t,coordinates:n}=this.options;if(t&&n!==`unitSquare`)return e;let r=this.options.buffer/this.options.extent;return Cf(t?e:Cf(e,1,-r,1+r,0,-1/0,1/0,this.options)||[],1,-r,1+r,1,-1/0,1/0,this.options)||[]}splitTile(e,t,n,r,i,a,o){let s=[e,t,n,r],c=this.options,l=c.debug;for(;s.length;){r=s.pop(),n=s.pop(),t=s.pop(),e=s.pop();let u=1<1&&console.time(`creation`),f=this.tiles[d]=mp(e,t,n,r,c),this.tileCoords.push({z:t,x:n,y:r,id:d}),l)){l>1&&(console.log(`tile z%d-%d-%d (features: %d, points: %d, simplified: %d)`,t,n,r,f.numFeatures,f.numPoints,f.numSimplified),console.timeEnd(`creation`));let e=`z${t}`;this.stats[e]=(this.stats[e]||0)+1,this.total++}if(f.source=e,i==null){if(t===c.indexMaxZoom||f.numPoints<=c.indexMaxPoints)continue}else if(t===c.maxZoom||t===i)continue;else if(i!=null){let e=i-t;if(n!==a>>e||r!==o>>e)continue}if(f.source=null,!e.length)continue;l>1&&console.time(`clipping`);let p=.5*c.buffer/c.extent,m=.5-p,h=.5+p,g=1+p,_=null,v=null,y=null,b=null,x=Cf(e,u,n-p,n+h,0,f.minX,f.maxX,c),S=Cf(e,u,n+m,n+g,0,f.minX,f.maxX,c);x&&(_=Cf(x,u,r-p,r+h,1,f.minY,f.maxY,c),v=Cf(x,u,r+m,r+g,1,f.minY,f.maxY,c)),S&&(y=Cf(S,u,r-p,r+h,1,f.minY,f.maxY,c),b=Cf(S,u,r+m,r+g,1,f.minY,f.maxY,c)),l>1&&console.timeEnd(`clipping`),s.push(_||[],t+1,n*2,r*2),s.push(v||[],t+1,n*2,r*2+1),s.push(y||[],t+1,n*2+1,r*2),s.push(b||[],t+1,n*2+1,r*2+1)}}invalidateTiles(e){if(!e.length)return;let t=this.options,{debug:n}=t,r=1/0,i=-1/0,a=1/0,o=-1/0;for(let t of e)r=Math.min(r,t.minX),i=Math.max(i,t.maxX),a=Math.min(a,t.minY),o=Math.max(o,t.maxY);let s=t.buffer/t.extent,c=/* @__PURE__ */ new Set;for(let t in this.tiles){let l=this.tiles[t],u=1<=f||o=m)continue;let h=!1;for(let t of e)if(t.maxX>=d&&t.minX=p&&t.minY1&&console.log(`invalidate tile z%d-%d-%d (features: %d, points: %d, simplified: %d)`,l.z,l.x,l.y,l.numFeatures,l.numPoints,l.numSimplified);let e=`z${l.z}`;this.stats[e]=(this.stats[e]||0)-1,this.total--}delete this.tiles[t],c.add(t)}}c.size&&(this.tileCoords=this.tileCoords.filter(e=>!c.has(e.id)))}};function Dp(e,t,n){return((1<24)throw Error(`maxZoom should be in the 0-24 range`);if(t.promoteId&&t.generateId)throw Error(`promoteId and generateId cannot be used together.`);t.updateable&&(this.unlocated=/* @__PURE__ */ new Map);let r=af(e,t,this.unlocated);n&&(console.timeEnd(`preprocess data`),console.log(`index: maxZoom: %d, maxPoints: %d`,t.indexMaxZoom,t.indexMaxPoints),console.time(`generate tiles`)),r=If(r,t),t.updateable&&(this.source=r),this.initializeIndex(r,t)}initializeIndex(e,t){this.tileIndex=t.cluster?new op({...t.clusterOptions,coordinates:t.coordinates,wrap:t.wrap}):new Ep(t),e.length&&this.tileIndex.initialize(e)}getTile(e,t,n){return e=+e,t=+t,n=+n,e<0||e>24?null:this.tileIndex.getTile(e,t,n)}updateData(e,t){let n=this.options;if(!n.updateable)throw Error("to update tile geojson `updateable` option must be set to true");let{affected:r,source:i}=Bf(this.source,e,n,this.unlocated);t&&({affected:r,source:i}=this.filterUpdate(i,r,t)),r.length&&(this.source=i,this.tileIndex.updateIndex(i,r,n))}filterUpdate(e,t,n){let r=/* @__PURE__ */ new Set;for(let i of e)i.id!=null&&(n(yf(i,this.worldCoordinateHelper))||(t.push(i),r.add(i.id)));e=e.filter(e=>!r.has(e.id));for(let[e,t]of this.unlocated??[])t.geometry&&!n(t)&&this.unlocated.delete(e);return{affected:t,source:e}}getData(){if(!this.options.updateable)throw Error("to retrieve data the `updateable` option must be set to true");return vf(this.source,this.worldCoordinateHelper)}updateClusterOptions(e,t){let n=this.options.cluster;this.options.cluster=e,this.options.clusterOptions=t,n==e?this.tileIndex.updateIndex(this.source,[],this.options):this.initializeIndex(this.source,this.options)}getClusterExpansionZoom(e){return this.tileIndex.getClusterExpansionZoom(e)}getClusterChildren(e){return this.tileIndex.getChildren(e)}getClusterLeaves(e,t,n){return this.tileIndex.getLeaves(e,t,n)}};const Ap=Ho([{name:`a_pos_normal`,components:2,type:`Int16`},{name:`a_data`,components:4,type:`Uint8`},{name:`a_offset_normal`,components:2,type:`Int8`}],2),jp=Ap.members;Ap.size,Ap.alignment;const Mp=Ho([{name:`a_uv_x`,components:1,type:`Float32`},{name:`a_split_index`,components:1,type:`Float32`}]),Np=Mp.members;Mp.size,Mp.alignment;const Pp=Math.cos(75/2*(Math.PI/180)),Fp=1/2,Ip=2**14/Fp;var Lp=class{constructor(e){this.zoom=e.zoom,this.overscaling=e.overscaling,this.layers=e.layers,this.layerIds=this.layers.map(e=>e.id),this.index=e.index,this.hasDependencies=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={};for(let e of this.layers)this.gradients[e.id]={};this.layoutVertexArray=new js,this.layoutVertexArray2=new Ms,this.indexArray=new Bs,this.programConfigurations=new mc(e.layers,e.zoom),this.segments=new Ws,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter(e=>e.isStateDependent()).map(e=>e.id)}populate(e,t,n){this.hasDependencies=Ml(`line`,this.layers,t)||this.hasLineDasharray(this.layers);let r=this.layers[0].layout.get(`line-sort-key`),i=!r.isConstant(),a=[],o=new K(this.zoom),s=this.layers[0]._featureFilter.needGeometry;for(let{feature:t,id:c,index:l,sourceLayerIndex:u}of e){let e=xc(t,s);if(!this.layers[0]._featureFilter.filter(o,e,n))continue;let d=i?r.evaluate(e,{},n):void 0,f={id:c,properties:t.properties,type:t.type,sourceLayerIndex:u,index:l,geometry:s?e.geometry:bc(t),patterns:{},dashes:{},sortKey:d};a.push(f)}i&&a.sort((e,t)=>e.sortKey-t.sortKey);for(let r of a){let{geometry:i,index:a,sourceLayerIndex:o}=r;this.hasDependencies?(Ml(`line`,this.layers,t)?Nl(`line`,this.layers,r,{zoom:this.zoom},t):this.hasLineDasharray(this.layers)&&this.addLineDashDependencies(this.layers,r,this.zoom,t),this.patternFeatures.push(r)):this.addFeature(r,i,a,n,{},{},t.subdivisionGranularity);let s=e[a].feature;t.featureIndex.insert(s,i,a,o,this.index)}}update(e,t,n,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(e,t,this.stateDependentLayers,{imagePositions:n,dashPositions:r})}addFeatures({options:e,canonical:t,patternPositions:n,dashPositions:r}){for(let i of this.patternFeatures)this.addFeature(i,i.geometry,i.index,t,n,r,e.subdivisionGranularity)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(e){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=e.createVertexBuffer(this.layoutVertexArray2,Np)),this.layoutVertexBuffer=e.createVertexBuffer(this.layoutVertexArray,jp),this.indexBuffer=e.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(e),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(e){if(e.properties&&Object.hasOwn(e.properties,`geojsonvt_clip_start`)&&Object.hasOwn(e.properties,`geojsonvt_clip_end`))return{start:+e.properties[fp],end:+e.properties[pp]}}addFeature(e,t,n,r,i,a,o){let s=this.layers[0].layout,c=s.get(`line-join`).evaluate(e,{}),l=s.get(`line-cap`).evaluate(e,{}),u=s.get(`line-miter-limit`).evaluate(e,{}),d=s.get(`line-round-limit`).evaluate(e,{});this.lineClips=this.lineFeatureClips(e);for(let n of t)this.addLine(n,e,c,l,u,d,r,o);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,e,n,{imagePositions:i,dashPositions:a,canonical:r})}addLine(e,t,n,r,i,a,o,s){this.distance=0,this.scaledDistance=0,this.totalDistance=0;let c=o?s.line.getGranularityForZoomLevel(o.z):1;if(e=Fu(e,c),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let t=0;t=2&&e[u-1].equals(e[u-2]);)u--;let d=0;for(;d0,w=o.mult(Math.min(v,2)),T=S((v-3)/5,0,1);if(x&&t>d){let e=m.dist(h);if(e>2*f){let t=m.sub(m.sub(h)._mult(f/e)._round());this.updateDistance(h,t),this.addCurrentVertex(t,_,0,0,p),h=t}}let E=h&&g,D=E?n:l?`butt`:r;if(E&&D===`round`&&(vi&&(D=`bevel`),D===`bevel`&&(v>2&&(D=`flipbevel`),v100)o=y.mult(-1);else{let e=v*_.add(y).mag()/_.sub(y).mag();o._perp()._mult(e*(C?-1:1))}this.addCurrentVertex(m,o,0,0,p,!1,w,T),this.addCurrentVertex(m,o.mult(-1),0,0,p,!1,w,T)}else if(D===`bevel`||D===`fakeround`){let e=-Math.sqrt(v*v-1),t=C?e:0,n=C?0:e;if(h&&this.addCurrentVertex(m,_,t,n,p,!1,w),D===`fakeround`){let e=Math.round(b*180/Math.PI/20);for(let t=1;t2*f){let t=m.add(g.sub(m)._mult(f/e)._round());this.updateDistance(m,t),this.addCurrentVertex(t,y,0,0,p),m=t}}}}addCurrentVertex(e,t,n,r,i,a=!1,o=t,s=0){let c=t.x+t.y*n,l=t.y-t.x*n,u=-t.x+t.y*r,d=-t.y-t.x*r,f=o.x+(t.x-o.x)*s,p=o.y+(t.y-o.y)*s;this.addHalfVertex(e,c,l,f,p,a,!1,i),this.addHalfVertex(e,u,d,-f,-p,a,!0,i),this.distance>Ip/2&&this.totalDistance===0&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(e,t,n,r,i,a,o,s))}addHalfVertex({x:e,y:t},n,r,i,a,o,s,c){let l=(this.lineClips?this.scaledDistance*(Ip-1):this.scaledDistance)*Fp;if(this.layoutVertexArray.emplaceBack((e<<1)+ +!!o,(t<<1)+ +!!s,Math.round(63*n)+128,Math.round(63*r)+128,(l&63)<<2,l>>6,Math.round(63*i),Math.round(63*a)),this.lineClips){let e=(this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start);this.layoutVertexArray2.emplaceBack(e,this.lineClipsArray.length)}let u=c.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,u,this.e2),c.primitiveLength++),s?this.e2=u:this.e1=u}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance}updateDistance(e,t){this.distance+=e.dist(t),this.updateScaledDistance()}hasLineDasharray(e){for(let t of e){let e=t.paint.get(`line-dasharray`);if(e&&!e.isConstant())return!0}return!1}addLineDashDependencies(e,t,n,r){for(let i of e){let e=i.paint.get(`line-dasharray`);if(!e||e.value.kind===`constant`)continue;let a=i.layout.get(`line-cap`).evaluate(t,{})===`round`,o={dasharray:e.value.evaluate({zoom:n-1},t,{}),round:a},s={dasharray:e.value.evaluate({zoom:n},t,{}),round:a},c={dasharray:e.value.evaluate({zoom:n+1},t,{}),round:a},l=`${o.dasharray.join(`,`)},${o.round}`,u=`${s.dasharray.join(`,`)},${s.round}`,d=`${c.dasharray.join(`,`)},${c.round}`;r.dashDependencies[l]=o,r.dashDependencies[u]=s,r.dashDependencies[d]=c,t.dashes[i.id]={min:l,mid:u,max:d}}}};G(`LineBucket`,Lp,{omit:[`layers`,`patternFeatures`]});let Rp;const zp=()=>Rp||=new Fo({"line-cap":new J(N.layout_line[`line-cap`],`line-cap`),"line-join":new J(N.layout_line[`line-join`],`line-join`),"line-miter-limit":new J(N.layout_line[`line-miter-limit`],`line-miter-limit`),"line-round-limit":new J(N.layout_line[`line-round-limit`],`line-round-limit`),"line-sort-key":new J(N.layout_line[`line-sort-key`],`line-sort-key`)});let Bp;const Vp=()=>Bp||=new Fo({"line-opacity":new J(N.paint_line[`line-opacity`],`line-opacity`),"line-layer-opacity":new q(N.paint_line[`line-layer-opacity`],`line-layer-opacity`),"line-color":new J(N.paint_line[`line-color`],`line-color`),"line-translate":new q(N.paint_line[`line-translate`],`line-translate`),"line-translate-anchor":new q(N.paint_line[`line-translate-anchor`],`line-translate-anchor`),"line-width":new J(N.paint_line[`line-width`],`line-width`),"line-gap-width":new J(N.paint_line[`line-gap-width`],`line-gap-width`),"line-offset":new J(N.paint_line[`line-offset`],`line-offset`),"line-blur":new J(N.paint_line[`line-blur`],`line-blur`),"line-dasharray":new Mo(N.paint_line[`line-dasharray`],`line-dasharray`),"line-pattern":new Mo(N.paint_line[`line-pattern`],`line-pattern`),"line-gradient":new Po(N.paint_line[`line-gradient`],`line-gradient`)});var Hp={get paint(){return Vp()},get layout(){return zp()}},Up=class extends J{possiblyEvaluate(e,t){return t=new K(Math.floor(t.zoom),{now:t.now,fadeDuration:t.fadeDuration,zoomHistory:t.zoomHistory,transition:t.transition}),super.possiblyEvaluate(e,t)}evaluate(e,t,n,r){return t=w({},t,{zoom:Math.floor(t.zoom)}),super.evaluate(e,t,n,r)}};let Wp;var Gp=class extends Ro{constructor(e,t){super(e,Hp,t),this.gradientVersion=0,Wp||(Wp=new Up(Hp.paint.properties[`line-width`].specification,`line-floorwidth`),Wp.useIntegerZoom=!0)}_handleSpecialPaintPropertyUpdate(e){if(e===`line-gradient`){let e=this.gradientExpression();this.stepInterpolant=_i(e)?e._styleExpression.expression instanceof jt:!1,this.gradientVersion=(this.gradientVersion+1)%(2**53-1)}}gradientExpression(){return this._transitionablePaint._values[`line-gradient`].value.expression}recalculate(e,t){super.recalculate(e,t),this.paint._values[`line-floorwidth`]=Wp.possiblyEvaluate(this._transitioningPaint._values[`line-width`].value,e)}createBucket(e){return new Lp(e)}queryRadius(e){let t=e,n=Kp(Hc(`line-width`,this,t),Hc(`line-gap-width`,this,t)),r=Hc(`line-offset`,this,t);return n/2+Math.abs(r)+Uc(this.paint.get(`line-translate`))}queryIntersectsFeature({queryGeometry:e,feature:t,featureState:n,geometry:r,transform:i,pixelsToTileUnits:a}){let o=Wc(e,this.paint.get(`line-translate`),this.paint.get(`line-translate-anchor`),-i.bearingInRadians,a),s=a/2*Kp(this.paint.get(`line-width`).evaluate(t,n),this.paint.get(`line-gap-width`).evaluate(t,n)),c=this.paint.get(`line-offset`).evaluate(t,n);return c&&(r=Kc(r,c*a)),Mc(o,r,s)}isTileClipped(){return!0}};function Kp(e,t){return t>0?t+2*e:e}const qp=Ho([{name:`a_pos_offset`,components:4,type:`Int16`},{name:`a_data`,components:4,type:`Uint16`},{name:`a_pixeloffset`,components:4,type:`Int16`},{name:`a_height_offset`,components:1,type:`Float32`}],4),Jp=Ho([{name:`a_projected_pos`,components:3,type:`Float32`}],4);Ho([{name:`a_fade_opacity`,components:1,type:`Uint32`}],4);const Yp=Ho([{name:`a_placed`,components:2,type:`Uint8`},{name:`a_shift`,components:2,type:`Float32`},{name:`a_box_real`,components:2,type:`Int16`}]);Ho([{type:`Int16`,name:`anchorPointX`},{type:`Int16`,name:`anchorPointY`},{type:`Int16`,name:`x1`},{type:`Int16`,name:`y1`},{type:`Int16`,name:`x2`},{type:`Int16`,name:`y2`},{type:`Uint32`,name:`featureIndex`},{type:`Uint16`,name:`sourceLayerIndex`},{type:`Uint16`,name:`bucketIndex`}]);const Xp=Ho([{name:`a_pos`,components:2,type:`Int16`},{name:`a_anchor_pos`,components:2,type:`Int16`},{name:`a_extrude`,components:2,type:`Int16`}],4);Ho([{name:`a_pos`,components:2,type:`Float32`},{name:`a_radius`,components:1,type:`Float32`},{name:`a_flags`,components:2,type:`Int16`}],4),Ho([{name:`triangle`,components:3,type:`Uint16`}]),Ho([{type:`Int16`,name:`anchorX`},{type:`Int16`,name:`anchorY`},{type:`Uint16`,name:`glyphStartIndex`},{type:`Uint16`,name:`numGlyphs`},{type:`Uint32`,name:`vertexStartIndex`},{type:`Uint32`,name:`lineStartIndex`},{type:`Uint32`,name:`lineLength`},{type:`Uint16`,name:`segment`},{type:`Uint16`,name:`lowerSize`},{type:`Uint16`,name:`upperSize`},{type:`Float32`,name:`lineOffsetX`},{type:`Float32`,name:`lineOffsetY`},{type:`Uint8`,name:`writingMode`},{type:`Uint8`,name:`placedOrientation`},{type:`Uint8`,name:`hidden`},{type:`Uint32`,name:`crossTileID`},{type:`Int16`,name:`associatedIconIndex`},{type:`Float32`,name:`heightOffset`}]),Ho([{type:`Int16`,name:`anchorX`},{type:`Int16`,name:`anchorY`},{type:`Int16`,name:`rightJustifiedTextSymbolIndex`},{type:`Int16`,name:`centerJustifiedTextSymbolIndex`},{type:`Int16`,name:`leftJustifiedTextSymbolIndex`},{type:`Int16`,name:`verticalPlacedTextSymbolIndex`},{type:`Int16`,name:`placedIconSymbolIndex`},{type:`Int16`,name:`verticalPlacedIconSymbolIndex`},{type:`Uint16`,name:`key`},{type:`Uint16`,name:`textBoxStartIndex`},{type:`Uint16`,name:`textBoxEndIndex`},{type:`Uint16`,name:`verticalTextBoxStartIndex`},{type:`Uint16`,name:`verticalTextBoxEndIndex`},{type:`Uint16`,name:`iconBoxStartIndex`},{type:`Uint16`,name:`iconBoxEndIndex`},{type:`Uint16`,name:`verticalIconBoxStartIndex`},{type:`Uint16`,name:`verticalIconBoxEndIndex`},{type:`Uint16`,name:`featureIndex`},{type:`Uint16`,name:`numHorizontalGlyphVertices`},{type:`Uint16`,name:`numVerticalGlyphVertices`},{type:`Uint16`,name:`numIconVertices`},{type:`Uint16`,name:`numVerticalIconVertices`},{type:`Uint16`,name:`useRuntimeCollisionCircles`},{type:`Uint32`,name:`crossTileID`},{type:`Float32`,name:`textBoxScale`},{type:`Float32`,name:`collisionCircleDiameter`},{type:`Uint16`,name:`textAnchorOffsetStartIndex`},{type:`Uint16`,name:`textAnchorOffsetEndIndex`},{type:`Float32`,name:`heightOffset`}]),Ho([{type:`Float32`,name:`offsetX`}]),Ho([{type:`Int16`,name:`x`},{type:`Int16`,name:`y`},{type:`Int16`,name:`tileUnitDistanceFromAnchor`}]),Ho([{type:`Uint16`,name:`textAnchor`},{type:`Float32`,components:2,name:`textOffset`}]);const Zp=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus=`unavailable`,this.pluginURL=null,this.loadScriptResolve=()=>{}}setState(e){this.pluginStatus=e.pluginStatus,this.pluginURL=e.pluginURL}getState(){return{pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(e){if(Zp.isParsed())throw Error(`RTL text plugin already registered.`);this.applyArabicShaping=e.applyArabicShaping,this.processBidirectionalText=e.processBidirectionalText,this.processStyledBidirectionalText=e.processStyledBidirectionalText,this.loadScriptResolve()}isParsed(){return this.applyArabicShaping!=null&&this.processBidirectionalText!=null&&this.processStyledBidirectionalText!=null}getRTLTextPluginStatus(){return this.pluginStatus}async syncState(e,t){if(this.isParsed())return this.getState();if(e.pluginStatus!==`loading`)return this.setState(e),e;let n=e.pluginURL,r=new Promise(e=>{this.loadScriptResolve=e}),i=new Promise(e=>setTimeout(()=>e(),this.TIMEOUT));if(await t(n),await Promise.race([r,i]),this.isParsed()){let e={pluginStatus:`loaded`,pluginURL:n};return this.setState(e),e}throw this.setState({pluginStatus:`error`,pluginURL:``}),Error(`RTL Text Plugin failed to import scripts from ${n}`)}};function Qp(e){return/[\u0600-\u0604\u0606-\u060B\u060D-\u061A\u061C-\u061E\u0620-\u063F\u0641-\u064A\u0656-\u066F\u0671-\u06DC\u06DE-\u070D\u070F-\u074A\u074D-\u077F\u07C0-\u07FA\u07FD-\u07FF\u0840-\u085B\u085E\u0860-\u086A\u0870-\u0891\u0897-\u08E1\u08E3-\u08FF\u1800\u1801\u1804\u1806-\u1819\u1820-\u1878\u1880-\u18AA\uA840-\uA877\uFB50-\uFD3D\uFD40-\uFDCF\uFDF0-\uFDFF\uFE70-\uFE74\uFE76-\uFEFC]|\uD802[\uDEC0-\uDEE6\uDEEB-\uDEF6\uDF80-\uDF91\uDF99-\uDF9C\uDFA9-\uDFAF]|\uD803[\uDD00-\uDD27\uDD30-\uDD39\uDE60-\uDE7E\uDEC2-\uDEC7\uDED0-\uDED8\uDEFA-\uDEFF\uDF30-\uDF59\uDF70-\uDF89\uDFB0-\uDFCB]|\uD805[\uDE60-\uDE6C]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9C-\uDC9F]|\uD83A[\uDD00-\uDD4B\uDD50-\uDD59\uDD5E\uDD5F]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB\uDEF0\uDEF1]/gim.test(String.fromCodePoint(e))}function $p(e){return/[\u0591-\u05C7\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0604\u0606-\u060B\u060D-\u061A\u061C-\u061E\u0620-\u063F\u0641-\u064A\u0656-\u066F\u0671-\u06DC\u06DE-\u070D\u070F-\u074A\u074D-\u07B1\u07C0-\u07FA\u07FD-\u082D\u0830-\u083E\u0840-\u085B\u085E\u0860-\u086A\u0870-\u0891\u0897-\u08E1\u08E3-\u08FF\uFB1D-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFD3D\uFD40-\uFDCF\uFDF0-\uFDFF\uFE70-\uFE74\uFE76-\uFEFC]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC57-\uDC9E\uDCA7-\uDCAF\uDCE0-\uDCF2\uDCF4\uDCF5\uDCFB-\uDD1B\uDD1F-\uDD39\uDD3F-\uDD59\uDD80-\uDDB7\uDDBC-\uDDCF\uDDD2-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE38-\uDE3A\uDE3F-\uDE48\uDE50-\uDE58\uDE60-\uDE9F\uDEC0-\uDEE6\uDEEB-\uDEF6\uDF00-\uDF35\uDF39-\uDF55\uDF58-\uDF72\uDF78-\uDF91\uDF99-\uDF9C\uDFA9-\uDFAF]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDCFA-\uDD27\uDD30-\uDD39\uDD40-\uDD65\uDD69-\uDD85\uDD8E\uDD8F\uDE60-\uDE7E\uDE80-\uDEA9\uDEAB-\uDEAD\uDEB0\uDEB1\uDEC2-\uDEC7\uDED0-\uDED8\uDEFA-\uDF27\uDF30-\uDF59\uDF70-\uDF89\uDFB0-\uDFCB\uDFE0-\uDFF6]|\uD83A[\uDC00-\uDCC4\uDCC7-\uDCD6\uDD00-\uDD4B\uDD50-\uDD59\uDD5E\uDD5F]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB\uDEF0\uDEF1]/gim.test(String.fromCodePoint(e))}function em(e){return/[\u02EA\u02EB\u2E80-\u2FDF\u2FF0-\u303F\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FD-\u30FF\u3105-\u312F\u31A0-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uF900-\uFA6D\uFA70-\uFAD9\uFE10-\uFE1F\uFE30-\uFE4F\uFF00-\uFFEF]|\uD81B[\uDFE0-\uDFFF]|[\uD81C-\uD822\uD840-\uD868\uD86A-\uD86D\uD86F-\uD872\uD874-\uD879\uD880-\uD883\uD885-\uD88C][\uDC00-\uDFFF]|\uD823[\uDC00-\uDCD5\uDCFF-\uDD1E\uDD80-\uDDF2]|\uD82B[\uDFF0-\uDFFF]|\uD82C[\uDC00-\uDEFB]|\uD83C[\uDE00-\uDEFF]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEAD\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0\uDFF0-\uDFFF]|\uD87B[\uDC00-\uDE5D]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A\uDF50-\uDFFF]|\uD88D[\uDC00-\uDC79]/gim.test(String.fromCodePoint(e))}function tm(e){return/[\u02EA\u02EB\u1100-\u11FF\u1401-\u167F\u18B0-\u18FF\u2065\u20DD-\u20E0\u20E2-\u20E4\u2B97\u2BF0-\u2BFF\u2E50\u2E51\u2E80-\u3007\u3012\u3013\u3020-\u302F\u3031-\u30FB\u30FD-\uA4CF\uA960-\uA97F\uAC00-\uD7FF\uF900-\uFAFF\uFE10-\uFE1F\uFE30-\uFE48\uFE50-\uFE57\uFE5F-\uFE62\uFE67-\uFE6F\uFF00-\uFF07\uFF0A-\uFF0C\uFF0E-\uFF19\uFF1F-\uFF3A\uFF3C\uFF3E\uFF40-\uFF5A\uFFE0-\uFFE2\uFFE4-\uFFE7\uFFF0-\uFFF8]|\uD802[\uDD80-\uDD9F]|\uD805[\uDD80-\uDDFF]|\uD806[\uDE00-\uDEBF]|[\uD80C-\uD810\uD81C-\uD822\uD83C\uD83D\uD840-\uD87E\uD880-\uD8BE][\uDC00-\uDFFF]|\uD811[\uDC00-\uDE7F]|\uD81B[\uDFE0-\uDFFF]|\uD823[\uDC00-\uDDFF]|\uD82B[\uDFF0-\uDFFF]|\uD82C[\uDC00-\uDEFF]|\uD833[\uDEC0-\uDFCF]|\uD834[\uDC00-\uDDFF\uDEE0-\uDF7F]|\uD836[\uDC00-\uDEAF]|\uD83E[\uDD00-\uDEFF]|[\uD87F\uD8BF][\uDC00-\uDFFD]/gim.test(String.fromCodePoint(e))}function nm(e){return/[\xA7\xA9\xAE\xB1\xBC-\xBE\xD7\xF7\u2016\u2020\u2021\u2030\u2031\u203B\u203C\u2042\u2047-\u2049\u2051\u2100-\u218F\u221E\u2234\u2235\u2300-\u2307\u230C-\u231F\u2324-\u2328\u232B\u237D-\u239A\u23BE-\u23CD\u23CF\u23D1-\u23DB\u23E2-\u2422\u2424-\u24FF\u25A0-\u2619\u2620-\u2767\u2776-\u2793\u2B12-\u2B2F\u2B50-\u2B59\u2BB8-\u2BEB\u3000-\u303F\u30A0-\u30FF\uE000-\uF8FF\uFE30-\uFE6F\uFF00-\uFFEF\uFFFC\uFFFD]|[\uDB80-\uDBFF][\uDC00-\uDFFF]/gim.test(String.fromCodePoint(e))}function rm(e){return/[\r\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0600-\u0605\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DD\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0890\u0891\u0897-\u089F\u08CA-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D62\u0D63\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E33-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB3-\u0EBC\u0EC8-\u0ECE\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1037\u1039-\u103E\u1056-\u1059\u105E-\u1060\u1071-\u1074\u1082\u1084-\u1086\u108D\u109D\u1100-\u11FF\u135D-\u135F\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u180F\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60\u1A62\u1A65-\u1A7C\u1A7F\u1AB0-\u1ADD\u1AE0-\u1AEB\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA960-\uA97C\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFF9E\uFF9F]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD803[\uDD24-\uDD27\uDD69-\uDD6D\uDEAB\uDEAC\uDEFA-\uDEFF\uDF46-\uDF50\uDF82-\uDF85]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC70\uDC73\uDC74\uDC7F-\uDC82\uDCB0-\uDCBA\uDCBD\uDCC2\uDCCD\uDD00-\uDD02\uDD27-\uDD34\uDD45\uDD46\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDDC2\uDDC3\uDDC9-\uDDCC\uDDCE\uDDCF\uDE2C-\uDE37\uDE3E\uDE41\uDEDF-\uDEEA\uDF00-\uDF03\uDF3B\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74\uDFB8-\uDFC0\uDFC2\uDFC5\uDFC7-\uDFCA\uDFCC-\uDFD2\uDFE1\uDFE2]|\uD805[\uDC35-\uDC46\uDC5E\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDDDC\uDDDD\uDE30-\uDE40\uDEAB-\uDEB7\uDF1D-\uDF1F\uDF22-\uDF2B]|\uD806[\uDC2C-\uDC3A\uDD30-\uDD35\uDD37\uDD38\uDD3B-\uDD43\uDDD1-\uDDD7\uDDDA-\uDDE0\uDDE4\uDE01-\uDE0A\uDE33-\uDE39\uDE3B-\uDE3E\uDE47\uDE51-\uDE5B\uDE84-\uDE99\uDF60-\uDF67]|\uD807[\uDC2F-\uDC36\uDC38-\uDC3F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD31-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD8A-\uDD8E\uDD90\uDD91\uDD93-\uDD97\uDEF3-\uDEF6\uDF00-\uDF03\uDF34-\uDF3A\uDF3E-\uDF42\uDF5A]|\uD80D[\uDC40\uDC47-\uDC55]|\uD818[\uDD1E-\uDD2F]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDD63\uDD67-\uDD6A\uDF4F\uDF51-\uDF87\uDF8F-\uDF92\uDFE4\uDFF0\uDFF1]|\uD82F[\uDC9D\uDC9E]|\uD833[\uDF00-\uDF2D\uDF30-\uDF46]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A\uDC8F\uDD30-\uDD36\uDEAE\uDEEC-\uDEEF]|\uD839[\uDCEC-\uDCEF\uDDEE\uDDEF\uDEE3\uDEE6\uDEEE\uDEEF\uDEF5]|\uD83A[\uDCD0-\uDCD6\uDD44-\uDD4A]|\uD83C[\uDDE6-\uDDFF\uDFFB-\uDFFF]|\uDB40[\uDC20-\uDC7F\uDD00-\uDDEF]/.test(e)}function im(e){return/[\u0E01-\u0E3A\u0E40-\u0E4E\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECE\u0EDC-\u0EDF\u0F00-\u0F47\u0F49-\u0F6C\u0F71-\u0F97\u0F99-\u0FBC\u0FBE-\u0FCC\u0FCE-\u0FD4\u0FD9\u0FDA\u1000-\u103F\u1050-\u108F\u109A-\u109F\u1780-\u17D3\u17D7\u17DC\u17DD\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19DE\u19DF\u1A20-\u1A5E\u1A60-\u1A7C\u1AA0-\u1AAD\u1B00-\u1B4C\u1B4E-\u1B7F\uA980-\uA9CD\uA9D0-\uA9D9\uA9DE-\uA9EF\uA9FA-\uA9FE\uAA60-\uAAC2\uAADB-\uAADF]|\uD805[\uDF00-\uDF1A\uDF1D-\uDF2B\uDF3A\uDF3B\uDF3F-\uDF46]/gim.test(String.fromCodePoint(e))}function am(e,t){return/(?:[\u1039\u17D2\u1A60\u1BAB\u200D\uAAF6]|\uD802\uDE3F|\uD804[\uDD33\uDFD0]|\uD806[\uDD3E\uDE47\uDE99]|\uD807[\uDD45\uDD97\uDF42])$/.test(e)||/^\p{gc=Mc}/u.test(t)}const om={C:`18g,1;g2,3;4nb,1`,D:`17k,1;5,1;1,1;1,5;4,d;1,7;1,2;z,2;8,g;i,12;1,2;9,1;1,1;1,2;14,3;2,1;28,9;3,f;2,4;1,1;2,3;2,6;7a,1;2,5;1,1;g,a;5,2;2,6;1,f`,R:`17m,4;1,1;1,1;5,4;l,1;14,3;1,3;g,i;12,1;2,9;1,1;1,1;2,2;1,1;o,2;2x,3;f,2;4,1;1,2;3,2;6u,j;b,1;r,3;1,1;2,2;6,1`,T:`174,b;1,1;1a,l;g,1;2t,7;2,6;2,2;1,4;bt,9;16,o;1,t;1clb,1`},sm={1569:[65152,0,0,0],1570:[65153,65154,0,0],1571:[65155,65156,0,0],1572:[65157,65158,0,0],1573:[65159,65160,0,0],1574:[65161,65162,65163,65164],1575:[65165,65166,0,0],1576:[65167,65168,65169,65170],1577:[65171,65172,0,0],1578:[65173,65174,65175,65176],1579:[65177,65178,65179,65180],1580:[65181,65182,65183,65184],1581:[65185,65186,65187,65188],1582:[65189,65190,65191,65192],1583:[65193,65194,0,0],1584:[65195,65196,0,0],1585:[65197,65198,0,0],1586:[65199,65200,0,0],1587:[65201,65202,65203,65204],1588:[65205,65206,65207,65208],1589:[65209,65210,65211,65212],1590:[65213,65214,65215,65216],1591:[65217,65218,65219,65220],1592:[65221,65222,65223,65224],1593:[65225,65226,65227,65228],1594:[65229,65230,65231,65232],1601:[65233,65234,65235,65236],1602:[65237,65238,65239,65240],1603:[65241,65242,65243,65244],1604:[65245,65246,65247,65248],1605:[65249,65250,65251,65252],1606:[65253,65254,65255,65256],1607:[65257,65258,65259,65260],1608:[65261,65262,0,0],1609:[65263,65264,64488,64489],1610:[65265,65266,65267,65268],1611:[65136,0,0,65137],1612:[65138,0,0,0],1613:[65140,0,0,0],1614:[65142,0,0,65143],1615:[65144,0,0,65145],1616:[65146,0,0,65147],1617:[65148,0,0,65149],1618:[65150,0,0,65151],1649:[64336,64337,0,0],1655:[64477,0,0,0],1657:[64358,64359,64360,64361],1658:[64350,64351,64352,64353],1659:[64338,64339,64340,64341],1662:[64342,64343,64344,64345],1663:[64354,64355,64356,64357],1664:[64346,64347,64348,64349],1667:[64374,64375,64376,64377],1668:[64370,64371,64372,64373],1670:[64378,64379,64380,64381],1671:[64382,64383,64384,64385],1672:[64392,64393,0,0],1676:[64388,64389,0,0],1677:[64386,64387,0,0],1678:[64390,64391,0,0],1681:[64396,64397,0,0],1688:[64394,64395,0,0],1700:[64362,64363,64364,64365],1702:[64366,64367,64368,64369],1705:[64398,64399,64400,64401],1709:[64467,64468,64469,64470],1711:[64402,64403,64404,64405],1713:[64410,64411,64412,64413],1715:[64406,64407,64408,64409],1722:[64414,64415,0,0],1723:[64416,64417,64418,64419],1726:[64426,64427,64428,64429],1728:[64420,64421,0,0],1729:[64422,64423,64424,64425],1733:[64480,64481,0,0],1734:[64473,64474,0,0],1735:[64471,64472,0,0],1736:[64475,64476,0,0],1737:[64482,64483,0,0],1739:[64478,64479,0,0],1740:[64508,64509,64510,64511],1744:[64484,64485,64486,64487],1746:[64430,64431,0,0],1747:[64432,64433,0,0]},cm={لآ:[65269,65270],لأ:[65271,65272],لإ:[65273,65274],لا:[65275,65276]},lm=1604,um=/[\u0600-\u06ff\u0750-\u077f\u0870-\u089f\u08a0-\u08ff\ufb50-\ufdff\ufe70-\ufeff]/;function dm(e,t,n){let r=0;for(let i of e.split(`;`)){let[e,a]=i.split(`,`).map(e=>parseInt(e,36)),o=r+e;for(let e=o;e{let t=e.codePointAt(0);return{codePoint:t,type:pm(t),form:null}})}function vm(e){let t=e.filter(e=>e.type!==`T`);for(let e=0;e0&&mm(t[e-1].type),i=e+1String.fromCodePoint(xm(e))).join(``)}function Cm(e,t,n){let r=t.layout.get(`text-transform`).evaluate(n,{});return r===`uppercase`?e=e.toLocaleUpperCase():r===`lowercase`&&(e=e.toLocaleLowerCase()),(Zp.applyArabicShaping??Sm)(e)}function wm(e,t,n){for(let r of e.sections)r.text=Cm(r.text,t,n);return e}function Tm(e,t,n){let r=n?t.last.points:t.first.points,i=n?r[r.length-1]:r[0];return`${e}:${i.x}:${i.y}`}function Em(e){let t=e.first.points,n=t.length;for(let t=e.first.next;t;t=t.next)n+=t.points.length-1;let r=Array(n);for(let e=0;e=0&&am(t[e],n)?t[e]+=n:t.push(n)}return t}function Pm(e){let t=/* @__PURE__ */ new Set;if(Am){Mm??=new Intl.Segmenter(void 0,{granularity:`word`});for(let{index:n}of Mm.segment(e))t.add(n);return t}let n=0;for(let r of e.split(/\b|(?=\p{Ideo})/u))t.add(n),n+=r.length;return t}function Fm(e){let t=e.codePointAt(0);return e.length>(t>65535?2:1)}function Im(e){return/\s/u.test(String.fromCodePoint(e))}function Lm(e){return/[\p{P}\p{S}]/u.test(String.fromCodePoint(e))}function Rm(e){for(let t of e)if(tm(t.codePointAt(0)))return!0;return!1}function zm(e){for(let t of e)if(!Bm(t.codePointAt(0)))return!1;return!0}function Bm(e){return!Qp(e)}function Vm(e){return!(tm(e)||nm(e))}function Hm(e){return/\p{sc=Arab}/u.test(String.fromCodePoint(e))}function Um(e){return $p(e)}function Wm(e){for(let t of e)if(Um(t.codePointAt(0)))return!0;return!1}const Gm={"!":`︕`,"#":`#`,$:`$`,"%":`%`,"&":`&`,"(":`︵`,")":`︶`,"*":`*`,"+":`+`,",":`︐`,"-":`︲`,".":`・`,"/":`/`,":":`︓`,";":`︔`,"<":`︿`,"=":`=`,">":`﹀`,"?":`︖`,"@":`@`,"[":`﹇`,"\\":`\`,"]":`﹈`,"^":`^`,_:`︳`,"`":```,"{":`︷`,"|":`―`,"}":`︸`,"~":`~`,"¢":`¢`,"£":`£`,"¥":`¥`,"¦":`¦`,"¬":`¬`,"¯":` ̄`,"–":`︲`,"—":`︱`,"‘":`﹃`,"’":`﹄`,"“":`﹁`,"”":`﹂`,"…":`︙`,"⋯":`︙`,"‧":`・`,"₩":`₩`,"、":`︑`,"。":`︒`,"〈":`︿`,"〉":`﹀`,"《":`︽`,"》":`︾`,"「":`﹁`,"」":`﹂`,"『":`﹃`,"』":`﹄`,"【":`︻`,"】":`︼`,"〔":`︹`,"〕":`︺`,"〖":`︗`,"〗":`︘`,"!":`︕`,"(":`︵`,")":`︶`,",":`︐`,"-":`︲`,".":`・`,":":`︓`,";":`︔`,"<":`︿`,">":`﹀`,"?":`︖`,"[":`﹇`,"]":`﹈`,"_":`︳`,"{":`︷`,"|":`―`,"}":`︸`,"⦅":`︵`,"⦆":`︶`,"。":`︒`,"「":`﹁`,"」":`﹂`};function Km(e){let t=``,n={premature:!0,value:void 0},r=e[Symbol.iterator](),i=r.next(),a=e[Symbol.iterator]();a.next();let o=a.next();for(;!i.done;)(o.done||!Vm(o.value.codePointAt(0))||Gm[o.value])&&(n.premature||!Vm(n.value.codePointAt(0))||Gm[n.value])&&Gm[i.value]?t+=Gm[i.value]:t+=i.value,n={value:i.value,premature:!1},i=r.next(),o=a.next();return t}const qm={10:!0,13:!0,32:!0,38:!0,41:!0,43:!0,45:!0,47:!0,173:!0,183:!0,8203:!0,8208:!0,8211:!0,8231:!0},Jm={40:!0};function Ym(e,t,n,r,i,a){if(`fontStack`in t){let r=n[t.fontStack]?.default,a=r?.[e];if(a)return a.metrics.advance*t.scale+i;let o=0;for(let n of e){let e=r?.[n];e&&(o+=e.metrics.advance*t.scale+i)}return o}{let e=r[t.imageName];return e?e.displaySize[0]*t.scale*24/a+i:0}}function Xm(e,t,n,r){let i=(e-t)**2;return r?e{let o=n.slice(r,r+i.length);r+=i.length;let s=this.getSection(a);return t?.[a]!==!1&&`fontStack`in s&&e[s.fontStack]?.vertical?.[i]?i:o}),this.text=this.cachedGraphemes.join(``)}hasZeroWidthSpaces(){return this.text.includes(``)}trim(){let e=this.graphemes(),t=0;for(;tt&&Zm(e[n-1]);)n--;this.text=e.slice(t,n).join(``),this.sectionIndex=this.sectionIndex.slice(t,n),this.cachedGraphemes=null}substring(t,n){let r=this.graphemes().slice(t,n).join(``),i=this.sectionIndex.slice(t,n);return new e(r,this.sections,i)}toCodeUnitIndex(e){return this.graphemes().slice(0,e).join(``).length}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((e,t)=>Math.max(e,this.sections[t].scale),0)}getMaxImageSize(e){let t=0,n=0;for(let r=0;r0?n[n.length-1]:``,i=Nm(r+e);this.text+=e,this.cachedGraphemes=n.slice(0,r?-1:void 0).concat(i);let a=i.length-+!!r;for(let e=0;e=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}determineLineBreaks(e,t,n,r,i){let a=this.determineTotalWidth(e,n,r,i);if(e>=0&&a>0&&a<=t&&!/[\n\r]/.test(this.text))return[this.length()];let o=[],s=a/Math.max(1,Math.ceil(a/t)),c=this.hasZeroWidthSpaces(),l=this.graphemes(),u=null,d=0,f=0;for(let t=0;t0){let e=l[t-1].codePointAt(0),n=a.codePointAt(0),r=em(e),i=im(e)&&im(n);(qm[e]||r||`imageName`in this.getSection(t-1)||l[t+1]!==void 0&&Jm[n]||i&&(u??=Pm(this.text)).has(f))&&o.push($m(t,d,s,o,Qm(e,n,r&&c),!1))}Im(a.codePointAt(0))||(d+=Ym(a,this.getSection(t),n,r,e,i)),f+=a.length}return eh($m(this.length(),d,s,o,0,!0))}determineTotalWidth(e,t,n,r){let i=0,a=0;for(let o of this.graphemes()){let s=this.getSection(a);i+=Ym(o,s,t,n,e,r),a++}return i}};function nh(){return(function(e){var t={R:`13k,1a,2,3,3,2+1j,ch+16,a+1,5+2,2+n,5,a,4,6+16,4+3,h+1b,4mo,179q,2+9,2+11,2i9+7y,2+68,4,3+4,5+13,4+3,2+4k,3+29,8+cf,1t+7z,w+17,3+3m,1t+3z,16o1+5r,8+30,8+mc,29+1r,29+4v,75+73`,EN:`1c+9,3d+1,6,187+9,513,4+5,7+9,sf+j,175h+9,qw+q,161f+1d,4xt+a,25i+9`,ES:`17,2,6dp+1,f+1,av,16vr,mx+1,4o,2`,ET:`z+2,3h+3,b+1,ym,3e+1,2o,p4+1,8,6u,7c,g6,1wc,1n9+4,30+1b,2n,6d,qhx+1,h0m,a+1,49+2,63+1,4+1,6bb+3,12jj`,AN:`16o+5,2j+9,2+1,35,ed,1ff2+9,87+u`,CS:`18,2+1,b,2u,12k,55v,l,17v0,2,3,53,2+1,b`,B:`a,3,f+2,2v,690`,S:`9,2,k`,WS:`c,k,4f4,1vk+a,u,1j,335`,ON:`x+1,4+4,h+5,r+5,r+3,z,5+3,2+1,2+1,5,2+2,3+4,o,w,ci+1,8+d,3+d,6+8,2+g,39+1,9,6+1,2,33,b8,3+1,3c+1,7+1,5r,b,7h+3,sa+5,2,3i+6,jg+3,ur+9,2v,ij+1,9g+9,7+a,8m,4+1,49+x,14u,2+2,c+2,e+2,e+2,e+1,i+n,e+e,2+p,u+2,e+2,36+1,2+3,2+1,b,2+2,6+5,2,2,2,h+1,5+4,6+3,3+f,16+2,5+3l,3+81,1y+p,2+40,q+a,m+13,2r+ch,2+9e,75+hf,3+v,2+2w,6e+5,f+6,75+2a,1a+p,2+2g,d+5x,r+b,6+3,4+o,g,6+1,6+2,2k+1,4,2j,5h+z,1m+1,1e+f,t+2,1f+e,d+3,4o+3,2s+1,w,535+1r,h3l+1i,93+2,2s,b+1,3l+x,2v,4g+3,21+3,kz+1,g5v+1,5a,j+9,n+v,2,3,2+8,2+1,3+2,2,3,46+1,4+4,h+5,r+5,r+a,3h+2,4+6,b+4,78,1r+24,4+c,4,1hb,ey+6,103+j,16j+c,1ux+7,5+g,fsh,jdq+1t,4,57+2e,p1,1m,1m,1m,1m,4kt+1,7j+17,5+2r,d+e,3+e,2+e,2+10,m+4,w,1n+5,1q,4z+5,4b+rb,9+c,4+c,4+37,d+2g,8+b,l+b,5+1j,9+9,7+13,9+t,3+1,27+3c,2+29,2+3q,d+d,3+4,4+2,6+6,a+o,8+6,a+2,e+6,16+42,2+1i`,BN:`0+8,6+d,2s+5,2+p,e,4m9,1kt+2,2b+5,5+5,17q9+v,7k,6p+8,6+1,119d+3,440+7,96s+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+1,1ekf+75,6p+2rz,1ben+1,1ekf+1,1ekf+1`,NSM:`lc+33,7o+6,7c+18,2,2+1,2+1,2,21+a,1d+k,h,2u+6,3+5,3+1,2+3,10,v+q,2k+a,1n+8,a,p+3,2+8,2+2,2+4,18+2,3c+e,2+v,1k,2,5+7,5,4+6,b+1,u,1n,5+3,9,l+1,r,3+1,1m,5+1,5+1,3+2,4,v+1,4,c+1,1m,5+4,2+1,5,l+1,n+5,2,1n,3,2+3,9,8+1,c+1,v,1q,d,1f,4,1m+2,6+2,2+3,8+1,c+1,u,1n,g+1,l+1,t+1,1m+1,5+3,9,l+1,u,21,8+2,2,2j,3+6,d+7,2r,3+8,c+5,23+1,s,2,2,1k+d,2+4,2+1,6+a,2+z,a,2v+3,2+5,2+1,3+1,q+1,5+2,h+3,e,3+1,7,g,jk+2,qb+2,u+2,u+1,v+1,1t+1,2+6,9,3+a,a,1a+2,3c+1,z,3b+2,5+1,a,7+2,64+1,3,1n,2+6,2,2,3+7,7+9,3,1d+g,1s+3,1d,2+4,2,6,15+8,d+1,x+3,3+1,2+2,1l,2+1,4,2+2,1n+7,3+1,49+2,2+c,2+6,5,7,4+1,5j+1l,2+4,k1+w,2db+2,3y,2p+v,ff+3,30+1,n9x+3,2+9,x+1,29+1,7l,4,5,q+1,6,48+1,r+h,e,13+7,q+a,1b+2,1d,3+3,3+1,14,1w+5,3+1,3+1,d,9,1c,1g,2+2,3+1,6+1,2,17+1,9,6n,3,5,fn5,ki+f,h+f,r2,6b,46+4,1af+2,2+1,6+3,15+2,5,4m+1,fy+3,as+1,4a+a,4x,1j+e,1l+2,1e+3,3+1,1y+2,11+4,2+7,1r,d+1,1h+8,b+3,3,2o+2,3,2+1,7,4h,4+7,m+1,1m+1,4,12+6,4+4,5g+7,3+2,2,o,2d+5,2,5+1,2+1,6n+3,7+1,2+1,s+1,2e+7,3,2+1,2z,2,3+5,2,2u+2,3+3,2+4,78+8,2+1,75+1,2,5,41+3,3+1,5,x+5,3+1,15+5,3+3,9,a+5,3+2,1b+c,2+1,bb+6,2+5,2d+l,3+6,2+1,2+1,3f+5,4,2+1,2+6,2,21+1,4,2,9o+1,f0c+4,1o+6,t5,1s+3,2a,f5l+1,43t+2,i+7,3+6,v+3,45+2,1j0+1i,5+1d,9,f,n+4,2+e,11t+6,2+g,3+6,2+1,2+4,7a+6,c6+3,15t+6,32+6,gzhy+6n`,AL:`16w,3,2,e+1b,z+2,2+2s,g+1,8+1,b+m,2+t,s+2i,c+e,4h+f,1d+1e,1bwe+dp,3+3z,x+c,2+1,35+3y,2rm+z,5+7,b+5,dt+l,c+u,17nl+27,1t+27,4x+6n,3+d`,LRO:`6ct`,RLO:`6cu`,LRE:`6cq`,RLE:`6cr`,PDF:`6cs`,LRI:`6ee`,RLI:`6ef`,FSI:`6eg`,PDI:`6eh`},n={},r={};n.L=1,r[1]=`L`,Object.keys(t).forEach(function(e,t){n[e]=1<1,1e>2,u>2,2wt>1,1>1,1ge>1,1wp>1,1j>1,f>1,hm>1,1>1,u>1,u6>1,1>1,+5,28>1,w>1,1>1,+3,b8>1,1>1,+3,1>3,-1>-1,3>1,1>1,+2,1s>1,1>1,x>1,th>1,1>1,+2,db>1,1>1,+3,3>1,1>1,+2,14qm>1,1>1,+1,4q>1,1e>2,u>2,2>1,+1`,canonical:`6f1>-6dx,6dy>-6dx,6ec>-6ed,6ee>-6ed,6ww>2jj,-2ji>2jj,14r4>-1e7l,1e7m>-1e7l,1e7m>-1e5c,1e5d>-1e5b,1e5c>-14qx,14qy>-14qx,14vn>-1ecg,1ech>-1ecg,1edu>-1ecg,1eci>-1ecg,1eda>-1ecg,1eci>-1ecg,1eci>-168q,168r>-168q,168s>-14ye,14yf>-14ye`};function m(e,t){var n=0,r=/* @__PURE__ */ new Map,i=t&&/* @__PURE__ */ new Map,a;return e.split(`,`).forEach(function e(o){if(o.indexOf(`+`)!==-1)for(var s=+o;s--;)e(a);else{a=o;var c=o.split(`>`),l=c[0],u=c[1];l=String.fromCodePoint(n+=parseInt(l,36)),u=String.fromCodePoint(n+=parseInt(u,36)),r.set(l,u),t&&i.set(u,l)}}),{map:r,reverseMap:i}}var h,g,_;function v(){if(!h){var e=m(p.pairs,!0),t=e.map,n=e.reverseMap;h=t,g=n,_=m(p.canonical,!1).map}}function y(e){return v(),h.get(e)||null}function b(e){return v(),g.get(e)||null}function x(e){return v(),_.get(e)||null}var S=n.L,C=n.R,w=n.EN,T=n.ES,E=n.ET,D=n.AN,O=n.CS,k=n.B,A=n.S,j=n.ON,ee=n.BN,te=n.NSM,ne=n.AL,re=n.LRO,ie=n.RLO,ae=n.LRE,oe=n.RLE,se=n.PDF,ce=n.LRI,le=n.RLI,ue=n.FSI,de=n.PDI;function fe(e,t){for(var n=125,r=new Uint32Array(e.length),l=0;l0)ge--;else if(ve>0){for(_e=0;!he[he.length-1]._isolate;)he.pop();var Se=he[he.length-1]._isolInitIndex;Se!=null&&(m.set(Se,ye),m.set(ye,Se)),he.pop(),ve--}M=he[he.length-1],p[ye]=M._level,M._override&&f(ye,M._override)}else be&se?(ge===0&&(_e>0?_e--:!M._isolate&&he.length>1&&(he.pop(),M=he[he.length-1])),p[ye]=M._level):be&k&&(p[ye]=g.level)}else p[ye]=M._level,M._override&&be!==ee&&f(ye,M._override)}for(var F=[],I=null,L=g.start;L<=g.end;L++){var Ce=r[L];if(!(Ce&s)){var we=p[L],Te=Ce&i,R=Ce===de;I&&we===I._level?(I._end=L,I._endsWithIsolInit=Te):F.push(I={_start:L,_end:L,_level:we,_startsWithPDI:R,_endsWithIsolInit:Te})}}for(var Ee=[],De=0;De=0;Le--)if(!(r[Le]&s)){Ie=p[Le];break}var Re=Me[Me.length-1],ze=p[Re],Be=g.level;if(!(r[Re]&i)){for(var Ve=Re+1;Ve<=g.end;Ve++)if(!(r[Ve]&s)){Be=p[Ve];break}}Ee.push({_seqIndices:Me,_sosType:Math.max(Ie,Fe)%2?C:S,_eosType:Math.max(Be,ze)%2?C:S})}}for(var He=0;He=0;Xe--)if(!(r[B[Xe]]&s)){Ye=r[B[Xe]];break}f(Je,Ye&(i|de)?j:Ye)}}if(u.get(w))for(var Ze=0;Ze=-1;$e--){var et=$e===-1?We:r[B[$e]];if(et&a){et===ne&&f(Qe,D);break}}}if(u.get(ne))for(var tt=0;tt=0&&(at=r[B[st]],at&s);st--);for(var ct=rt+1;ct=0&&r[B[ut]]&(E|s);ut--)f(B[ut],w);for(lt++;lt=0&&r[B[V]]&s;V--)f(B[V],j);for(var pt=dt+1;pt=0;wt--){var Tt=bt[wt].char;if(Tt===Ct||Tt===b(x(St))||y(x(Tt))===St){yt.push([bt[wt].seqIndex,xt]),bt.length=wt;break}}}yt.sort(function(e,t){return e[0]-t[0]});for(var U=0;U=0;Pt--){var Ft=B[Pt];if(r[Ft]&H){var It=r[Ft]&vt?C:S;At=It===Ke?Ke:It;break}}}if(At){if(r[B[Dt]]=r[B[Ot]]=At,At!==Ke){for(var Lt=Dt+1;Lt=0;Ut--)if(r[B[Ut]]&s)Bt=Ut;else{Ht=r[B[Ut]]&vt?C:S;break}for(var Wt=Ge,Gt=zt+1;Gt=0&&d(e[Xt])&c;Xt--)p[Xt]=g.level}}return{levels:p,paragraphs:h};function Zt(t,n){for(var a=t;a1,j>2,t>2,u>2,1a>g,2v3>1,1>1,1ge>1,1wd>1,b>1,1j>1,f>1,ai>3,-2>3,+1,8>1k0,-1jq>1y7,-1y6>1hf,-1he>1h6,-1h5>1ha,-1h8>1qi,-1pu>1,6>3u,-3s>7,6>1,1>1,f>1,1>1,+2,3>1,1>1,+13,4>1,1>1,6>1eo,-1ee>1,3>1mg,-1me>1mk,-1mj>1mi,-1mg>1mi,-1md>1,1>1,+2,1>10k,-103>1,1>1,4>1,5>1,1>1,+10,3>1,1>8,-7>8,+1,-6>7,+1,a>1,1>1,u>1,u6>1,1>1,+5,26>1,1>1,2>1,2>2,8>1,7>1,4>1,1>1,+5,b8>1,1>1,+3,1>3,-2>1,2>1,1>1,+2,c>1,3>1,1>1,+2,h>1,3>1,a>1,1>1,2>1,3>1,1>1,d>1,f>1,3>1,1a>1,1>1,6>1,7>1,13>1,k>1,1>1,+19,4>1,1>1,+2,2>1,1>1,+18,m>1,a>1,1>1,lk>1,1>1,4>1,2>1,f>1,3>1,1>1,+3,db>1,1>1,+3,3>1,1>1,+2,14qm>1,1>1,+1,6>1,4j>1,j>2,t>2,u>2,2>1,+1`,me;function he(){if(!me){var e=m(pe,!0),t=e.map;e.reverseMap.forEach(function(e,n){t.set(n,e)}),me=t}}function M(e){return he(),me.get(e)||null}function ge(e,t,n,r){var i=e.length;n=Math.max(0,n==null?0:+n),r=Math.min(i-1,r==null?i-1:+r);for(var a=/* @__PURE__ */ new Map,o=n;o<=r;o++)if(t[o]&1){var s=M(e[o]);s!==null&&a.set(o,s)}return a}function _e(e,t,n,r){var i=e.length;n=Math.max(0,n==null?0:+n),r=Math.min(i-1,r==null?i-1:+r);var a=[];return t.paragraphs.forEach(function(i){var o=Math.max(n,i.start),s=Math.min(r,i.end);if(o=o&&d(e[u])&c;u--)l[u]=i.level;for(var f=i.level,p=1/0,m=0;mf&&(f=h),h=p;g--)for(var _=0;_=g){for(var v=_;_+1