@hupu-tech/shaper 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.4 — 2026-11-12
4
+
5
+ - CLI 和 MCP 默认每 24 小时后台检查稳定版,新连接启用已验证更新;失败保留原版并退避重试。
6
+ - 受管技能随工具更新;支持固定版本,源码调试和已有项目不自动修改。
7
+
8
+ ## 0.2.3 — 2026-11-12
9
+
10
+ - 精简使用文档,聚焦安装、项目接入、开发和提审。
11
+ - 明确新建应用必须经过浏览器确认。
12
+
3
13
  ## 0.2.2 — 2026-11-12
4
14
 
5
15
  - 收紧 npm 发行白名单,移除内部文档与环境信息。
package/README.md CHANGED
@@ -1,131 +1,61 @@
1
1
  # Shaper
2
2
 
3
- **在你熟悉的 AI 工具中开发网页、游戏和互动体验。**
4
-
5
- Shaper 将项目初始化、本地预览、平台上传和审核流程连接起来。一个 npm 包提供命令行工具(CLI)、标准 stdio MCP 服务和开发技能(Skills),支持通过 AI 对话或终端完成开发。
6
-
7
- ```bash
8
- npm install -g @hupu-tech/shaper
9
- shaper install --ide cursor
10
- ```
11
-
12
- [安装](#安装) · [快速开始](#快速开始) · [接入-ai-工具](#接入-ai-工具) · [项目结构](#项目结构) · [常用命令](#常用命令) · [常见问题](#常见问题)
13
-
14
- ## 功能
15
-
16
- - **AI 工具接入**:为 Codex、Cursor、Claude Code 安装 MCP 和用户级技能。
17
- - **项目初始化**:提供 HTML、React、Phaser 模板;已有工程保留原代码和构建方式。
18
- - **本地开发**:启动预览、查看日志、检查配置和构建产物。
19
- - **平台交付**:上传生成预览,在浏览器核对资料后提交审核。
20
- - **后台开发**:按需接入应用云服务、部署后台源码和执行版本化数据库迁移。
21
- - **统一应用归属**:网页、CLI、MCP 复用同一个 App ID,避免重复创建和错误关联。
22
-
23
- ## 环境要求
24
-
25
- - Node.js **22.14 或以上**,建议使用 Node.js 24。
26
- - npm,以及一个拥有对应 Shaper 平台访问权限的账号。
27
- - 通过 AI 开发时,需要支持 Skills 或 stdio MCP 的客户端。
28
-
29
- 已在 macOS 验证构建和安装流程。Windows 已适配 npm 命令入口、技能 junction 和凭据目录权限,完整实机验收仍在进行;Linux 完整链路也尚未验收。登录、上传和云能力需要目标 Shaper 服务启用对应接口。
3
+ 在你熟悉的 AI 工具中开发网页、游戏和互动体验。提供项目初始化、本地预览、上传提审,以及配套的 Skills 和 MCP。
30
4
 
31
5
  ## 安装
32
6
 
33
- 全局安装后,可在任意业务项目目录使用 `shaper`:
7
+ 需要 Node.js 22.14+,建议使用 Node.js 24。
34
8
 
35
9
  ```bash
36
10
  npm install -g @hupu-tech/shaper
37
- shaper --version
38
- ```
39
-
40
- 也可以不全局安装,使用 npx 执行命令:
41
-
42
- ```bash
43
- npx -y @hupu-tech/shaper --help
44
- npx -y @hupu-tech/shaper install --ide cursor
45
- ```
46
-
47
- 安装开发工具不会创建平台应用,也不会自动提交审核。
48
-
49
- ## 快速开始
50
-
51
- ### 1. 连接你的 AI 工具
52
-
53
- 按实际使用的客户端选择一条:
54
-
55
- ```bash
56
11
  shaper install --ide cursor
57
- shaper install --ide codex
58
- shaper install --ide claude
59
12
  ```
60
13
 
61
- 安装后按提示重启客户端或重新加载 MCP。你也可以一次安装到多个客户端:
14
+ 将 `cursor` 换成 `codex` 或 `claude`,即可接入对应客户端。安装后按提示重启客户端。技能安装一次,多个项目共用。
62
15
 
63
- ```bash
64
- shaper install --ide codex,cursor,claude
65
- ```
16
+ ## 开始开发
66
17
 
67
- ### 2. 初始化业务项目
68
-
69
- 从 Shaper 网页开始创作时,复制网页生成的命令,在**业务项目目录**运行。将示例中的 `AppID` 替换为网页提供的真实值:
18
+ 在项目目录执行网页提供的初始化命令,将 `AppID` 替换为实际应用 ID:
70
19
 
71
20
  ```bash
72
21
  shaper init --app AppID
73
22
  ```
74
23
 
75
- 已有应用会直接验证并关联;尚未创建的预分配 ID 会打开浏览器,完成登录及“创建并连接”确认后继续。
24
+ 新建应用必须在浏览器确认“创建并连接”,确认前不会创建应用或完成项目绑定。已有项目保留原代码和构建方式;应用 ID 冲突时,先核对归属,不要覆盖绑定。
76
25
 
77
- 也可以直接创建一个新目录:
26
+ 也可以从模板新建项目:
78
27
 
79
28
  ```bash
80
29
  shaper init my-project --template react
81
30
  cd my-project
82
31
  ```
83
32
 
84
- 模板支持 `h5`、`react`、`phaser`,未指定时使用 `h5`。空目录初始化会保存预分配 ID,经浏览器确认后创建应用,重试复用同一 ID。
85
-
86
- **已有项目先核对原 App ID。** 已绑定或已识别的旧 ID 与命令目标冲突时,初始化会停止;已有源码但无法确定归属时,需要明确指定应用。不要使用新建应用来绕过权限或绑定错误。
33
+ 模板支持 `h5`、`react`、`phaser`,默认使用 `h5`。
87
34
 
88
- ### 3. 开发和预览
35
+ 接下来直接向 AI 描述需求:
89
36
 
90
- 接入 AI 后,可以直接告诉它:
37
+ > 请检查当前项目配置,帮我实现需求,并启动本地预览。
91
38
 
92
- > 请检查当前项目的 Shaper 绑定和工程配置,帮我实现需求,并启动本地预览。保留已有代码和构建方式。
93
-
94
- 也可以在终端操作:
39
+ 或使用命令行:
95
40
 
96
41
  ```bash
97
- shaper dev
98
- shaper logs
99
- shaper check
100
- shaper build
42
+ shaper dev # 本地预览
43
+ shaper check # 检查工程配置
44
+ shaper build # 构建
101
45
  ```
102
46
 
103
- `dev` 返回本地预览地址。`check` 检查工程配置,不代表业务行为已经验证;完成开发后仍需检查实际页面与交互。
104
-
105
- ### 4. 上传和提审
47
+ ## 上传与提审
106
48
 
107
49
  ```bash
108
50
  shaper deploy
109
- ```
110
-
111
- 命令构建并上传当前应用,返回版本 ID 和预览信息。确认页面效果后,将下面的 `VersionID` 替换为上传返回的版本 ID:
112
-
113
- ```bash
114
51
  shaper publish --version VersionID --description "本次更新说明"
115
52
  ```
116
53
 
117
- 该命令准备资料并打开浏览器确认页。你可以补充封面、修改应用信息,**点击提交后才进入审核**。打开确认页不等于已提审,审核通过也需以平台实际发布状态为准。
54
+ `deploy` 构建并上传,返回版本 ID 和预览信息。预览确认后,将 `VersionID` 替换为实际版本 ID;在打开的浏览器页面核对资料,确认提交后进入审核。
118
55
 
119
- ## 接入 AI 工具
56
+ ## 其他 AI 工具
120
57
 
121
- | 客户端 | 接入方式 |
122
- | --- | --- |
123
- | Codex | `shaper install --ide codex` |
124
- | Cursor | `shaper install --ide cursor` |
125
- | Claude Code | `shaper install --ide claude` |
126
- | WorkBuddy、TRAE 等其他客户端 | 按客户端支持的方式手动配置 Skills 和 stdio MCP,目前没有自动安装参数 |
127
-
128
- 手动 MCP 配置示例:
58
+ WorkBuddy、TRAE 等客户端需手动接入,配置方式以客户端支持为准。stdio MCP 配置示例:
129
59
 
130
60
  ```json
131
61
  {
@@ -138,146 +68,36 @@ shaper publish --version VersionID --description "本次更新说明"
138
68
  }
139
69
  ```
140
70
 
141
- 不同客户端的配置文件位置和结构可能不同。若 GUI 客户端找不到 `shaper`,使用 Node 可执行文件绝对路径作为 command,将安装包中 `dist/cli.js` 的绝对路径放在 args 首位,后面接 `mcp`、`serve`;Windows 可用这种方式避开 `.cmd` 启动差异。`npm root -g` 可查询全局包目录。
142
-
143
- 手动安装技能时,读取包内 `skills/manifest.json`,按客户端规范接入对应技能目录。不要给未支持的客户端套用 `--ide cursor` 等参数。
144
-
145
- 默认提供七个核心技能:
146
-
147
- | 技能 | 职责 |
148
- | --- | --- |
149
- | `shaper-product` | 明确目标、用户流程和完成条件 |
150
- | `shaper-design` | 视觉、交互及体验设计 |
151
- | `shaper-development` | 项目归属、工程接入和前端开发 |
152
- | `shaper-game-development` | 玩法实现与游戏开发流程 |
153
- | `shaper-backend` | 应用云服务、后台部署和数据库迁移 |
154
- | `hupu-business` | 虎扑用户、分享及容器能力接入 |
155
- | `shaper-release` | 构建、预览、提审确认和结果检查 |
156
-
157
- 可选安装离线养成玩法技能:
158
-
159
- ```bash
160
- shaper install --ide cursor --skills shaper-idle-game
161
- ```
162
-
163
- 技能按用户级安装,后续项目复用;`init` 不把整套技能复制到每个项目。
164
-
165
- ## 项目结构
166
-
167
- 新模板采用统一结构,React 和 Phaser 的差异放在业务源码中:
168
-
169
- ```text
170
- my-project/
171
- ├─ package.json
172
- ├─ package-lock.json
173
- ├─ shaper.config.json # 开发命令、构建命令、产物目录
174
- ├─ index.html
175
- ├─ src/ # 业务源码
176
- ├─ public/ # 保留路径的静态资源
177
- ├─ docs/
178
- │ ├─ product.md
179
- │ ├─ design.md
180
- │ └─ validation.md
181
- ├─ AGENTS.md # AI 项目入口
182
- ├─ dist/ # 构建生成
183
- └─ .shaper/ # 本地绑定与工具状态,不提交 Git
184
- ```
185
-
186
- 已有 HTML 或其他打包工程无需为了接入而整体搬迁。缺失的启动、构建配置需要结合原工程调整,并验证实际产物;不保证任意旧项目都能机械转换。
71
+ 技能目录见安装包内的 `skills/manifest.json`。客户端找不到命令时,可使用 Node 和包内 `dist/cli.js` 的绝对路径启动 MCP。
187
72
 
188
- ## 常用命令
73
+ ## 项目与后端
189
74
 
190
- 在业务项目目录执行;完整参数以 `shaper <命令> --help` 为准。
75
+ - `shaper.config.json`:开发、构建命令及产物目录。
76
+ - `src/`、`public/`:业务源码与静态资源。
77
+ - `docs/`、`AGENTS.md`:项目文档与 AI 开发入口。
78
+ - `.shaper/`:本地绑定和工具状态,不提交 Git。
191
79
 
192
- | 命令 | 用途 |
193
- | --- | --- |
194
- | `shaper config` | 查看有效服务地址 |
195
- | `shaper doctor` | 查看安装与登录状态 |
196
- | `shaper status` | 查看当前项目绑定、版本和预览状态 |
197
- | `shaper login` / `shaper logout` | 登录或退出当前服务的共用账号 |
198
- | `shaper projects` | 列出已获授权的应用 |
199
- | `shaper init` | 初始化或接入项目 |
200
- | `shaper dev` / `shaper stop` | 启动或停止本地预览 |
201
- | `shaper logs` | 查看本地运行日志 |
202
- | `shaper check` / `shaper build` | 检查配置或构建网页 |
203
- | `shaper deploy` | 上传当前应用的构建产物 |
204
- | `shaper publish` | 打开指定版本的提审确认页 |
80
+ 已有 HTML 或其他框架项目可以接入,无需统一改成 React。需要后端时,让 AI 使用后台开发技能处理云服务、数据库和网关;命令入口为 `shaper cloud --help`。
205
81
 
206
- `shaper link --app AppID` 用于明确更换目录关联,应先确认目标应用和影响;它不迁移源码或云资源。
207
-
208
- ## 服务地址与登录
209
-
210
- CLI 和 MCP 共用全局配置,设置服务地址无需先登录:
211
-
212
- ```bash
213
- shaper config --server https://shaper.example.com
214
- shaper config
215
- ```
216
-
217
- 上例是占位地址,请替换为平台提供的服务地址。未配置时默认使用 `https://shaper.hupu.com`。服务地址必须是 HTTPS origin,本机回环 HTTP 地址仅用于本地调试。
218
-
219
- - 全局目录:macOS/Linux 为 `~/.config/shaper`,Windows 为 `%USERPROFILE%\.config\shaper`。
220
- - `SHAPER_CONFIG_HOME` 可指定独立配置目录;`SHAPER_SERVER` 可覆盖当前进程的默认服务。
221
- - 修改地址后重启已运行的 MCP;环境变量需要由相应客户端进程继承。
222
- - 登录凭据按服务保存,项目只保存 App ID 和服务地址。切换服务不会迁移应用。
223
- - 同一服务的多个项目和 Agent 共用登录;补充授权保留已有权限,退出会影响该服务的全部本地项目。
224
-
225
- 已有应用需要补充权限时使用 `shaper login --app AppID`;需要云权限时使用 `shaper login --cloud`。初始化尚未创建的应用时直接用 `init --app`,由初始化流程完成浏览器确认。
226
-
227
- ## 应用云服务
228
-
229
- 需要后端时再接入,不是所有网页都需要开通云服务。先初始化并关联应用,然后:
230
-
231
- ```bash
232
- shaper login --cloud
233
- shaper cloud init cloud/functions/api
234
- shaper cloud enable
235
- shaper cloud status
236
- ```
237
-
238
- 资源就绪后维护后台代码和数据库迁移,再使用 `shaper cloud deploy --directory cloud/functions/api` 部署。云资源可能产生费用,以平台提供的套餐和权限为准。
239
-
240
- 后台结构按职责分开:
241
-
242
- ```text
243
- cloud/
244
- ├─ functions/api/ # 服务源码和运行配置
245
- ├─ database/migrations/ # 版本化 SQL 迁移
246
- └─ gateway/routes.json # 路由声明
247
- ```
248
-
249
- 返回 `queued` / `running` 只代表已受理或执行中。使用 `shaper cloud operation OperationID` 查询最终结果;依赖迁移的代码须等迁移成功后再部署。网页上传与后台部署分别执行;一期每个应用只有一份活动后台服务。
250
-
251
- ## 升级与卸载
252
-
253
- 升级全局 CLI 后,重新安装客户端集成,使 MCP 和技能使用新版快照:
82
+ ## 升级与排查
254
83
 
255
84
  ```bash
256
85
  npm install -g @hupu-tech/shaper@latest
257
86
  shaper install --ide cursor
258
87
  ```
259
88
 
260
- 也可用 `shaper update --version 0.2.2 --ide cursor` 安装指定客户端运行时版本;该命令不替代全局 npm 包升级。
261
-
262
- ```bash
263
- shaper uninstall
264
- npm uninstall -g @hupu-tech/shaper
265
- ```
266
-
267
- `shaper uninstall` 只移除本工具管理的客户端配置与技能链接,保留登录和运行时缓存。若需撤销登录,在卸载 CLI 前执行 `shaper logout`。
268
-
269
- ## 常见问题
270
-
271
- **安装成功,AI 仍找不到工具?** 重新加载 MCP 或重启客户端,并运行 `shaper doctor`。手动接入时检查客户端是否能找到 command;优先使用绝对路径。
89
+ 旧版本首次升级后,重新安装一次客户端集成。之后默认每 24 小时在后台检查稳定版,更新成功后下次启动生效;失败继续使用当前版本,1 小时后重试。运行中的 MCP 不会被中断。
272
90
 
273
- **初始化提示应用 ID 冲突?** 当前目录可能属于另一个应用。核对原绑定和网页入口,回到原应用继续或使用新的空目录;不要删除绑定来绕过冲突。
91
+ 安装器管理的技能随工具更新,重新打开 AI 会话后生效;手动复制的技能需自行更新。已有项目代码、依赖和模板不会自动修改。
274
92
 
275
- **登录页面无法打开或服务未启用?** 用 `shaper config` 核对服务公开地址。CLI 配置地址不会自动启用后端 OAuth,需要服务端完成授权配置。
93
+ 需要固定版本时使用 `shaper update --version <版本号> --ide cursor`;重新运行 `shaper install --ide cursor` 恢复自动更新。
276
94
 
277
- **上传成功为什么还没上线?** 上传、确认提审、审核和发布是不同状态。完成浏览器确认后,在平台查看该版本的实际审核结果。
95
+ - `shaper doctor`:检查安装和登录状态。
96
+ - `shaper status`:查看当前项目状态。
97
+ - `shaper --help`:查看命令;`shaper <命令> --help` 查看参数。
278
98
 
279
- **可以使用 Vue 或其他技术栈吗?** 可以保留已有工程,通过 `shaper.config.json` 配置真实开发、构建命令和输出目录。内置模板只是起点,不代表只允许三种技术栈;仍需符合平台交付包约束。
99
+ 已验证 macOS;Windows 和 Linux 完整流程尚待实机验证。
280
100
 
281
101
  ## 许可证
282
102
 
283
- Copyright © 2026 Hupu。当前包标记为 `UNLICENSED`,保留所有权利。公开分发不代表采用开源许可证,具体条款见包内 LICENSE。
103
+ Copyright © 2026 Hupu。`UNLICENSED`,保留所有权利,详见 LICENSE。
package/dist/cli.js CHANGED
@@ -1,14 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import{c as B,d as G,g as c}from"./shared-BTZI42QW.js";import{a as m,b as y,d as J,e as q,f as be,g as se,h as $,i as D,m as K,n as z,o as V,q as Q,r as U,s as H,v as W,w as Y,x as Z}from"./shared-2ZNSJXPO.js";import{Command as rt}from"commander";import{readFile as Te}from"node:fs/promises";import{resolve as l}from"node:path";import{readFileSync as De}from"node:fs";var X=JSON.parse(De(new URL("../package.json",import.meta.url),"utf8")).version;import{mkdir as P,readFile as x,writeFile as le,mkdtemp as Je,lstat as te,readlink as ee,symlink as Ce,unlink as me,rm as L,rename as qe}from"node:fs/promises";import{dirname as de,join as u,resolve as $e}from"node:path";import{homedir as Ke,tmpdir as ze}from"node:os";import{execa as Ie}from"execa";import{realpath as Fe}from"node:fs/promises";import{dirname as Ae,resolve as Me,toNamespacedPath as ke}from"node:path";async function _e(e,o){let i=Me(Ae(e),o);try{return ke(await Fe(i))}catch(n){if(n.code!=="ENOENT")throw n;return ke(i)}}async function N(e,o,i){if(o===void 0||i===void 0)return!1;let[n,t]=await Promise.all([_e(e,o),_e(e,i)]);return n===t}import{createHash as Ve,randomUUID as Ee}from"node:crypto";import*as pe from"@iarna/toml";import{parse as Qe,modify as Ue,applyEdits as He}from"jsonc-parser";import Ne from"proper-lockfile";import{Client as Be}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Ge}from"@modelcontextprotocol/sdk/client/stdio.js";var We=["codex","cursor","claude"],Se="# >>> Shaper managed MCP >>>",ce="# <<< Shaper managed MCP <<<",F=()=>u(y(),"installation.json");async function A(e){return x(e,"utf8").catch(o=>{if(o.code==="ENOENT")return"";throw o})}function Ye(e){let o=[],i=Qe(e||"{}",o,{allowTrailingComma:!0});if(o.length||!i||typeof i!="object"||Array.isArray(i))throw new m("INVALID_IDE_CONFIG","IDE \u914D\u7F6E\u65E0\u6CD5\u89E3\u6790\uFF0C\u8BF7\u5148\u4FEE\u590D\u914D\u7F6E\u6587\u4EF6\u3002");return i}function ue(e,o){return JSON.stringify(e)===JSON.stringify(o)}function Ze(e,o){return u(o,e==="codex"?".codex/config.toml":e==="cursor"?".cursor/mcp.json":".claude.json")}function xe(e,o,i,n){if(e==="codex"){let k=pe.parse(o).mcp_servers?.shaper,h=o.indexOf(Se),S=o.indexOf(ce),I=h>=0&&S>h;if(k&&(!I||!n||!ue(k,n)))throw new m("IDE_CONFIG_CONFLICT","Codex \u7684 shaper MCP \u914D\u7F6E\u4E0D\u5C5E\u4E8E\u672C\u6B21\u5B89\u88C5\uFF0C\u5DF2\u4FDD\u7559\u539F\u914D\u7F6E\u3002");let C=I?o.slice(0,h)+o.slice(S+ce.length).replace(/^\r?\n/,""):o,T=i?`${C.trimEnd()}
3
-
4
- ${Se}
5
- [mcp_servers.shaper]
6
- command = ${JSON.stringify(i.command)}
7
- args = ${JSON.stringify(i.args)}
8
- ${ce}
9
- `:C;return pe.parse(T),T}let w=Ye(o).mcpServers?.shaper;if(w&&(!n||!ue(w,n)))throw new m("IDE_CONFIG_CONFLICT",`${e} \u7684 shaper MCP \u914D\u7F6E\u5DF2\u5B58\u5728\u6216\u5DF2\u88AB\u4FEE\u6539\uFF0C\u5DF2\u4FDD\u7559\u539F\u914D\u7F6E\u3002`);return He(o||`{}
10
- `,Ue(o||`{}
11
- `,["mcpServers","shaper"],i,{formattingOptions:{insertSpaces:!0,tabSize:2}}))}async function we(e,o,i){await P(de(e),{recursive:!0});try{if((await te(e)).isSymbolicLink())throw new m("UNSAFE_IDE_CONFIG",`IDE \u914D\u7F6E\u662F\u7B26\u53F7\u94FE\u63A5\uFF0C\u8BF7\u624B\u52A8\u914D\u7F6E\uFF1A${e}`)}catch(t){if(t.code!=="ENOENT")throw t}if(await A(e)!==o)throw new m("IDE_CONFIG_CHANGED",`\u914D\u7F6E\u5728\u5B89\u88C5\u671F\u95F4\u53D1\u751F\u53D8\u5316\uFF1A${e}`);if(o){let t=u(y(),"backups",`${Date.now()}-${Ee()}.bak`);await P(de(t),{recursive:!0,mode:448}),await le(t,o,{mode:384,flag:"wx"})}let n=`${e}.${Ee()}.tmp`;await le(n,i,{mode:384,flag:"wx"}),await qe(n,e)}async function oe(){try{return await q(F())}catch(e){if(e.code==="ENOENT")return;throw e}}async function Oe(){let e;try{e=await q(u(y(),"install-pending.json"))}catch(o){if(o.code==="ENOENT")return;throw o}if(e.next&&ue(await oe(),e.next)){await L(u(y(),"install-pending.json"));return}for(let o of e.edits){let i=await A(o.path);if(i!==o.before&&i!==o.after)throw new m("INSTALL_RECOVERY_CONFLICT",`\u5B89\u88C5\u4E2D\u65AD\u540E\u914D\u7F6E\u5DF2\u88AB\u6539\u52A8\uFF0C\u4FDD\u7559\u73B0\u573A\uFF1A${o.path}`)}for(let o of e.skills)try{if(!(await te(o.path)).isSymbolicLink())throw new m("INSTALL_RECOVERY_CONFLICT",`\u5B89\u88C5\u4E2D\u65AD\u540E\u6280\u80FD\u5DF2\u88AB\u6539\u52A8\uFF1A${o.path}`);let i=await ee(o.path);if(!await N(o.path,i,o.target)&&!await N(o.path,i,o.previous))throw new m("INSTALL_RECOVERY_CONFLICT",`\u5B89\u88C5\u4E2D\u65AD\u540E\u6280\u80FD\u94FE\u63A5\u5DF2\u88AB\u6539\u52A8\uFF1A${o.path}`)}catch(i){if(i.code!=="ENOENT")throw i}for(let o of e.edits)await A(o.path)===o.after&&await we(o.path,o.after,o.before);for(let o of e.skills){let i=await ee(o.path).catch(t=>{if(t.code!=="ENOENT")throw t}),n=await N(o.path,i,o.previous);!n&&await N(o.path,i,o.target)&&await me(o.path),o.previous&&!n&&await Ce(o.previous,o.path,process.platform==="win32"?"junction":"dir")}e.previous?await J(F(),e.previous):await L(F(),{force:!0}),await L(u(y(),"install-pending.json"))}async function Xe(e){if(e&&!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test(e))throw new m("INVALID_VERSION","\u66F4\u65B0\u7248\u672C\u5FC5\u987B\u662F\u5B8C\u6574\u7684\u7248\u672C\u53F7\u3002");let o=await Je(u(ze(),"shaper-install-"));try{let i=await Ie("npm",["pack",...e?[`@hupu-tech/shaper@${e}`]:[],"--ignore-scripts","--json","--pack-destination",o],{cwd:D,timeout:18e4,maxBuffer:1048576}),n=JSON.parse(i.stdout)[0],t=u(o,n.filename),w=Ve("sha256").update(await x(t)).digest("hex").slice(0,16),g=u(y(),"runtimes",`${n.version}-${w}`),k=u(g,"node_modules","@hupu-tech","shaper","dist","cli.js");try{await x(u(g,".complete"))}catch(h){if(h.code!=="ENOENT")throw h;await P(g,{recursive:!0,mode:448}),await Ie("npm",["install","--prefix",g,t,"--omit=dev","--ignore-scripts","--no-audit","--no-fund"],{timeout:24e4,maxBuffer:4*1024*1024}),await le(u(g,".complete"),`${w}
12
- `,{mode:384})}return await x(k),{root:u(g,"node_modules","@hupu-tech","shaper"),version:n.version,entry:k}}finally{await L(o,{recursive:!0,force:!0})}}async function et(e){let o=new Ge({...e,stderr:"pipe"}),i=new Be({name:"shaper-installer",version:"1.0.0"});try{await i.connect(o,{timeout:15e3});let n=await i.listTools();if(!n.tools.some(t=>t.name==="shaper_status"))throw new m("MCP_VERIFICATION_FAILED","MCP \u672A\u8FD4\u56DE Shaper \u5DE5\u5177\u3002");return{tools:n.tools.length,protocol:"stdio"}}finally{await i.close(),await o.close()}}async function fe(e,o={}){if(!e.length||e.some(n=>!We.includes(n)))throw new m("INVALID_IDE","\u652F\u6301 codex\u3001cursor\u3001claude\u3002");await P(y(),{recursive:!0,mode:448});let i=await Ne.lock(y(),{retries:0});try{await Oe();let n=$e(o.home??Ke()),t=await oe();if(o.dev&&o.version)throw new m("INVALID_ARGUMENT","\u672C\u5730\u8C03\u8BD5\u6A21\u5F0F\u4E0D\u80FD\u6307\u5B9A\u53D1\u884C\u7248\u672C\u3002");let w=o.dev?{root:D,entry:u(D,"dist","cli.js"),version:(await q(u(D,"package.json"))).version}:await Xe(o.version);o.dev&&await x(w.entry).catch(()=>{throw new m("BUILD_REQUIRED","\u8BF7\u5148\u5728\u672C\u5730\u5305\u76EE\u5F55\u6267\u884C pnpm build\u3002")});let g={command:process.execPath,args:[w.entry,"mcp","serve"]},k=await et(g),h=[...new Set(e)].map(a=>({ide:a,path:Ze(a,n),entry:g})),S=await Promise.all(h.map(async a=>{let f=await A(a.path);return{...a,before:f,after:xe(a.ide,f,g,t?.entries.find(re=>re.path===a.path)?.entry)}})),I=new Set(e.map(a=>u(n,a==="codex"?".agents/skills":`.${a}/skills`))),C=JSON.parse(await x(u(w.root,"skills/manifest.json"),"utf8")),T=o.skills??[];for(let a of T)if(!C.optional.some(f=>f.split("/").at(-1)===a))throw new m("UNKNOWN_SKILL",`\u672A\u77E5\u4E13\u4E1A\u6280\u80FD\uFF1A${a}`);let ye=[...C.default,...C.compatibility,...C.optional.filter(a=>T.includes(a.split("/").at(-1))||t?.skills.some(f=>f.path.endsWith("/"+a.split("/").at(-1))))];if(ye.some(a=>!/^(core|game|compat)\/[a-z0-9-]+$/.test(a)))throw new m("INVALID_SKILL_MANIFEST","\u6280\u80FD\u53D1\u884C\u6E05\u5355\u65E0\u6548\u3002");let R=[];for(let a of I)for(let f of ye){let re=f.split("/").at(-1),j=u(a,re),he=u(w.root,"skills",f);await x(u(he,"SKILL.md"));let ve;try{let M=await te(j),ae=t?.skills.find(Re=>Re.path===j);if(!M.isSymbolicLink()||!ae||!await N(j,await ee(j),ae.target))throw new m("SKILL_CONFLICT",`\u5DF2\u5B58\u5728\u6280\u80FD\uFF0C\u5B89\u88C5\u672A\u8986\u76D6\uFF1A${j}`);ve=ae.target}catch(M){if(M.code!=="ENOENT")throw M}R.push({path:j,target:he,previous:ve})}let ge={schemaVersion:1,runtime:w.root,version:w.version,entries:[...(t?.entries??[]).filter(a=>!h.some(f=>f.path===a.path)),...h],skills:[...(t?.skills??[]).filter(a=>!R.some(f=>f.path===a.path)),...R.map(({path:a,target:f})=>({path:a,target:f}))]};await J(u(y(),"install-pending.json"),{edits:S,skills:R,previous:t,next:ge});for(let a of S)await we(a.path,a.before,a.after);for(let a of R)await P(de(a.path),{recursive:!0}),a.previous&&await me(a.path),await Ce(a.target,a.path,process.platform==="win32"?"junction":"dir");return await J(F(),ge),await L(u(y(),"install-pending.json"),{force:!0}),{installed:!0,mode:o.dev?"development":"snapshot",runtime:w.root,version:w.version,ides:e,...k,restartIde:!0,cli:{command:process.execPath,args:[w.entry]}}}finally{await i()}}async function je(){await P(y(),{recursive:!0,mode:448});let e=await Ne.lock(y(),{retries:0});try{await Oe();let o=await oe();if(!o)return{uninstalled:!0,alreadyAbsent:!0};let i=await Promise.all(o.entries.map(async n=>{let t=await A(n.path);return{...n,before:t,after:xe(n.ide,t,void 0,n.entry)}}));for(let n of o.skills)try{if(!(await te(n.path)).isSymbolicLink()||!await N(n.path,await ee(n.path),n.target))throw new m("SKILL_CONFLICT",`\u6280\u80FD\u5DF2\u88AB\u4FEE\u6539\uFF0C\u5378\u8F7D\u4FDD\u7559\uFF1A${n.path}`)}catch(t){if(t.code!=="ENOENT")throw t}for(let n of i)await we(n.path,n.before,n.after);for(let n of o.skills)await me(n.path).catch(t=>{if(t.code!=="ENOENT")throw t});return await L(F(),{force:!0}),{uninstalled:!0,credentialsRetained:!0,runtimeRetained:!0}}finally{await e()}}async function Le(){let e=await oe();return e?{installed:!0,version:e.version,ides:e.entries.map(o=>o.ide),runtime:e.runtime}:{installed:!1}}import{McpServer as tt}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as ot}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as s}from"zod";import{isAbsolute as nt}from"node:path";var d=s.string().min(1).refine(nt,"workspace must be an absolute path").describe("Absolute local project directory. Never infer from the MCP process working directory."),b=s.string().regex(/^[a-z][a-z0-9-]{0,31}$/),ne=s.string().min(1).max(64),O=s.string().min(16).max(100).optional();function it(e,o={}){let i=new tt({name:"shaper",version:X},{instructions:"Use installed Shaper skills for workflows. Always pass the intended absolute workspace. All sessions share one login per Shaper server. Reuse it; request additional permissions only when needed. Browser consent adds permissions without replacing existing access. Local binding contains only the server and app ID, never tokens. Never choose a recent app as a fallback. Web delivery and backend service deployment have separate targets. Queued, running or uncertain results do not confirm completion. Use hupu_cloud_operation to confirm asynchronous results."});function n(t,w,g,k,h="write"){i.registerTool(w,{description:g,inputSchema:t,annotations:{readOnlyHint:h==="read",destructiveHint:h==="destructive",openWorldHint:!0}},async S=>{try{let I=await k(S);return{content:[{type:"text",text:JSON.stringify(I,null,2)}]}}catch(I){return{isError:!0,content:[{type:"text",text:JSON.stringify($(I))}]}}})}return n({workspace:d.optional()},"shaper_status","Read current identity, local project binding and development session. Does not start services.",t=>e.status(t.workspace),"read"),n({cloud:s.boolean().default(!1),openBrowser:s.boolean().default(!0),appId:s.string().min(1).max(200).optional(),reauthorize:s.boolean().default(!1)},"shaper_auth_start","Reuse the global login when permissions suffice. Otherwise start browser consent and return a flow ID. appId adds access to an existing application; cloud=true adds cloud permissions. Existing permissions are retained. reauthorize=true opens consent explicitly.",t=>e.auth.start(t)),n({flowId:s.string()},"shaper_auth_status","Read browser authorization result for a flow started by this MCP session.",t=>e.auth.status(t.flowId),"read"),n({},"shaper_logout","Sign out globally for this Shaper server. All local projects and Agent sessions share this login.",()=>e.auth.logout(),"destructive"),n({},"shaper_projects","List applications available to this authorization.",()=>e.api.projects(),"read"),n({workspace:d,template:s.enum(["h5","react","phaser"]).optional(),name:ne.optional(),appId:s.string().optional(),installDependencies:s.boolean().default(!0)},"shaper_init","Create a vanilla HTML, React or Phaser project and a Shaper application, or initialize an existing source directory. Resolve existing identity first; missing apps require browser creation consent. A pending result requires finishing authorization and retrying with the same workspace/appId. Never overwrite a conflicting existing binding.",t=>K(e.api,t.workspace,t)),n({workspace:d,appId:s.string()},"shaper_link","Associate the local source directory with an existing authorized Shaper application.",t=>z(e.api,t.workspace,t.appId)),n({workspace:d},"shaper_dev_start","Start a local development server using shaper.config.json and return its verified URL.",t=>W(t.workspace)),n({workspace:d},"shaper_dev_stop","Stop the development session managed for this project.",t=>Y(t.workspace)),n({workspace:d},"shaper_dev_logs","Read recent local development output.",t=>Z(t.workspace),"read"),n({workspace:d},"shaper_build","Run the project build command and verify the web output.",t=>V(t.workspace)),n({workspace:d},"shaper_check","Check project configuration; this is not a behavior or cloud connectivity test.",t=>H(t.workspace),"read"),n({workspace:d},"shaper_web_deploy","Build and upload web code through Shaper; return request status, validation and preview details.",t=>Q(e.api,t.workspace)),n({workspace:d,versionId:s.string(),description:s.string().min(1),coverPath:s.string().optional()},"shaper_web_publish","Prepare review details and open a browser confirmation page. This does NOT submit review: the user edits details and submits in the browser. Cover is optional here and can be supplied in the browser.",t=>U(e.api,t.workspace,t.versionId,t.description,t.coverPath)),n({workspace:d,directory:s.string().optional()},"hupu_cloud_init","Create a local Node backend source directory; does not provision resources or overwrite existing code.",t=>B(t.workspace,t.directory)),n({workspace:d,directory:s.string().optional()},"hupu_cloud_build","Build backend artifacts locally. Deployment also builds by default, so this is only needed to inspect or reuse artifacts.",t=>G(t.workspace,t.directory)),n({workspace:d},"hupu_cloud_status","Read application cloud readiness and current release. No test/production environments or resource profiles are selected by developers.",t=>e.cloud.status(t.workspace),"read"),n({workspace:d,operationId:s.string()},"hupu_cloud_operation","Query the original cloud operation until succeeded or failed. Queued/running are not completion; never resubmit with a new key to bypass an unknown result.",t=>e.cloud.operation(t.workspace,t.operationId),"read"),n({workspace:d},"hupu_cloud_enable","Enable cloud resources for this application; may incur resource charges. Reuses existing resources. Check cloud status for resource readiness before deploying.",t=>e.cloud.enable(t.workspace)),n({workspace:d,directory:s.string().optional(),manifestFile:s.string().optional(),bundleFile:s.string().optional(),idempotencyKey:O},"hupu_cloud_deploy","Publish the whole backend service and its declared routes. Default: build cloud/functions/api (legacy functions/api is detected). Alternatively pass both manifestFile and bundleFile, without directory. Confirm required migrations have completed before deploying. Queued means accepted, not deployed. One application has one active service.",t=>e.cloud.deploy(t.workspace,{...t.directory!==void 0?{directory:t.directory}:{},...t.manifestFile!==void 0?{manifestFile:t.manifestFile}:{},...t.bundleFile!==void 0?{bundleFile:t.bundleFile}:{}},t.idempotencyKey)),n({workspace:d,version:s.string(),file:s.string(),idempotencyKey:O},"hupu_cloud_database_migrate","Submit a versioned PostgreSQL migration file. Queued/running only confirms acceptance or execution. Without succeeded, platform confirmation is required before dependent changes; no migration completion query or retry is exposed. Applied versions are immutable.",t=>e.cloud.migrate(t.workspace,t.version,t.file,t.idempotencyKey)),n({workspace:d},"hupu_cloud_routes","Inspect effective routes. To change routes, edit cloud.json and deploy the service so source and runtime agree.",t=>e.cloud.routes(t.workspace),"read"),o.legacyCloud&&(n({workspace:d},"hupu_legacy_cloud_capabilities","Read Hupu Cloud runtimes, database dialect and environment-creation capabilities for this app.",t=>e.legacyCloud.capabilities(t.workspace),"read"),n({workspace:d},"hupu_legacy_cloud_environments","List cloud environments belonging to this Shaper application.",t=>e.legacyCloud.environments(t.workspace),"read"),n({workspace:d,environment:b,postgres:s.boolean().default(!1)},"hupu_legacy_cloud_create","Provision an environment for this app using the platform-approved plan. This may incur cloud charges. PostgreSQL must be requested at creation.",t=>e.legacyCloud.create(t.workspace,t.environment,t.postgres)),n({workspace:d,environment:b},"hupu_legacy_cloud_status","Refresh the readiness of this Hupu Cloud environment.",t=>e.legacyCloud.status(t.workspace,t.environment),"read"),n({workspace:d,environment:b},"hupu_legacy_cloud_functions","List cloud functions and deployment states.",t=>e.legacyCloud.functions(t.workspace,t.environment),"read"),n({workspace:d,environment:b,name:ne,directory:s.string(),idempotencyKey:O},"hupu_legacy_cloud_function_deploy","Legacy event-function deployment only (index.js exporting main). For new HTTP backends use hupu_cloud_init and hupu_cloud_deploy.",t=>e.legacyCloud.deployFunction(t.workspace,t.environment,t.name,t.directory,t.idempotencyKey)),n({workspace:d,environment:b,name:ne,payload:s.unknown(),idempotencyKey:O},"hupu_legacy_cloud_function_invoke","Invoke a cloud function with JSON input; report execution status and output.",t=>e.legacyCloud.invoke(t.workspace,t.environment,t.name,t.payload,t.idempotencyKey)),n({workspace:d,environment:b,name:ne},"hupu_legacy_cloud_function_logs","Read recent function logs.",t=>e.legacyCloud.logs(t.workspace,t.environment,t.name),"read"),n({workspace:d,environment:b,sql:s.string().min(1).max(6e4),idempotencyKey:O},"hupu_legacy_cloud_database_query","Execute privileged PostgreSQL SQL in the selected app environment. This can mutate or delete data; follow the requested business scope.",t=>e.legacyCloud.sql(t.workspace,t.environment,t.sql,t.idempotencyKey),"destructive"),n({workspace:d,environment:b,prefix:s.string().optional(),cursor:s.string().optional()},"hupu_legacy_cloud_storage_list","List private cloud objects, with pagination.",t=>e.legacyCloud.listObjects(t.workspace,t.environment,t.prefix,t.cursor),"read"),n({workspace:d,environment:b,objectKey:s.string(),file:s.string(),idempotencyKey:O},"hupu_legacy_cloud_storage_upload","Upload a project file (maximum 10 MiB) to private application storage. Replaces the same object key.",t=>e.legacyCloud.putObject(t.workspace,t.environment,t.objectKey,t.file,t.idempotencyKey)),n({workspace:d,environment:b,objectKey:s.string(),destination:s.string()},"hupu_legacy_cloud_storage_download","Download a cloud object to a new file inside the project; existing files are never overwritten.",t=>e.legacyCloud.getObject(t.workspace,t.environment,t.objectKey,t.destination)),n({workspace:d,environment:b,objectKey:s.string(),idempotencyKey:O},"hupu_legacy_cloud_storage_delete","Delete the explicitly requested object from application storage.",t=>e.legacyCloud.deleteObject(t.workspace,t.environment,t.objectKey,t.idempotencyKey),"destructive")),i}async function Pe(e={}){let o=await c.create(),i=it(o,e);await i.connect(new ot);let n=async()=>{await o.auth.close(),await i.close()};process.once("SIGTERM",()=>{n()}),process.once("SIGINT",()=>{n()}),process.stdin.once("end",()=>{n()})}var p=new rt().name("shaper").description("Shaper \u672C\u5730\u5F00\u53D1\u3001\u7F51\u9875\u4EA4\u4ED8\u4E0E\u864E\u6251\u4E91\u5DE5\u5177").version(X),ie=e=>process.stdout.write(JSON.stringify(e,null,2)+`
13
- `),r=e=>async(...o)=>{ie(await e(...o))};p.command("install").description("\u5168\u5C40\u5B89\u88C5 MCP \u548C Skills \u5230\u6307\u5B9A IDE").requiredOption("--ide <names>","codex,cursor,claude").option("--dev","\u76F4\u63A5\u4F7F\u7528\u5F53\u524D\u672C\u5730\u5305\u8FD0\u884C MCP \u548C\u6280\u80FD\uFF0C\u4E0D\u590D\u5236\u53D1\u884C\u5FEB\u7167").option("--skills <names>","\u9644\u52A0\u4E13\u4E1A\u6280\u80FD\uFF0C\u9017\u53F7\u5206\u9694").action(r(async e=>fe(e.ide.split(","),{skills:e.skills?.split(","),dev:e.dev===!0})));p.command("update").description("\u5B89\u88C5\u6307\u5B9A\u53D1\u5E03\u7248\u672C\uFF0C\u4FDD\u7559\u539F IDE \u8BBE\u7F6E").requiredOption("--version <version>").requiredOption("--ide <names>").action(r(async e=>fe(e.ide.split(","),{version:e.version})));p.command("uninstall").description("\u79FB\u9664\u672C\u5DE5\u5177\u7BA1\u7406\u7684 IDE \u914D\u7F6E\u548C\u6280\u80FD\u94FE\u63A5").action(r(je));p.command("doctor").description("\u68C0\u67E5\u5B89\u88C5\u4E0E\u9879\u76EE\u72B6\u6001").option("--cwd <directory>").action(r(async e=>({installation:await Le(),status:await(await c.create()).status(e.cwd&&l(e.cwd))})));p.command("config").description("\u67E5\u770B\u6216\u8BBE\u7F6E CLI / MCP \u5171\u7528\u7684\u9ED8\u8BA4\u670D\u52A1\uFF1B\u4E0D\u9700\u8981\u767B\u5F55").option("--server <origin>","\u4FDD\u5B58\u9ED8\u8BA4\u670D\u52A1\u5730\u5740").action(r(async e=>(e.server&&await se(e.server),{server:await be(),configDirectory:y(),source:process.env.SHAPER_SERVER?"SHAPER_SERVER":"global config or default",...e.server?{saved:!0,configuredServer:e.server,restartMcp:!0}:{}})));p.command("login").description("\u8FDE\u63A5\u5168\u5C40\u8D26\u53F7\uFF1B\u5DF2\u6709\u6743\u9650\u76F4\u63A5\u590D\u7528").option("--server <origin>").option("--cloud","\u8FFD\u52A0\u4E91\u51FD\u6570\u548C\u6570\u636E\u5E93\u7BA1\u7406\u6743\u9650").option("--app <appId>","\u4E3A\u5DF2\u6709\u5E94\u7528\u8865\u5145\u6388\u6743").option("--reauthorize","\u6253\u5F00\u7F51\u9875\u589E\u52A0\u6388\u6743\u8303\u56F4").option("--no-browser","\u4EC5\u8F93\u51FA\u6388\u6743\u94FE\u63A5").action(async e=>{let o=await c.create(e.server);try{let i=await o.auth.start({cloud:e.cloud===!0,openBrowser:e.browser!==!1,reauthorize:e.reauthorize===!0,...e.app?{appId:e.app}:{}});ie(i),i.status==="pending"&&ie(await o.auth.wait(i.flowId)),e.server&&await se(o.auth.server)}finally{await o.auth.close()}});p.command("logout").description("\u9000\u51FA\u5168\u5C40\u8D26\u53F7\uFF0C\u5F53\u524D\u670D\u52A1\u7684\u6240\u6709\u672C\u5730\u9879\u76EE\u90FD\u9700\u8981\u91CD\u65B0\u767B\u5F55").action(r(async()=>(await c.create()).auth.logout()));p.command("whoami").description("\u8BFB\u53D6\u5F53\u524D\u767B\u5F55\u8EAB\u4EFD\u4E0E\u6388\u6743\u8303\u56F4").action(r(async()=>(await c.create()).api.me()));p.command("init").argument("[directory]","\u5DE5\u7A0B\u76EE\u5F55",".").option("--name <name>").option("--app <appId>","\u5173\u8054\u6307\u5B9A\u5E94\u7528\uFF1B\u5C1A\u672A\u521B\u5EFA\u65F6\u5728\u6D4F\u89C8\u5668\u786E\u8BA4\u521B\u5EFA").option("--template <name>","\u7A7A\u76EE\u5F55\u6A21\u677F\uFF1Ah5\u3001react\u3001phaser").option("--no-install","\u8DF3\u8FC7\u4F9D\u8D56\u5B89\u88C5").action(r(async(e,o)=>K((await c.create()).api,l(e),{...o.name?{name:o.name}:{},...o.app?{appId:o.app}:{},waitForAuthorization:!0,template:o.template,installDependencies:o.install!==!1})));p.command("link").requiredOption("--app <appId>").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(r(async e=>z((await c.create()).api,l(e.cwd),e.app)));p.command("projects").action(r(async()=>(await c.create()).api.projects()));p.command("status").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(r(async e=>(await c.create()).status(l(e.cwd))));p.command("dev").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(r(async e=>W(l(e.cwd))));p.command("stop").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(r(async e=>Y(l(e.cwd))));p.command("logs").description("\u8BFB\u53D6\u672C\u5730\u5F00\u53D1\u670D\u52A1\u65E5\u5FD7").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(r(async e=>Z(l(e.cwd))));p.command("build").description("\u6784\u5EFA\u7F51\u9875\u5236\u54C1").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(r(async e=>V(l(e.cwd))));p.command("check").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(async e=>{let o=await H(l(e.cwd));ie(o),o.passed||(process.exitCode=1)});p.command("deploy").description("\u6784\u5EFA\u7F51\u9875\u5E76\u4EA4\u4ED8\u5230 Shaper \u9884\u89C8").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(r(async e=>Q((await c.create()).api,l(e.cwd))));p.command("publish").description("\u6253\u5F00\u6D4F\u89C8\u5668\u786E\u8BA4\u6307\u5B9A\u7248\u672C\u7684\u5BA1\u6838\u63D0\u4EA4").requiredOption("--version <versionId>").requiredOption("--description <text>").option("--cover <file>","\u53EF\u9009\u5DE5\u7A0B\u5185\u5C01\u9762\uFF0C\u4E5F\u53EF\u5728\u6D4F\u89C8\u5668\u8865\u5145").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(r(async e=>U((await c.create()).api,l(e.cwd),e.version,e.description,e.cover)));var E=p.command("cloud").description("\u5E94\u7528\u4E91\u670D\u52A1\uFF1A\u5F00\u901A\u3001\u53D1\u5E03\u3001\u6570\u636E\u5E93\u8FC1\u79FB\u3001\u72B6\u6001\u548C\u8DEF\u7531");function _(e,o,i){return e.command(o).description(i).option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".")}_(E,"init [directory]","\u521B\u5EFA\u540E\u53F0\u670D\u52A1\u6E90\u7801\u76EE\u5F55\uFF0C\u9ED8\u8BA4 cloud/functions/api\uFF0C\u4E0D\u8986\u76D6\u5DF2\u6709\u4EE3\u7801").action(r(async(e,o)=>B(l(o.cwd),e)));_(E,"build [directory]","\u6784\u5EFA\u540E\u53F0\u670D\u52A1\u5236\u54C1\uFF1B\u4E0D\u90E8\u7F72").action(r(async(e,o)=>G(l(o.cwd),e)));_(E,"status","\u67E5\u770B\u5E94\u7528\u4E91\u670D\u52A1\u662F\u5426\u5C31\u7EEA\u3001\u5F53\u524D\u90E8\u7F72\u4E86\u4EC0\u4E48").action(r(async e=>(await c.create()).cloud.status(l(e.cwd))));_(E,"operation <operationId>","\u67E5\u8BE2\u539F\u4E91\u64CD\u4F5C\u7684\u6700\u7EC8\u7ED3\u679C\uFF0C\u4E0D\u91CD\u590D\u63D0\u4EA4").action(r(async(e,o)=>(await c.create()).cloud.operation(l(o.cwd),e)));_(E,"enable","\u5F00\u901A\u5E94\u7528\u4E91\u670D\u52A1\uFF0C\u91CD\u590D\u8C03\u7528\u590D\u7528\u5DF2\u6709\u8D44\u6E90").action(r(async e=>(await c.create()).cloud.enable(l(e.cwd))));_(E,"deploy","\u53D1\u5E03\u540E\u53F0\u670D\u52A1\u4E0E cloud.json \u8DEF\u7531\uFF1B\u9ED8\u8BA4\u4ECE cloud/functions/api \u6784\u5EFA").option("--directory <directory>","\u6E90\u7801\u76EE\u5F55\uFF1B\u4E0D\u80FD\u4E0E\u5236\u54C1\u53C2\u6570\u6DF7\u7528").option("--manifest <file>","\u5DF2\u6709\u5236\u54C1\u7684 manifest\uFF1B\u987B\u540C\u65F6\u63D0\u4F9B --bundle").option("--bundle <file>","\u5DF2\u6709\u5236\u54C1\u7684 bundle\uFF1B\u987B\u540C\u65F6\u63D0\u4F9B --manifest").option("--key <key>","\u8BF7\u6C42\u5E42\u7B49\u952E\uFF1B\u9ED8\u8BA4\u6309\u5185\u5BB9\u751F\u6210").action(r(async e=>(await c.create()).cloud.deploy(l(e.cwd),{...e.directory!==void 0?{directory:e.directory}:{},...e.manifest!==void 0?{manifestFile:e.manifest}:{},...e.bundle!==void 0?{bundleFile:e.bundle}:{}},e.key)));var at=E.command("db").description("\u5E94\u7528\u7684\u6570\u636E\u5E93\u53D8\u66F4");_(at,"migrate","\u63D0\u4EA4\u7248\u672C\u5316 PostgreSQL \u8FC1\u79FB").requiredOption("--version <version>").requiredOption("--file <file>").option("--key <key>").action(r(async e=>(await c.create()).cloud.migrate(l(e.cwd),e.version,e.file,e.key)));_(E,"routes","\u67E5\u770B\u5DF2\u751F\u6548\u8DEF\u7531\uFF1B\u4FEE\u6539 cloud.json \u540E\u91CD\u65B0 deploy").action(r(async e=>(await c.create()).cloud.routes(l(e.cwd))));var st=p.command("legacy").description("\u5B58\u91CF\u7CFB\u7EDF\u517C\u5BB9\u5DE5\u5177"),ct=st.command("cloud").description("\u65E7\u4E8B\u4EF6\u51FD\u6570\u6267\u884C\u5668\uFF1B\u4E0D\u80FD\u64CD\u4F5C\u65B0\u7248\u5E94\u7528\u4E91\u8D44\u6E90");function v(e,o){return _(ct,e,o)}v("capabilities","\u8BFB\u53D6\u8FD0\u884C\u65F6\u3001\u6570\u636E\u5E93\u65B9\u8A00\u4E0E\u5957\u9910\u914D\u7F6E").action(r(async e=>(await c.create()).legacyCloud.capabilities(l(e.cwd))));v("list","\u5217\u51FA\u5F53\u524D\u5E94\u7528\u7684\u4E91\u73AF\u5883").action(r(async e=>(await c.create()).legacyCloud.environments(l(e.cwd))));v("create <environment>","\u6309\u5E73\u53F0\u5957\u9910\u5F00\u901A\u4E91\u73AF\u5883\uFF0C\u53EF\u80FD\u4EA7\u751F\u8D39\u7528").option("--postgres","\u540C\u65F6\u5F00\u901A PostgreSQL").action(r(async(e,o)=>(await c.create()).legacyCloud.create(l(o.cwd),e,o.postgres===!0)));v("status <environment>","\u8BFB\u53D6\u771F\u5B9E\u4E91\u73AF\u5883\u72B6\u6001").action(r(async(e,o)=>(await c.create()).legacyCloud.status(l(o.cwd),e)));v("functions <environment>","\u5217\u51FA\u4E91\u51FD\u6570\u53CA\u72B6\u6001").action(r(async(e,o)=>(await c.create()).legacyCloud.functions(l(o.cwd),e)));v("deploy <environment> <name> <directory>","\u90E8\u7F72\u5DF2\u6253\u5305\u7684\u4E91\u51FD\u6570\u76EE\u5F55").option("--key <key>","\u8BF7\u6C42\u5E42\u7B49\u952E").action(r(async(e,o,i,n)=>(await c.create()).legacyCloud.deployFunction(l(n.cwd),e,o,i,n.key)));v("invoke <environment> <name>","\u6267\u884C\u4E91\u51FD\u6570").option("--input <file>","JSON \u8F93\u5165\u6587\u4EF6").option("--key <key>").action(r(async(e,o,i)=>(await c.create()).legacyCloud.invoke(l(i.cwd),e,o,i.input?JSON.parse(await Te(i.input,"utf8")):{},i.key)));v("logs <environment> <name>","\u67E5\u770B\u4E91\u51FD\u6570\u65E5\u5FD7").action(r(async(e,o,i)=>(await c.create()).legacyCloud.logs(l(i.cwd),e,o)));v("sql <environment>","\u6267\u884C\u6570\u636E\u5E93\u7BA1\u7406 SQL").requiredOption("--file <file>","SQL \u6587\u4EF6").option("--key <key>").action(r(async(e,o)=>(await c.create()).legacyCloud.sql(l(o.cwd),e,await Te(o.file,"utf8"),o.key)));v("storage-list <environment>","\u5217\u51FA\u4E91\u5B58\u50A8\u5BF9\u8C61").option("--prefix <prefix>").option("--cursor <cursor>").action(r(async(e,o)=>(await c.create()).legacyCloud.listObjects(l(o.cwd),e,o.prefix,o.cursor)));v("storage-put <environment> <objectKey> <file>","\u4E0A\u4F20\u5DE5\u7A0B\u5185\u6587\u4EF6\u5230\u79C1\u6709\u4E91\u5B58\u50A8").option("--key <key>").action(r(async(e,o,i,n)=>(await c.create()).legacyCloud.putObject(l(n.cwd),e,o,i,n.key)));v("storage-get <environment> <objectKey> <destination>","\u4E0B\u8F7D\u5230\u5DE5\u7A0B\u5185\u7684\u65B0\u6587\u4EF6").action(r(async(e,o,i,n)=>(await c.create()).legacyCloud.getObject(l(n.cwd),e,o,i)));v("storage-delete <environment> <objectKey>","\u5220\u9664\u6307\u5B9A\u4E91\u5B58\u50A8\u5BF9\u8C61").option("--key <key>").action(r(async(e,o,i)=>(await c.create()).legacyCloud.deleteObject(l(i.cwd),e,o,i.key)));p.command("mcp").command("serve").description("\u542F\u52A8 stdio MCP \u670D\u52A1").option("--legacy-cloud","\u989D\u5916\u5F00\u653E\u65E7\u4E91\u7EF4\u62A4\u5DE5\u5177").action(async e=>Pe({legacyCloud:e.legacyCloud===!0}));try{await p.parseAsync()}catch(e){process.stderr.write(JSON.stringify($(e))+`
2
+ import{c as D,d as z,e as T,f as C}from"./shared-BQF7QNXK.js";import{c as S,d as j,g as a}from"./shared-NQ3JXFQJ.js";import{c as x,d as I,e as P}from"./shared-JYAK4XUO.js";import{b as K,f as E,g as L,h as w,m as f,n as v,o as h,q as b,r as k,s as _}from"./shared-WR2EQORG.js";import{Command as G}from"commander";import{readFile as M}from"node:fs/promises";import{resolve as c}from"node:path";import{McpServer as W}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as B}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as r}from"zod";import{isAbsolute as U}from"node:path";var s=r.string().min(1).refine(U,"workspace must be an absolute path").describe("Absolute local project directory. Never infer from the MCP process working directory."),u=r.string().regex(/^[a-z][a-z0-9-]{0,31}$/),O=r.string().min(1).max(64),g=r.string().min(16).max(100).optional();function V(e,o={}){let d=new W({name:"shaper",version:C},{instructions:"Use installed Shaper skills for workflows. Always pass the intended absolute workspace. All sessions share one login per Shaper server. Reuse it; request additional permissions only when needed. Browser consent adds permissions without replacing existing access. Local binding contains only the server and app ID, never tokens. Never choose a recent app as a fallback. Web delivery and backend service deployment have separate targets. Queued, running or uncertain results do not confirm completion. Use hupu_cloud_operation to confirm asynchronous results."});function i(t,N,Q,H,F="write"){d.registerTool(N,{description:Q,inputSchema:t,annotations:{readOnlyHint:F==="read",destructiveHint:F==="destructive",openWorldHint:!0}},async J=>{try{let R=await H(J);return{content:[{type:"text",text:JSON.stringify(R,null,2)}]}}catch(R){return{isError:!0,content:[{type:"text",text:JSON.stringify(w(R))}]}}})}return i({workspace:s.optional()},"shaper_status","Read current identity, local project binding and development session. Does not start services.",t=>e.status(t.workspace),"read"),i({cloud:r.boolean().default(!1),openBrowser:r.boolean().default(!0),appId:r.string().min(1).max(200).optional(),reauthorize:r.boolean().default(!1)},"shaper_auth_start","Reuse the global login when permissions suffice. Otherwise start browser consent and return a flow ID. appId adds access to an existing application; cloud=true adds cloud permissions. Existing permissions are retained. reauthorize=true opens consent explicitly.",t=>e.auth.start(t)),i({flowId:r.string()},"shaper_auth_status","Read browser authorization result for a flow started by this MCP session.",t=>e.auth.status(t.flowId),"read"),i({},"shaper_logout","Sign out globally for this Shaper server. All local projects and Agent sessions share this login.",()=>e.auth.logout(),"destructive"),i({},"shaper_projects","List applications available to this authorization.",()=>e.api.projects(),"read"),i({workspace:s,template:r.enum(["h5","react","phaser"]).optional(),name:O.optional(),appId:r.string().optional(),installDependencies:r.boolean().default(!0)},"shaper_init","Create a vanilla HTML, React or Phaser project and a Shaper application, or initialize an existing source directory. Resolve existing identity first; missing apps require browser creation consent. A pending result requires finishing authorization and retrying with the same workspace/appId. Never overwrite a conflicting existing binding.",t=>f(e.api,t.workspace,t)),i({workspace:s,appId:r.string()},"shaper_link","Associate the local source directory with an existing authorized Shaper application.",t=>v(e.api,t.workspace,t.appId)),i({workspace:s},"shaper_dev_start","Start a local development server using shaper.config.json and return its verified URL.",t=>x(t.workspace)),i({workspace:s},"shaper_dev_stop","Stop the development session managed for this project.",t=>I(t.workspace)),i({workspace:s},"shaper_dev_logs","Read recent local development output.",t=>P(t.workspace),"read"),i({workspace:s},"shaper_build","Run the project build command and verify the web output.",t=>h(t.workspace)),i({workspace:s},"shaper_check","Check project configuration; this is not a behavior or cloud connectivity test.",t=>_(t.workspace),"read"),i({workspace:s},"shaper_web_deploy","Build and upload web code through Shaper; return request status, validation and preview details.",t=>b(e.api,t.workspace)),i({workspace:s,versionId:r.string(),description:r.string().min(1),coverPath:r.string().optional()},"shaper_web_publish","Prepare review details and open a browser confirmation page. This does NOT submit review: the user edits details and submits in the browser. Cover is optional here and can be supplied in the browser.",t=>k(e.api,t.workspace,t.versionId,t.description,t.coverPath)),i({workspace:s,directory:r.string().optional()},"hupu_cloud_init","Create a local Node backend source directory; does not provision resources or overwrite existing code.",t=>S(t.workspace,t.directory)),i({workspace:s,directory:r.string().optional()},"hupu_cloud_build","Build backend artifacts locally. Deployment also builds by default, so this is only needed to inspect or reuse artifacts.",t=>j(t.workspace,t.directory)),i({workspace:s},"hupu_cloud_status","Read application cloud readiness and current release. No test/production environments or resource profiles are selected by developers.",t=>e.cloud.status(t.workspace),"read"),i({workspace:s,operationId:r.string()},"hupu_cloud_operation","Query the original cloud operation until succeeded or failed. Queued/running are not completion; never resubmit with a new key to bypass an unknown result.",t=>e.cloud.operation(t.workspace,t.operationId),"read"),i({workspace:s},"hupu_cloud_enable","Enable cloud resources for this application; may incur resource charges. Reuses existing resources. Check cloud status for resource readiness before deploying.",t=>e.cloud.enable(t.workspace)),i({workspace:s,directory:r.string().optional(),manifestFile:r.string().optional(),bundleFile:r.string().optional(),idempotencyKey:g},"hupu_cloud_deploy","Publish the whole backend service and its declared routes. Default: build cloud/functions/api (legacy functions/api is detected). Alternatively pass both manifestFile and bundleFile, without directory. Confirm required migrations have completed before deploying. Queued means accepted, not deployed. One application has one active service.",t=>e.cloud.deploy(t.workspace,{...t.directory!==void 0?{directory:t.directory}:{},...t.manifestFile!==void 0?{manifestFile:t.manifestFile}:{},...t.bundleFile!==void 0?{bundleFile:t.bundleFile}:{}},t.idempotencyKey)),i({workspace:s,version:r.string(),file:r.string(),idempotencyKey:g},"hupu_cloud_database_migrate","Submit a versioned PostgreSQL migration file. Queued/running only confirms acceptance or execution. Without succeeded, platform confirmation is required before dependent changes; no migration completion query or retry is exposed. Applied versions are immutable.",t=>e.cloud.migrate(t.workspace,t.version,t.file,t.idempotencyKey)),i({workspace:s},"hupu_cloud_routes","Inspect effective routes. To change routes, edit cloud.json and deploy the service so source and runtime agree.",t=>e.cloud.routes(t.workspace),"read"),o.legacyCloud&&(i({workspace:s},"hupu_legacy_cloud_capabilities","Read Hupu Cloud runtimes, database dialect and environment-creation capabilities for this app.",t=>e.legacyCloud.capabilities(t.workspace),"read"),i({workspace:s},"hupu_legacy_cloud_environments","List cloud environments belonging to this Shaper application.",t=>e.legacyCloud.environments(t.workspace),"read"),i({workspace:s,environment:u,postgres:r.boolean().default(!1)},"hupu_legacy_cloud_create","Provision an environment for this app using the platform-approved plan. This may incur cloud charges. PostgreSQL must be requested at creation.",t=>e.legacyCloud.create(t.workspace,t.environment,t.postgres)),i({workspace:s,environment:u},"hupu_legacy_cloud_status","Refresh the readiness of this Hupu Cloud environment.",t=>e.legacyCloud.status(t.workspace,t.environment),"read"),i({workspace:s,environment:u},"hupu_legacy_cloud_functions","List cloud functions and deployment states.",t=>e.legacyCloud.functions(t.workspace,t.environment),"read"),i({workspace:s,environment:u,name:O,directory:r.string(),idempotencyKey:g},"hupu_legacy_cloud_function_deploy","Legacy event-function deployment only (index.js exporting main). For new HTTP backends use hupu_cloud_init and hupu_cloud_deploy.",t=>e.legacyCloud.deployFunction(t.workspace,t.environment,t.name,t.directory,t.idempotencyKey)),i({workspace:s,environment:u,name:O,payload:r.unknown(),idempotencyKey:g},"hupu_legacy_cloud_function_invoke","Invoke a cloud function with JSON input; report execution status and output.",t=>e.legacyCloud.invoke(t.workspace,t.environment,t.name,t.payload,t.idempotencyKey)),i({workspace:s,environment:u,name:O},"hupu_legacy_cloud_function_logs","Read recent function logs.",t=>e.legacyCloud.logs(t.workspace,t.environment,t.name),"read"),i({workspace:s,environment:u,sql:r.string().min(1).max(6e4),idempotencyKey:g},"hupu_legacy_cloud_database_query","Execute privileged PostgreSQL SQL in the selected app environment. This can mutate or delete data; follow the requested business scope.",t=>e.legacyCloud.sql(t.workspace,t.environment,t.sql,t.idempotencyKey),"destructive"),i({workspace:s,environment:u,prefix:r.string().optional(),cursor:r.string().optional()},"hupu_legacy_cloud_storage_list","List private cloud objects, with pagination.",t=>e.legacyCloud.listObjects(t.workspace,t.environment,t.prefix,t.cursor),"read"),i({workspace:s,environment:u,objectKey:r.string(),file:r.string(),idempotencyKey:g},"hupu_legacy_cloud_storage_upload","Upload a project file (maximum 10 MiB) to private application storage. Replaces the same object key.",t=>e.legacyCloud.putObject(t.workspace,t.environment,t.objectKey,t.file,t.idempotencyKey)),i({workspace:s,environment:u,objectKey:r.string(),destination:r.string()},"hupu_legacy_cloud_storage_download","Download a cloud object to a new file inside the project; existing files are never overwritten.",t=>e.legacyCloud.getObject(t.workspace,t.environment,t.objectKey,t.destination)),i({workspace:s,environment:u,objectKey:r.string(),idempotencyKey:g},"hupu_legacy_cloud_storage_delete","Delete the explicitly requested object from application storage.",t=>e.legacyCloud.deleteObject(t.workspace,t.environment,t.objectKey,t.idempotencyKey),"destructive")),d}async function A(e={}){let o=await a.create(),d=V(o,e);await d.connect(new B);let i=async()=>{await o.auth.close(),await d.close()};process.once("SIGTERM",()=>{i()}),process.once("SIGINT",()=>{i()}),process.stdin.once("end",()=>{i()})}var l=new G().name("shaper").description("Shaper \u672C\u5730\u5F00\u53D1\u3001\u7F51\u9875\u4EA4\u4ED8\u4E0E\u864E\u6251\u4E91\u5DE5\u5177").version(C),q=e=>process.stdout.write(JSON.stringify(e,null,2)+`
3
+ `),n=e=>async(...o)=>{q(await e(...o))};l.command("install").description("\u5168\u5C40\u5B89\u88C5 MCP \u548C Skills \u5230\u6307\u5B9A IDE").requiredOption("--ide <names>","codex,cursor,claude").option("--dev","\u76F4\u63A5\u4F7F\u7528\u5F53\u524D\u672C\u5730\u5305\u8FD0\u884C MCP \u548C\u6280\u80FD\uFF0C\u4E0D\u590D\u5236\u53D1\u884C\u5FEB\u7167").option("--skills <names>","\u9644\u52A0\u4E13\u4E1A\u6280\u80FD\uFF0C\u9017\u53F7\u5206\u9694").action(n(async e=>D(e.ide.split(","),{skills:e.skills?.split(","),dev:e.dev===!0})));l.command("update").description("\u5B89\u88C5\u6307\u5B9A\u53D1\u5E03\u7248\u672C\uFF0C\u4FDD\u7559\u539F IDE \u8BBE\u7F6E").requiredOption("--version <version>").requiredOption("--ide <names>").action(n(async e=>D(e.ide.split(","),{version:e.version})));l.command("uninstall").description("\u79FB\u9664\u672C\u5DE5\u5177\u7BA1\u7406\u7684 IDE \u914D\u7F6E\u548C\u6280\u80FD\u94FE\u63A5").action(n(z));l.command("doctor").description("\u68C0\u67E5\u5B89\u88C5\u4E0E\u9879\u76EE\u72B6\u6001").option("--cwd <directory>").action(n(async e=>({installation:await T(),status:await(await a.create()).status(e.cwd&&c(e.cwd))})));l.command("config").description("\u67E5\u770B\u6216\u8BBE\u7F6E CLI / MCP \u5171\u7528\u7684\u9ED8\u8BA4\u670D\u52A1\uFF1B\u4E0D\u9700\u8981\u767B\u5F55").option("--server <origin>","\u4FDD\u5B58\u9ED8\u8BA4\u670D\u52A1\u5730\u5740").action(n(async e=>(e.server&&await L(e.server),{server:await E(),configDirectory:K(),source:process.env.SHAPER_SERVER?"SHAPER_SERVER":"global config or default",...e.server?{saved:!0,configuredServer:e.server,restartMcp:!0}:{}})));l.command("login").description("\u8FDE\u63A5\u5168\u5C40\u8D26\u53F7\uFF1B\u5DF2\u6709\u6743\u9650\u76F4\u63A5\u590D\u7528").option("--server <origin>").option("--cloud","\u8FFD\u52A0\u4E91\u51FD\u6570\u548C\u6570\u636E\u5E93\u7BA1\u7406\u6743\u9650").option("--app <appId>","\u4E3A\u5DF2\u6709\u5E94\u7528\u8865\u5145\u6388\u6743").option("--reauthorize","\u6253\u5F00\u7F51\u9875\u589E\u52A0\u6388\u6743\u8303\u56F4").option("--no-browser","\u4EC5\u8F93\u51FA\u6388\u6743\u94FE\u63A5").action(async e=>{let o=await a.create(e.server);try{let d=await o.auth.start({cloud:e.cloud===!0,openBrowser:e.browser!==!1,reauthorize:e.reauthorize===!0,...e.app?{appId:e.app}:{}});q(d),d.status==="pending"&&q(await o.auth.wait(d.flowId)),e.server&&await L(o.auth.server)}finally{await o.auth.close()}});l.command("logout").description("\u9000\u51FA\u5168\u5C40\u8D26\u53F7\uFF0C\u5F53\u524D\u670D\u52A1\u7684\u6240\u6709\u672C\u5730\u9879\u76EE\u90FD\u9700\u8981\u91CD\u65B0\u767B\u5F55").action(n(async()=>(await a.create()).auth.logout()));l.command("whoami").description("\u8BFB\u53D6\u5F53\u524D\u767B\u5F55\u8EAB\u4EFD\u4E0E\u6388\u6743\u8303\u56F4").action(n(async()=>(await a.create()).api.me()));l.command("init").argument("[directory]","\u5DE5\u7A0B\u76EE\u5F55",".").option("--name <name>").option("--app <appId>","\u5173\u8054\u6307\u5B9A\u5E94\u7528\uFF1B\u5C1A\u672A\u521B\u5EFA\u65F6\u5728\u6D4F\u89C8\u5668\u786E\u8BA4\u521B\u5EFA").option("--template <name>","\u7A7A\u76EE\u5F55\u6A21\u677F\uFF1Ah5\u3001react\u3001phaser").option("--no-install","\u8DF3\u8FC7\u4F9D\u8D56\u5B89\u88C5").action(n(async(e,o)=>f((await a.create()).api,c(e),{...o.name?{name:o.name}:{},...o.app?{appId:o.app}:{},waitForAuthorization:!0,template:o.template,installDependencies:o.install!==!1})));l.command("link").requiredOption("--app <appId>").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(n(async e=>v((await a.create()).api,c(e.cwd),e.app)));l.command("projects").action(n(async()=>(await a.create()).api.projects()));l.command("status").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(n(async e=>(await a.create()).status(c(e.cwd))));l.command("dev").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(n(async e=>x(c(e.cwd))));l.command("stop").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(n(async e=>I(c(e.cwd))));l.command("logs").description("\u8BFB\u53D6\u672C\u5730\u5F00\u53D1\u670D\u52A1\u65E5\u5FD7").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(n(async e=>P(c(e.cwd))));l.command("build").description("\u6784\u5EFA\u7F51\u9875\u5236\u54C1").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(n(async e=>h(c(e.cwd))));l.command("check").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(async e=>{let o=await _(c(e.cwd));q(o),o.passed||(process.exitCode=1)});l.command("deploy").description("\u6784\u5EFA\u7F51\u9875\u5E76\u4EA4\u4ED8\u5230 Shaper \u9884\u89C8").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(n(async e=>b((await a.create()).api,c(e.cwd))));l.command("publish").description("\u6253\u5F00\u6D4F\u89C8\u5668\u786E\u8BA4\u6307\u5B9A\u7248\u672C\u7684\u5BA1\u6838\u63D0\u4EA4").requiredOption("--version <versionId>").requiredOption("--description <text>").option("--cover <file>","\u53EF\u9009\u5DE5\u7A0B\u5185\u5C01\u9762\uFF0C\u4E5F\u53EF\u5728\u6D4F\u89C8\u5668\u8865\u5145").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(n(async e=>k((await a.create()).api,c(e.cwd),e.version,e.description,e.cover)));var y=l.command("cloud").description("\u5E94\u7528\u4E91\u670D\u52A1\uFF1A\u5F00\u901A\u3001\u53D1\u5E03\u3001\u6570\u636E\u5E93\u8FC1\u79FB\u3001\u72B6\u6001\u548C\u8DEF\u7531");function m(e,o,d){return e.command(o).description(d).option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".")}m(y,"init [directory]","\u521B\u5EFA\u540E\u53F0\u670D\u52A1\u6E90\u7801\u76EE\u5F55\uFF0C\u9ED8\u8BA4 cloud/functions/api\uFF0C\u4E0D\u8986\u76D6\u5DF2\u6709\u4EE3\u7801").action(n(async(e,o)=>S(c(o.cwd),e)));m(y,"build [directory]","\u6784\u5EFA\u540E\u53F0\u670D\u52A1\u5236\u54C1\uFF1B\u4E0D\u90E8\u7F72").action(n(async(e,o)=>j(c(o.cwd),e)));m(y,"status","\u67E5\u770B\u5E94\u7528\u4E91\u670D\u52A1\u662F\u5426\u5C31\u7EEA\u3001\u5F53\u524D\u90E8\u7F72\u4E86\u4EC0\u4E48").action(n(async e=>(await a.create()).cloud.status(c(e.cwd))));m(y,"operation <operationId>","\u67E5\u8BE2\u539F\u4E91\u64CD\u4F5C\u7684\u6700\u7EC8\u7ED3\u679C\uFF0C\u4E0D\u91CD\u590D\u63D0\u4EA4").action(n(async(e,o)=>(await a.create()).cloud.operation(c(o.cwd),e)));m(y,"enable","\u5F00\u901A\u5E94\u7528\u4E91\u670D\u52A1\uFF0C\u91CD\u590D\u8C03\u7528\u590D\u7528\u5DF2\u6709\u8D44\u6E90").action(n(async e=>(await a.create()).cloud.enable(c(e.cwd))));m(y,"deploy","\u53D1\u5E03\u540E\u53F0\u670D\u52A1\u4E0E cloud.json \u8DEF\u7531\uFF1B\u9ED8\u8BA4\u4ECE cloud/functions/api \u6784\u5EFA").option("--directory <directory>","\u6E90\u7801\u76EE\u5F55\uFF1B\u4E0D\u80FD\u4E0E\u5236\u54C1\u53C2\u6570\u6DF7\u7528").option("--manifest <file>","\u5DF2\u6709\u5236\u54C1\u7684 manifest\uFF1B\u987B\u540C\u65F6\u63D0\u4F9B --bundle").option("--bundle <file>","\u5DF2\u6709\u5236\u54C1\u7684 bundle\uFF1B\u987B\u540C\u65F6\u63D0\u4F9B --manifest").option("--key <key>","\u8BF7\u6C42\u5E42\u7B49\u952E\uFF1B\u9ED8\u8BA4\u6309\u5185\u5BB9\u751F\u6210").action(n(async e=>(await a.create()).cloud.deploy(c(e.cwd),{...e.directory!==void 0?{directory:e.directory}:{},...e.manifest!==void 0?{manifestFile:e.manifest}:{},...e.bundle!==void 0?{bundleFile:e.bundle}:{}},e.key)));var Z=y.command("db").description("\u5E94\u7528\u7684\u6570\u636E\u5E93\u53D8\u66F4");m(Z,"migrate","\u63D0\u4EA4\u7248\u672C\u5316 PostgreSQL \u8FC1\u79FB").requiredOption("--version <version>").requiredOption("--file <file>").option("--key <key>").action(n(async e=>(await a.create()).cloud.migrate(c(e.cwd),e.version,e.file,e.key)));m(y,"routes","\u67E5\u770B\u5DF2\u751F\u6548\u8DEF\u7531\uFF1B\u4FEE\u6539 cloud.json \u540E\u91CD\u65B0 deploy").action(n(async e=>(await a.create()).cloud.routes(c(e.cwd))));var $=l.command("legacy").description("\u5B58\u91CF\u7CFB\u7EDF\u517C\u5BB9\u5DE5\u5177"),X=$.command("cloud").description("\u65E7\u4E8B\u4EF6\u51FD\u6570\u6267\u884C\u5668\uFF1B\u4E0D\u80FD\u64CD\u4F5C\u65B0\u7248\u5E94\u7528\u4E91\u8D44\u6E90");function p(e,o){return m(X,e,o)}p("capabilities","\u8BFB\u53D6\u8FD0\u884C\u65F6\u3001\u6570\u636E\u5E93\u65B9\u8A00\u4E0E\u5957\u9910\u914D\u7F6E").action(n(async e=>(await a.create()).legacyCloud.capabilities(c(e.cwd))));p("list","\u5217\u51FA\u5F53\u524D\u5E94\u7528\u7684\u4E91\u73AF\u5883").action(n(async e=>(await a.create()).legacyCloud.environments(c(e.cwd))));p("create <environment>","\u6309\u5E73\u53F0\u5957\u9910\u5F00\u901A\u4E91\u73AF\u5883\uFF0C\u53EF\u80FD\u4EA7\u751F\u8D39\u7528").option("--postgres","\u540C\u65F6\u5F00\u901A PostgreSQL").action(n(async(e,o)=>(await a.create()).legacyCloud.create(c(o.cwd),e,o.postgres===!0)));p("status <environment>","\u8BFB\u53D6\u771F\u5B9E\u4E91\u73AF\u5883\u72B6\u6001").action(n(async(e,o)=>(await a.create()).legacyCloud.status(c(o.cwd),e)));p("functions <environment>","\u5217\u51FA\u4E91\u51FD\u6570\u53CA\u72B6\u6001").action(n(async(e,o)=>(await a.create()).legacyCloud.functions(c(o.cwd),e)));p("deploy <environment> <name> <directory>","\u90E8\u7F72\u5DF2\u6253\u5305\u7684\u4E91\u51FD\u6570\u76EE\u5F55").option("--key <key>","\u8BF7\u6C42\u5E42\u7B49\u952E").action(n(async(e,o,d,i)=>(await a.create()).legacyCloud.deployFunction(c(i.cwd),e,o,d,i.key)));p("invoke <environment> <name>","\u6267\u884C\u4E91\u51FD\u6570").option("--input <file>","JSON \u8F93\u5165\u6587\u4EF6").option("--key <key>").action(n(async(e,o,d)=>(await a.create()).legacyCloud.invoke(c(d.cwd),e,o,d.input?JSON.parse(await M(d.input,"utf8")):{},d.key)));p("logs <environment> <name>","\u67E5\u770B\u4E91\u51FD\u6570\u65E5\u5FD7").action(n(async(e,o,d)=>(await a.create()).legacyCloud.logs(c(d.cwd),e,o)));p("sql <environment>","\u6267\u884C\u6570\u636E\u5E93\u7BA1\u7406 SQL").requiredOption("--file <file>","SQL \u6587\u4EF6").option("--key <key>").action(n(async(e,o)=>(await a.create()).legacyCloud.sql(c(o.cwd),e,await M(o.file,"utf8"),o.key)));p("storage-list <environment>","\u5217\u51FA\u4E91\u5B58\u50A8\u5BF9\u8C61").option("--prefix <prefix>").option("--cursor <cursor>").action(n(async(e,o)=>(await a.create()).legacyCloud.listObjects(c(o.cwd),e,o.prefix,o.cursor)));p("storage-put <environment> <objectKey> <file>","\u4E0A\u4F20\u5DE5\u7A0B\u5185\u6587\u4EF6\u5230\u79C1\u6709\u4E91\u5B58\u50A8").option("--key <key>").action(n(async(e,o,d,i)=>(await a.create()).legacyCloud.putObject(c(i.cwd),e,o,d,i.key)));p("storage-get <environment> <objectKey> <destination>","\u4E0B\u8F7D\u5230\u5DE5\u7A0B\u5185\u7684\u65B0\u6587\u4EF6").action(n(async(e,o,d,i)=>(await a.create()).legacyCloud.getObject(c(i.cwd),e,o,d)));p("storage-delete <environment> <objectKey>","\u5220\u9664\u6307\u5B9A\u4E91\u5B58\u50A8\u5BF9\u8C61").option("--key <key>").action(n(async(e,o,d)=>(await a.create()).legacyCloud.deleteObject(c(d.cwd),e,o,d.key)));l.command("mcp").command("serve").description("\u542F\u52A8 stdio MCP \u670D\u52A1").option("--legacy-cloud","\u989D\u5916\u5F00\u653E\u65E7\u4E91\u7EF4\u62A4\u5DE5\u5177").action(async e=>A({legacyCloud:e.legacyCloud===!0}));try{await l.parseAsync()}catch(e){process.stderr.write(JSON.stringify(w(e))+`
14
4
  `),process.exitCode=1}
@@ -1 +1 @@
1
- import{d as S,j as v,k as E,t as y}from"./shared-2ZNSJXPO.js";import{createServer as C}from"node:http";import{createServer as R}from"node:net";import{spawn as k}from"node:child_process";import{randomBytes as T,timingSafeEqual as b}from"node:crypto";import{join as I}from"node:path";import{mkdir as x}from"node:fs/promises";async function H(){let t=await v(process.argv[2]),m=process.argv[3],u=await E(t),l=await new Promise((e,o)=>{let n=R();n.once("error",o),n.listen(0,"127.0.0.1",()=>{let s=n.address();if(!s||typeof s=="string")return o(new Error("No free port"));n.close(()=>e(s.port))})}),c=u.devUrl.replaceAll("{port}",String(l));if(new URL(c).hostname!=="127.0.0.1"&&new URL(c).hostname!=="localhost")throw new Error("devUrl must be loopback");let h=T(32).toString("base64url"),r,a=!0,p=!1,g=!1,d=C(async(e,o)=>{let n=Buffer.from(e.headers.authorization??""),s=Buffer.from(`Bearer ${h}`);if(n.length!==s.length||!b(n,s)){o.writeHead(401).end();return}if(o.setHeader("Content-Type","application/json"),o.setHeader("Cache-Control","no-store"),e.method==="GET"&&e.url==="/status"){o.end(JSON.stringify({id:m,running:a,ready:p}));return}if(e.method==="POST"&&e.url==="/stop"){o.end(JSON.stringify({stopped:!0})),await i();return}o.writeHead(404).end()});async function i(){if(!g){if(g=!0,r?.pid)if(process.platform==="win32")k("taskkill",["/pid",String(r.pid),"/T","/F"],{stdio:"ignore"});else try{process.kill(-r.pid,"SIGTERM")}catch(e){if(e.code!=="ESRCH")throw e}setTimeout(()=>{if(r?.pid&&process.platform!=="win32")try{process.kill(-r.pid,"SIGKILL")}catch(e){e.code!=="ESRCH"&&console.error("Unable to terminate the development process group")}d.close(),process.exit(0)},3e3)}}await new Promise((e,o)=>{d.once("error",o),d.listen(0,"127.0.0.1",e)});let f=d.address();if(!f||typeof f=="string")throw new Error("No control port");let w=y(t);await x(w,{recursive:!0,mode:448}),await S(I(w,"session.json"),{id:m,root:t,controlUrl:`http://127.0.0.1:${f.port}`,token:h,url:c,startedAt:new Date().toISOString()}),r=k(u.devCommand.replaceAll("{port}",String(l)),{cwd:t,shell:!0,detached:process.platform!=="win32",stdio:["ignore","inherit","inherit"],env:{...process.env,SHAPER_DEV_PORT:String(l)}}),r.once("error",e=>{console.error(e.message),a=!1,i()}),r.once("exit",e=>{console.error(`Development process exited: ${e}`),a=!1,p=!1,i()}),setInterval(()=>{!a||p||fetch(c,{signal:AbortSignal.timeout(1e3),redirect:"error"}).then(e=>{p=e.ok}).catch(()=>{})},250).unref(),process.on("SIGTERM",()=>void i()),process.on("SIGINT",()=>void i())}H().catch(t=>{console.error(t instanceof Error?t.message:"Development runner failed"),process.exitCode=1});
1
+ import{a as y}from"./shared-JYAK4XUO.js";import{d as S,j as v,k as E}from"./shared-WR2EQORG.js";import{createServer as C}from"node:http";import{createServer as R}from"node:net";import{spawn as k}from"node:child_process";import{randomBytes as T,timingSafeEqual as b}from"node:crypto";import{join as I}from"node:path";import{mkdir as x}from"node:fs/promises";async function H(){let t=await v(process.argv[2]),m=process.argv[3],u=await E(t),l=await new Promise((e,o)=>{let n=R();n.once("error",o),n.listen(0,"127.0.0.1",()=>{let s=n.address();if(!s||typeof s=="string")return o(new Error("No free port"));n.close(()=>e(s.port))})}),c=u.devUrl.replaceAll("{port}",String(l));if(new URL(c).hostname!=="127.0.0.1"&&new URL(c).hostname!=="localhost")throw new Error("devUrl must be loopback");let h=T(32).toString("base64url"),r,a=!0,p=!1,g=!1,d=C(async(e,o)=>{let n=Buffer.from(e.headers.authorization??""),s=Buffer.from(`Bearer ${h}`);if(n.length!==s.length||!b(n,s)){o.writeHead(401).end();return}if(o.setHeader("Content-Type","application/json"),o.setHeader("Cache-Control","no-store"),e.method==="GET"&&e.url==="/status"){o.end(JSON.stringify({id:m,running:a,ready:p}));return}if(e.method==="POST"&&e.url==="/stop"){o.end(JSON.stringify({stopped:!0})),await i();return}o.writeHead(404).end()});async function i(){if(!g){if(g=!0,r?.pid)if(process.platform==="win32")k("taskkill",["/pid",String(r.pid),"/T","/F"],{stdio:"ignore"});else try{process.kill(-r.pid,"SIGTERM")}catch(e){if(e.code!=="ESRCH")throw e}setTimeout(()=>{if(r?.pid&&process.platform!=="win32")try{process.kill(-r.pid,"SIGKILL")}catch(e){e.code!=="ESRCH"&&console.error("Unable to terminate the development process group")}d.close(),process.exit(0)},3e3)}}await new Promise((e,o)=>{d.once("error",o),d.listen(0,"127.0.0.1",e)});let f=d.address();if(!f||typeof f=="string")throw new Error("No control port");let w=y(t);await x(w,{recursive:!0,mode:448}),await S(I(w,"session.json"),{id:m,root:t,controlUrl:`http://127.0.0.1:${f.port}`,token:h,url:c,startedAt:new Date().toISOString()}),r=k(u.devCommand.replaceAll("{port}",String(l)),{cwd:t,shell:!0,detached:process.platform!=="win32",stdio:["ignore","inherit","inherit"],env:{...process.env,SHAPER_DEV_PORT:String(l)}}),r.once("error",e=>{console.error(e.message),a=!1,i()}),r.once("exit",e=>{console.error(`Development process exited: ${e}`),a=!1,p=!1,i()}),setInterval(()=>{!a||p||fetch(c,{signal:AbortSignal.timeout(1e3),redirect:"error"}).then(e=>{p=e.ok}).catch(()=>{})},250).unref(),process.on("SIGTERM",()=>void i()),process.on("SIGINT",()=>void i())}H().catch(t=>{console.error(t instanceof Error?t.message:"Development runner failed"),process.exitCode=1});
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as o,b as r,c as a,d as c,e as f,f as m,g as S}from"./shared-BTZI42QW.js";import{a as e,m as t,n as p,o as u,q as l,r as i,s as d,u as x,v as s,w as y,x as C}from"./shared-2ZNSJXPO.js";export{o as AuthManager,f as CloudApi,m as LegacyCloudApi,S as Shaper,r as ShaperApi,e as ShaperError,c as buildCloudService,u as buildProject,d as checkProject,l as deployWeb,C as devLogs,x as devStatus,a as initCloudService,t as initProject,p as linkProject,i as publishWeb,s as startDev,y as stopDev};
1
+ import{a as i,b as d,c as a,d as c,e as f,f as m,g as S}from"./shared-NQ3JXFQJ.js";import{b as x,c as s,d as y,e as C}from"./shared-JYAK4XUO.js";import{a as e,m as o,n as r,o as t,q as p,r as u,s as l}from"./shared-WR2EQORG.js";export{i as AuthManager,f as CloudApi,m as LegacyCloudApi,S as Shaper,d as ShaperApi,e as ShaperError,c as buildCloudService,t as buildProject,l as checkProject,p as deployWeb,C as devLogs,x as devStatus,a as initCloudService,o as initProject,r as linkProject,u as publishWeb,s as startDev,y as stopDev};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import{a as R,b as g,c as E,e as s,f as w}from"./shared-BQF7QNXK.js";import{b as d,d as a,e as x,i as f}from"./shared-WR2EQORG.js";import{spawn as I}from"node:child_process";import{access as L}from"node:fs/promises";import{join as A}from"node:path";import{fileURLToPath as J,pathToFileURL as V}from"node:url";import{access as b,mkdir as j}from"node:fs/promises";import{join as y}from"node:path";import{execa as N}from"execa";import T from"proper-lockfile";var h=1440*60*1e3,C=3600*1e3,c=()=>y(d(),"updates.json");async function p(){try{return await x(c())}catch{return{}}}function k(t,e=Date.now()){return!t.nextCheckAt||t.nextCheckAt<=e||t.nextCheckAt>e+h}function v(t,e){if(!/^\d+\.\d+\.\d+$/.test(t)||!/^\d+\.\d+\.\d+$/.test(e))return!1;let i=t.split(".").map(Number),n=e.split(".").map(Number);for(let r=0;r<3;r++)if(i[r]!==n[r])return i[r]>n[r];return!1}async function D(t){let e=await s(),i=await p(),n=e.installed?{root:e.runtime,version:e.version}:i.active;if(!n||e.mode!=="pinned"&&e.mode!=="development"&&!v(n.version,w))return t;let r=y(n.root,"dist","cli.js");try{return await b(r),r}catch{return t}}var U={latest:async()=>{let t=await N("npm",["view","@hupu-tech/shaper@latest","version","--json","--fetch-retries=0","--fetch-timeout=10000"],{timeout:15e3,maxBuffer:65536}),e=JSON.parse(t.stdout);if(typeof e!="string"||!/^\d+\.\d+\.\d+$/.test(e))throw new Error("Invalid stable version");return e},prepare:R,verify:t=>g({command:process.execPath,args:[t.entry,"mcp","serve"]})};async function S(t=U){let e=y(d(),"updater");await j(e,{recursive:!0,mode:448});let i;try{i=await T.lock(e,{retries:0})}catch(n){if(n.code==="ELOCKED")return;throw n}try{let n=await p();if(!k(n))return;let r=await s();if(r.mode==="development"||r.mode==="pinned")return;await a(c(),{...n,nextCheckAt:Date.now()+C});try{let o=await t.latest(),u=w;for(let l of[r.version,n.active?.version])l&&v(l,u)&&(u=l);if(!v(o,u)){await a(c(),{...n,nextCheckAt:Date.now()+h,lastResult:"checked"});return}let m=await t.prepare(o);if(m.version!==o)throw new Error("Runtime version mismatch");await t.verify(m),r.installed&&await E(r.ides,{automatic:!0,expectedRuntime:r.runtime,prepared:m}),await a(c(),{active:m,nextCheckAt:Date.now()+h,lastResult:"updated"})}catch{await a(c(),{...n,nextCheckAt:Date.now()+C,lastResult:"failed"})}}finally{await i()}}var P=process.argv.slice(2);if(P[0]==="--shaper-update-worker")await S().catch(()=>{});else{let t=A(f,"dist","cli.js"),e=t,i=await L(A(f,"src","cli.ts")).then(()=>!0,()=>!1),n=["install","update","uninstall"].includes(P[0]??"");if(!i&&!n)try{e=await D(t);let r=await s();if(r.mode!=="development"&&r.mode!=="pinned"&&k(await p())){let o=I(process.execPath,[J(import.meta.url),"--shaper-update-worker"],{detached:!0,stdio:"ignore",windowsHide:!0});o.on("error",()=>{}),o.unref()}}catch{}await import(V(e).href)}
@@ -0,0 +1,11 @@
1
+ import{a as s,b as p,d as T,e as _,i as k}from"./shared-WR2EQORG.js";import{mkdir as g,readFile as f,writeFile as F,mkdtemp as st,lstat as $,readlink as b,symlink as et,unlink as U,rm as N,rename as ct}from"node:fs/promises";import{dirname as P,join as o,resolve as lt}from"node:path";import{homedir as pt,tmpdir as dt}from"node:os";import{execa as Z}from"execa";import{realpath as at}from"node:fs/promises";import{dirname as it,resolve as ot,toNamespacedPath as q}from"node:path";async function Q(e,t){let i=ot(it(e),t);try{return q(await at(i))}catch(r){if(r.code!=="ENOENT")throw r;return q(i)}}async function h(e,t,i){if(t===void 0||i===void 0)return!1;let[r,a]=await Promise.all([Q(e,t),Q(e,i)]);return r===a}import{createHash as mt,randomUUID as X}from"node:crypto";import*as J from"@iarna/toml";import{parse as ft,modify as ut,applyEdits as wt}from"jsonc-parser";import G from"proper-lockfile";import{Client as ht}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as gt}from"@modelcontextprotocol/sdk/client/stdio.js";var Et=["codex","cursor","claude"],tt="# >>> Shaper managed MCP >>>",j="# <<< Shaper managed MCP <<<",x=()=>o(p(),"installation.json");async function S(e){return f(e,"utf8").catch(t=>{if(t.code==="ENOENT")return"";throw t})}function yt(e){let t=[],i=ft(e||"{}",t,{allowTrailingComma:!0});if(t.length||!i||typeof i!="object"||Array.isArray(i))throw new s("INVALID_IDE_CONFIG","IDE \u914D\u7F6E\u65E0\u6CD5\u89E3\u6790\uFF0C\u8BF7\u5148\u4FEE\u590D\u914D\u7F6E\u6587\u4EF6\u3002");return i}function M(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Nt(e,t){return o(t,e==="codex"?".codex/config.toml":e==="cursor"?".cursor/mcp.json":".claude.json")}function rt(e,t,i,r){if(e==="codex"){let m=J.parse(t).mcp_servers?.shaper,u=t.indexOf(tt),w=t.indexOf(j),E=u>=0&&w>u;if(m&&(!E||!r||!M(m,r)))throw new s("IDE_CONFIG_CONFLICT","Codex \u7684 shaper MCP \u914D\u7F6E\u4E0D\u5C5E\u4E8E\u672C\u6B21\u5B89\u88C5\uFF0C\u5DF2\u4FDD\u7559\u539F\u914D\u7F6E\u3002");let I=E?t.slice(0,u)+t.slice(w+j.length).replace(/^\r?\n/,""):t,L=i?`${I.trimEnd()}
2
+
3
+ ${tt}
4
+ [mcp_servers.shaper]
5
+ command = ${JSON.stringify(i.command)}
6
+ args = ${JSON.stringify(i.args)}
7
+ ${j}
8
+ `:I;return J.parse(L),L}let c=yt(t).mcpServers?.shaper;if(c&&(!r||!M(c,r)))throw new s("IDE_CONFIG_CONFLICT",`${e} \u7684 shaper MCP \u914D\u7F6E\u5DF2\u5B58\u5728\u6216\u5DF2\u88AB\u4FEE\u6539\uFF0C\u5DF2\u4FDD\u7559\u539F\u914D\u7F6E\u3002`);return wt(t||`{}
9
+ `,ut(t||`{}
10
+ `,["mcpServers","shaper"],i,{formattingOptions:{insertSpaces:!0,tabSize:2}}))}async function K(e,t,i){await g(P(e),{recursive:!0});try{if((await $(e)).isSymbolicLink())throw new s("UNSAFE_IDE_CONFIG",`IDE \u914D\u7F6E\u662F\u7B26\u53F7\u94FE\u63A5\uFF0C\u8BF7\u624B\u52A8\u914D\u7F6E\uFF1A${e}`)}catch(a){if(a.code!=="ENOENT")throw a}if(await S(e)!==t)throw new s("IDE_CONFIG_CHANGED",`\u914D\u7F6E\u5728\u5B89\u88C5\u671F\u95F4\u53D1\u751F\u53D8\u5316\uFF1A${e}`);if(t){let a=o(p(),"backups",`${Date.now()}-${X()}.bak`);await g(P(a),{recursive:!0,mode:448}),await F(a,t,{mode:384,flag:"wx"})}let r=`${e}.${X()}.tmp`;await F(r,i,{mode:384,flag:"wx"}),await ct(r,e)}async function D(){try{return await _(x())}catch(e){if(e.code==="ENOENT")return;throw e}}async function V(){let e;try{e=await _(o(p(),"install-pending.json"))}catch(t){if(t.code==="ENOENT")return;throw t}if(e.next&&M(await D(),e.next)){await N(o(p(),"install-pending.json"));return}for(let t of e.edits){let i=await S(t.path);if(i!==t.before&&i!==t.after)throw new s("INSTALL_RECOVERY_CONFLICT",`\u5B89\u88C5\u4E2D\u65AD\u540E\u914D\u7F6E\u5DF2\u88AB\u6539\u52A8\uFF0C\u4FDD\u7559\u73B0\u573A\uFF1A${t.path}`)}for(let t of e.skills)try{if(!(await $(t.path)).isSymbolicLink())throw new s("INSTALL_RECOVERY_CONFLICT",`\u5B89\u88C5\u4E2D\u65AD\u540E\u6280\u80FD\u5DF2\u88AB\u6539\u52A8\uFF1A${t.path}`);let i=await b(t.path);if(!await h(t.path,i,t.target)&&!await h(t.path,i,t.previous))throw new s("INSTALL_RECOVERY_CONFLICT",`\u5B89\u88C5\u4E2D\u65AD\u540E\u6280\u80FD\u94FE\u63A5\u5DF2\u88AB\u6539\u52A8\uFF1A${t.path}`)}catch(i){if(i.code!=="ENOENT")throw i}for(let t of e.edits)await S(t.path)===t.after&&await K(t.path,t.after,t.before);for(let t of e.skills){let i=await b(t.path).catch(a=>{if(a.code!=="ENOENT")throw a}),r=await h(t.path,i,t.previous);!r&&await h(t.path,i,t.target)&&await U(t.path),t.previous&&!r&&await et(t.previous,t.path,process.platform==="win32"?"junction":"dir")}e.previous?await T(x(),e.previous):await N(x(),{force:!0}),await N(o(p(),"install-pending.json"))}async function It(e){if(e&&!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test(e))throw new s("INVALID_VERSION","\u66F4\u65B0\u7248\u672C\u5FC5\u987B\u662F\u5B8C\u6574\u7684\u7248\u672C\u53F7\u3002");let t=await st(o(dt(),"shaper-install-"));try{let i=await Z("npm",["pack",...e?[`@hupu-tech/shaper@${e}`]:[],"--ignore-scripts","--json","--pack-destination",t],{cwd:k,timeout:18e4,maxBuffer:1048576}),r=JSON.parse(i.stdout)[0],a=o(t,r.filename),c=mt("sha256").update(await f(a)).digest("hex").slice(0,16),d=o(p(),"runtimes",`${r.version}-${c}`),m=o(d,"node_modules","@hupu-tech","shaper","dist","cli.js");await g(d,{recursive:!0,mode:448});let u=await G.lock(d,{retries:{retries:60,minTimeout:1e3,maxTimeout:1e3}});try{try{await f(o(d,".complete"))}catch(w){if(w.code!=="ENOENT")throw w;await g(d,{recursive:!0,mode:448}),await Z("npm",["install","--prefix",d,a,"--omit=dev","--ignore-scripts","--no-audit","--no-fund"],{timeout:24e4,maxBuffer:4*1024*1024}),await F(o(d,".complete"),`${c}
11
+ `,{mode:384})}await f(m)}finally{await u()}return{root:o(d,"node_modules","@hupu-tech","shaper"),version:r.version,entry:m}}finally{await N(t,{recursive:!0,force:!0})}}async function vt(e){let t=new gt({...e,stderr:"pipe"}),i=new ht({name:"shaper-installer",version:"1.0.0"});try{await i.connect(t,{timeout:15e3});let r=await i.listTools();if(!r.tools.some(a=>a.name==="shaper_status"))throw new s("MCP_VERIFICATION_FAILED","MCP \u672A\u8FD4\u56DE Shaper \u5DE5\u5177\u3002");return{tools:r.tools.length,protocol:"stdio"}}finally{await i.close(),await t.close()}}async function Jt(e,t={}){if(!e.length||e.some(r=>!Et.includes(r)))throw new s("INVALID_IDE","\u652F\u6301 codex\u3001cursor\u3001claude\u3002");await g(p(),{recursive:!0,mode:448});let i=await G.lock(p(),{retries:0});try{await V();let r=lt(t.home??pt()),a=await D();if(t.automatic&&(!a||a.mode==="development"||a.mode==="pinned"||t.expectedRuntime&&a.runtime!==t.expectedRuntime))throw new s("UPDATE_CANCELLED","\u5B89\u88C5\u8BBE\u7F6E\u5DF2\u6539\u53D8\uFF0C\u53D6\u6D88\u81EA\u52A8\u66F4\u65B0\u3002");if(t.dev&&t.version)throw new s("INVALID_ARGUMENT","\u672C\u5730\u8C03\u8BD5\u6A21\u5F0F\u4E0D\u80FD\u6307\u5B9A\u53D1\u884C\u7248\u672C\u3002");let c=t.dev?{root:k,entry:o(k,"dist","cli.js"),version:(await _(o(k,"package.json"))).version}:t.prepared??await It(t.version);t.dev&&await f(c.entry).catch(()=>{throw new s("BUILD_REQUIRED","\u8BF7\u5148\u5728\u672C\u5730\u5305\u76EE\u5F55\u6267\u884C pnpm build\u3002")});let d=await vt({command:process.execPath,args:[c.entry,"mcp","serve"]}),m=o(c.root,"dist","launcher.js"),u=await f(m).then(()=>!0,()=>!1),w={command:process.execPath,args:[t.dev||!u?c.entry:m,"mcp","serve"]},E=t.automatic&&a?a.entries:[...new Set(e)].map(n=>({ide:n,path:Nt(n,r),entry:w})),I=await Promise.all(E.map(async n=>{let l=await S(n.path);return{...n,before:l,after:rt(n.ide,l,n.entry,a?.entries.find(R=>R.path===n.path)?.entry)}})),L=new Set(t.automatic&&a?a.skills.map(n=>P(n.path)):e.map(n=>o(r,n==="codex"?".agents/skills":`.${n}/skills`))),O=JSON.parse(await f(o(c.root,"skills/manifest.json"),"utf8")),z=t.skills??[];for(let n of z)if(!O.optional.some(l=>l.split("/").at(-1)===n))throw new s("UNKNOWN_SKILL",`\u672A\u77E5\u4E13\u4E1A\u6280\u80FD\uFF1A${n}`);let B=[...O.default,...O.compatibility,...O.optional.filter(n=>z.includes(n.split("/").at(-1))||a?.skills.some(l=>l.path.endsWith("/"+n.split("/").at(-1))))];if(B.some(n=>!/^(core|game|compat)\/[a-z0-9-]+$/.test(n)))throw new s("INVALID_SKILL_MANIFEST","\u6280\u80FD\u53D1\u884C\u6E05\u5355\u65E0\u6548\u3002");let v=[];for(let n of L)for(let l of B){let R=l.split("/").at(-1),y=o(n,R),H=o(c.root,"skills",l);await f(o(H,"SKILL.md"));let W;try{let C=await $(y),A=a?.skills.find(nt=>nt.path===y);if(!C.isSymbolicLink()||!A||!await h(y,await b(y),A.target))throw new s("SKILL_CONFLICT",`\u5DF2\u5B58\u5728\u6280\u80FD\uFF0C\u5B89\u88C5\u672A\u8986\u76D6\uFF1A${y}`);W=A.target}catch(C){if(C.code!=="ENOENT")throw C}v.push({path:y,target:H,previous:W})}let Y={schemaVersion:1,mode:t.dev?"development":t.version&&!t.automatic?"pinned":"automatic",runtime:c.root,version:c.version,entries:[...(a?.entries??[]).filter(n=>!E.some(l=>l.path===n.path)),...E],skills:[...(a?.skills??[]).filter(n=>!v.some(l=>l.path===n.path)),...v.map(({path:n,target:l})=>({path:n,target:l}))]};await T(o(p(),"install-pending.json"),{edits:I,skills:v,previous:a,next:Y});for(let n of I)n.before!==n.after&&await K(n.path,n.before,n.after);for(let n of v)await g(P(n.path),{recursive:!0}),n.previous&&await U(n.path),await et(n.target,n.path,process.platform==="win32"?"junction":"dir");return await T(x(),Y),await N(o(p(),"install-pending.json"),{force:!0}),{installed:!0,mode:t.dev?"development":"snapshot",runtime:c.root,version:c.version,ides:e,...d,restartIde:!0,cli:{command:process.execPath,args:[c.entry]}}}catch(r){throw await V(),r}finally{await i()}}async function Mt(){await g(p(),{recursive:!0,mode:448});let e=await G.lock(p(),{retries:0});try{await V();let t=await D();if(!t)return{uninstalled:!0,alreadyAbsent:!0};let i=await Promise.all(t.entries.map(async r=>{let a=await S(r.path);return{...r,before:a,after:rt(r.ide,a,void 0,r.entry)}}));for(let r of t.skills)try{if(!(await $(r.path)).isSymbolicLink()||!await h(r.path,await b(r.path),r.target))throw new s("SKILL_CONFLICT",`\u6280\u80FD\u5DF2\u88AB\u4FEE\u6539\uFF0C\u5378\u8F7D\u4FDD\u7559\uFF1A${r.path}`)}catch(a){if(a.code!=="ENOENT")throw a}for(let r of i)r.before!==r.after&&await K(r.path,r.before,r.after);for(let r of t.skills)await U(r.path).catch(a=>{if(a.code!=="ENOENT")throw a});return await N(x(),{force:!0}),{uninstalled:!0,credentialsRetained:!0,runtimeRetained:!0}}finally{await e()}}async function Vt(){let e=await D();return e?{installed:!0,version:e.version,ides:e.entries.map(t=>t.ide),runtime:e.runtime,mode:e.mode}:{installed:!1}}import{readFileSync as kt}from"node:fs";var Kt=JSON.parse(kt(new URL("../package.json",import.meta.url),"utf8")).version;export{It as a,vt as b,Jt as c,Mt as d,Vt as e,Kt as f};
@@ -0,0 +1 @@
1
+ import{a as u,b as p,e as m,i as h,j as d,k as y}from"./shared-WR2EQORG.js";import{createHash as x,randomUUID as D}from"node:crypto";import{open as k,mkdir as N,readFile as A}from"node:fs/promises";import{join as l}from"node:path";import{spawn as v}from"node:child_process";import{z as i}from"zod";import I from"proper-lockfile";var P=i.object({id:i.string(),root:i.string(),controlUrl:i.string().url(),token:i.string(),url:i.string().url(),startedAt:i.string()}).strict();function g(e){return l(p(),"sessions",x("sha256").update(e).digest("hex"))}async function E(e){let t=P.parse(await m(l(g(e),"session.json")));if(t.root!==e||new URL(t.controlUrl).hostname!=="127.0.0.1")throw new u("INVALID_DEV_SESSION","\u672C\u5730\u5F00\u53D1\u4F1A\u8BDD\u8BB0\u5F55\u4E0D\u6B63\u786E\u3002");return t}async function f(e){let t=await d(e),r;try{r=await E(t)}catch(o){if(o.code==="ENOENT")return{running:!1,root:t};throw o}try{let o=await fetch(`${r.controlUrl}/status`,{headers:{Authorization:`Bearer ${r.token}`},redirect:"error",signal:AbortSignal.timeout(1500)}),n=await o.json();if(!o.ok||n.id!==r.id)throw new Error("Session mismatch");return{root:t,running:n.running,ready:n.ready,url:r.url,sessionId:r.id}}catch{return{root:t,running:!1,url:r.url,sessionId:r.id}}}async function R(e){let t=await d(e);await y(t);let r=g(t);await N(r,{recursive:!0,mode:448});let o=await I.lock(r,{retries:0});try{let n=await f(t);if(n.running)return n;let s=await k(l(r,"dev.log"),"w",384),a=v(process.execPath,[l(h,"dist","dev-runner.js"),t,D()],{cwd:t,detached:!0,stdio:["ignore",s.fd,s.fd],windowsHide:!0});await new Promise((w,c)=>{a.once("spawn",w),a.once("error",c)}),a.unref(),await s.close();for(let w=0;w<120;w++){await new Promise(S=>setTimeout(S,250));let c=await f(t);if(c.running&&c.ready)return c}throw new u("DEV_NOT_READY","\u5F00\u53D1\u670D\u52A1\u672A\u5728 30 \u79D2\u5185\u5C31\u7EEA\uFF0C\u8BF7\u67E5\u770B shaper logs\u3002\u8FD0\u884C\u72B6\u6001\u53EF\u901A\u8FC7 shaper status \u67E5\u8BE2\u3002")}finally{await o()}}async function V(e){let t=await d(e);if(!(await f(t)).running)return{stopped:!0,alreadyStopped:!0};let o=await E(t);if(!(await fetch(`${o.controlUrl}/stop`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`},redirect:"error",signal:AbortSignal.timeout(1e4)})).ok)throw new u("DEV_STOP_FAILED","\u5F00\u53D1\u4F1A\u8BDD\u672A\u80FD\u505C\u6B62\u3002");for(let s=0;s<30;s++){await new Promise(a=>setTimeout(a,200));try{await fetch(`${o.controlUrl}/status`,{headers:{Authorization:`Bearer ${o.token}`},redirect:"error",signal:AbortSignal.timeout(500)})}catch{return{stopped:!0,sessionId:o.id}}}throw new u("DEV_STOP_PENDING","\u505C\u6B62\u8BF7\u6C42\u5DF2\u53D1\u9001\uFF0C\u4F46\u4F1A\u8BDD\u4ECD\u672A\u9000\u51FA\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002")}async function L(e){let t=await d(e);try{let r=await A(l(g(t),"dev.log"),"utf8");return{root:t,log:r.slice(-16e3)}}catch(r){if(r.code==="ENOENT")return{root:t,log:"",message:"\u5C1A\u65E0\u672C\u5730\u8FD0\u884C\u65E5\u5FD7"};throw r}}export{g as a,f as b,R as c,V as d,L as e};
@@ -0,0 +1,17 @@
1
+ import{b as ce}from"./shared-JYAK4XUO.js";import{a,b as Y,c as A,d as ie,f as ae,h as C,i as O,j as S,k as ne,l as _,p as oe}from"./shared-WR2EQORG.js";import*as w from"oauth4webapi";import{createHash as Ce}from"node:crypto";import{chmod as de,lstat as he,mkdir as $e,readFile as De,rm as Le,writeFile as xe}from"node:fs/promises";import{join as Z}from"node:path";import{execFile as Oe}from"node:child_process";import{promisify as Ue}from"node:util";import je from"proper-lockfile";import{z as T}from"zod";var pe=T.object({accessToken:T.string().min(1),refreshToken:T.string().min(1).optional(),expiresAt:T.number(),scope:T.string()}).strict(),Pe=T.object({schemaVersion:T.literal(1),server:T.string(),tokens:pe}).strict(),ue=Ue(Oe),U;async function le(n){await $e(n,{recursive:!0,mode:448});let e=await he(n);if(!e.isDirectory()||e.isSymbolicLink())throw new a("UNSAFE_AUTH_DIRECTORY","\u767B\u5F55\u76EE\u5F55\u5FC5\u987B\u662F\u5F53\u524D\u7528\u6237\u7684\u771F\u5B9E\u76EE\u5F55\u3002");if(process.platform==="win32"){if(!U){let{stdout:t}=await ue("whoami.exe",["/user","/fo","csv","/nh"],{windowsHide:!0});if(U=t.match(/S-1-\d+(?:-\d+)+/)?.[0],!U)throw new a("AUTH_DIRECTORY_UNAVAILABLE","\u65E0\u6CD5\u786E\u5B9A\u5F53\u524D Windows \u7528\u6237\u3002")}await ue("icacls.exe",[n,"/inheritance:r","/grant:r",`*${U}:(OI)(CI)F`,"/remove:g","*S-1-1-0","*S-1-5-11","*S-1-5-32-545"],{windowsHide:!0})}else{if(e.uid!==process.getuid?.())throw new a("UNSAFE_AUTH_DIRECTORY","\u767B\u5F55\u76EE\u5F55\u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237\u3002");await de(n,448)}}function we(n){return Ce("sha256").update(A(n)).digest("hex")}async function fe(n){await le(Y());let e=Z(Y(),n);return await le(e),e}var j=class{async path(e){return Z(await fe("credentials"),`${we(e)}.json`)}async read(e){let t=await this.path(e);try{let r=await he(t);if(!r.isFile()||r.isSymbolicLink())throw new a("UNSAFE_CREDENTIAL_FILE","\u767B\u5F55\u51ED\u8BC1\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\u3002");if(process.platform!=="win32"){if(r.uid!==process.getuid?.())throw new a("UNSAFE_CREDENTIAL_FILE","\u767B\u5F55\u51ED\u8BC1\u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237\u3002");await de(t,384)}let s=Pe.safeParse(JSON.parse(await De(t,"utf8")));if(!s.success||s.data.server!==A(e))throw new a("INVALID_CREDENTIAL_FILE","\u767B\u5F55\u51ED\u8BC1\u6587\u4EF6\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5\u7528\u6237\u914D\u7F6E\u76EE\u5F55\u3002");return s.data.tokens}catch(r){if(r.code==="ENOENT")return;throw r instanceof SyntaxError?new a("INVALID_CREDENTIAL_FILE","\u767B\u5F55\u51ED\u8BC1\u6587\u4EF6\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5\u7528\u6237\u914D\u7F6E\u76EE\u5F55\u3002"):r}}async write(e,t){await ie(await this.path(e),{schemaVersion:1,server:A(e),tokens:pe.parse(t)})}async remove(e){await Le(await this.path(e),{force:!0})}};async function me(n,e,t){let r=Z(await fe("locks"),`${we(n)}-${e}`);await xe(r,"",{flag:"a",mode:384});try{return await je.lock(r,{stale:12e4,retries:{retries:t,minTimeout:100,maxTimeout:1e3}})}catch(s){throw e==="login"&&s.code==="ELOCKED"?new a("AUTH_ALREADY_PENDING","\u5176\u4ED6\u7EC8\u7AEF\u6216 Agent \u6B63\u5728\u8FDE\u63A5 Shaper\uFF0C\u8BF7\u5148\u5B8C\u6210\u8BE5\u7F51\u9875\u6388\u6743\u3002"):s}}async function P(n,e){let t=await me(n,"tokens",30);try{return await e()}finally{await t()}}async function Q(n){return me(n,"login",0)}import{createServer as Fe}from"node:http";import{randomUUID as qe}from"node:crypto";import*as y from"oauth4webapi";import ze from"open";var I={client_id:"shaper-cli",token_endpoint_auth_method:"none"},F=class{constructor(e){this.release=e}id=qe();listener;timer;abort=new AbortController;state={flowId:this.id,status:"pending"};handling;released;status(){return{...this.state}}async finish(e){this.state.status==="pending"&&(this.state={flowId:this.id,status:e?"failed":"complete",...e?{message:e}:{}}),clearTimeout(this.timer),this.listener?.close(),this.released??=this.release(),await this.released}async close(){this.abort.abort(),this.handling&&await this.handling,await this.finish("\u6388\u6743\u5DF2\u53D6\u6D88\uFF0C\u8BF7\u91CD\u65B0\u53D1\u8D77\u3002")}async start(e){let{metadata:t}=e;if(!t.authorization_endpoint)throw new a("AUTH_UNAVAILABLE","\u670D\u52A1\u672A\u63D0\u4F9B\u7F51\u9875\u6388\u6743\u5165\u53E3\u3002");let r=y.generateRandomState(),s="";this.listener=Fe((l,p)=>{if(l.method!=="GET"||!l.url?.startsWith("/oauth/callback?")||this.handling||this.state.status!=="pending"){p.writeHead(404).end();return}let h;try{h=y.validateAuthResponse(t,I,new URL(l.url,s),r)}catch{let f=new URL(l.url,s).searchParams;f.get("state")===r&&f.has("error")&&this.finish("\u7F51\u9875\u6388\u6743\u5DF2\u53D6\u6D88\u3002"),p.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}).end("\u6388\u6743\u672A\u5B8C\u6210\u3002");return}this.handling=(async()=>{try{let f=await y.authorizationCodeGrantRequest(t,I,y.None(),h,s,e.verifier,{[y.allowInsecureRequests]:e.server.startsWith("http://"),signal:AbortSignal.any([this.abort.signal,AbortSignal.timeout(2e4)]),additionalParameters:{resource:`${e.server}/api/v1/developer`}}),v=await y.processAuthorizationCodeResponse(t,I,f);this.abort.signal.throwIfAborted(),await e.save(v),await this.finish(),p.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'"}).end('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>Shaper \u5DF2\u8FDE\u63A5</title><h1>\u5F00\u53D1\u5DE5\u5177\u5DF2\u8FDE\u63A5</h1><p>\u53EF\u4EE5\u5173\u95ED\u6B64\u9875\u9762\uFF0C\u56DE\u5230 IDE \u6216\u7EC8\u7AEF\u7EE7\u7EED\u3002</p></html>')}catch{await this.finish("\u6388\u6743\u672A\u5B8C\u6210\uFF0C\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55\u3002"),p.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}).end("\u6388\u6743\u672A\u5B8C\u6210\u3002")}})()});let i=this.listener;await new Promise((l,p)=>{i.once("error",p),i.listen(0,"127.0.0.1",()=>{i.off("error",p),l()})});let u=i.address();if(!u||typeof u=="string")throw new a("CALLBACK_UNAVAILABLE","\u65E0\u6CD5\u542F\u52A8\u672C\u5730\u6388\u6743\u56DE\u8C03\u3002");s=`http://127.0.0.1:${u.port}/oauth/callback`;let o=new URL(t.authorization_endpoint),c={client_id:I.client_id,response_type:"code",redirect_uri:s,code_challenge:e.challenge,code_challenge_method:"S256",state:r,scope:e.scope,resource:`${e.server}/api/v1/developer`,prompt:"consent",...e.initialize?{shaper_init:"true"}:{},...e.applicationName?{shaper_name:e.applicationName}:{},...e.connection?{shaper_connection:e.connection}:{},...e.appId?{shaper_app:e.appId}:{}};for(let[l,p]of Object.entries(c))o.searchParams.set(l,p);if(this.timer=setTimeout(()=>{this.close()},3e5),this.timer.unref(),e.openBrowser!==!1)try{await ze(o.href,{wait:!1})}catch{}return{flowId:this.id,status:"pending",authorizationUrl:o.href,expiresIn:300}}};var X="openid offline_access projects:read projects:write web:deploy web:publish",He=`${X} cloud:read cloud:write`,Ve=(...n)=>[...new Set(n.flatMap(e=>e.split(" ")).filter(Boolean))].join(" "),q=class{constructor(e,t=new j){this.credentials=t;this.server=A(e)}flows=new Map;metadata;server;options(){return{[w.allowInsecureRequests]:this.server.startsWith("http://"),signal:AbortSignal.timeout(2e4)}}async discovery(){if(!this.metadata){let e=new URL(`${this.server}/api/oauth`),t=await w.processDiscoveryResponse(e,await w.discoveryRequest(e,this.options()));for(let r of["authorization_endpoint","token_endpoint","revocation_endpoint"]){let s=t[r];if(s&&new URL(s).origin!==this.server)throw new a("UNTRUSTED_AUTH_ENDPOINT","\u6388\u6743\u670D\u52A1\u8FD4\u56DE\u4E86\u5176\u4ED6\u6765\u6E90\u7684\u5730\u5740\u3002")}this.metadata=t}return this.metadata}async save(e,t){let r=e.refresh_token??t?.refreshToken;await this.credentials.write(this.server,{accessToken:e.access_token,expiresAt:Date.now()+(e.expires_in??900)*1e3,scope:e.scope??t?.scope??X,...r?{refreshToken:r}:{}})}async accessToken(){return P(this.server,async()=>{let e=await this.credentials.read(this.server);if(!e)throw new a("AUTH_REQUIRED","\u8BF7\u8FD0\u884C shaper login\uFF0C\u6216\u8C03\u7528 shaper_auth_start\u3002\u767B\u5F55\u7531\u672C\u673A\u6240\u6709\u9879\u76EE\u5171\u7528\u3002");if(e.expiresAt>Date.now()+6e4)return e.accessToken;if(!e.refreshToken)throw new a("AUTH_REQUIRED","\u6388\u6743\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002");let t=await this.discovery();try{let r=await w.refreshTokenGrantRequest(t,I,w.None(),e.refreshToken,{...this.options(),additionalParameters:{resource:`${this.server}/api/v1/developer`}}),s=await w.processRefreshTokenResponse(t,I,r);return await this.save(s,e),s.access_token}catch(r){throw r instanceof w.ResponseBodyError&&r.error==="invalid_grant"?new a("AUTH_REQUIRED","\u6388\u6743\u5DF2\u8FC7\u671F\u6216\u5DF2\u64A4\u9500\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002"):new a("AUTH_REFRESH_FAILED","\u6682\u65F6\u65E0\u6CD5\u7EED\u671F\u767B\u5F55\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u540E\u91CD\u8BD5\uFF1B\u539F\u767B\u5F55\u51ED\u8BC1\u5DF2\u4FDD\u7559\u3002")}})}async request(e,t){let r=await this.accessToken(),s=await fetch(`${this.server}/api/v1/developer/${e}`,{method:t===void 0?"GET":"POST",headers:{Authorization:`Bearer ${r}`,Accept:"application/json","Content-Type":"application/json"},...t===void 0?{}:{body:JSON.stringify(t)},redirect:"error",signal:AbortSignal.timeout(2e4)}),i=await s.json();if(!s.ok)throw new a(i.code??"AUTH_SERVICE_ERROR",i.message??"\u65E0\u6CD5\u8BFB\u53D6\u767B\u5F55\u72B6\u6001");return i}async identity(){return this.request("me")}async start(e={}){let t=[...this.flows.values()].find(i=>i.status().status==="pending");if(t)throw new a("AUTH_IN_PROGRESS","\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u6D4F\u89C8\u5668\u6388\u6743\uFF0C\u518D\u91CD\u8BD5\u521D\u59CB\u5316\u3002",{flowId:t.id});let r=await Q(this.server),s;try{let i;try{i=await this.identity()}catch(h){if(!(h instanceof a)||!["AUTH_REQUIRED","INVALID_TOKEN"].includes(h.code))throw h}let u=e.cloud?He:X,o=i&&u.split(" ").filter(h=>!["openid","offline_access"].includes(h)).every(h=>i.grant.scopes.includes(h));if(i&&o&&!e.reauthorize&&(!e.appId||i.grant.allApps||i.grant.appIds.includes(e.appId)))return await r(),{status:"complete",authenticated:!0,reused:!0,...i};let c=w.generateRandomCodeVerifier(),l=await w.calculatePKCECodeChallenge(c),p=i?await this.request("authorization",{codeChallenge:l}):void 0;for(let[h,f]of this.flows)f.status().status!=="pending"&&this.flows.delete(h);return s=new F(r),this.flows.set(s.id,s),await s.start({metadata:await this.discovery(),server:this.server,verifier:c,challenge:l,scope:Ve(u,p?.scopes.join(" ")??""),...e.initialize?{initialize:!0}:{},...e.applicationName?{applicationName:e.applicationName}:{},...p?{connection:p.connection}:{},...e.appId?{appId:e.appId}:{},...e.openBrowser===void 0?{}:{openBrowser:e.openBrowser},save:h=>P(this.server,()=>this.save(h))})}catch(i){throw s?await s.close():await r(),i}}status(e){let t=this.flows.get(e);if(!t)throw new a("AUTH_FLOW_NOT_FOUND","\u6388\u6743\u6D41\u7A0B\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5728\u53D1\u8D77\u6388\u6743\u7684 Agent \u6216\u7EC8\u7AEF\u4E2D\u67E5\u8BE2\u3002");return t.status()}async wait(e){for(;this.status(e).status==="pending";)await new Promise(r=>setTimeout(r,250));let t=this.status(e);if(t.status!=="complete")throw new a("AUTH_FAILED",t.message??"\u6388\u6743\u672A\u5B8C\u6210");return{authenticated:!0,...await this.identity()}}async logout(){let e=await Q(this.server);try{return await P(this.server,async()=>{let t=await this.credentials.read(this.server);if(t)try{let r=await w.revocationRequest(await this.discovery(),I,w.None(),t.refreshToken??t.accessToken,{...this.options(),additionalParameters:{token_type_hint:t.refreshToken?"refresh_token":"access_token"}});await w.processRevocationResponse(r)}catch{throw new a("REVOKE_FAILED","\u670D\u52A1\u7AEF\u64A4\u9500\u672A\u5B8C\u6210\uFF0C\u5DF2\u4FDD\u7559\u767B\u5F55\u51ED\u8BC1\uFF0C\u8BF7\u91CD\u8BD5\u6216\u5728\u7F51\u9875\u64A4\u9500\u6388\u6743\u3002")}await this.credentials.remove(this.server)}),{revoked:!0}}finally{await e()}}async close(){await Promise.all([...this.flows.values()].map(e=>e.close()))}};var z=class{constructor(e){this.auth=e}async request(e,t={}){if(!e.startsWith("/api/v1/developer/"))throw new a("INVALID_API_PATH","\u4E0D\u652F\u6301\u7684\u63A5\u53E3\u8DEF\u5F84");let r=new Headers({Accept:"application/json"});t.anonymous||r.set("Authorization",`Bearer ${await this.auth.accessToken()}`),t.key&&r.set("idempotency-key",t.key);let s;if(t.file){let o=new FormData;o.set("file",new Blob([new Uint8Array(t.file)],{type:"application/zip"}),"shaper.zip"),s=o}else t.body!==void 0&&(r.set("Content-Type","application/json"),s=JSON.stringify(t.body));let i;try{i=await fetch(`${this.auth.server}${e}`,{method:t.method??"GET",headers:r,...s?{body:s}:{},redirect:"error",signal:AbortSignal.timeout(18e4)})}catch{throw new a("NETWORK_ERROR","\u670D\u52A1\u8BF7\u6C42\u4E2D\u65AD\uFF0C\u7ED3\u679C\u5C1A\u672A\u786E\u8BA4\u3002\u8BF7\u8054\u7CFB\u5E73\u53F0\u6838\u67E5\uFF0C\u52FF\u91CD\u590D\u521B\u5EFA\u8D44\u6E90\u3002",t.key?{idempotencyKey:t.key}:void 0)}let u=await i.json();if(!i.ok)throw new a(u.code??"API_ERROR",u.message??`\u8BF7\u6C42\u5931\u8D25\uFF1A${i.status}`);return u}async me(){return this.auth.identity()}async projects(){return this.request("/api/v1/developer/projects")}async project(e){return this.request(`/api/v1/developer/projects/${encodeURIComponent(e)}`)}};import{createHash as Be}from"node:crypto";import{builtinModules as Je}from"node:module";import{readFile as N,writeFile as ee,mkdir as ye,lstat as M,realpath as H}from"node:fs/promises";import{resolve as R,join as m,relative as D,sep as B,dirname as ge,isAbsolute as Me}from"node:path";import{build as Ke}from"esbuild";import{z as d}from"zod";var ve=d.object({name:d.literal("@hupu/cloud-server"),version:d.string().regex(/^\d+\.\d+\.\d+$/)}).strict(),Se=d.object({method:d.enum(["GET","POST","PUT","PATCH","DELETE","HEAD"]),path:d.string().regex(/^\/(?:[a-zA-Z0-9_-]+\/?)*$/),access:d.enum(["public","user"]),handler:d.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,79}$/)}).strict(),We=d.object({version:d.literal(1),runtime:d.literal("nodejs20"),memoryMB:d.number().int().min(128).max(2048),timeoutSeconds:d.number().int().min(1).max(60),routes:d.array(Se).max(100),serverSdk:ve}).strict().superRefine((n,e)=>{let t=new Set,r=new Map;for(let s of n.routes){let i=`${s.method} ${s.path}`;(t.has(i)||s.path.startsWith("/__hupu")||r.has(s.path)&&r.get(s.path)!==s.access)&&e.addIssue({code:"custom",message:"\u8DEF\u7531\u91CD\u590D\u3001\u4F7F\u7528\u4FDD\u7559\u8DEF\u5F84\u6216\u540C\u4E00\u8DEF\u5F84\u7684\u9274\u6743\u8981\u6C42\u4E0D\u4E00\u81F4\u3002"}),t.add(i),r.set(s.path,s.access)}}),Ge=ve.extend({archive:d.string().regex(/^[a-z0-9.-]+\.tgz$/),sha256:d.string().regex(/^[a-f0-9]{64}$/),templateHashes:d.record(d.string(),d.string())}),J=n=>Be("sha256").update(n).digest("hex"),Ee=/(?:^|\/)(?:\.env(?:\.[^/]*)?|credentials\.json)$|\.(?:pem|key)$/i;function b(n,e){let t=D(n,e);if(Me(t)||t===".."||t.startsWith(`..${B}`))throw new a("INVALID_FUNCTION_PATH","\u4E91\u51FD\u6570\u6587\u4EF6\u5FC5\u987B\u4F4D\u4E8E\u5F00\u53D1\u8005\u5DE5\u7A0B\u5185\u3002")}async function $(n,e,t){let r=await H(e);if(b(n,r),Ee.test(r))throw new a("SECRET_FILE","\u4E0D\u80FD\u5C06\u51ED\u8BC1\u6587\u4EF6\u6253\u5165\u4E91\u51FD\u6570\u3002");let s=await M(r);if(!s.isFile()||s.size>t)throw new a("INVALID_FUNCTION_FILE","\u6587\u4EF6\u7C7B\u578B\u6216\u5927\u5C0F\u4E0D\u7B26\u5408\u8981\u6C42\u3002");return N(r,"utf8")}async function V(n,e){b(n,e);let t=n;for(let r of D(n,e).split(B).filter(Boolean)){t=m(t,r),await ye(t).catch(i=>{if(i.code!=="EEXIST")throw i});let s=await M(t);if(!s.isDirectory()||s.isSymbolicLink())throw new a("UNSAFE_FUNCTION_PATH","\u51FD\u6570\u76EE\u5F55\u4E0D\u80FD\u7ECF\u8FC7\u7B26\u53F7\u94FE\u63A5\u3002")}}async function Te(){let n=m(O,"vendor/cloud-server"),e=Ge.parse(JSON.parse(await N(m(n,"release.json"),"utf8"))),t=await N(m(n,e.archive));if(J(t)!==e.sha256)throw new a("SDK_ASSET_MISMATCH","Toolkit \u5185\u7F6E SDK \u53D1\u884C\u5305\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5 Toolkit\u3002");return{release:e,archive:t}}async function Ut(n,e="cloud/functions/api"){let t=await S(n);if(!/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(e))throw new a("INVALID_FUNCTION_PATH","\u8BF7\u4F7F\u7528\u5DE5\u7A0B\u5185\u7684\u76F8\u5BF9\u76EE\u5F55\uFF0C\u4F8B\u5982 functions/api\u3002");let{release:r,archive:s}=await Te(),i=new Map;for(let[c,l]of Object.entries(r.templateHashes)){if(!/^[a-zA-Z0-9_./-]+$/.test(c)||c.split("/").includes(".."))throw new a("SDK_ASSET_MISMATCH","\u6A21\u677F\u8DEF\u5F84\u4E0D\u6B63\u786E\u3002");let p=await N(m(O,"templates/cloud-service",c),"utf8");if(J(p)!==l)throw new a("SDK_ASSET_MISMATCH","\u6807\u51C6\u6A21\u677F\u4E0E SDK \u53D1\u884C\u8BB0\u5F55\u4E0D\u4E00\u81F4\u3002");i.set(c,p)}let u=e==="cloud/functions/api";if(u){let c=JSON.parse(i.get("cloud.json")),{routes:l,...p}=c;i.set("cloud.json",JSON.stringify(p,null,2)+`
2
+ `),i.set("../../gateway/routes.json",JSON.stringify({version:1,routes:l},null,2)+`
3
+ `);for(let[h,f]of[...i])h.startsWith("migrations/")&&(i.delete(h),i.set("../../database/"+h,f));for(let h of i.keys())if(h.startsWith("../")){let f=R(t,e,h);b(t,f);try{throw await M(f),new a("CLOUD_LAYOUT_EXISTS","\u6570\u636E\u5E93\u6216\u7F51\u5173\u58F0\u660E\u5DF2\u5B58\u5728\uFF0C\u8BF7\u6CBF\u7528\u73B0\u6709\u4E91\u5DE5\u7A0B\u3002")}catch(v){if(v.code!=="ENOENT")throw v}}}let o=R(t,e);await V(t,ge(o)),await ye(o).catch(c=>{throw c.code==="EEXIST"?new a("FUNCTION_EXISTS","\u76EE\u5F55\u5DF2\u5B58\u5728\uFF0C\u8BF7\u76F4\u63A5\u4FEE\u6539\u73B0\u6709\u6E90\u7801\u540E\u91CD\u65B0\u90E8\u7F72\uFF1B\u4E0D\u4F1A\u8986\u76D6\u3002"):c}),i.set("package.json",JSON.stringify({name:`hupu-function-${e.split("/").at(-1)}`,private:!0,version:"0.1.0",engines:{node:">=20"},dependencies:{[r.name]:`file:vendor/${r.archive}`},hupuCloud:{schemaVersion:1,entry:"handlers.cjs",manifest:"cloud.json",...u?{gateway:"../../gateway/routes.json"}:{}}},null,2)+`
4
+ `),i.set(".gitignore",`node_modules/
5
+ .env
6
+ .env.*
7
+ !vendor/*.tgz
8
+ `),i.set("README.md",u?`# \u5E94\u7528\u540E\u7AEF
9
+
10
+ \u6E90\u7801\u548C\u8FD0\u884C\u53C2\u6570\u5728\u6B64\u76EE\u5F55\uFF0C\u8DEF\u7531\u5728 ../../gateway/routes.json\uFF0C\u8FC1\u79FB\u5728 ../../database/migrations\u3002
11
+
12
+ \u5728\u9879\u76EE\u6839\u76EE\u5F55\u6267\u884C shaper cloud enable\uFF0C\u67E5\u8BE2\u8FD4\u56DE operationId \u81F3 succeeded\uFF1B\u6309\u987A\u5E8F\u63D0\u4EA4\u6570\u636E\u5E93\u8FC1\u79FB\u5E76\u67E5\u8BE2\u5B8C\u6210\uFF0C\u518D\u6267\u884C shaper cloud deploy\u3002\u6784\u5EFA\u81EA\u52A8\u7EC4\u5408 manifest\uFF0C\u4E0D\u91CD\u590D\u7EF4\u62A4\u8DEF\u7531\u3002
13
+
14
+ \u4F7F\u7528\u7B2C\u4E09\u65B9\u4F9D\u8D56\u65F6\u5728\u6B64\u76EE\u5F55 npm install \u5E76\u63D0\u4EA4 package-lock.json\u3002\u521D\u59CB\u5316\u4E0D\u4F1A\u5F00\u901A\u6216\u90E8\u7F72\u4E91\u8D44\u6E90\u3002
15
+ `:await N(m(O,"templates/cloud-service/README.md"),"utf8"));for(let[c,l]of i)await V(t,ge(m(o,c))),await ee(m(o,c),l,{flag:"wx"});return await V(t,m(o,"vendor")),await ee(m(o,"vendor",r.archive),s,{flag:"wx"}),{directory:e,files:[...i.keys(),`vendor/${r.archive}`],serverSdk:{name:r.name,version:r.version},next:u?"\u4FEE\u6539 cloud/functions/api \u6E90\u7801\u4E0E\u8FD0\u884C\u914D\u7F6E\u3001cloud/gateway/routes.json \u8DEF\u7531\u3001cloud/database/migrations \u8FC1\u79FB\uFF1B\u786E\u8BA4\u8FC1\u79FB\u5B8C\u6210\u540E\u90E8\u7F72\u3002":"\u4FEE\u6539 handlers.cjs/cloud.json\uFF1B\u786E\u8BA4\u6570\u636E\u5E93\u8FC1\u79FB\u5B8C\u6210\u540E\u90E8\u7F72\u3002"}}async function Ie(n,e){let t=await S(n);if(!e)try{await M(m(t,"cloud/functions/api/package.json")),e="cloud/functions/api"}catch(g){if(g.code!=="ENOENT")throw g;e="functions/api"}let r=await H(R(t,e));b(t,r);let s=JSON.parse(await $(t,m(r,"package.json"),65536)),i=d.object({schemaVersion:d.literal(1),entry:d.string().regex(/\.(?:cjs|js|ts)$/),manifest:d.string(),gateway:d.string().optional()}).strict().parse(s.hupuCloud),u=JSON.parse(await $(t,R(r,i.manifest),65536)),o=u.routes;if(i.gateway){if(u.routes!==void 0)throw new a("DUPLICATE_ROUTES","\u8DEF\u7531\u53EA\u7EF4\u62A4\u5728 gateway \u58F0\u660E\u4E2D\uFF0C\u4E0D\u80FD\u540C\u65F6\u5199\u5165\u8FD0\u884C\u914D\u7F6E\u3002");o=d.object({version:d.literal(1),routes:d.array(Se).max(100)}).strict().parse(JSON.parse(await $(t,R(r,i.gateway),65536))).routes}let c=We.parse({...u,routes:o}),{release:l}=await Te();if(c.serverSdk.version!==l.version)throw new a("SERVER_SDK_UNSUPPORTED","\u6B64 Toolkit \u4E0D\u652F\u6301\u6307\u5B9A SDK \u7248\u672C\uFF0C\u8BF7\u540C\u6B65\u5347\u7EA7 Toolkit \u4E0E Cloud \u670D\u52A1\u3002");let p=s.dependencies?.[l.name];if(p===`file:vendor/${l.archive}`){let g=await H(m(r,"vendor",l.archive));if(b(t,g),J(await N(g))!==l.sha256)throw new a("SDK_ASSET_MISMATCH","\u9879\u76EE\u4E2D\u7684 SDK \u53D1\u884C\u5305\u4E0E\u5F53\u524D Toolkit \u4E0D\u4E00\u81F4\u3002")}else if(p!==l.version)throw new a("SDK_DEPENDENCY_REQUIRED","package.json \u5FC5\u987B\u4F7F\u7528\u6A21\u677F\u5185\u7F6E SDK \u5305\u6216\u7CBE\u786E\u7248\u672C\uFF0C\u4E0D\u80FD\u4F7F\u7528\u6D6E\u52A8\u7248\u672C\u3002");let h=R(r,i.entry);await $(t,h,8*1024*1024);let f=await Ke({absWorkingDir:t,entryPoints:[h],outfile:"app.cjs",write:!1,bundle:!0,platform:"node",format:"cjs",target:"node20",metafile:!0,sourcemap:!1,external:[l.name],logLevel:"silent",plugins:[{name:"hupu-source-policy",setup(g){g.onLoad({filter:/.*/},async E=>{let k=await H(E.path);if(Ee.test(k))throw new a("SECRET_FILE","\u6784\u5EFA\u56FE\u5305\u542B\u51ED\u8BC1\u6587\u4EF6\u3002");k.includes(`${B}node_modules${B}`)||b(t,k)}),g.onResolve({filter:/^@hupu\/cloud-server\//},()=>({errors:[{text:"\u53EA\u80FD\u4ECE @hupu/cloud-server \u516C\u5171\u5165\u53E3\u5BFC\u5165\u3002"}]}))}}]}),v=f.outputFiles[0].text,Ne=new Set(Je.flatMap(g=>[g,`node:${g}`]));for(let g of Object.values(f.metafile.outputs))for(let E of g.imports)if(E.external&&E.path!==l.name&&!Ne.has(E.path))throw new a("UNBUNDLED_DEPENDENCY",`\u4F9D\u8D56\u6CA1\u6709\u6253\u5305\uFF1A${E.path}`);if(Buffer.byteLength(v)>8*1024*1024||/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(v))throw new a("INVALID_ARTIFACT","\u5236\u54C1\u8FC7\u5927\u6216\u5305\u542B\u79C1\u94A5\u3002");let te=JSON.stringify(c,null,2)+`
16
+ `,re=J(te+`
17
+ `+v),x=m(t,".shaper/cloud-build",re);await V(t,x);for(let[g,E]of[["cloud.json",te],["app.cjs",v]]){let k=m(x,g);try{await ee(k,E,{flag:"wx"})}catch(se){if(se.code!=="EEXIST"||await $(t,k,8*1024*1024)!==E)throw se}}return{directory:D(t,r),manifestFile:D(t,m(x,"cloud.json")),bundleFile:D(t,m(x,"app.cjs")),sha256:re,bytes:Buffer.byteLength(v),serverSdk:c.serverSdk,routes:c.routes}}import{createHash as ke}from"node:crypto";import{resolve as Ye,relative as Ze,sep as Qe}from"node:path";import{readFile as Xe,realpath as et,stat as tt}from"node:fs/promises";var K=class{constructor(e){this.api=e}async status(e){return this.api.request(`${(await this.target(e)).url}/status`)}async operation(e,t){if(!/^op_[a-zA-Z0-9-]{1,64}$/.test(t))throw new a("INVALID_OPERATION_ID","\u9700\u8981\u6709\u6548\u7684\u4E91\u64CD\u4F5C\u7F16\u53F7\u3002");return this.api.request(`${(await this.target(e)).url}/operations/${t}`)}async enable(e){return this.api.request(`${(await this.target(e)).url}/enable`,{method:"POST",body:{}})}async deploy(e,t={},r){await this.target(e);let s=t.manifestFile!==void 0||t.bundleFile!==void 0;if(s&&(t.directory!==void 0||!t.manifestFile||!t.bundleFile))throw new a("INVALID_DEPLOY_INPUT","\u9009\u62E9\u6E90\u7801\u76EE\u5F55\uFF0C\u6216\u540C\u65F6\u63D0\u4F9B manifest \u548C bundle\u3002\u4E24\u79CD\u8F93\u5165\u4E0D\u80FD\u6DF7\u7528\u3002");let i=s?{manifestFile:t.manifestFile,bundleFile:t.bundleFile}:await Ie(e,t.directory),u=await this.upload(e,i.manifestFile,i.bundleFile,r);return{artifact:i,...u}}async routes(e){return this.api.request(`${(await this.target(e)).url}/routes`)}async migrate(e,t,r,s){if(!/^[0-9]{8,20}_[a-zA-Z0-9_-]+$/.test(t))throw new a("INVALID_MIGRATION","\u8FC1\u79FB\u7248\u672C\u683C\u5F0F\u4E3A\u65F6\u95F4\u6233_\u540D\u79F0\u3002");let{root:i,url:u}=await this.target(e),o=await this.source(i,r,6e4),c=s??ke("sha256").update(`${t}:${o}`).digest("hex");return this.api.request(`${u}/migrations`,{method:"POST",body:{version:t,dialect:"postgresql",sql:o,idempotencyKey:c}})}async source(e,t,r){let s=await et(Ye(e,t));if(this.checkContained(e,s),/(?:^|\/)(?:\.env(?:\..*)?|credentials\.json)$|\.(?:pem|key)$/i.test(s))throw new a("SECRET_FILE","\u4E0D\u80FD\u4E0A\u4F20\u51ED\u8BC1\u6587\u4EF6\u3002");if((await tt(s)).size>r)throw new a("ARTIFACT_TOO_LARGE","\u6587\u4EF6\u8D85\u8FC7\u5141\u8BB8\u5927\u5C0F\u3002");return Xe(s,"utf8")}async upload(e,t,r,s){let{root:i,url:u}=await this.target(e),o=JSON.parse(await this.source(i,t,65536));if(o.serverSdk!=null){let[p,h]=await Promise.all([this.status(e),this.api.request(`${u}/capabilities`)]),f=h.serverSdk;if(!f||f.name!==o.serverSdk.name||!f.versions.includes(o.serverSdk.version)||f.packaging!=="platform-external")throw new a("SERVER_SDK_UNSUPPORTED","\u5F53\u524D\u5E94\u7528\u4E0D\u652F\u6301\u6B64 SDK\uFF1B\u8BF7\u8054\u7CFB\u5E73\u53F0\u7BA1\u7406\u5458\u68C0\u67E5\u670D\u52A1\u914D\u7F6E\u6216\u5347\u7EA7 Toolkit\u3002");if(p.status!=="ready")throw new a("CLOUD_NOT_READY","\u8BF7\u5148\u5F00\u901A\u5E94\u7528\u4E91\u670D\u52A1\uFF0C\u5E76\u901A\u8FC7 cloud status \u786E\u8BA4\u8D44\u6E90 ready\u3002")}let c=await this.source(i,r,8*1024*1024),l=s??ke("sha256").update(JSON.stringify({manifest:o,bundle:c})).digest("hex");return this.api.request(`${u}/deployments`,{method:"POST",body:{manifest:o,bundle:c,idempotencyKey:l}})}async target(e){let t=await S(e),r=await _(t,this.api.auth.server),s=`/api/v1/developer/projects/${encodeURIComponent(r.appId)}/cloud-v2`;return{root:t,url:s}}checkContained(e,t){let r=Ze(e,t);if(r===".."||r.startsWith(`..${Qe}`))throw new a("INVALID_FILE_PATH","\u5236\u54C1\u6587\u4EF6\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u76EE\u5F55\u5185\u3002")}};import{createHash as rt,randomUUID as L}from"node:crypto";import{resolve as W,relative as Ae,sep as _e,dirname as st,basename as it}from"node:path";import{readFile as at,writeFile as nt,realpath as Re,stat as ot}from"node:fs/promises";var G=class{constructor(e){this.api=e}async base(e,t){let r=await S(e),s=await _(r,this.api.auth.server),i=`/api/v1/developer/projects/${encodeURIComponent(s.appId)}/cloud`;if(t&&!/^[a-z][a-z0-9-]{0,31}$/.test(t))throw new a("INVALID_ENVIRONMENT","\u73AF\u5883\u540D\u5FC5\u987B\u662F\u5C0F\u5199\u5B57\u6BCD\u5F00\u5934\uFF0C\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u8FDE\u5B57\u7B26\uFF0C\u6700\u591A 32 \u4F4D\u3002");return{root:r,url:t?`${i}/environments/${encodeURIComponent(t)}`:i}}async capabilities(e){return this.api.request(`${(await this.base(e)).url}/capabilities`)}async environments(e){return this.api.request(`${(await this.base(e)).url}/environments`)}async create(e,t,r=!1){let{url:s}=await this.base(e),i=rt("sha256").update(`environment:${s}:${t}:${r}`).digest("hex");return this.api.request(`${s}/environments`,{method:"POST",body:{name:t,postgres:r},key:i})}async status(e,t){return this.api.request((await this.base(e,t)).url)}async functions(e,t){return this.api.request(`${(await this.base(e,t)).url}/functions`)}async deployFunction(e,t,r,s,i){let{root:u,url:o}=await this.base(e,t),c=await S(W(u,s)),l=Ae(u,c);if(l===".."||l.startsWith(`..${_e}`))throw new a("INVALID_FUNCTION_PATH","\u51FD\u6570\u4EE3\u7801\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u76EE\u5F55\u5185\u3002");let p=await oe(c,{files:1e3,bytes:30*1024*1024});return this.api.request(`${o}/functions/${encodeURIComponent(r)}/deploy`,{method:"POST",file:p.content,key:i??L()})}async invoke(e,t,r,s,i){return this.api.request(`${(await this.base(e,t)).url}/functions/${encodeURIComponent(r)}/invoke`,{method:"POST",body:s,key:i??L()})}async logs(e,t,r){return this.api.request(`${(await this.base(e,t)).url}/functions/${encodeURIComponent(r)}/logs`)}async sql(e,t,r,s){return this.api.request(`${(await this.base(e,t)).url}/database/query`,{method:"POST",body:{sql:r},key:s??L()})}async listObjects(e,t,r="",s){let i=new URLSearchParams({prefix:r,...s?{cursor:s}:{}});return this.api.request(`${(await this.base(e,t)).url}/storage?${i}`)}async putObject(e,t,r,s,i){let{root:u,url:o}=await this.base(e,t),c=await Re(W(u,s));if(this.checkContained(u,c),/(?:^|\/)(?:\.env(?:\..*)?|credentials\.json)$|\.(?:pem|key)$/i.test(c))throw new a("SECRET_FILE","\u51ED\u8BC1\u6587\u4EF6\u4E0D\u80FD\u4F5C\u4E3A\u4E1A\u52A1\u5BF9\u8C61\u4E0A\u4F20\u3002");if((await ot(c)).size>10*1024*1024)throw new a("OBJECT_TOO_LARGE","\u5BF9\u8C61\u4E0D\u80FD\u8D85\u8FC7 10 MiB\u3002");return this.api.request(`${o}/storage/object?${new URLSearchParams({key:r})}`,{method:"POST",file:await at(c),key:i??L()})}async getObject(e,t,r,s){let{root:i,url:u}=await this.base(e,t),o=W(await Re(st(W(i,s))),it(s));this.checkContained(i,o);let c=await this.api.request(`${u}/storage/object?${new URLSearchParams({key:r})}`);return await nt(o,Buffer.from(c.base64,"base64"),{flag:"wx",mode:384}),{key:r,bytes:c.bytes,path:o}}async deleteObject(e,t,r,s){return this.api.request(`${(await this.base(e,t)).url}/storage/object?${new URLSearchParams({key:r})}`,{method:"DELETE",key:s??L()})}checkContained(e,t){let r=Ae(e,t);if(r===".."||r.startsWith(`..${_e}`))throw new a("INVALID_FILE_PATH","\u5BF9\u8C61\u6587\u4EF6\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u76EE\u5F55\u5185\u3002")}};var be=class n{constructor(e){this.auth=e;this.api=new z(e),this.cloud=new K(this.api),this.legacyCloud=new G(this.api)}api;cloud;legacyCloud;static async create(e){return new n(new q(e??await ae()))}async status(e){let t;try{t={authenticated:!0,...await this.api.me()}}catch(s){t={authenticated:!1,error:C(s)}}let r;if(e){let s=await S(e),i;try{let o=await _(s,this.auth.server);try{let c=await this.api.project(o.appId);i={...o,authorized:!0,name:c.name,versions:c.versions}}catch(c){i={...o,authorized:!1,error:C(c)}}}catch(o){i={linked:!1,error:C(o)}}let u;try{u=await ne(s)}catch(o){u={error:C(o)}}r={root:s,binding:i,config:u,dev:await ce(s)}}return{server:this.auth.server,identity:t,...r?{project:r}:{}}}};export{q as a,z as b,Ut as c,Ie as d,K as e,G as f,be as g};
@@ -0,0 +1,15 @@
1
+ import{homedir as Y}from"node:os";import{join as O,resolve as Z,dirname as tt}from"node:path";import{mkdir as et,readFile as nt,rename as rt,writeFile as it,lstat as at,rm as ot}from"node:fs/promises";import{randomUUID as st}from"node:crypto";import{z as T}from"zod";var a=class extends Error{constructor(r,e,i){super(e);this.code=r;this.details=i}},ct=T.object({schemaVersion:T.literal(1),server:T.string().url()}).strict();function V(){return Z(process.env.SHAPER_CONFIG_HOME??O(Y(),".config","shaper"))}function _(t){let n=new URL(t);if(n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.protocol!=="https:"&&!(n.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(n.hostname)))throw new a("INVALID_SERVER","\u670D\u52A1\u5730\u5740\u5FC5\u987B\u662F HTTPS origin\uFF1B\u672C\u673A\u5F00\u53D1\u5141\u8BB8\u56DE\u73AF HTTP\u3002");return n.origin}async function N(t,n){await et(tt(t),{recursive:!0,mode:448});try{if((await at(t)).isSymbolicLink())throw new a("UNSAFE_FILE",`\u914D\u7F6E\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\uFF1A${t}`)}catch(e){if(e.code!=="ENOENT")throw e}let r=`${t}.${st()}.tmp`;try{await it(r,JSON.stringify(n,null,2)+`
2
+ `,{mode:384,flag:"wx"}),await rt(r,t)}finally{await ot(r,{force:!0})}}async function S(t){return JSON.parse(await nt(t,"utf8"))}async function At(){if(process.env.SHAPER_SERVER)return _(process.env.SHAPER_SERVER);try{return _(ct.parse(await S(O(V(),"config.json"))).server)}catch(t){if(t.code==="ENOENT")return"https://shaper.hupu.com";throw new a("INVALID_CONFIG","\u7528\u6237\u914D\u7F6E\u65E0\u6CD5\u8BFB\u53D6\uFF0C\u8BF7\u4F7F\u7528 shaper config --server \u91CD\u65B0\u8BBE\u7F6E\u670D\u52A1\u5730\u5740\u3002")}}async function Rt(t){await N(O(V(),"config.json"),{schemaVersion:1,server:_(t)})}function bt(t){return{code:t instanceof a?t.code:"OPERATION_FAILED",message:t instanceof Error?t.message:"\u64CD\u4F5C\u672A\u5B8C\u6210",...t instanceof a&&t.details!==void 0?{details:t.details}:{}}}import{realpath as k,mkdir as z,readdir as P,readFile as I,writeFile as v,lstat as G,cp as pt,appendFile as dt}from"node:fs/promises";import{resolve as x,join as p,relative as C,sep as L,dirname as lt,basename as ut,isAbsolute as H}from"node:path";import{fileURLToPath as ft}from"node:url";import{randomUUID as K,createHash as M}from"node:crypto";import{spawn as wt}from"node:child_process";import ht from"adm-zip";import mt from"open";import{z as g}from"zod";import W from"proper-lockfile";var $=x(lt(ft(import.meta.url)),".."),gt=g.object({schemaVersion:g.literal(1),devCommand:g.string().min(1).max(500),buildCommand:g.string().min(1).max(500),outputDir:g.string().min(1),devUrl:g.string().default("http://127.0.0.1:{port}")}).passthrough(),Et=g.object({schemaVersion:g.literal(1),appId:g.string().min(1).max(200),server:g.string().url()}).strict();async function j(t){if(!t||!H(t))throw new a("WORKSPACE_REQUIRED","\u8BF7\u6307\u5B9A\u5DE5\u7A0B\u7684\u7EDD\u5BF9\u8DEF\u5F84\u3002");return k(x(t))}async function A(t){let n=p(t,".shaper");if(await z(n,{recursive:!0,mode:448}),(await G(n)).isSymbolicLink())throw new a("UNSAFE_WORKSPACE",".shaper \u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\u3002");return n}async function R(t){return gt.parse(await S(p(t,"shaper.config.json")))}async function U(t,n){let r=Et.parse(await S(p(t,".shaper","project.json")));if(r.server!==n)throw new a("SERVER_MISMATCH","\u6B64\u5DE5\u7A0B\u7ED1\u5B9A\u7684 Shaper \u670D\u52A1\u4E0E\u5F53\u524D\u767B\u5F55\u670D\u52A1\u4E0D\u540C\u3002\u8BF7\u663E\u5F0F\u5207\u6362\u670D\u52A1\u6216\u91CD\u65B0\u5173\u8054\u3002");return r}async function q(t,n,r){let e=await A(t);await N(p(e,"project.json"),{schemaVersion:1,appId:n,server:r})}async function Vt(t,n,r={}){if(!n||!H(n))throw new a("WORKSPACE_REQUIRED","\u8BF7\u6307\u5B9A\u5DE5\u7A0B\u7684\u7EDD\u5BF9\u8DEF\u5F84\u3002");await z(n,{recursive:!0});let e=await j(n),i=await A(e),s=await W.lock(i,{retries:0});try{let c;try{c=await U(e,t.auth.server)}catch(o){if(o.code!=="ENOENT")throw o}if(c&&r.appId&&r.appId!==c.appId)throw new a("ALREADY_LINKED",`\u5F53\u524D\u76EE\u5F55\u5C5E\u4E8E ${c.appId}\uFF0C\u4E0E\u63D0\u793A\u8BCD\u4E2D\u7684 ${r.appId} \u4E0D\u4E00\u81F4\u3002\u8BF7\u56DE\u5230\u539F\u5E94\u7528\u7EE7\u7EED\uFF0C\u6216\u6362\u4E00\u4E2A\u7A7A\u76EE\u5F55\uFF1Binit \u4E0D\u4F1A\u8986\u76D6\u7ED1\u5B9A\u3002`);let f=(await P(e)).filter(o=>![".git",".shaper",".shaper.lock",".DS_Store"].includes(o));if(!c&&f.length&&r.template)throw new a("EXISTING_PROJECT","\u6A21\u677F\u53EA\u7528\u4E8E\u7A7A\u76EE\u5F55\uFF1B\u8BF7\u4FDD\u7559\u5DF2\u6709\u9879\u76EE\u7684\u6784\u5EFA\u65B9\u5F0F\u3002");if(r.template&&!["h5","react","phaser"].includes(r.template))throw new a("INVALID_TEMPLATE","\u652F\u6301 h5\u3001react\u3001phaser \u6A21\u677F\u3002");let l=new Set;for(let o of["shaper.config.json","shaper.project.json",".shaper/config.json"]){let E=await S(p(e,o)).catch(m=>{if(m.code!=="ENOENT")throw m});for(let m of[E?.appId,E?.applicationId])typeof m=="string"&&m.startsWith("app_")&&l.add(m)}let d=c?.appId??r.appId??[...l][0];if(l.size>1||d&&[...l].some(o=>o!==d))throw new a("APP_ID_CONFLICT","\u539F\u9879\u76EE\u5E94\u7528 ID \u4E0E\u76EE\u6807\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u6838\u5BF9\u65E7\u9879\u76EE\u914D\u7F6E\uFF1B\u4E0D\u4F1A\u521B\u5EFA\u6216\u5207\u6362\u5E94\u7528\u3002");let u=p(i,"init.json"),h=c?void 0:await S(u).catch(o=>{if(o.code!=="ENOENT")throw o});if(!c&&h&&(!h.appId||h.server!==t.auth.server||d&&d!==h.appId))throw new a("INIT_CONFLICT","\u5B58\u5728\u672A\u5B8C\u6210\u7684\u521D\u59CB\u5316\uFF0C\u8BF7\u6838\u5BF9 .shaper/init.json \u4E2D\u7684\u539F\u5E94\u7528\u548C\u670D\u52A1\uFF0C\u4E0D\u8981\u53E6\u5EFA\u5E94\u7528\u3002");if(!d&&!h&&f.length)throw new a("APP_REQUIRED","\u5DF2\u6709\u9879\u76EE\u5C1A\u672A\u8BC6\u522B\u5230\u5E94\u7528 ID\u3002\u8BF7\u5148\u786E\u8BA4\u539F\u5E94\u7528\uFF0C\u518D\u4F7F\u7528 init --app\uFF1B\u65B0\u4F5C\u54C1\u8BF7\u4ECE\u7F51\u9875\u5F00\u59CB\u521B\u4F5C\u5E76\u643A\u5E26\u9884\u5206\u914D ID\u3002");let w=d??h?.appId??`app_${K().replaceAll("-","").slice(0,10)}`;!h&&!c&&(h={appId:w,server:t.auth.server},await N(u,h));let b;try{b=await t.project(w)}catch(o){if(!(o instanceof a)||!["AUTH_REQUIRED","INVALID_TOKEN","PROJECT_NOT_AUTHORIZED","INSUFFICIENT_SCOPE","NOT_FOUND"].includes(o.code))throw o;let E=await t.auth.start({appId:w,...r.name?{applicationName:r.name}:{},initialize:!c&&l.size===0,reauthorize:!0});if(E.status==="pending"){if(!r.waitForAuthorization)return{root:e,appId:w,...E,status:"awaiting_confirmation",next:"\u5728\u6D4F\u89C8\u5668\u5B8C\u6210\u767B\u5F55\u548C\u521B\u5EFA/\u5173\u8054\u786E\u8BA4\uFF0C\u6388\u6743\u5B8C\u6210\u540E\u4F7F\u7528\u540C\u4E00\u76EE\u5F55\u548C\u53C2\u6570\u91CD\u8BD5 init\u3002"};process.stderr.write(`\u8BF7\u5728\u6D4F\u89C8\u5668\u786E\u8BA4\u521B\u5EFA\u6216\u5173\u8054\u5E94\u7528\uFF1A${E.authorizationUrl}
3
+ `),await t.auth.wait(E.flowId)}b=await t.project(w)}let Q=b.name;if(c)return r.installDependencies!==!1&&await I(p(i,"install-pending"),"utf8").catch(E=>{if(E.code==="ENOENT")return"";throw E})&&(await D("npm ci",e),await v(p(i,"install-pending"),"")),{root:e,...c,alreadyInitialized:!0};if(f.length===0){let o=r.template??"h5";if(!["h5","react","phaser"].includes(o))throw new a("INVALID_TEMPLATE","\u652F\u6301 h5\u3001react\u3001phaser \u6A21\u677F\u3002");let E=p($,"templates",o);for(let m of(await P(E)).filter(y=>!["node_modules","dist"].includes(y)))await pt(p(E,m),p(e,m),{recursive:!0,force:!1,errorOnExist:!0});r.installDependencies!==!1&&await v(p(i,"install-pending"),`npm ci
4
+ `)}else{if(r.template)throw new a("EXISTING_PROJECT","\u6A21\u677F\u53EA\u7528\u4E8E\u7A7A\u76EE\u5F55\uFF1B\u5DF2\u6709\u5DE5\u7A0B\u76F4\u63A5 init\uFF0C\u4FDD\u7559\u6280\u672F\u6808\u548C\u6E90\u7801\u3002");try{await R(e)}catch(o){if(o.code!=="ENOENT")throw o;await N(p(e,"shaper.config.json"),{schemaVersion:1,devCommand:"npm run dev -- --host 127.0.0.1 --port {port} --strictPort",buildCommand:"npm run build",outputDir:"dist"})}}try{await I(p(e,"package.json"))}catch(o){if(o.code!=="ENOENT")throw o;if(await I(p(e,"index.html")).catch(m=>{if(m.code!=="ENOENT")throw m})!==void 0){for(let m of["package.json","package-lock.json","vite.config.js"])try{let y=await I(p($,"templates/h5",m));if(m==="package.json"){let J=JSON.parse(y.toString("utf8"));J.scripts.check="vite build",y=Buffer.from(JSON.stringify(J,null,2)+`
5
+ `)}await v(p(e,m),y,{flag:"wx"})}catch(y){if(y.code!=="EEXIST")throw y}r.installDependencies!==!1&&await v(p(i,"install-pending"),`npm ci
6
+ `)}}await B(e),await q(e,w,t.auth.server);let X=await I(p(i,"install-pending"),"utf8").catch(o=>{if(o.code==="ENOENT")return"";throw o});return r.installDependencies!==!1&&X&&(await D("npm ci",e),await v(p(i,"install-pending"),"")),{root:e,name:Q,appId:w}}finally{await s()}}async function $t(t,n,r){let e=await j(n),i=await W.lock(await A(e),{retries:0});try{let s=await t.project(r);return await q(e,s.appId,t.auth.server),await B(e),{root:e,appId:s.appId,name:s.name}}finally{await i()}}async function B(t){let n=p(t,".gitignore"),r=await I(n,"utf8").catch(u=>{if(u.code==="ENOENT")return"";throw u}),i=["/.shaper/","/.shaper.lock/","/node_modules/","/dist/",".env",".env.*","!.env.example"].filter(u=>!r.split(`
7
+ `).includes(u));i.length&&await dt(n,`
8
+ # Shaper local state and generated files
9
+ ${i.join(`
10
+ `)}
11
+ `);let s=p(t,"AGENTS.md"),c=await I(s,"utf8").catch(u=>{if(u.code==="ENOENT")return"";throw u}),f="<!-- shaper:project -->",l=`
12
+ ${f}
13
+ Read docs/product.md for goals and rules, docs/design.md for experience and implementation decisions, and docs/validation.md for actual evidence when these files exist. Use the globally installed shaper-development skill for local development and shaper-release for web delivery. For Hupu login/share use hupu-business; for functions or databases use shaper-backend. Pass this project's absolute path to project tools. Read shaper.config.json for commands and query shaper_status for live identity. Web publishing belongs to Shaper; cloud functions are deployed separately.
14
+ <!-- /shaper:project -->
15
+ `,d=c.includes(f)?c.replace(/<!-- shaper:project -->[\s\S]*?<!-- \/shaper:project -->\n?/,l.trimStart()):c+l;d!==c&&await v(s,d)}async function D(t,n){await new Promise((r,e)=>{let i=wt(t,{cwd:n,shell:!0,stdio:["ignore","pipe","pipe"]});i.stdout.on("data",s=>process.stderr.write(s)),i.stderr.on("data",s=>process.stderr.write(s)),i.once("error",e),i.once("exit",s=>s===0?r():e(new a("COMMAND_FAILED",`\u5DE5\u7A0B\u547D\u4EE4\u9000\u51FA\u7801\uFF1A${s??"signal"}`)))})}async function It(t){let n=await j(t),r=await R(n);await D(r.buildCommand,n);let e=await F(n,r.outputDir);return await I(p(e,"index.html")),{root:n,output:e}}async function F(t,n){let r=await k(x(t,n)),e=C(t,r);if(e===".."||e.startsWith(`..${L}`)||x(t,e)!==r)throw new a("INVALID_OUTPUT","\u8F93\u51FA\u76EE\u5F55\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u5185\u90E8\u3002");return r}async function yt(t,n={files:300,bytes:200*1024*1024}){let r=await k(t),e=new ht,i=0,s=0;async function c(f){for(let l of(await P(f,{withFileTypes:!0})).sort((d,u)=>d.name.localeCompare(u.name))){if(/^(\.git|\.shaper|node_modules|\.DS_Store)$/.test(l.name))continue;if(/^(\.env(?:\..*)?|credentials\.json|.*\.(pem|key))$/i.test(l.name))throw new a("SECRET_FILE_IN_PACKAGE",`\u8F93\u51FA\u76EE\u5F55\u5305\u542B\u654F\u611F\u914D\u7F6E\u6587\u4EF6\uFF1A${l.name}`);let d=p(f,l.name);if(l.isSymbolicLink())throw new a("SYMLINK_IN_PACKAGE",`\u4EA4\u4ED8\u5185\u5BB9\u4E2D\u4E0D\u5141\u8BB8\u7B26\u53F7\u94FE\u63A5\uFF1A${l.name}`);if(l.isDirectory()){await c(d);continue}if(!l.isFile())throw new a("INVALID_PACKAGE_FILE","\u4EA4\u4ED8\u76EE\u5F55\u5305\u542B\u975E\u5E38\u89C4\u6587\u4EF6\u3002");let u=await G(d);if(i+=u.size,s++,s>n.files||i>n.bytes)throw new a("PACKAGE_TOO_LARGE","\u4EA4\u4ED8\u5305\u8D85\u8FC7\u6587\u4EF6\u6570\u6216\u5927\u5C0F\u9650\u5236\u3002");e.addFile(C(r,d).split(L).join("/"),await I(d))}}await c(r);for(let f of e.getEntries())f.header.time=new Date(2e3,0,1);return{content:e.toBuffer(),files:s,bytes:i}}async function zt(t,n,r={}){let e=await j(n),i=await U(e,t.auth.server),s=r.build===!1?await F(e,(await R(e)).outputDir):(await It(e)).output,c=await yt(s),f=M("sha256").update(c.content).digest("hex"),l=await A(e),d=p(l,"web-deploy.json"),u=K();try{let w=g.object({sha256:g.string(),key:g.string(),appId:g.string(),server:g.string()}).passthrough().parse(await S(d));w.sha256===f&&w.appId===i.appId&&w.server===t.auth.server&&(u=w.key)}catch(w){if(w.code!=="ENOENT")throw w}await N(d,{sha256:f,key:u,appId:i.appId,server:t.auth.server});let h=await t.request(`/api/v1/developer/projects/${encodeURIComponent(i.appId)}/web/deploy`,{method:"POST",file:c.content,key:u});return await N(d,{sha256:f,key:u,appId:i.appId,server:t.auth.server,response:h}),h}async function Gt(t,n,r,e,i){let s=await j(n),c=await U(s,t.auth.server),f=i?await I(await F(s,i)):void 0;if(f&&f.length>2*1024*1024)throw new a("INVALID_COVER","\u5C01\u9762\u4E0D\u80FD\u8D85\u8FC7 2 MiB\u3002");let l=f?{filename:ut(i),base64:f.toString("base64")}:void 0,d={versionId:r,description:e,...l?{cover:l}:{}},u=M("sha256").update(JSON.stringify({appId:c.appId,body:d})).digest("hex"),h=await t.request(`/api/v1/developer/projects/${encodeURIComponent(c.appId)}/web/publish`,{method:"POST",body:d,key:u});if(h.result?.confirmationUrl){let w=new URL(h.result.confirmationUrl);if(w.origin!==t.auth.server||w.pathname!=="/applications/create")throw new a("INVALID_CONFIRMATION_URL","\u786E\u8BA4\u9875\u9762\u5730\u5740\u4E0D\u6B63\u786E");try{await mt(w.href,{wait:!1})}catch{}}return{...h,submitted:!1,next:"\u5728\u6D4F\u89C8\u5668\u6838\u5BF9\u5E94\u7528\u4FE1\u606F\u5E76\u70B9\u51FB\u63D0\u4EA4\u5BA1\u6838\u3002\u901A\u8FC7\u5E94\u7528\u7248\u672C\u72B6\u6001\u67E5\u8BE2\u6700\u7EC8\u7ED3\u679C\u3002"}}async function Ht(t){let n=await j(t),r=await R(n),e=[];try{await I(p(n,"package.json"))}catch{e.push("package.json \u4E0D\u5B58\u5728")}let i=x(n,r.outputDir),s=C(n,i);return(s===".."||s.startsWith(`..${L}`))&&e.push("outputDir \u8D85\u51FA\u5DE5\u7A0B\u76EE\u5F55"),{root:n,passed:e.length===0,findings:e,checks:["project configuration","package manifest","output path"],notRun:["application behavior","build","cloud connectivity"]}}export{a,V as b,_ as c,N as d,S as e,At as f,Rt as g,bt as h,$ as i,j,R as k,U as l,Vt as m,$t as n,It as o,yt as p,zt as q,Gt as r,Ht as s};
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@hupu-tech/shaper",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "Shaper local developer tools, MCP server and Hupu integration skills",
5
5
  "type": "module",
6
6
  "bin": {
7
- "shaper": "dist/cli.js"
7
+ "shaper": "dist/launcher.js"
8
8
  },
9
9
  "exports": {
10
10
  ".": "./dist/index.js",
@@ -1,15 +0,0 @@
1
- import{homedir as nt}from"node:os";import{join as C,resolve as ot,dirname as it}from"node:path";import{mkdir as at,readFile as st,rename as ct,writeFile as pt,lstat as dt,rm as lt}from"node:fs/promises";import{randomUUID as ut}from"node:crypto";import{z as P}from"zod";var a=class extends Error{constructor(n,r,o){super(r);this.code=n;this.details=o}},ft=P.object({schemaVersion:P.literal(1),server:P.string().url()}).strict();function b(){return ot(process.env.SHAPER_CONFIG_HOME??C(nt(),".config","shaper"))}function k(t){let e=new URL(t);if(e.username||e.password||e.search||e.hash||e.pathname!=="/"||e.protocol!=="https:"&&!(e.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(e.hostname)))throw new a("INVALID_SERVER","\u670D\u52A1\u5730\u5740\u5FC5\u987B\u662F HTTPS origin\uFF1B\u672C\u673A\u5F00\u53D1\u5141\u8BB8\u56DE\u73AF HTTP\u3002");return e.origin}async function v(t,e){await at(it(t),{recursive:!0,mode:448});try{if((await dt(t)).isSymbolicLink())throw new a("UNSAFE_FILE",`\u914D\u7F6E\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\uFF1A${t}`)}catch(r){if(r.code!=="ENOENT")throw r}let n=`${t}.${ut()}.tmp`;try{await pt(n,JSON.stringify(e,null,2)+`
2
- `,{mode:384,flag:"wx"}),await ct(n,t)}finally{await lt(n,{force:!0})}}async function N(t){return JSON.parse(await st(t,"utf8"))}async function Ft(){if(process.env.SHAPER_SERVER)return k(process.env.SHAPER_SERVER);try{return k(ft.parse(await N(C(b(),"config.json"))).server)}catch(t){if(t.code==="ENOENT")return"https://shaper.hupu.com";throw new a("INVALID_CONFIG","\u7528\u6237\u914D\u7F6E\u65E0\u6CD5\u8BFB\u53D6\uFF0C\u8BF7\u4F7F\u7528 shaper config --server \u91CD\u65B0\u8BBE\u7F6E\u670D\u52A1\u5730\u5740\u3002")}}async function Vt(t){await v(C(b(),"config.json"),{schemaVersion:1,server:k(t)})}function $t(t){return{code:t instanceof a?t.code:"OPERATION_FAILED",message:t instanceof Error?t.message:"\u64CD\u4F5C\u672A\u5B8C\u6210",...t instanceof a&&t.details!==void 0?{details:t.details}:{}}}import{realpath as J,mkdir as M,readdir as U,readFile as I,writeFile as A,lstat as W,cp as wt,appendFile as ht}from"node:fs/promises";import{resolve as T,join as d,relative as F,sep as V,dirname as mt,basename as gt,isAbsolute as B}from"node:path";import{fileURLToPath as Et}from"node:url";import{randomUUID as q,createHash as Q}from"node:crypto";import{spawn as It}from"node:child_process";import yt from"adm-zip";import Nt from"open";import{z as g}from"zod";import X from"proper-lockfile";var R=T(mt(Et(import.meta.url)),".."),St=g.object({schemaVersion:g.literal(1),devCommand:g.string().min(1).max(500),buildCommand:g.string().min(1).max(500),outputDir:g.string().min(1),devUrl:g.string().default("http://127.0.0.1:{port}")}).passthrough(),vt=g.object({schemaVersion:g.literal(1),appId:g.string().min(1).max(200),server:g.string().url()}).strict();async function y(t){if(!t||!B(t))throw new a("WORKSPACE_REQUIRED","\u8BF7\u6307\u5B9A\u5DE5\u7A0B\u7684\u7EDD\u5BF9\u8DEF\u5F84\u3002");return J(T(t))}async function D(t){let e=d(t,".shaper");if(await M(e,{recursive:!0,mode:448}),(await W(e)).isSymbolicLink())throw new a("UNSAFE_WORKSPACE",".shaper \u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\u3002");return e}async function j(t){return St.parse(await N(d(t,"shaper.config.json")))}async function $(t,e){let n=vt.parse(await N(d(t,".shaper","project.json")));if(n.server!==e)throw new a("SERVER_MISMATCH","\u6B64\u5DE5\u7A0B\u7ED1\u5B9A\u7684 Shaper \u670D\u52A1\u4E0E\u5F53\u524D\u767B\u5F55\u670D\u52A1\u4E0D\u540C\u3002\u8BF7\u663E\u5F0F\u5207\u6362\u670D\u52A1\u6216\u91CD\u65B0\u5173\u8054\u3002");return n}async function Y(t,e,n){let r=await D(t);await v(d(r,"project.json"),{schemaVersion:1,appId:e,server:n})}async function Zt(t,e,n={}){if(!e||!B(e))throw new a("WORKSPACE_REQUIRED","\u8BF7\u6307\u5B9A\u5DE5\u7A0B\u7684\u7EDD\u5BF9\u8DEF\u5F84\u3002");await M(e,{recursive:!0});let r=await y(e),o=await D(r),i=await X.lock(o,{retries:0});try{let s;try{s=await $(r,t.auth.server)}catch(p){if(p.code!=="ENOENT")throw p}if(s&&n.appId&&n.appId!==s.appId)throw new a("ALREADY_LINKED",`\u5F53\u524D\u76EE\u5F55\u5C5E\u4E8E ${s.appId}\uFF0C\u4E0E\u63D0\u793A\u8BCD\u4E2D\u7684 ${n.appId} \u4E0D\u4E00\u81F4\u3002\u8BF7\u56DE\u5230\u539F\u5E94\u7528\u7EE7\u7EED\uFF0C\u6216\u6362\u4E00\u4E2A\u7A7A\u76EE\u5F55\uFF1Binit \u4E0D\u4F1A\u8986\u76D6\u7ED1\u5B9A\u3002`);let l=(await U(r)).filter(p=>![".git",".shaper",".shaper.lock",".DS_Store"].includes(p));if(!s&&l.length&&n.template)throw new a("EXISTING_PROJECT","\u6A21\u677F\u53EA\u7528\u4E8E\u7A7A\u76EE\u5F55\uFF1B\u8BF7\u4FDD\u7559\u5DF2\u6709\u9879\u76EE\u7684\u6784\u5EFA\u65B9\u5F0F\u3002");if(n.template&&!["h5","react","phaser"].includes(n.template))throw new a("INVALID_TEMPLATE","\u652F\u6301 h5\u3001react\u3001phaser \u6A21\u677F\u3002");let c=new Set;for(let p of["shaper.config.json","shaper.project.json",".shaper/config.json"]){let E=await N(d(r,p)).catch(m=>{if(m.code!=="ENOENT")throw m});for(let m of[E?.appId,E?.applicationId])typeof m=="string"&&m.startsWith("app_")&&c.add(m)}let u=s?.appId??n.appId??[...c][0];if(c.size>1||u&&[...c].some(p=>p!==u))throw new a("APP_ID_CONFLICT","\u539F\u9879\u76EE\u5E94\u7528 ID \u4E0E\u76EE\u6807\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u6838\u5BF9\u65E7\u9879\u76EE\u914D\u7F6E\uFF1B\u4E0D\u4F1A\u521B\u5EFA\u6216\u5207\u6362\u5E94\u7528\u3002");let f=d(o,"init.json"),h=s?void 0:await N(f).catch(p=>{if(p.code!=="ENOENT")throw p});if(!s&&h&&(!h.appId||h.server!==t.auth.server||u&&u!==h.appId))throw new a("INIT_CONFLICT","\u5B58\u5728\u672A\u5B8C\u6210\u7684\u521D\u59CB\u5316\uFF0C\u8BF7\u6838\u5BF9 .shaper/init.json \u4E2D\u7684\u539F\u5E94\u7528\u548C\u670D\u52A1\uFF0C\u4E0D\u8981\u53E6\u5EFA\u5E94\u7528\u3002");if(!u&&!h&&l.length)throw new a("APP_REQUIRED","\u5DF2\u6709\u9879\u76EE\u5C1A\u672A\u8BC6\u522B\u5230\u5E94\u7528 ID\u3002\u8BF7\u5148\u786E\u8BA4\u539F\u5E94\u7528\uFF0C\u518D\u4F7F\u7528 init --app\uFF1B\u65B0\u4F5C\u54C1\u8BF7\u4ECE\u7F51\u9875\u5F00\u59CB\u521B\u4F5C\u5E76\u643A\u5E26\u9884\u5206\u914D ID\u3002");let w=u??h?.appId??`app_${q().replaceAll("-","").slice(0,10)}`;!h&&!s&&(h={appId:w,server:t.auth.server},await v(f,h));let O;try{O=await t.project(w)}catch(p){if(!(p instanceof a)||!["AUTH_REQUIRED","INVALID_TOKEN","PROJECT_NOT_AUTHORIZED","INSUFFICIENT_SCOPE","NOT_FOUND"].includes(p.code))throw p;let E=await t.auth.start({appId:w,...n.name?{applicationName:n.name}:{},initialize:!s&&c.size===0,reauthorize:!0});if(E.status==="pending"){if(!n.waitForAuthorization)return{root:r,appId:w,...E,status:"awaiting_confirmation",next:"\u5728\u6D4F\u89C8\u5668\u5B8C\u6210\u767B\u5F55\u548C\u521B\u5EFA/\u5173\u8054\u786E\u8BA4\uFF0C\u6388\u6743\u5B8C\u6210\u540E\u4F7F\u7528\u540C\u4E00\u76EE\u5F55\u548C\u53C2\u6570\u91CD\u8BD5 init\u3002"};process.stderr.write(`\u8BF7\u5728\u6D4F\u89C8\u5668\u786E\u8BA4\u521B\u5EFA\u6216\u5173\u8054\u5E94\u7528\uFF1A${E.authorizationUrl}
3
- `),await t.auth.wait(E.flowId)}O=await t.project(w)}let et=O.name;if(s)return n.installDependencies!==!1&&await I(d(o,"install-pending"),"utf8").catch(E=>{if(E.code==="ENOENT")return"";throw E})&&(await L("npm ci",r),await A(d(o,"install-pending"),"")),{root:r,...s,alreadyInitialized:!0};if(l.length===0){let p=n.template??"h5";if(!["h5","react","phaser"].includes(p))throw new a("INVALID_TEMPLATE","\u652F\u6301 h5\u3001react\u3001phaser \u6A21\u677F\u3002");let E=d(R,"templates",p);for(let m of(await U(E)).filter(S=>!["node_modules","dist"].includes(S)))await wt(d(E,m),d(r,m),{recursive:!0,force:!1,errorOnExist:!0});n.installDependencies!==!1&&await A(d(o,"install-pending"),`npm ci
4
- `)}else{if(n.template)throw new a("EXISTING_PROJECT","\u6A21\u677F\u53EA\u7528\u4E8E\u7A7A\u76EE\u5F55\uFF1B\u5DF2\u6709\u5DE5\u7A0B\u76F4\u63A5 init\uFF0C\u4FDD\u7559\u6280\u672F\u6808\u548C\u6E90\u7801\u3002");try{await j(r)}catch(p){if(p.code!=="ENOENT")throw p;await v(d(r,"shaper.config.json"),{schemaVersion:1,devCommand:"npm run dev -- --host 127.0.0.1 --port {port} --strictPort",buildCommand:"npm run build",outputDir:"dist"})}}try{await I(d(r,"package.json"))}catch(p){if(p.code!=="ENOENT")throw p;if(await I(d(r,"index.html")).catch(m=>{if(m.code!=="ENOENT")throw m})!==void 0){for(let m of["package.json","package-lock.json","vite.config.js"])try{let S=await I(d(R,"templates/h5",m));if(m==="package.json"){let K=JSON.parse(S.toString("utf8"));K.scripts.check="vite build",S=Buffer.from(JSON.stringify(K,null,2)+`
5
- `)}await A(d(r,m),S,{flag:"wx"})}catch(S){if(S.code!=="EEXIST")throw S}n.installDependencies!==!1&&await A(d(o,"install-pending"),`npm ci
6
- `)}}await Z(r),await Y(r,w,t.auth.server);let rt=await I(d(o,"install-pending"),"utf8").catch(p=>{if(p.code==="ENOENT")return"";throw p});return n.installDependencies!==!1&&rt&&(await L("npm ci",r),await A(d(o,"install-pending"),"")),{root:r,name:et,appId:w}}finally{await i()}}async function te(t,e,n){let r=await y(e),o=await X.lock(await D(r),{retries:0});try{let i=await t.project(n);return await Y(r,i.appId,t.auth.server),await Z(r),{root:r,appId:i.appId,name:i.name}}finally{await o()}}async function Z(t){let e=d(t,".gitignore"),n=await I(e,"utf8").catch(f=>{if(f.code==="ENOENT")return"";throw f}),o=["/.shaper/","/.shaper.lock/","/node_modules/","/dist/",".env",".env.*","!.env.example"].filter(f=>!n.split(`
7
- `).includes(f));o.length&&await ht(e,`
8
- # Shaper local state and generated files
9
- ${o.join(`
10
- `)}
11
- `);let i=d(t,"AGENTS.md"),s=await I(i,"utf8").catch(f=>{if(f.code==="ENOENT")return"";throw f}),l="<!-- shaper:project -->",c=`
12
- ${l}
13
- Read docs/product.md for goals and rules, docs/design.md for experience and implementation decisions, and docs/validation.md for actual evidence when these files exist. Use the globally installed shaper-development skill for local development and shaper-release for web delivery. For Hupu login/share use hupu-business; for functions or databases use shaper-backend. Pass this project's absolute path to project tools. Read shaper.config.json for commands and query shaper_status for live identity. Web publishing belongs to Shaper; cloud functions are deployed separately.
14
- <!-- /shaper:project -->
15
- `,u=s.includes(l)?s.replace(/<!-- shaper:project -->[\s\S]*?<!-- \/shaper:project -->\n?/,c.trimStart()):s+c;u!==s&&await A(i,u)}async function L(t,e){await new Promise((n,r)=>{let o=It(t,{cwd:e,shell:!0,stdio:["ignore","pipe","pipe"]});o.stdout.on("data",i=>process.stderr.write(i)),o.stderr.on("data",i=>process.stderr.write(i)),o.once("error",r),o.once("exit",i=>i===0?n():r(new a("COMMAND_FAILED",`\u5DE5\u7A0B\u547D\u4EE4\u9000\u51FA\u7801\uFF1A${i??"signal"}`)))})}async function xt(t){let e=await y(t),n=await j(e);await L(n.buildCommand,e);let r=await z(e,n.outputDir);return await I(d(r,"index.html")),{root:e,output:r}}async function z(t,e){let n=await J(T(t,e)),r=F(t,n);if(r===".."||r.startsWith(`..${V}`)||T(t,r)!==n)throw new a("INVALID_OUTPUT","\u8F93\u51FA\u76EE\u5F55\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u5185\u90E8\u3002");return n}async function At(t,e={files:300,bytes:200*1024*1024}){let n=await J(t),r=new yt,o=0,i=0;async function s(l){for(let c of(await U(l,{withFileTypes:!0})).sort((u,f)=>u.name.localeCompare(f.name))){if(/^(\.git|\.shaper|node_modules|\.DS_Store)$/.test(c.name))continue;if(/^(\.env(?:\..*)?|credentials\.json|.*\.(pem|key))$/i.test(c.name))throw new a("SECRET_FILE_IN_PACKAGE",`\u8F93\u51FA\u76EE\u5F55\u5305\u542B\u654F\u611F\u914D\u7F6E\u6587\u4EF6\uFF1A${c.name}`);let u=d(l,c.name);if(c.isSymbolicLink())throw new a("SYMLINK_IN_PACKAGE",`\u4EA4\u4ED8\u5185\u5BB9\u4E2D\u4E0D\u5141\u8BB8\u7B26\u53F7\u94FE\u63A5\uFF1A${c.name}`);if(c.isDirectory()){await s(u);continue}if(!c.isFile())throw new a("INVALID_PACKAGE_FILE","\u4EA4\u4ED8\u76EE\u5F55\u5305\u542B\u975E\u5E38\u89C4\u6587\u4EF6\u3002");let f=await W(u);if(o+=f.size,i++,i>e.files||o>e.bytes)throw new a("PACKAGE_TOO_LARGE","\u4EA4\u4ED8\u5305\u8D85\u8FC7\u6587\u4EF6\u6570\u6216\u5927\u5C0F\u9650\u5236\u3002");r.addFile(F(n,u).split(V).join("/"),await I(u))}}await s(n);for(let l of r.getEntries())l.header.time=new Date(2e3,0,1);return{content:r.toBuffer(),files:i,bytes:o}}async function ee(t,e,n={}){let r=await y(e),o=await $(r,t.auth.server),i=n.build===!1?await z(r,(await j(r)).outputDir):(await xt(r)).output,s=await At(i),l=Q("sha256").update(s.content).digest("hex"),c=await D(r),u=d(c,"web-deploy.json"),f=q();try{let w=g.object({sha256:g.string(),key:g.string(),appId:g.string(),server:g.string()}).passthrough().parse(await N(u));w.sha256===l&&w.appId===o.appId&&w.server===t.auth.server&&(f=w.key)}catch(w){if(w.code!=="ENOENT")throw w}await v(u,{sha256:l,key:f,appId:o.appId,server:t.auth.server});let h=await t.request(`/api/v1/developer/projects/${encodeURIComponent(o.appId)}/web/deploy`,{method:"POST",file:s.content,key:f});return await v(u,{sha256:l,key:f,appId:o.appId,server:t.auth.server,response:h}),h}async function re(t,e,n,r,o){let i=await y(e),s=await $(i,t.auth.server),l=o?await I(await z(i,o)):void 0;if(l&&l.length>2*1024*1024)throw new a("INVALID_COVER","\u5C01\u9762\u4E0D\u80FD\u8D85\u8FC7 2 MiB\u3002");let c=l?{filename:gt(o),base64:l.toString("base64")}:void 0,u={versionId:n,description:r,...c?{cover:c}:{}},f=Q("sha256").update(JSON.stringify({appId:s.appId,body:u})).digest("hex"),h=await t.request(`/api/v1/developer/projects/${encodeURIComponent(s.appId)}/web/publish`,{method:"POST",body:u,key:f});if(h.result?.confirmationUrl){let w=new URL(h.result.confirmationUrl);if(w.origin!==t.auth.server||w.pathname!=="/applications/create")throw new a("INVALID_CONFIRMATION_URL","\u786E\u8BA4\u9875\u9762\u5730\u5740\u4E0D\u6B63\u786E");try{await Nt(w.href,{wait:!1})}catch{}}return{...h,submitted:!1,next:"\u5728\u6D4F\u89C8\u5668\u6838\u5BF9\u5E94\u7528\u4FE1\u606F\u5E76\u70B9\u51FB\u63D0\u4EA4\u5BA1\u6838\u3002\u901A\u8FC7\u5E94\u7528\u7248\u672C\u72B6\u6001\u67E5\u8BE2\u6700\u7EC8\u7ED3\u679C\u3002"}}async function ne(t){let e=await y(t),n=await j(e),r=[];try{await I(d(e,"package.json"))}catch{r.push("package.json \u4E0D\u5B58\u5728")}let o=T(e,n.outputDir),i=F(e,o);return(i===".."||i.startsWith(`..${V}`))&&r.push("outputDir \u8D85\u51FA\u5DE5\u7A0B\u76EE\u5F55"),{root:e,passed:r.length===0,findings:r,checks:["project configuration","package manifest","output path"],notRun:["application behavior","build","cloud connectivity"]}}import{createHash as jt,randomUUID as Tt}from"node:crypto";import{open as _t,mkdir as bt,readFile as Rt}from"node:fs/promises";import{join as _}from"node:path";import{spawn as Dt}from"node:child_process";import{z as x}from"zod";import Ot from"proper-lockfile";var Pt=x.object({id:x.string(),root:x.string(),controlUrl:x.string().url(),token:x.string(),url:x.string().url(),startedAt:x.string()}).strict();function G(t){return _(b(),"sessions",jt("sha256").update(t).digest("hex"))}async function tt(t){let e=Pt.parse(await N(_(G(t),"session.json")));if(e.root!==t||new URL(e.controlUrl).hostname!=="127.0.0.1")throw new a("INVALID_DEV_SESSION","\u672C\u5730\u5F00\u53D1\u4F1A\u8BDD\u8BB0\u5F55\u4E0D\u6B63\u786E\u3002");return e}async function H(t){let e=await y(t),n;try{n=await tt(e)}catch(r){if(r.code==="ENOENT")return{running:!1,root:e};throw r}try{let r=await fetch(`${n.controlUrl}/status`,{headers:{Authorization:`Bearer ${n.token}`},redirect:"error",signal:AbortSignal.timeout(1500)}),o=await r.json();if(!r.ok||o.id!==n.id)throw new Error("Session mismatch");return{root:e,running:o.running,ready:o.ready,url:n.url,sessionId:n.id}}catch{return{root:e,running:!1,url:n.url,sessionId:n.id}}}async function fe(t){let e=await y(t);await j(e);let n=G(e);await bt(n,{recursive:!0,mode:448});let r=await Ot.lock(n,{retries:0});try{let o=await H(e);if(o.running)return o;let i=await _t(_(n,"dev.log"),"w",384),s=Dt(process.execPath,[_(R,"dist","dev-runner.js"),e,Tt()],{cwd:e,detached:!0,stdio:["ignore",i.fd,i.fd],windowsHide:!0});await new Promise((l,c)=>{s.once("spawn",l),s.once("error",c)}),s.unref(),await i.close();for(let l=0;l<120;l++){await new Promise(u=>setTimeout(u,250));let c=await H(e);if(c.running&&c.ready)return c}throw new a("DEV_NOT_READY","\u5F00\u53D1\u670D\u52A1\u672A\u5728 30 \u79D2\u5185\u5C31\u7EEA\uFF0C\u8BF7\u67E5\u770B shaper logs\u3002\u8FD0\u884C\u72B6\u6001\u53EF\u901A\u8FC7 shaper status \u67E5\u8BE2\u3002")}finally{await r()}}async function we(t){let e=await y(t);if(!(await H(e)).running)return{stopped:!0,alreadyStopped:!0};let r=await tt(e);if(!(await fetch(`${r.controlUrl}/stop`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`},redirect:"error",signal:AbortSignal.timeout(1e4)})).ok)throw new a("DEV_STOP_FAILED","\u5F00\u53D1\u4F1A\u8BDD\u672A\u80FD\u505C\u6B62\u3002");for(let i=0;i<30;i++){await new Promise(s=>setTimeout(s,200));try{await fetch(`${r.controlUrl}/status`,{headers:{Authorization:`Bearer ${r.token}`},redirect:"error",signal:AbortSignal.timeout(500)})}catch{return{stopped:!0,sessionId:r.id}}}throw new a("DEV_STOP_PENDING","\u505C\u6B62\u8BF7\u6C42\u5DF2\u53D1\u9001\uFF0C\u4F46\u4F1A\u8BDD\u4ECD\u672A\u9000\u51FA\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002")}async function he(t){let e=await y(t);try{let n=await Rt(_(G(e),"dev.log"),"utf8");return{root:e,log:n.slice(-16e3)}}catch(n){if(n.code==="ENOENT")return{root:e,log:"",message:"\u5C1A\u65E0\u672C\u5730\u8FD0\u884C\u65E5\u5FD7"};throw n}}export{a,b,k as c,v as d,N as e,Ft as f,Vt as g,$t as h,R as i,y as j,j as k,$ as l,Zt as m,te as n,xt as o,At as p,ee as q,re as r,ne as s,G as t,H as u,fe as v,we as w,he as x};
@@ -1,17 +0,0 @@
1
- import{a,b as Y,c as A,d as ie,f as ae,h as C,i as O,j as S,k as ne,l as _,p as oe,u as ce}from"./shared-2ZNSJXPO.js";import*as w from"oauth4webapi";import{createHash as Ce}from"node:crypto";import{chmod as de,lstat as he,mkdir as $e,readFile as De,rm as Le,writeFile as xe}from"node:fs/promises";import{join as Z}from"node:path";import{execFile as Oe}from"node:child_process";import{promisify as Ue}from"node:util";import je from"proper-lockfile";import{z as T}from"zod";var pe=T.object({accessToken:T.string().min(1),refreshToken:T.string().min(1).optional(),expiresAt:T.number(),scope:T.string()}).strict(),Pe=T.object({schemaVersion:T.literal(1),server:T.string(),tokens:pe}).strict(),ue=Ue(Oe),U;async function le(n){await $e(n,{recursive:!0,mode:448});let e=await he(n);if(!e.isDirectory()||e.isSymbolicLink())throw new a("UNSAFE_AUTH_DIRECTORY","\u767B\u5F55\u76EE\u5F55\u5FC5\u987B\u662F\u5F53\u524D\u7528\u6237\u7684\u771F\u5B9E\u76EE\u5F55\u3002");if(process.platform==="win32"){if(!U){let{stdout:t}=await ue("whoami.exe",["/user","/fo","csv","/nh"],{windowsHide:!0});if(U=t.match(/S-1-\d+(?:-\d+)+/)?.[0],!U)throw new a("AUTH_DIRECTORY_UNAVAILABLE","\u65E0\u6CD5\u786E\u5B9A\u5F53\u524D Windows \u7528\u6237\u3002")}await ue("icacls.exe",[n,"/inheritance:r","/grant:r",`*${U}:(OI)(CI)F`,"/remove:g","*S-1-1-0","*S-1-5-11","*S-1-5-32-545"],{windowsHide:!0})}else{if(e.uid!==process.getuid?.())throw new a("UNSAFE_AUTH_DIRECTORY","\u767B\u5F55\u76EE\u5F55\u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237\u3002");await de(n,448)}}function we(n){return Ce("sha256").update(A(n)).digest("hex")}async function fe(n){await le(Y());let e=Z(Y(),n);return await le(e),e}var j=class{async path(e){return Z(await fe("credentials"),`${we(e)}.json`)}async read(e){let t=await this.path(e);try{let r=await he(t);if(!r.isFile()||r.isSymbolicLink())throw new a("UNSAFE_CREDENTIAL_FILE","\u767B\u5F55\u51ED\u8BC1\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\u3002");if(process.platform!=="win32"){if(r.uid!==process.getuid?.())throw new a("UNSAFE_CREDENTIAL_FILE","\u767B\u5F55\u51ED\u8BC1\u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237\u3002");await de(t,384)}let s=Pe.safeParse(JSON.parse(await De(t,"utf8")));if(!s.success||s.data.server!==A(e))throw new a("INVALID_CREDENTIAL_FILE","\u767B\u5F55\u51ED\u8BC1\u6587\u4EF6\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5\u7528\u6237\u914D\u7F6E\u76EE\u5F55\u3002");return s.data.tokens}catch(r){if(r.code==="ENOENT")return;throw r instanceof SyntaxError?new a("INVALID_CREDENTIAL_FILE","\u767B\u5F55\u51ED\u8BC1\u6587\u4EF6\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5\u7528\u6237\u914D\u7F6E\u76EE\u5F55\u3002"):r}}async write(e,t){await ie(await this.path(e),{schemaVersion:1,server:A(e),tokens:pe.parse(t)})}async remove(e){await Le(await this.path(e),{force:!0})}};async function me(n,e,t){let r=Z(await fe("locks"),`${we(n)}-${e}`);await xe(r,"",{flag:"a",mode:384});try{return await je.lock(r,{stale:12e4,retries:{retries:t,minTimeout:100,maxTimeout:1e3}})}catch(s){throw e==="login"&&s.code==="ELOCKED"?new a("AUTH_ALREADY_PENDING","\u5176\u4ED6\u7EC8\u7AEF\u6216 Agent \u6B63\u5728\u8FDE\u63A5 Shaper\uFF0C\u8BF7\u5148\u5B8C\u6210\u8BE5\u7F51\u9875\u6388\u6743\u3002"):s}}async function P(n,e){let t=await me(n,"tokens",30);try{return await e()}finally{await t()}}async function Q(n){return me(n,"login",0)}import{createServer as Fe}from"node:http";import{randomUUID as qe}from"node:crypto";import*as y from"oauth4webapi";import ze from"open";var I={client_id:"shaper-cli",token_endpoint_auth_method:"none"},F=class{constructor(e){this.release=e}id=qe();listener;timer;abort=new AbortController;state={flowId:this.id,status:"pending"};handling;released;status(){return{...this.state}}async finish(e){this.state.status==="pending"&&(this.state={flowId:this.id,status:e?"failed":"complete",...e?{message:e}:{}}),clearTimeout(this.timer),this.listener?.close(),this.released??=this.release(),await this.released}async close(){this.abort.abort(),this.handling&&await this.handling,await this.finish("\u6388\u6743\u5DF2\u53D6\u6D88\uFF0C\u8BF7\u91CD\u65B0\u53D1\u8D77\u3002")}async start(e){let{metadata:t}=e;if(!t.authorization_endpoint)throw new a("AUTH_UNAVAILABLE","\u670D\u52A1\u672A\u63D0\u4F9B\u7F51\u9875\u6388\u6743\u5165\u53E3\u3002");let r=y.generateRandomState(),s="";this.listener=Fe((l,p)=>{if(l.method!=="GET"||!l.url?.startsWith("/oauth/callback?")||this.handling||this.state.status!=="pending"){p.writeHead(404).end();return}let h;try{h=y.validateAuthResponse(t,I,new URL(l.url,s),r)}catch{let f=new URL(l.url,s).searchParams;f.get("state")===r&&f.has("error")&&this.finish("\u7F51\u9875\u6388\u6743\u5DF2\u53D6\u6D88\u3002"),p.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}).end("\u6388\u6743\u672A\u5B8C\u6210\u3002");return}this.handling=(async()=>{try{let f=await y.authorizationCodeGrantRequest(t,I,y.None(),h,s,e.verifier,{[y.allowInsecureRequests]:e.server.startsWith("http://"),signal:AbortSignal.any([this.abort.signal,AbortSignal.timeout(2e4)]),additionalParameters:{resource:`${e.server}/api/v1/developer`}}),v=await y.processAuthorizationCodeResponse(t,I,f);this.abort.signal.throwIfAborted(),await e.save(v),await this.finish(),p.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'"}).end('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>Shaper \u5DF2\u8FDE\u63A5</title><h1>\u5F00\u53D1\u5DE5\u5177\u5DF2\u8FDE\u63A5</h1><p>\u53EF\u4EE5\u5173\u95ED\u6B64\u9875\u9762\uFF0C\u56DE\u5230 IDE \u6216\u7EC8\u7AEF\u7EE7\u7EED\u3002</p></html>')}catch{await this.finish("\u6388\u6743\u672A\u5B8C\u6210\uFF0C\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55\u3002"),p.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}).end("\u6388\u6743\u672A\u5B8C\u6210\u3002")}})()});let i=this.listener;await new Promise((l,p)=>{i.once("error",p),i.listen(0,"127.0.0.1",()=>{i.off("error",p),l()})});let u=i.address();if(!u||typeof u=="string")throw new a("CALLBACK_UNAVAILABLE","\u65E0\u6CD5\u542F\u52A8\u672C\u5730\u6388\u6743\u56DE\u8C03\u3002");s=`http://127.0.0.1:${u.port}/oauth/callback`;let o=new URL(t.authorization_endpoint),c={client_id:I.client_id,response_type:"code",redirect_uri:s,code_challenge:e.challenge,code_challenge_method:"S256",state:r,scope:e.scope,resource:`${e.server}/api/v1/developer`,prompt:"consent",...e.initialize?{shaper_init:"true"}:{},...e.applicationName?{shaper_name:e.applicationName}:{},...e.connection?{shaper_connection:e.connection}:{},...e.appId?{shaper_app:e.appId}:{}};for(let[l,p]of Object.entries(c))o.searchParams.set(l,p);if(this.timer=setTimeout(()=>{this.close()},3e5),this.timer.unref(),e.openBrowser!==!1)try{await ze(o.href,{wait:!1})}catch{}return{flowId:this.id,status:"pending",authorizationUrl:o.href,expiresIn:300}}};var X="openid offline_access projects:read projects:write web:deploy web:publish",He=`${X} cloud:read cloud:write`,Ve=(...n)=>[...new Set(n.flatMap(e=>e.split(" ")).filter(Boolean))].join(" "),q=class{constructor(e,t=new j){this.credentials=t;this.server=A(e)}flows=new Map;metadata;server;options(){return{[w.allowInsecureRequests]:this.server.startsWith("http://"),signal:AbortSignal.timeout(2e4)}}async discovery(){if(!this.metadata){let e=new URL(`${this.server}/api/oauth`),t=await w.processDiscoveryResponse(e,await w.discoveryRequest(e,this.options()));for(let r of["authorization_endpoint","token_endpoint","revocation_endpoint"]){let s=t[r];if(s&&new URL(s).origin!==this.server)throw new a("UNTRUSTED_AUTH_ENDPOINT","\u6388\u6743\u670D\u52A1\u8FD4\u56DE\u4E86\u5176\u4ED6\u6765\u6E90\u7684\u5730\u5740\u3002")}this.metadata=t}return this.metadata}async save(e,t){let r=e.refresh_token??t?.refreshToken;await this.credentials.write(this.server,{accessToken:e.access_token,expiresAt:Date.now()+(e.expires_in??900)*1e3,scope:e.scope??t?.scope??X,...r?{refreshToken:r}:{}})}async accessToken(){return P(this.server,async()=>{let e=await this.credentials.read(this.server);if(!e)throw new a("AUTH_REQUIRED","\u8BF7\u8FD0\u884C shaper login\uFF0C\u6216\u8C03\u7528 shaper_auth_start\u3002\u767B\u5F55\u7531\u672C\u673A\u6240\u6709\u9879\u76EE\u5171\u7528\u3002");if(e.expiresAt>Date.now()+6e4)return e.accessToken;if(!e.refreshToken)throw new a("AUTH_REQUIRED","\u6388\u6743\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002");let t=await this.discovery();try{let r=await w.refreshTokenGrantRequest(t,I,w.None(),e.refreshToken,{...this.options(),additionalParameters:{resource:`${this.server}/api/v1/developer`}}),s=await w.processRefreshTokenResponse(t,I,r);return await this.save(s,e),s.access_token}catch(r){throw r instanceof w.ResponseBodyError&&r.error==="invalid_grant"?new a("AUTH_REQUIRED","\u6388\u6743\u5DF2\u8FC7\u671F\u6216\u5DF2\u64A4\u9500\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002"):new a("AUTH_REFRESH_FAILED","\u6682\u65F6\u65E0\u6CD5\u7EED\u671F\u767B\u5F55\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u540E\u91CD\u8BD5\uFF1B\u539F\u767B\u5F55\u51ED\u8BC1\u5DF2\u4FDD\u7559\u3002")}})}async request(e,t){let r=await this.accessToken(),s=await fetch(`${this.server}/api/v1/developer/${e}`,{method:t===void 0?"GET":"POST",headers:{Authorization:`Bearer ${r}`,Accept:"application/json","Content-Type":"application/json"},...t===void 0?{}:{body:JSON.stringify(t)},redirect:"error",signal:AbortSignal.timeout(2e4)}),i=await s.json();if(!s.ok)throw new a(i.code??"AUTH_SERVICE_ERROR",i.message??"\u65E0\u6CD5\u8BFB\u53D6\u767B\u5F55\u72B6\u6001");return i}async identity(){return this.request("me")}async start(e={}){let t=[...this.flows.values()].find(i=>i.status().status==="pending");if(t)throw new a("AUTH_IN_PROGRESS","\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u6D4F\u89C8\u5668\u6388\u6743\uFF0C\u518D\u91CD\u8BD5\u521D\u59CB\u5316\u3002",{flowId:t.id});let r=await Q(this.server),s;try{let i;try{i=await this.identity()}catch(h){if(!(h instanceof a)||!["AUTH_REQUIRED","INVALID_TOKEN"].includes(h.code))throw h}let u=e.cloud?He:X,o=i&&u.split(" ").filter(h=>!["openid","offline_access"].includes(h)).every(h=>i.grant.scopes.includes(h));if(i&&o&&!e.reauthorize&&(!e.appId||i.grant.allApps||i.grant.appIds.includes(e.appId)))return await r(),{status:"complete",authenticated:!0,reused:!0,...i};let c=w.generateRandomCodeVerifier(),l=await w.calculatePKCECodeChallenge(c),p=i?await this.request("authorization",{codeChallenge:l}):void 0;for(let[h,f]of this.flows)f.status().status!=="pending"&&this.flows.delete(h);return s=new F(r),this.flows.set(s.id,s),await s.start({metadata:await this.discovery(),server:this.server,verifier:c,challenge:l,scope:Ve(u,p?.scopes.join(" ")??""),...e.initialize?{initialize:!0}:{},...e.applicationName?{applicationName:e.applicationName}:{},...p?{connection:p.connection}:{},...e.appId?{appId:e.appId}:{},...e.openBrowser===void 0?{}:{openBrowser:e.openBrowser},save:h=>P(this.server,()=>this.save(h))})}catch(i){throw s?await s.close():await r(),i}}status(e){let t=this.flows.get(e);if(!t)throw new a("AUTH_FLOW_NOT_FOUND","\u6388\u6743\u6D41\u7A0B\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5728\u53D1\u8D77\u6388\u6743\u7684 Agent \u6216\u7EC8\u7AEF\u4E2D\u67E5\u8BE2\u3002");return t.status()}async wait(e){for(;this.status(e).status==="pending";)await new Promise(r=>setTimeout(r,250));let t=this.status(e);if(t.status!=="complete")throw new a("AUTH_FAILED",t.message??"\u6388\u6743\u672A\u5B8C\u6210");return{authenticated:!0,...await this.identity()}}async logout(){let e=await Q(this.server);try{return await P(this.server,async()=>{let t=await this.credentials.read(this.server);if(t)try{let r=await w.revocationRequest(await this.discovery(),I,w.None(),t.refreshToken??t.accessToken,{...this.options(),additionalParameters:{token_type_hint:t.refreshToken?"refresh_token":"access_token"}});await w.processRevocationResponse(r)}catch{throw new a("REVOKE_FAILED","\u670D\u52A1\u7AEF\u64A4\u9500\u672A\u5B8C\u6210\uFF0C\u5DF2\u4FDD\u7559\u767B\u5F55\u51ED\u8BC1\uFF0C\u8BF7\u91CD\u8BD5\u6216\u5728\u7F51\u9875\u64A4\u9500\u6388\u6743\u3002")}await this.credentials.remove(this.server)}),{revoked:!0}}finally{await e()}}async close(){await Promise.all([...this.flows.values()].map(e=>e.close()))}};var z=class{constructor(e){this.auth=e}async request(e,t={}){if(!e.startsWith("/api/v1/developer/"))throw new a("INVALID_API_PATH","\u4E0D\u652F\u6301\u7684\u63A5\u53E3\u8DEF\u5F84");let r=new Headers({Accept:"application/json"});t.anonymous||r.set("Authorization",`Bearer ${await this.auth.accessToken()}`),t.key&&r.set("idempotency-key",t.key);let s;if(t.file){let o=new FormData;o.set("file",new Blob([new Uint8Array(t.file)],{type:"application/zip"}),"shaper.zip"),s=o}else t.body!==void 0&&(r.set("Content-Type","application/json"),s=JSON.stringify(t.body));let i;try{i=await fetch(`${this.auth.server}${e}`,{method:t.method??"GET",headers:r,...s?{body:s}:{},redirect:"error",signal:AbortSignal.timeout(18e4)})}catch{throw new a("NETWORK_ERROR","\u670D\u52A1\u8BF7\u6C42\u4E2D\u65AD\uFF0C\u7ED3\u679C\u5C1A\u672A\u786E\u8BA4\u3002\u8BF7\u8054\u7CFB\u5E73\u53F0\u6838\u67E5\uFF0C\u52FF\u91CD\u590D\u521B\u5EFA\u8D44\u6E90\u3002",t.key?{idempotencyKey:t.key}:void 0)}let u=await i.json();if(!i.ok)throw new a(u.code??"API_ERROR",u.message??`\u8BF7\u6C42\u5931\u8D25\uFF1A${i.status}`);return u}async me(){return this.auth.identity()}async projects(){return this.request("/api/v1/developer/projects")}async project(e){return this.request(`/api/v1/developer/projects/${encodeURIComponent(e)}`)}};import{createHash as Be}from"node:crypto";import{builtinModules as Je}from"node:module";import{readFile as N,writeFile as ee,mkdir as ye,lstat as M,realpath as H}from"node:fs/promises";import{resolve as R,join as m,relative as D,sep as B,dirname as ge,isAbsolute as Me}from"node:path";import{build as Ke}from"esbuild";import{z as d}from"zod";var ve=d.object({name:d.literal("@hupu/cloud-server"),version:d.string().regex(/^\d+\.\d+\.\d+$/)}).strict(),Se=d.object({method:d.enum(["GET","POST","PUT","PATCH","DELETE","HEAD"]),path:d.string().regex(/^\/(?:[a-zA-Z0-9_-]+\/?)*$/),access:d.enum(["public","user"]),handler:d.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,79}$/)}).strict(),We=d.object({version:d.literal(1),runtime:d.literal("nodejs20"),memoryMB:d.number().int().min(128).max(2048),timeoutSeconds:d.number().int().min(1).max(60),routes:d.array(Se).max(100),serverSdk:ve}).strict().superRefine((n,e)=>{let t=new Set,r=new Map;for(let s of n.routes){let i=`${s.method} ${s.path}`;(t.has(i)||s.path.startsWith("/__hupu")||r.has(s.path)&&r.get(s.path)!==s.access)&&e.addIssue({code:"custom",message:"\u8DEF\u7531\u91CD\u590D\u3001\u4F7F\u7528\u4FDD\u7559\u8DEF\u5F84\u6216\u540C\u4E00\u8DEF\u5F84\u7684\u9274\u6743\u8981\u6C42\u4E0D\u4E00\u81F4\u3002"}),t.add(i),r.set(s.path,s.access)}}),Ge=ve.extend({archive:d.string().regex(/^[a-z0-9.-]+\.tgz$/),sha256:d.string().regex(/^[a-f0-9]{64}$/),templateHashes:d.record(d.string(),d.string())}),J=n=>Be("sha256").update(n).digest("hex"),Ee=/(?:^|\/)(?:\.env(?:\.[^/]*)?|credentials\.json)$|\.(?:pem|key)$/i;function b(n,e){let t=D(n,e);if(Me(t)||t===".."||t.startsWith(`..${B}`))throw new a("INVALID_FUNCTION_PATH","\u4E91\u51FD\u6570\u6587\u4EF6\u5FC5\u987B\u4F4D\u4E8E\u5F00\u53D1\u8005\u5DE5\u7A0B\u5185\u3002")}async function $(n,e,t){let r=await H(e);if(b(n,r),Ee.test(r))throw new a("SECRET_FILE","\u4E0D\u80FD\u5C06\u51ED\u8BC1\u6587\u4EF6\u6253\u5165\u4E91\u51FD\u6570\u3002");let s=await M(r);if(!s.isFile()||s.size>t)throw new a("INVALID_FUNCTION_FILE","\u6587\u4EF6\u7C7B\u578B\u6216\u5927\u5C0F\u4E0D\u7B26\u5408\u8981\u6C42\u3002");return N(r,"utf8")}async function V(n,e){b(n,e);let t=n;for(let r of D(n,e).split(B).filter(Boolean)){t=m(t,r),await ye(t).catch(i=>{if(i.code!=="EEXIST")throw i});let s=await M(t);if(!s.isDirectory()||s.isSymbolicLink())throw new a("UNSAFE_FUNCTION_PATH","\u51FD\u6570\u76EE\u5F55\u4E0D\u80FD\u7ECF\u8FC7\u7B26\u53F7\u94FE\u63A5\u3002")}}async function Te(){let n=m(O,"vendor/cloud-server"),e=Ge.parse(JSON.parse(await N(m(n,"release.json"),"utf8"))),t=await N(m(n,e.archive));if(J(t)!==e.sha256)throw new a("SDK_ASSET_MISMATCH","Toolkit \u5185\u7F6E SDK \u53D1\u884C\u5305\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5 Toolkit\u3002");return{release:e,archive:t}}async function Ut(n,e="cloud/functions/api"){let t=await S(n);if(!/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(e))throw new a("INVALID_FUNCTION_PATH","\u8BF7\u4F7F\u7528\u5DE5\u7A0B\u5185\u7684\u76F8\u5BF9\u76EE\u5F55\uFF0C\u4F8B\u5982 functions/api\u3002");let{release:r,archive:s}=await Te(),i=new Map;for(let[c,l]of Object.entries(r.templateHashes)){if(!/^[a-zA-Z0-9_./-]+$/.test(c)||c.split("/").includes(".."))throw new a("SDK_ASSET_MISMATCH","\u6A21\u677F\u8DEF\u5F84\u4E0D\u6B63\u786E\u3002");let p=await N(m(O,"templates/cloud-service",c),"utf8");if(J(p)!==l)throw new a("SDK_ASSET_MISMATCH","\u6807\u51C6\u6A21\u677F\u4E0E SDK \u53D1\u884C\u8BB0\u5F55\u4E0D\u4E00\u81F4\u3002");i.set(c,p)}let u=e==="cloud/functions/api";if(u){let c=JSON.parse(i.get("cloud.json")),{routes:l,...p}=c;i.set("cloud.json",JSON.stringify(p,null,2)+`
2
- `),i.set("../../gateway/routes.json",JSON.stringify({version:1,routes:l},null,2)+`
3
- `);for(let[h,f]of[...i])h.startsWith("migrations/")&&(i.delete(h),i.set("../../database/"+h,f));for(let h of i.keys())if(h.startsWith("../")){let f=R(t,e,h);b(t,f);try{throw await M(f),new a("CLOUD_LAYOUT_EXISTS","\u6570\u636E\u5E93\u6216\u7F51\u5173\u58F0\u660E\u5DF2\u5B58\u5728\uFF0C\u8BF7\u6CBF\u7528\u73B0\u6709\u4E91\u5DE5\u7A0B\u3002")}catch(v){if(v.code!=="ENOENT")throw v}}}let o=R(t,e);await V(t,ge(o)),await ye(o).catch(c=>{throw c.code==="EEXIST"?new a("FUNCTION_EXISTS","\u76EE\u5F55\u5DF2\u5B58\u5728\uFF0C\u8BF7\u76F4\u63A5\u4FEE\u6539\u73B0\u6709\u6E90\u7801\u540E\u91CD\u65B0\u90E8\u7F72\uFF1B\u4E0D\u4F1A\u8986\u76D6\u3002"):c}),i.set("package.json",JSON.stringify({name:`hupu-function-${e.split("/").at(-1)}`,private:!0,version:"0.1.0",engines:{node:">=20"},dependencies:{[r.name]:`file:vendor/${r.archive}`},hupuCloud:{schemaVersion:1,entry:"handlers.cjs",manifest:"cloud.json",...u?{gateway:"../../gateway/routes.json"}:{}}},null,2)+`
4
- `),i.set(".gitignore",`node_modules/
5
- .env
6
- .env.*
7
- !vendor/*.tgz
8
- `),i.set("README.md",u?`# \u5E94\u7528\u540E\u7AEF
9
-
10
- \u6E90\u7801\u548C\u8FD0\u884C\u53C2\u6570\u5728\u6B64\u76EE\u5F55\uFF0C\u8DEF\u7531\u5728 ../../gateway/routes.json\uFF0C\u8FC1\u79FB\u5728 ../../database/migrations\u3002
11
-
12
- \u5728\u9879\u76EE\u6839\u76EE\u5F55\u6267\u884C shaper cloud enable\uFF0C\u67E5\u8BE2\u8FD4\u56DE operationId \u81F3 succeeded\uFF1B\u6309\u987A\u5E8F\u63D0\u4EA4\u6570\u636E\u5E93\u8FC1\u79FB\u5E76\u67E5\u8BE2\u5B8C\u6210\uFF0C\u518D\u6267\u884C shaper cloud deploy\u3002\u6784\u5EFA\u81EA\u52A8\u7EC4\u5408 manifest\uFF0C\u4E0D\u91CD\u590D\u7EF4\u62A4\u8DEF\u7531\u3002
13
-
14
- \u4F7F\u7528\u7B2C\u4E09\u65B9\u4F9D\u8D56\u65F6\u5728\u6B64\u76EE\u5F55 npm install \u5E76\u63D0\u4EA4 package-lock.json\u3002\u521D\u59CB\u5316\u4E0D\u4F1A\u5F00\u901A\u6216\u90E8\u7F72\u4E91\u8D44\u6E90\u3002
15
- `:await N(m(O,"templates/cloud-service/README.md"),"utf8"));for(let[c,l]of i)await V(t,ge(m(o,c))),await ee(m(o,c),l,{flag:"wx"});return await V(t,m(o,"vendor")),await ee(m(o,"vendor",r.archive),s,{flag:"wx"}),{directory:e,files:[...i.keys(),`vendor/${r.archive}`],serverSdk:{name:r.name,version:r.version},next:u?"\u4FEE\u6539 cloud/functions/api \u6E90\u7801\u4E0E\u8FD0\u884C\u914D\u7F6E\u3001cloud/gateway/routes.json \u8DEF\u7531\u3001cloud/database/migrations \u8FC1\u79FB\uFF1B\u786E\u8BA4\u8FC1\u79FB\u5B8C\u6210\u540E\u90E8\u7F72\u3002":"\u4FEE\u6539 handlers.cjs/cloud.json\uFF1B\u786E\u8BA4\u6570\u636E\u5E93\u8FC1\u79FB\u5B8C\u6210\u540E\u90E8\u7F72\u3002"}}async function Ie(n,e){let t=await S(n);if(!e)try{await M(m(t,"cloud/functions/api/package.json")),e="cloud/functions/api"}catch(g){if(g.code!=="ENOENT")throw g;e="functions/api"}let r=await H(R(t,e));b(t,r);let s=JSON.parse(await $(t,m(r,"package.json"),65536)),i=d.object({schemaVersion:d.literal(1),entry:d.string().regex(/\.(?:cjs|js|ts)$/),manifest:d.string(),gateway:d.string().optional()}).strict().parse(s.hupuCloud),u=JSON.parse(await $(t,R(r,i.manifest),65536)),o=u.routes;if(i.gateway){if(u.routes!==void 0)throw new a("DUPLICATE_ROUTES","\u8DEF\u7531\u53EA\u7EF4\u62A4\u5728 gateway \u58F0\u660E\u4E2D\uFF0C\u4E0D\u80FD\u540C\u65F6\u5199\u5165\u8FD0\u884C\u914D\u7F6E\u3002");o=d.object({version:d.literal(1),routes:d.array(Se).max(100)}).strict().parse(JSON.parse(await $(t,R(r,i.gateway),65536))).routes}let c=We.parse({...u,routes:o}),{release:l}=await Te();if(c.serverSdk.version!==l.version)throw new a("SERVER_SDK_UNSUPPORTED","\u6B64 Toolkit \u4E0D\u652F\u6301\u6307\u5B9A SDK \u7248\u672C\uFF0C\u8BF7\u540C\u6B65\u5347\u7EA7 Toolkit \u4E0E Cloud \u670D\u52A1\u3002");let p=s.dependencies?.[l.name];if(p===`file:vendor/${l.archive}`){let g=await H(m(r,"vendor",l.archive));if(b(t,g),J(await N(g))!==l.sha256)throw new a("SDK_ASSET_MISMATCH","\u9879\u76EE\u4E2D\u7684 SDK \u53D1\u884C\u5305\u4E0E\u5F53\u524D Toolkit \u4E0D\u4E00\u81F4\u3002")}else if(p!==l.version)throw new a("SDK_DEPENDENCY_REQUIRED","package.json \u5FC5\u987B\u4F7F\u7528\u6A21\u677F\u5185\u7F6E SDK \u5305\u6216\u7CBE\u786E\u7248\u672C\uFF0C\u4E0D\u80FD\u4F7F\u7528\u6D6E\u52A8\u7248\u672C\u3002");let h=R(r,i.entry);await $(t,h,8*1024*1024);let f=await Ke({absWorkingDir:t,entryPoints:[h],outfile:"app.cjs",write:!1,bundle:!0,platform:"node",format:"cjs",target:"node20",metafile:!0,sourcemap:!1,external:[l.name],logLevel:"silent",plugins:[{name:"hupu-source-policy",setup(g){g.onLoad({filter:/.*/},async E=>{let k=await H(E.path);if(Ee.test(k))throw new a("SECRET_FILE","\u6784\u5EFA\u56FE\u5305\u542B\u51ED\u8BC1\u6587\u4EF6\u3002");k.includes(`${B}node_modules${B}`)||b(t,k)}),g.onResolve({filter:/^@hupu\/cloud-server\//},()=>({errors:[{text:"\u53EA\u80FD\u4ECE @hupu/cloud-server \u516C\u5171\u5165\u53E3\u5BFC\u5165\u3002"}]}))}}]}),v=f.outputFiles[0].text,Ne=new Set(Je.flatMap(g=>[g,`node:${g}`]));for(let g of Object.values(f.metafile.outputs))for(let E of g.imports)if(E.external&&E.path!==l.name&&!Ne.has(E.path))throw new a("UNBUNDLED_DEPENDENCY",`\u4F9D\u8D56\u6CA1\u6709\u6253\u5305\uFF1A${E.path}`);if(Buffer.byteLength(v)>8*1024*1024||/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(v))throw new a("INVALID_ARTIFACT","\u5236\u54C1\u8FC7\u5927\u6216\u5305\u542B\u79C1\u94A5\u3002");let te=JSON.stringify(c,null,2)+`
16
- `,re=J(te+`
17
- `+v),x=m(t,".shaper/cloud-build",re);await V(t,x);for(let[g,E]of[["cloud.json",te],["app.cjs",v]]){let k=m(x,g);try{await ee(k,E,{flag:"wx"})}catch(se){if(se.code!=="EEXIST"||await $(t,k,8*1024*1024)!==E)throw se}}return{directory:D(t,r),manifestFile:D(t,m(x,"cloud.json")),bundleFile:D(t,m(x,"app.cjs")),sha256:re,bytes:Buffer.byteLength(v),serverSdk:c.serverSdk,routes:c.routes}}import{createHash as ke}from"node:crypto";import{resolve as Ye,relative as Ze,sep as Qe}from"node:path";import{readFile as Xe,realpath as et,stat as tt}from"node:fs/promises";var K=class{constructor(e){this.api=e}async status(e){return this.api.request(`${(await this.target(e)).url}/status`)}async operation(e,t){if(!/^op_[a-zA-Z0-9-]{1,64}$/.test(t))throw new a("INVALID_OPERATION_ID","\u9700\u8981\u6709\u6548\u7684\u4E91\u64CD\u4F5C\u7F16\u53F7\u3002");return this.api.request(`${(await this.target(e)).url}/operations/${t}`)}async enable(e){return this.api.request(`${(await this.target(e)).url}/enable`,{method:"POST",body:{}})}async deploy(e,t={},r){await this.target(e);let s=t.manifestFile!==void 0||t.bundleFile!==void 0;if(s&&(t.directory!==void 0||!t.manifestFile||!t.bundleFile))throw new a("INVALID_DEPLOY_INPUT","\u9009\u62E9\u6E90\u7801\u76EE\u5F55\uFF0C\u6216\u540C\u65F6\u63D0\u4F9B manifest \u548C bundle\u3002\u4E24\u79CD\u8F93\u5165\u4E0D\u80FD\u6DF7\u7528\u3002");let i=s?{manifestFile:t.manifestFile,bundleFile:t.bundleFile}:await Ie(e,t.directory),u=await this.upload(e,i.manifestFile,i.bundleFile,r);return{artifact:i,...u}}async routes(e){return this.api.request(`${(await this.target(e)).url}/routes`)}async migrate(e,t,r,s){if(!/^[0-9]{8,20}_[a-zA-Z0-9_-]+$/.test(t))throw new a("INVALID_MIGRATION","\u8FC1\u79FB\u7248\u672C\u683C\u5F0F\u4E3A\u65F6\u95F4\u6233_\u540D\u79F0\u3002");let{root:i,url:u}=await this.target(e),o=await this.source(i,r,6e4),c=s??ke("sha256").update(`${t}:${o}`).digest("hex");return this.api.request(`${u}/migrations`,{method:"POST",body:{version:t,dialect:"postgresql",sql:o,idempotencyKey:c}})}async source(e,t,r){let s=await et(Ye(e,t));if(this.checkContained(e,s),/(?:^|\/)(?:\.env(?:\..*)?|credentials\.json)$|\.(?:pem|key)$/i.test(s))throw new a("SECRET_FILE","\u4E0D\u80FD\u4E0A\u4F20\u51ED\u8BC1\u6587\u4EF6\u3002");if((await tt(s)).size>r)throw new a("ARTIFACT_TOO_LARGE","\u6587\u4EF6\u8D85\u8FC7\u5141\u8BB8\u5927\u5C0F\u3002");return Xe(s,"utf8")}async upload(e,t,r,s){let{root:i,url:u}=await this.target(e),o=JSON.parse(await this.source(i,t,65536));if(o.serverSdk!=null){let[p,h]=await Promise.all([this.status(e),this.api.request(`${u}/capabilities`)]),f=h.serverSdk;if(!f||f.name!==o.serverSdk.name||!f.versions.includes(o.serverSdk.version)||f.packaging!=="platform-external")throw new a("SERVER_SDK_UNSUPPORTED","\u5F53\u524D\u5E94\u7528\u4E0D\u652F\u6301\u6B64 SDK\uFF1B\u8BF7\u8054\u7CFB\u5E73\u53F0\u7BA1\u7406\u5458\u68C0\u67E5\u670D\u52A1\u914D\u7F6E\u6216\u5347\u7EA7 Toolkit\u3002");if(p.status!=="ready")throw new a("CLOUD_NOT_READY","\u8BF7\u5148\u5F00\u901A\u5E94\u7528\u4E91\u670D\u52A1\uFF0C\u5E76\u901A\u8FC7 cloud status \u786E\u8BA4\u8D44\u6E90 ready\u3002")}let c=await this.source(i,r,8*1024*1024),l=s??ke("sha256").update(JSON.stringify({manifest:o,bundle:c})).digest("hex");return this.api.request(`${u}/deployments`,{method:"POST",body:{manifest:o,bundle:c,idempotencyKey:l}})}async target(e){let t=await S(e),r=await _(t,this.api.auth.server),s=`/api/v1/developer/projects/${encodeURIComponent(r.appId)}/cloud-v2`;return{root:t,url:s}}checkContained(e,t){let r=Ze(e,t);if(r===".."||r.startsWith(`..${Qe}`))throw new a("INVALID_FILE_PATH","\u5236\u54C1\u6587\u4EF6\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u76EE\u5F55\u5185\u3002")}};import{createHash as rt,randomUUID as L}from"node:crypto";import{resolve as W,relative as Ae,sep as _e,dirname as st,basename as it}from"node:path";import{readFile as at,writeFile as nt,realpath as Re,stat as ot}from"node:fs/promises";var G=class{constructor(e){this.api=e}async base(e,t){let r=await S(e),s=await _(r,this.api.auth.server),i=`/api/v1/developer/projects/${encodeURIComponent(s.appId)}/cloud`;if(t&&!/^[a-z][a-z0-9-]{0,31}$/.test(t))throw new a("INVALID_ENVIRONMENT","\u73AF\u5883\u540D\u5FC5\u987B\u662F\u5C0F\u5199\u5B57\u6BCD\u5F00\u5934\uFF0C\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u8FDE\u5B57\u7B26\uFF0C\u6700\u591A 32 \u4F4D\u3002");return{root:r,url:t?`${i}/environments/${encodeURIComponent(t)}`:i}}async capabilities(e){return this.api.request(`${(await this.base(e)).url}/capabilities`)}async environments(e){return this.api.request(`${(await this.base(e)).url}/environments`)}async create(e,t,r=!1){let{url:s}=await this.base(e),i=rt("sha256").update(`environment:${s}:${t}:${r}`).digest("hex");return this.api.request(`${s}/environments`,{method:"POST",body:{name:t,postgres:r},key:i})}async status(e,t){return this.api.request((await this.base(e,t)).url)}async functions(e,t){return this.api.request(`${(await this.base(e,t)).url}/functions`)}async deployFunction(e,t,r,s,i){let{root:u,url:o}=await this.base(e,t),c=await S(W(u,s)),l=Ae(u,c);if(l===".."||l.startsWith(`..${_e}`))throw new a("INVALID_FUNCTION_PATH","\u51FD\u6570\u4EE3\u7801\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u76EE\u5F55\u5185\u3002");let p=await oe(c,{files:1e3,bytes:30*1024*1024});return this.api.request(`${o}/functions/${encodeURIComponent(r)}/deploy`,{method:"POST",file:p.content,key:i??L()})}async invoke(e,t,r,s,i){return this.api.request(`${(await this.base(e,t)).url}/functions/${encodeURIComponent(r)}/invoke`,{method:"POST",body:s,key:i??L()})}async logs(e,t,r){return this.api.request(`${(await this.base(e,t)).url}/functions/${encodeURIComponent(r)}/logs`)}async sql(e,t,r,s){return this.api.request(`${(await this.base(e,t)).url}/database/query`,{method:"POST",body:{sql:r},key:s??L()})}async listObjects(e,t,r="",s){let i=new URLSearchParams({prefix:r,...s?{cursor:s}:{}});return this.api.request(`${(await this.base(e,t)).url}/storage?${i}`)}async putObject(e,t,r,s,i){let{root:u,url:o}=await this.base(e,t),c=await Re(W(u,s));if(this.checkContained(u,c),/(?:^|\/)(?:\.env(?:\..*)?|credentials\.json)$|\.(?:pem|key)$/i.test(c))throw new a("SECRET_FILE","\u51ED\u8BC1\u6587\u4EF6\u4E0D\u80FD\u4F5C\u4E3A\u4E1A\u52A1\u5BF9\u8C61\u4E0A\u4F20\u3002");if((await ot(c)).size>10*1024*1024)throw new a("OBJECT_TOO_LARGE","\u5BF9\u8C61\u4E0D\u80FD\u8D85\u8FC7 10 MiB\u3002");return this.api.request(`${o}/storage/object?${new URLSearchParams({key:r})}`,{method:"POST",file:await at(c),key:i??L()})}async getObject(e,t,r,s){let{root:i,url:u}=await this.base(e,t),o=W(await Re(st(W(i,s))),it(s));this.checkContained(i,o);let c=await this.api.request(`${u}/storage/object?${new URLSearchParams({key:r})}`);return await nt(o,Buffer.from(c.base64,"base64"),{flag:"wx",mode:384}),{key:r,bytes:c.bytes,path:o}}async deleteObject(e,t,r,s){return this.api.request(`${(await this.base(e,t)).url}/storage/object?${new URLSearchParams({key:r})}`,{method:"DELETE",key:s??L()})}checkContained(e,t){let r=Ae(e,t);if(r===".."||r.startsWith(`..${_e}`))throw new a("INVALID_FILE_PATH","\u5BF9\u8C61\u6587\u4EF6\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u76EE\u5F55\u5185\u3002")}};var be=class n{constructor(e){this.auth=e;this.api=new z(e),this.cloud=new K(this.api),this.legacyCloud=new G(this.api)}api;cloud;legacyCloud;static async create(e){return new n(new q(e??await ae()))}async status(e){let t;try{t={authenticated:!0,...await this.api.me()}}catch(s){t={authenticated:!1,error:C(s)}}let r;if(e){let s=await S(e),i;try{let o=await _(s,this.auth.server);try{let c=await this.api.project(o.appId);i={...o,authorized:!0,name:c.name,versions:c.versions}}catch(c){i={...o,authorized:!1,error:C(c)}}}catch(o){i={linked:!1,error:C(o)}}let u;try{u=await ne(s)}catch(o){u={error:C(o)}}r={root:s,binding:i,config:u,dev:await ce(s)}}return{server:this.auth.server,identity:t,...r?{project:r}:{}}}};export{q as a,z as b,Ut as c,Ie as d,K as e,G as f,be as g};