dsh-design-studio 0.17.0 → 0.19.0

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/lib/core.js CHANGED
@@ -568,7 +568,7 @@ export function askOf(data) {
568
568
  /**
569
569
  * @param opts.alive (origin) → 这个预览服务器还开着吗(开的太多时旧的会被关掉;发现没了就重开)
570
570
  */
571
- export function createTracker({ open, drafts = null, skipPorts = () => new Set(), now = Date.now, log = () => {}, store = null, history = null, alive = () => true, autoOpen = () => true, beforeRestore = () => {} }) {
571
+ export function createTracker({ open, drafts = null, skipPorts = () => new Set(), now = Date.now, log = () => {}, store = null, history = null, alive = () => true, autoOpen = () => true, beforeRestore = () => {}, trust = () => '', watchTag = () => '' }) {
572
572
  const states = new Map() // sessionId → state
573
573
  const cwds = new Map() // sessionId → 最近一次工具的工作目录
574
574
  let saved = {}
@@ -1191,6 +1191,8 @@ export function createTracker({ open, drafts = null, skipPorts = () => new Set()
1191
1191
  view,
1192
1192
  origin,
1193
1193
  vrev: st.vrev,
1194
+ trust: file ? trust() : '', // 「哪些算别人做的」的指纹:所有会话共用,远程看的右侧栏按它作废留着的打包结果
1195
+ watch: file ? watchTag(target.root) : '', // 预览服务器有没有在监听这个目录(开始 / 停止监听就变):画布缩略图按它重新要(停了就得自己定时再要)
1194
1196
  focus: file ? path.basename(target.file) : target.path,
1195
1197
  hidden: st.hidden || 0, // 超过上限收起来的屏数
1196
1198
  maxScreens: MAX_SCREENS,
@@ -9,6 +9,8 @@
9
9
  * GET inspire 灵感(参考图、网址、我的风格)
10
10
  * POST inspire { op, … } addImage / addUrl / addStyle / addMarket / remove
11
11
  * GET inspimg ?id= 灵感里的图片
12
+ * GET/POST ghauth { op } 一键投稿:连 GitHub(设备授权)、断开
13
+ * POST submit { path } 一键投稿:把刚打好的分享包投上去(见 submit.js)
12
14
  */
13
15
 
14
16
  import crypto from 'node:crypto'
@@ -23,6 +25,7 @@ import { PERSONAL_CODES } from './policy.js'
23
25
  import { readZip, ZipError } from './zip.js'
24
26
  import { renderPack } from './render.js'
25
27
  import { preparePack, installPack, baseFor, slugOf, UseError } from './use.js'
28
+ import { createGitHub, GhError, packPrint } from './submit.js'
26
29
 
27
30
  const THUMB_DIR = path.join(os.homedir(), '.dsh', 'cache', 'dsh-design-studio', 'works', 'thumbs')
28
31
  const MAX_ZIP_BODY = 12 * 1024 * 1024 // base64 的 8MB zip
@@ -102,8 +105,10 @@ export function describeWork(w) {
102
105
  return { ...base, title: manifestTitle(dir) || product || w.title || path.basename(dir), kind, screens: screens.length, first: screens[0] || '', updated: Math.round(updated || w.updated || w.seen || 0), thumb: sig ? crypto.createHash('sha1').update(sig).digest('hex').slice(0, 10) : '' }
103
106
  }
104
107
 
105
- export function createLibraryRoutes({ admit, readBody, json, tracker, library, inspiration, studio, open, storeLoad, version = '', exported, log = () => {}, thumbDir = THUMB_DIR, downloads = path.join(os.homedir(), 'Downloads'), sessionCwd = async (id) => tracker.cwdOf(id), render = renderPack }) {
108
+ export function createLibraryRoutes({ admit, readBody, json, tracker, library, inspiration, studio, open, storeLoad, version = '', exported, log = () => {}, thumbDir = THUMB_DIR, downloads = path.join(os.homedir(), 'Downloads'), sessionCwd = async (id) => tracker.cwdOf(id), render = renderPack, github = createGitHub({ log }) }) {
106
109
  const lang = (body) => (body && body.lang === 'en' ? 'en' : 'zh')
110
+ // 这次运行里「分享到市场」打出来的包(一键投稿只投这些):zip 路径 → { ref, slug, title, license }
111
+ const shared = new Map()
107
112
 
108
113
  // 作品库里登记的、目录在哪(id → 记录):只认列得出来的,别让请求指到别的目录
109
114
  const byId = (id) => library.list().find((w) => idOf(w.dir) === id) || null
@@ -273,7 +278,8 @@ export function createLibraryRoutes({ admit, readBody, json, tracker, library, i
273
278
  const stem = slugOf(t.zh || t.en || path.basename(dir), 'design')
274
279
  let file = path.join(downloads, `${stem}.zip`)
275
280
  for (let i = 2; fs.existsSync(file) && i < 100; i++) file = path.join(downloads, `${stem}-${i}.zip`)
276
- fs.writeFileSync(file, zipOf(p), { flag: 'wx' })
281
+ const zip = zipOf(p)
282
+ fs.writeFileSync(file, zip, { flag: 'wx' })
277
283
  exported.add(file)
278
284
  if (!share) return json(res, 200, { ...out, path: file })
279
285
  // 作者这边记下:分享记号 + 这次填的名字介绍(下次分享预填、「我的作品」认得出已上架);从市场来的 from 留着
@@ -283,7 +289,10 @@ export function createLibraryRoutes({ admit, readBody, json, tracker, library, i
283
289
  const tmp = path.join(dir, `.design.json.${process.pid}.tmp`)
284
290
  fs.writeFileSync(tmp, JSON.stringify(mine, null, 2) + '\n')
285
291
  fs.renameSync(tmp, path.join(dir, 'design.json'))
286
- json(res, 200, { ...out, path: file, share: { ref: shareHash.slice(0, 12), slug: slugFor(t.en, t.zh, path.basename(dir)), title: t.zh || t.en || '' } })
292
+ const sh = { ref: shareHash.slice(0, 12), slug: slugFor(t.en, t.zh, path.basename(dir)), title: t.zh || t.en || '' }
293
+ // 一键投稿认这份:查过的内容指纹(重新打包也一样,投过的认得出)+ zip 本身的指纹(投之前被改过就不认)
294
+ shared.set(file, { ...sh, license, pack: packPrint(p.files), zipSha: crypto.createHash('sha256').update(zip).digest('hex') })
295
+ json(res, 200, { ...out, path: file, share: { ...sh, license } })
287
296
  } catch (e) {
288
297
  log(e)
289
298
  json(res, 500, { error: e.message })
@@ -356,5 +365,45 @@ export function createLibraryRoutes({ admit, readBody, json, tracker, library, i
356
365
  fs.createReadStream(file).on('error', () => res.end()).pipe(res)
357
366
  }
358
367
 
359
- return { works, workthumb, pack, usezip, inspire, inspimg }
368
+ // 一键投稿的错误:auth 要重新连 GitHub(不用 401,免得和 DSH 自己的登录混了)
369
+ const ghFail = (res, e) => {
370
+ if (!(e instanceof GhError)) { log(e); return json(res, 500, { error: 'device' }) }
371
+ json(res, e.code === 'auth' || e.code === 'who' ? 409 : e.code === 'busy' ? 429 : 502, { error: e.code, msg: String(e.message || '').slice(0, 200), status: e.status || 0 })
372
+ }
373
+
374
+ /** GET:连没连 GitHub、正在等输的码;POST { op: start | cancel | logout } */
375
+ async function ghauth(req, res) {
376
+ if (!admit(req, res)) return
377
+ if (req.method === 'GET') return json(res, 200, github.status())
378
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
379
+ let body
380
+ try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
381
+ try {
382
+ if (body.op === 'start') return json(res, 200, await github.start())
383
+ if (body.op === 'cancel') github.cancel()
384
+ else if (body.op === 'logout') github.logout()
385
+ else return json(res, 400, { error: 'bad op' })
386
+ json(res, 200, github.status())
387
+ } catch (e) { ghFail(res, e) }
388
+ }
389
+
390
+ /** POST { path }:把刚才「分享到市场」打好的包直接投上去 → { url }(投稿 issue) */
391
+ async function submit(req, res) {
392
+ if (!admit(req, res)) return
393
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
394
+ let body
395
+ try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
396
+ const file = String(body.path || '')
397
+ const s = shared.get(file)
398
+ let zip = null
399
+ try { zip = s ? fs.readFileSync(file) : null } catch { zip = null }
400
+ if (!s || !zip || crypto.createHash('sha256').update(zip).digest('hex') !== s.zipSha) return json(res, 404, { error: 'notShared' })
401
+ try {
402
+ const { zipSha, ...meta } = s
403
+ const r = await github.submit({ zip, ...meta, as: typeof body.login === 'string' ? body.login.slice(0, 39) : '' })
404
+ json(res, 200, { ok: true, ...r })
405
+ } catch (e) { ghFail(res, e) }
406
+ }
407
+
408
+ return { works, workthumb, pack, usezip, inspire, inspimg, ghauth, submit }
360
409
  }
@@ -0,0 +1,288 @@
1
+ /**
2
+ * 一键投稿到设计市场(不用离开 DSH、不用拖 zip、不用装 git):
3
+ *
4
+ * 1. 连 GitHub:设备授权——插件给一个码,用户在 github.com/login/device 输进去点同意。
5
+ * 拿到的令牌只要 public_repo(动自己的公开仓库、开 issue),存在这台电脑上(只有自己能读),
6
+ * 不发给页面、不进日志;「断开」就删掉。
7
+ * 2. 投稿:zip 放进投稿人自己的仓库——内容仓库的主人直接放内容仓库的一个分支,
8
+ * 别人(包括有写权限的协作者)先 fork 一份放进去;只放一个提交,地址按提交号钉死(之后改不了内容)。
9
+ * 机器人只认「仓库主人 = 投稿人」的地址,所以协作者也得走自己的 fork。
10
+ * 3. 用投稿人的身份开投稿 issue,格式和网页表单一样(四个确认在插件里勾过了)。
11
+ * 之后和网页表单投稿完全一样:机器人下载、检查、转 PR、贴审核卡。
12
+ */
13
+
14
+ import crypto from 'node:crypto'
15
+ import fs from 'node:fs'
16
+ import path from 'node:path'
17
+ import { LIBRARY_DIR } from '../works.js'
18
+
19
+ // OAuth 应用「DSH Design Studio」(OrderG-X 名下,开了设备授权)的 Client ID:公开的,不是密钥
20
+ export const GH_CLIENT_ID = process.env.DSH_DESIGN_GH_CLIENT_ID ?? 'Ov23li7T6UcUOBKYE7Tc'
21
+ export const GALLERY = 'OrderG-X/dsh-design-gallery'
22
+ export const AUTH_FILE = path.join(LIBRARY_DIR, 'github.json')
23
+ const API = 'https://api.github.com'
24
+ const SCOPE = 'public_repo'
25
+ const UA = 'dsh-design-studio'
26
+ export const ZIP_MAX = 8 * 1024 * 1024 // 和机器人收稿的上限一样
27
+
28
+ // 投稿表单「授权」「确认」两栏的原文(机器人按表单的格式读)
29
+ export const FORM_LIC = { 'CC0-1.0': 'CC0-1.0(谁都能随便用,不用署名 / anyone can use it, no credit needed)', 'CC-BY-4.0': 'CC-BY-4.0(别人用要署你的名 / others must credit you)' }
30
+ const FORM_AGREE = [
31
+ '这是我自己(或用设计台)做的原创设计,图片都是自己做的或 CC0 / 公有领域 / This is my original design; all images are mine or CC0 / public domain',
32
+ '品牌是虚构的,没有仿冒真实网站、应用或机构 / The brand is made up and does not imitate a real site, app or organization',
33
+ '里面没有真实的个人信息 / It contains no real personal data',
34
+ '同意按上面选的授权公开,并收进设计市场 / I agree to publish it under the license above in the design gallery',
35
+ ]
36
+
37
+ /** 出错的种类(页面按 code 出提示):auth 要重新连、net 连不上 GitHub、denied 用户点了拒绝、expired 码过期… */
38
+ export class GhError extends Error {
39
+ constructor(code, msg = '', status = 0) {
40
+ super(msg || code)
41
+ this.code = code
42
+ this.status = status
43
+ }
44
+ }
45
+
46
+ /** 投稿 issue 的正文:和网页表单交出来的一样(「### 标题」一段一段),机器人照常读;开头记着包的指纹(重试时认出投过了) */
47
+ export function issueBody({ zipUrl, slug = '', license = 'CC0-1.0', pack = '' }) {
48
+ return [
49
+ '<!-- 设计台一键投稿 / Submitted from the design studio -->',
50
+ ...(/^[0-9a-f]{64}$/.test(pack) ? [`<!-- dsh-pack: ${pack} -->`] : []),
51
+ '### 设计包 / Design pack',
52
+ '',
53
+ zipUrl,
54
+ '',
55
+ '### 短名 / Short name',
56
+ '',
57
+ /^[a-z0-9-]{3,40}$/.test(slug) ? slug : '_No response_',
58
+ '',
59
+ '### 授权 / License',
60
+ '',
61
+ FORM_LIC[license] || FORM_LIC['CC0-1.0'],
62
+ '',
63
+ '### 确认 / Confirm',
64
+ '',
65
+ ...FORM_AGREE.map((x) => `- [X] ${x}`),
66
+ '',
67
+ ].join('\n')
68
+ }
69
+
70
+ /** 包的内容指纹:文件路径 + 内容(不含 zip 里的时间),同一套内容重新打包也一样 */
71
+ export function packPrint(files) {
72
+ const h = crypto.createHash('sha256')
73
+ for (const f of [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))) {
74
+ const d = Buffer.from(f.data)
75
+ h.update(`${f.path}\0${d.length}\0`)
76
+ h.update(d)
77
+ }
78
+ return h.digest('hex')
79
+ }
80
+
81
+ export function createGitHub({ file = AUTH_FILE, clientId = GH_CLIENT_ID, fetcher = (...a) => globalThis.fetch(...a), wait = (ms) => new Promise((r) => setTimeout(r, ms)), now = () => Date.now(), log = () => {} } = {}) {
82
+ let flow = null // 正在等用户输码:{ code, uri, expiresAt, interval, error }
83
+ let busy = null // 正在投的(一次只投一个,连点不会开两个 issue)
84
+ let epoch = 0 // 每次「断开」加一:断开前发出去的换令牌、等输码,回来时作废,不能把授权又写回来
85
+ let gen = 0 // 每次开始连、取消、断开都加一:要码的请求回来时对不上就作废(不能在取消之后又冒出一个码)
86
+
87
+ function load() {
88
+ try {
89
+ const a = JSON.parse(fs.readFileSync(file, 'utf8'))
90
+ return a && typeof a.token === 'string' && a.token && typeof a.login === 'string' ? a : null
91
+ } catch { return null }
92
+ }
93
+ function save(a) {
94
+ fs.mkdirSync(path.dirname(file), { recursive: true })
95
+ const tmp = `${file}.${process.pid}.tmp`
96
+ fs.writeFileSync(tmp, JSON.stringify(a, null, 2) + '\n', { mode: 0o600 })
97
+ fs.renameSync(tmp, file)
98
+ try { fs.chmodSync(file, 0o600) } catch { /* Windows 不认,没关系 */ }
99
+ }
100
+ function clear() {
101
+ try { fs.rmSync(file, { force: true }) } catch { /* 删不掉下次再说 */ }
102
+ }
103
+
104
+ async function form(url, params) {
105
+ let r
106
+ try {
107
+ r = await fetcher(url, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': UA }, body: new URLSearchParams(params).toString(), signal: AbortSignal.timeout(20000) })
108
+ } catch (e) { throw new GhError('net', String((e && e.message) || e)) }
109
+ // GitHub 临时出毛病(限流、5xx):算连不上,授权留着,等会儿再试
110
+ if (r.status === 429 || r.status >= 500) throw new GhError('net', `HTTP ${r.status}`)
111
+ let j = null
112
+ try { j = await r.json() } catch { j = null }
113
+ if (!j || typeof j !== 'object') throw new GhError('net', `HTTP ${r.status}`)
114
+ return j
115
+ }
116
+
117
+ async function call(token, method, p, body) {
118
+ let r
119
+ try {
120
+ r = await fetcher(API + p, {
121
+ method,
122
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': UA, ...(body ? { 'Content-Type': 'application/json' } : {}) },
123
+ body: body ? JSON.stringify(body) : undefined,
124
+ signal: AbortSignal.timeout(90000),
125
+ })
126
+ } catch (e) { throw new GhError('net', String((e && e.message) || e)) }
127
+ let j = null
128
+ try { j = await r.json() } catch { j = null }
129
+ // 令牌被拒:只删这一个(请求途中用户可能已经断开又重新连上了,新令牌不能跟着删)
130
+ if (r.status === 401) {
131
+ const a = load()
132
+ if (a && a.token === token) clear()
133
+ throw new GhError('auth', 'token rejected', 401)
134
+ }
135
+ if (r.status < 200 || r.status >= 300) throw new GhError('api', String((j && j.message) || `HTTP ${r.status}`).slice(0, 200), r.status)
136
+ // 回包读不全(被截断、不是 JSON):当连不上,别把「没读到」当成「没有」接着往下走
137
+ if (!j || typeof j !== 'object') throw new GhError('net', `bad response ${r.status}`)
138
+ return j
139
+ }
140
+
141
+ const record = (j, who) => ({
142
+ token: j.access_token,
143
+ refresh: typeof j.refresh_token === 'string' ? j.refresh_token : '',
144
+ expiresAt: Number(j.expires_in) > 0 ? now() + Number(j.expires_in) * 1000 : 0,
145
+ refreshExpiresAt: Number(j.refresh_token_expires_in) > 0 ? now() + Number(j.refresh_token_expires_in) * 1000 : 0,
146
+ login: String(who.login),
147
+ id: Number(who.id) || 0,
148
+ })
149
+
150
+ /** 能用的令牌:快过期了先换新的;换不了就要重新连 */
151
+ async function token() {
152
+ const a = load()
153
+ if (!a) throw new GhError('auth')
154
+ if (!a.expiresAt || now() < a.expiresAt - 120000) return a.token
155
+ if (a.refresh && (!a.refreshExpiresAt || now() < a.refreshExpiresAt)) {
156
+ // 连不上 GitHub(form 抛 net):原样抛出去,授权留着,等会儿再试;GitHub 明说不行才要重新连
157
+ const at = epoch
158
+ const j = await form('https://github.com/login/oauth/access_token', { client_id: clientId, grant_type: 'refresh_token', refresh_token: a.refresh })
159
+ if (at !== epoch) throw new GhError('auth') // 等回包的时候用户断开了
160
+ if (typeof j.access_token === 'string' && j.access_token) {
161
+ save(record(j, a))
162
+ return j.access_token
163
+ }
164
+ // 没给令牌也没说为什么:当临时故障,授权留着
165
+ if (typeof j.error !== 'string' || !j.error) throw new GhError('net', 'refresh: no token')
166
+ }
167
+ clear()
168
+ throw new GhError('auth')
169
+ }
170
+
171
+ async function poll(f, deviceCode) {
172
+ const at = epoch
173
+ while (flow === f && at === epoch) {
174
+ await wait(f.interval * 1000)
175
+ if (flow !== f) return
176
+ if (now() > f.expiresAt) { f.error = 'expired'; return }
177
+ let j
178
+ try {
179
+ j = await form('https://github.com/login/oauth/access_token', { client_id: clientId, device_code: deviceCode, grant_type: 'urn:ietf:params:oauth:grant-type:device_code' })
180
+ } catch { continue } // 网络抖一下:接着等,码过期了自然停
181
+ if (flow !== f) return
182
+ if (j.error === 'authorization_pending') continue
183
+ if (j.error === 'slow_down') { f.interval = Math.max(f.interval + 5, Number(j.interval) || 0); continue }
184
+ if (j.error || typeof j.access_token !== 'string' || !j.access_token) { f.error = j.error === 'access_denied' ? 'denied' : j.error === 'expired_token' ? 'expired' : 'device'; return }
185
+ const who = await call(j.access_token, 'GET', '/user')
186
+ if (flow !== f || at !== epoch) return
187
+ save(record(j, who))
188
+ flow = null
189
+ return
190
+ }
191
+ }
192
+
193
+ /** 给页面看的状态:连上的账号、或者正在等输的码(令牌不出这个文件) */
194
+ function status() {
195
+ const a = load()
196
+ return { ready: !!clientId, login: a ? a.login : '', flow: flow ? { code: flow.code, uri: flow.uri, expiresAt: flow.expiresAt, error: flow.error } : null, busy: !!busy }
197
+ }
198
+
199
+ async function start() {
200
+ if (!clientId) throw new GhError('noApp')
201
+ flow = null
202
+ const my = ++gen
203
+ const j = await form('https://github.com/login/device/code', { client_id: clientId, scope: SCOPE })
204
+ if (my !== gen) return status() // 等码的时候点了取消、断开或者又点了一次连
205
+ if (typeof j.device_code !== 'string' || typeof j.user_code !== 'string') throw new GhError('device', String(j.error_description || j.error || ''))
206
+ const uri = /^https:\/\/github\.com\/login\/device\b/.test(String(j.verification_uri)) ? String(j.verification_uri) : 'https://github.com/login/device'
207
+ const f = { code: j.user_code.slice(0, 20), uri, expiresAt: now() + Math.min(Number(j.expires_in) || 900, 1800) * 1000, interval: Math.max(5, Number(j.interval) || 5), error: '' }
208
+ flow = f
209
+ poll(f, j.device_code).catch((e) => {
210
+ if (flow === f) f.error = e instanceof GhError ? e.code : 'device'
211
+ log(e)
212
+ })
213
+ return status()
214
+ }
215
+
216
+ function cancel() { gen++; flow = null }
217
+ function logout() {
218
+ epoch++
219
+ gen++
220
+ flow = null
221
+ clear()
222
+ }
223
+
224
+ async function submitOnce({ zip, title, ref, slug, license, pack: fp = '', as = '' }) {
225
+ if (!Buffer.isBuffer(zip) || !zip.length) throw new GhError('zip')
226
+ if (zip.length > ZIP_MAX) throw new GhError('big')
227
+ const tok = await token()
228
+ const me = await call(tok, 'GET', '/user')
229
+ const login = String(me.login || '')
230
+ if (!/^[A-Za-z0-9-]{1,39}$/.test(login)) throw new GhError('api', 'no login')
231
+ // 面板上显示的是另一个账号(别的窗口断开又连了别人):先不投,让用户看清楚用谁投再点
232
+ if (as && String(as).toLowerCase() !== login.toLowerCase()) throw new GhError('who', login)
233
+ // 同一个包投过、那条投稿还开着(上次 issue 建好了但回包丢了、用户又点了一次):直接给那条,不再开第二个。
234
+ // 指纹按包里的文件内容算(routes 打包时算好传进来),重新打包时间变了也认得出;没传就按 zip 本身
235
+ const pack = /^[0-9a-f]{64}$/.test(fp) ? fp : crypto.createHash('sha256').update(zip).digest('hex')
236
+ const mark = `<!-- dsh-pack: ${pack} -->`
237
+ let had = null
238
+ for (let page = 1; !had; page++) {
239
+ // 开着的超过一千条还没翻完:查不全就不投(宁可不投,也不重复开)
240
+ if (page > 10) throw new GhError('api', 'too many open issues to check for duplicates')
241
+ const mine = await call(tok, 'GET', `/repos/${GALLERY}/issues?creator=${encodeURIComponent(login)}&state=open&per_page=100&page=${page}`)
242
+ if (!Array.isArray(mine)) throw new GhError('net', 'issues: not a list')
243
+ had = mine.find((x) => x && !x.pull_request && typeof x.body === 'string' && x.body.includes(mark) && /^https:\/\/github\.com\//.test(String(x.html_url))) || null
244
+ if (mine.length < 100) break
245
+ }
246
+ if (had) return { url: had.html_url, number: had.number, login, fork: '', again: true }
247
+ // 放 zip 的仓库:内容仓库的主人放内容仓库,别人(协作者也一样)放自己的 fork——机器人只认「仓库主人 = 投稿人」
248
+ let target = GALLERY
249
+ if (login.toLowerCase() !== GALLERY.split('/')[0].toLowerCase()) {
250
+ const fk = await call(tok, 'POST', `/repos/${GALLERY}/forks`, { default_branch_only: true })
251
+ const owner = String((fk.owner && fk.owner.login) || '')
252
+ if (typeof fk.full_name !== 'string' || owner.toLowerCase() !== login.toLowerCase() || !/^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9._-]{1,100}$/.test(fk.full_name)) throw new GhError('fork', String(fk.full_name || ''))
253
+ target = fk.full_name
254
+ }
255
+ // fork 是后台慢慢建的:建好之前写不进去,隔几秒再试(最多一分多钟)
256
+ let blob
257
+ for (let i = 0; ; i++) {
258
+ try {
259
+ blob = await call(tok, 'POST', `/repos/${target}/git/blobs`, { content: zip.toString('base64'), encoding: 'base64' })
260
+ break
261
+ } catch (e) {
262
+ if (i >= 14 || !(e instanceof GhError) || !(e.status === 404 || e.status === 409)) throw e
263
+ await wait(5000)
264
+ }
265
+ }
266
+ const tree = await call(tok, 'POST', `/repos/${target}/git/trees`, { tree: [{ path: 'submission.zip', mode: '100644', type: 'blob', sha: blob.sha }] })
267
+ const commit = await call(tok, 'POST', `/repos/${target}/git/commits`, { message: `design submission ${ref}`, tree: tree.sha, parents: [] })
268
+ if (!/^[0-9a-f]{40}$/.test(String(commit.sha))) throw new GhError('api', 'no commit')
269
+ // 挂一个分支,免得提交被当成没人要的清理掉
270
+ await call(tok, 'POST', `/repos/${target}/git/refs`, { ref: `refs/heads/dsh-submit/${ref}-${now().toString(36)}`, sha: commit.sha })
271
+ const zipUrl = `https://github.com/${target}/raw/${commit.sha}/submission.zip`
272
+ const issue = await call(tok, 'POST', `/repos/${GALLERY}/issues`, {
273
+ title: `投稿 / Submission: ${String(title).replace(/\s+/g, ' ').trim().slice(0, 60)} · ${ref}`,
274
+ body: issueBody({ zipUrl, slug, license, pack }),
275
+ labels: ['submission'], // 外人开的会被 GitHub 悄悄去掉;机器人按标题认,回复时补上
276
+ })
277
+ if (!/^https:\/\/github\.com\//.test(String(issue.html_url))) throw new GhError('api', 'no issue')
278
+ return { url: issue.html_url, number: issue.number, login, fork: target !== GALLERY ? target : '' }
279
+ }
280
+
281
+ async function submit(opts) {
282
+ if (busy) throw new GhError('busy')
283
+ busy = submitOnce(opts)
284
+ try { return await busy } finally { busy = null }
285
+ }
286
+
287
+ return { status, start, cancel, logout, submit, token }
288
+ }