dsh-design-studio 1.5.0 → 2.0.1

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.
Files changed (195) hide show
  1. package/README.en.md +6 -5
  2. package/README.md +7 -6
  3. package/THIRD_PARTY_NOTICES.md +108 -0
  4. package/assets/art/README.md +102 -0
  5. package/assets/art/brand-mark.webp +0 -0
  6. package/assets/art/check-clean.webp +0 -0
  7. package/assets/art/coach-markup.webp +0 -0
  8. package/assets/art/drop-file.webp +0 -0
  9. package/assets/art/empty-components.webp +0 -0
  10. package/assets/art/empty-data.webp +0 -0
  11. package/assets/art/empty-error.webp +0 -0
  12. package/assets/art/empty-frames.webp +0 -0
  13. package/assets/art/empty-history.webp +0 -0
  14. package/assets/art/empty-market.webp +0 -0
  15. package/assets/art/empty-notes.webp +0 -0
  16. package/assets/art/empty-search.webp +0 -0
  17. package/assets/art/empty-tokens.webp +0 -0
  18. package/assets/art/empty-works.webp +0 -0
  19. package/assets/art/guide-icon.webp +0 -0
  20. package/assets/art/kind-app.webp +0 -0
  21. package/assets/art/kind-desktop.webp +0 -0
  22. package/assets/art/kind-diagram.webp +0 -0
  23. package/assets/art/kind-dshplugin.webp +0 -0
  24. package/assets/art/kind-email.webp +0 -0
  25. package/assets/art/kind-embedded.webp +0 -0
  26. package/assets/art/kind-framed.webp +0 -0
  27. package/assets/art/kind-miniprogram.webp +0 -0
  28. package/assets/art/kind-poster.webp +0 -0
  29. package/assets/art/kind-slides.webp +0 -0
  30. package/assets/art/kind-tablet.webp +0 -0
  31. package/assets/art/kind-web.webp +0 -0
  32. package/assets/art/placeholder-inspire-img.webp +0 -0
  33. package/assets/art/wait-creating.webp +0 -0
  34. package/assets/demo.gif +0 -0
  35. package/assets/hero-sm.jpg +0 -0
  36. package/assets/motion/ai-capsule.html +124 -0
  37. package/assets/motion/ai-glow-input.html +112 -0
  38. package/assets/motion/balance-odometer.html +112 -0
  39. package/assets/motion/bottom-sheet.html +149 -0
  40. package/assets/motion/brightness-pill.html +114 -0
  41. package/assets/motion/comet-ring.html +95 -0
  42. package/assets/motion/copy-morph.html +116 -0
  43. package/assets/motion/cube-grid.html +103 -0
  44. package/assets/motion/day-night.html +120 -0
  45. package/assets/motion/dial-knob.html +130 -0
  46. package/assets/motion/dock-magnify.html +118 -0
  47. package/assets/motion/download-ring.html +135 -0
  48. package/assets/motion/expand-card.html +137 -0
  49. package/assets/motion/flip-card.html +100 -0
  50. package/assets/motion/hold-pay.html +137 -0
  51. package/assets/motion/holo-card.html +130 -0
  52. package/assets/motion/keycap.html +92 -0
  53. package/assets/motion/like-jelly.html +88 -0
  54. package/assets/motion/liquid-progress.html +113 -0
  55. package/assets/motion/liquid-segment.html +127 -0
  56. package/assets/motion/live-capsule.html +144 -0
  57. package/assets/motion/marker-highlight.html +94 -0
  58. package/assets/motion/marquee-logos.html +110 -0
  59. package/assets/motion/otp-code.html +111 -0
  60. package/assets/motion/password-eye.html +136 -0
  61. package/assets/motion/ruler-slider.html +140 -0
  62. package/assets/motion/search-expand.html +81 -0
  63. package/assets/motion/send-fly.html +121 -0
  64. package/assets/motion/skeleton-shine.html +124 -0
  65. package/assets/motion/star-rate.html +98 -0
  66. package/assets/motion/success-check.html +114 -0
  67. package/assets/motion/suggest-chips.html +134 -0
  68. package/assets/motion/swipe-row.html +126 -0
  69. package/assets/motion/tabbar-bounce.html +92 -0
  70. package/assets/motion/tactile-controls.html +89 -0
  71. package/assets/motion/text-scramble.html +173 -0
  72. package/assets/motion/toast-stack.html +115 -0
  73. package/assets/motion/token-stream.html +106 -0
  74. package/assets/motion/voice-orb.html +144 -0
  75. package/assets/showcase/alley-noodles-1.webp +0 -0
  76. package/assets/showcase/alley-noodles-2.webp +0 -0
  77. package/assets/showcase/alley-noodles-3.webp +0 -0
  78. package/assets/showcase/autumn-sale-1.webp +0 -0
  79. package/assets/showcase/bold-folio-1.webp +0 -0
  80. package/assets/showcase/bold-folio-2.webp +0 -0
  81. package/assets/showcase/book-club-1.webp +0 -0
  82. package/assets/showcase/book-club-2.webp +0 -0
  83. package/assets/showcase/book-club-3.webp +0 -0
  84. package/assets/showcase/flower-order-1.webp +0 -0
  85. package/assets/showcase/little-painter-1.webp +0 -0
  86. package/assets/showcase/little-painter-2.webp +0 -0
  87. package/assets/showcase/moon-fair-1.webp +0 -0
  88. package/assets/showcase/nail-booking-1.webp +0 -0
  89. package/assets/showcase/nail-booking-2.webp +0 -0
  90. package/assets/showcase/nail-booking-3.webp +0 -0
  91. package/assets/showcase/night-run-1.webp +0 -0
  92. package/assets/showcase/paw-diary-1.webp +0 -0
  93. package/assets/showcase/paw-diary-2.webp +0 -0
  94. package/assets/showcase/paw-diary-3.webp +0 -0
  95. package/assets/showcase/pixel-planet-1.webp +0 -0
  96. package/assets/showcase/pixel-planet-2.webp +0 -0
  97. package/assets/showcase/pixel-planet-3.webp +0 -0
  98. package/assets/showcase/pocket-ledger-1.webp +0 -0
  99. package/assets/showcase/pocket-ledger-2.webp +0 -0
  100. package/assets/showcase/shiftloom-1.webp +0 -0
  101. package/assets/showcase/shiftloom-2.webp +0 -0
  102. package/assets/showcase/slow-breath-1.webp +0 -0
  103. package/assets/showcase/slow-breath-2.webp +0 -0
  104. package/assets/showcase/slow-breath-3.webp +0 -0
  105. package/assets/showcase/slow-trip-1.webp +0 -0
  106. package/assets/showcase/slow-trip-2.webp +0 -0
  107. package/assets/showcase/slow-trip-3.webp +0 -0
  108. package/assets/showcase/slow-weekly-1.webp +0 -0
  109. package/assets/showcase/stay-confirm-1.webp +0 -0
  110. package/assets/showcase/stove-recipes-1.webp +0 -0
  111. package/assets/showcase/stove-recipes-2.webp +0 -0
  112. package/assets/showcase/strobewatch-1.webp +0 -0
  113. package/assets/showcase/strobewatch-2.webp +0 -0
  114. package/assets/showcase/tapeworks-1.webp +0 -0
  115. package/assets/showcase/tapeworks-2.webp +0 -0
  116. package/assets/showcase/tea-brand-pitch-1.webp +0 -0
  117. package/assets/showcase/tea-brand-pitch-2.webp +0 -0
  118. package/assets/showcase/tea-brand-pitch-3.webp +0 -0
  119. package/assets/showcase/time-bookshop-1.webp +0 -0
  120. package/assets/showcase/time-bookshop-2.webp +0 -0
  121. package/assets/showcase/water-journey-1.webp +0 -0
  122. package/assets/showcase/water-journey-2.webp +0 -0
  123. package/assets/showcase/water-journey-3.webp +0 -0
  124. package/assets/showcase/weekend-go-1.webp +0 -0
  125. package/assets/showcase/weekend-go-2.webp +0 -0
  126. package/assets/showcase/weekend-go-3.webp +0 -0
  127. package/assets/showcase/winter-soup-1.webp +0 -0
  128. package/assets/showcase/year-review-1.webp +0 -0
  129. package/assets/showcase/year-review-2.webp +0 -0
  130. package/assets/showcase/year-review-3.webp +0 -0
  131. package/lib/browser.js +3 -1
  132. package/lib/bundle.js +8 -3
  133. package/lib/canvthumb.js +9 -6
  134. package/lib/client.js +7428 -2624
  135. package/lib/components.js +4 -2
  136. package/lib/core.js +762 -132
  137. package/lib/design-page-settings.js +48 -0
  138. package/lib/design-scope.js +36 -0
  139. package/lib/design-transactions.js +259 -0
  140. package/lib/drop-folder.js +25 -0
  141. package/lib/edits.js +125 -8
  142. package/lib/embedded/lvgl_shot.c +133 -0
  143. package/lib/embedded/qml_shot.py +66 -0
  144. package/lib/embedded-shot.js +400 -0
  145. package/lib/embedded-trust.js +76 -0
  146. package/lib/fonts.js +30 -21
  147. package/lib/frames.js +23 -23
  148. package/lib/gallery/css.js +9 -2
  149. package/lib/gallery/market-routes.js +23 -7
  150. package/lib/gallery/pack.js +25 -8
  151. package/lib/gallery/policy.js +6 -4
  152. package/lib/gallery/routes.js +255 -83
  153. package/lib/gallery/submit.js +285 -57
  154. package/lib/gallery/use.js +13 -4
  155. package/lib/handoff-embedded.js +1182 -0
  156. package/lib/handoff.js +212 -71
  157. package/lib/history.js +393 -43
  158. package/lib/htmlpack.js +34 -13
  159. package/lib/impl.js +3 -0
  160. package/lib/index.js +661 -136
  161. package/lib/inspire.js +73 -26
  162. package/lib/kinds.js +11 -2
  163. package/lib/look.js +45 -25
  164. package/lib/mock.js +41 -4
  165. package/lib/motion.js +90 -0
  166. package/lib/page-settings.js +103 -0
  167. package/lib/picker.js +348 -70
  168. package/lib/rules.js +85 -0
  169. package/lib/serve.js +154 -15
  170. package/lib/showcase.json +22 -0
  171. package/lib/styles.js +16 -7
  172. package/lib/system.js +19 -8
  173. package/lib/tool.js +2 -1
  174. package/lib/tweaks.js +146 -9
  175. package/lib/works.js +151 -19
  176. package/locale/auto/en.json +1 -1
  177. package/locale/auto/zh.json +1 -1
  178. package/locale/en.json +1 -1
  179. package/locale/offline/en.json +1 -1
  180. package/locale/offline/zh.json +2 -2
  181. package/locale/zh.json +1 -1
  182. package/package.json +3 -2
  183. package/skills/ui-design/SKILL.md +56 -46
  184. package/skills/ui-design/frames/dsh/frame.json +1 -1
  185. package/skills/ui-design/references/app.md +29 -2
  186. package/skills/ui-design/references/components.md +1 -1
  187. package/skills/ui-design/references/desktop.md +1 -1
  188. package/skills/ui-design/references/dshplugin.md +12 -12
  189. package/skills/ui-design/references/embedded.md +40 -0
  190. package/skills/ui-design/references/frames.md +20 -20
  191. package/skills/ui-design/references/miniprogram.md +2 -2
  192. package/skills/ui-design/references/mock.md +16 -0
  193. package/skills/ui-design/references/poster.md +2 -1
  194. package/skills/ui-design/references/tweaks.md +17 -0
  195. package/skills/ui-design/tokens.css +19 -5
@@ -15,6 +15,7 @@ import crypto from 'node:crypto'
15
15
  import fs from 'node:fs'
16
16
  import path from 'node:path'
17
17
  import { LIBRARY_DIR } from '../works.js'
18
+ import { readZip } from './zip.js'
18
19
 
19
20
  // OAuth 应用「DSH Design Studio」(OrderG-X 名下,开了设备授权)的 Client ID:公开的,不是密钥
20
21
  export const GH_CLIENT_ID = process.env.DSH_DESIGN_GH_CLIENT_ID ?? 'Ov23li7T6UcUOBKYE7Tc'
@@ -78,9 +79,63 @@ export function packPrint(files) {
78
79
  return h.digest('hex')
79
80
  }
80
81
 
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
+ const PACK_RE = /^[0-9a-f]{64}$/
83
+ const LOGIN_RE = /^[A-Za-z0-9-]{1,39}$/
84
+ const activeSubmissions = new Set()
85
+ const issueBase = `https://github.com/${GALLERY}/issues/`
86
+ const digest = value => crypto.createHash('sha256').update(value).digest('hex')
87
+
88
+ /** Private records, separate from both github.json and the designer's files. */
89
+ export function submissionFiles(dir) {
90
+ const fileOf = (key) => path.join(dir, digest(key) + '.json')
91
+ return {
92
+ read(key) {
93
+ try { return JSON.parse(fs.readFileSync(fileOf(key), 'utf8')) }
94
+ catch (e) { if (e.code === 'ENOENT') return null; throw e }
95
+ },
96
+ write(key, record) {
97
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
98
+ const file = fileOf(key), tmp = file + '.' + crypto.randomUUID() + '.tmp'
99
+ try {
100
+ fs.writeFileSync(tmp, JSON.stringify(record, null, 2) + '\n', { flag: 'wx', mode: 0o600 })
101
+ fs.renameSync(tmp, file)
102
+ } finally { fs.rmSync(tmp, { force: true }) }
103
+ },
104
+ }
105
+ }
106
+
107
+ export function issueNumber(value) {
108
+ const input = String(value ?? '').trim()
109
+ const raw = input.toLowerCase().startsWith(issueBase.toLowerCase())
110
+ ? input.slice(issueBase.length).split(/[?#]/, 1)[0].replace(/\/$/, '') : input
111
+ const n = /^[1-9][0-9]{0,14}$/.test(raw) ? Number(raw) : 0
112
+ return Number.isSafeInteger(n) ? n : 0
113
+ }
114
+
115
+ function receipt(issue) {
116
+ const number = issueNumber(issue?.number)
117
+ if (!number || issue?.pull_request || String(issue.html_url).toLowerCase() !== (issueBase + number).toLowerCase()) return null
118
+ const state = issue.state === 'closed' ? 'closed' : 'open'
119
+ const labels = Array.isArray(issue.labels) ? issue.labels.map(l => typeof l === 'string' ? l : l?.name) : []
120
+ return { number, url: issueBase + number, state: labels.includes('rejected') ? 'rejected' : state, login: issue.user?.login || '' }
121
+ }
122
+
123
+ const attach = /https:\/\/github\.com\/user-attachments\/(?:files|assets)\/[\w-]+\/[^\s)"'<>]+?\.zip\b/gi
124
+ const allowedAttachment = url => url.protocol === 'https:' && !url.username && !url.password && !url.port
125
+ && (url.hostname === 'github.com' || url.hostname.endsWith('.githubusercontent.com') || /^github-production-user-asset-[a-z0-9]+\.s3\.amazonaws\.com$/.test(url.hostname))
126
+ const packMarker = pack => `<!-- dsh-pack: ${pack} -->`
127
+ const hasMarker = (issue, pack) => String(issue?.body || '').split(/\r?\n/).includes(packMarker(pack))
128
+ const packTitle = (issue, ref) => ref && String(issue?.title || '').startsWith('投稿 / Submission:') && issue.title.endsWith(' · ' + ref)
129
+
130
+ function attachmentOf(issue) {
131
+ const field = /^### 设计包 \/ Design pack\s*\r?\n([\s\S]*?)(?=^### |$(?![\s\S]))/m.exec(String(issue?.body || ''))?.[1]
132
+ const urls = [...new Set(field?.match(attach) || [])]
133
+ return urls.length === 1 ? urls[0] : ''
134
+ }
135
+
136
+ export function createGitHub({ file = AUTH_FILE, records = submissionFiles(path.join(path.dirname(file), 'gallery-uploads')), clientId = GH_CLIENT_ID, fetcher = (...a) => globalThis.fetch(...a), wait = (ms) => new Promise((r) => setTimeout(r, ms)), now = () => Date.now(), log = () => {} } = {}) {
82
137
  let flow = null // 正在等用户输码:{ code, uri, expiresAt, interval, error }
83
- let busy = null // 正在投的(一次只投一个,连点不会开两个 issue)
138
+ const busyKey = path.resolve(file)
84
139
  let epoch = 0 // 每次「断开」加一:断开前发出去的换令牌、等输码,回来时作废,不能把授权又写回来
85
140
  let gen = 0 // 每次开始连、取消、断开都加一:要码的请求回来时对不上就作废(不能在取消之后又冒出一个码)
86
141
 
@@ -119,7 +174,7 @@ export function createGitHub({ file = AUTH_FILE, clientId = GH_CLIENT_ID, fetche
119
174
  try {
120
175
  r = await fetcher(API + p, {
121
176
  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' } : {}) },
177
+ headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': UA, ...(body ? { 'Content-Type': 'application/json' } : {}) },
123
178
  body: body ? JSON.stringify(body) : undefined,
124
179
  signal: AbortSignal.timeout(90000),
125
180
  })
@@ -127,11 +182,12 @@ export function createGitHub({ file = AUTH_FILE, clientId = GH_CLIENT_ID, fetche
127
182
  let j = null
128
183
  try { j = await r.json() } catch { j = null }
129
184
  // 令牌被拒:只删这一个(请求途中用户可能已经断开又重新连上了,新令牌不能跟着删)
130
- if (r.status === 401) {
185
+ if (token && r.status === 401) {
131
186
  const a = load()
132
187
  if (a && a.token === token) clear()
133
188
  throw new GhError('auth', 'token rejected', 401)
134
189
  }
190
+ if (r.status === 204) return null
135
191
  if (r.status < 200 || r.status >= 300) throw new GhError('api', String((j && j.message) || `HTTP ${r.status}`).slice(0, 200), r.status)
136
192
  // 回包读不全(被截断、不是 JSON):当连不上,别把「没读到」当成「没有」接着往下走
137
193
  if (!j || typeof j !== 'object') throw new GhError('net', `bad response ${r.status}`)
@@ -193,7 +249,7 @@ export function createGitHub({ file = AUTH_FILE, clientId = GH_CLIENT_ID, fetche
193
249
  /** 给页面看的状态:连上的账号、或者正在等输的码(令牌不出这个文件) */
194
250
  function status() {
195
251
  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 }
252
+ return { ready: !!clientId, login: a ? a.login : '', flow: flow ? { code: flow.code, uri: flow.uri, expiresAt: flow.expiresAt, error: flow.error } : null, busy: activeSubmissions.has(busyKey) }
197
253
  }
198
254
 
199
255
  async function start() {
@@ -221,68 +277,240 @@ export function createGitHub({ file = AUTH_FILE, clientId = GH_CLIENT_ID, fetche
221
277
  clear()
222
278
  }
223
279
 
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')
280
+ async function account(as) {
281
+ const at = epoch
227
282
  const tok = await token()
228
- const me = await call(tok, 'GET', '/user')
283
+ const api = (...args) => {
284
+ if (at !== epoch) throw new GhError('auth')
285
+ return call(tok, ...args)
286
+ }
287
+ const me = await api('GET', '/user')
229
288
  const login = String(me.login || '')
230
- if (!/^[A-Za-z0-9-]{1,39}$/.test(login)) throw new GhError('api', 'no login')
231
- // 面板上显示的是另一个账号(别的窗口断开又连了别人):先不投,让用户看清楚用谁投再点
289
+ if (at !== epoch) throw new GhError('auth')
290
+ if (!LOGIN_RE.test(login)) throw new GhError('api', 'no login')
232
291
  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}`)
292
+ return { api, login, id: Number(me.id) || 0 }
293
+ }
294
+
295
+ const uploadKey = (who, pack) => `${who.id || who.login.toLowerCase()}:${pack}`
296
+ const zipUrlOf = r => r?.sha ? `https://github.com/${r.target}/raw/${r.sha}/submission.zip` : ''
297
+ const showProgress = (r, login) => r ? {
298
+ stage: r.issue ? 'submitted' : ({ pending: 'publicationUnknown', public: 'uploaded', removed: 'withdrawn' })[r.branchState] || 'uploading',
299
+ login, issue: r.issue || null,
300
+ branch: r.branch || '', repo: r.target || '',
301
+ branchUrl: r.branch ? `https://github.com/${r.target}/tree/${r.branch}` : '',
302
+ zipUrl: r.branch && r.branchState !== 'removed' ? zipUrlOf(r) : '',
303
+ canWithdraw: !r.issue && (r.branchState === 'public' || r.branchState === 'pending'),
304
+ } : null
305
+
306
+ function progress(pack) {
307
+ const who = load()
308
+ return who && PACK_RE.test(pack) ? showProgress(records.read(uploadKey(who, pack)), who.login) : null
309
+ }
310
+
311
+ async function matchesAttachment(issue, pack) {
312
+ const start = attachmentOf(issue)
313
+ if (!start) return false
314
+ let url = new URL(start)
315
+ for (let i = 0; i < 5; i++) {
316
+ if (!allowedAttachment(url)) break
317
+ let reply
318
+ try { reply = await fetcher(url.href, { redirect: 'manual', signal: AbortSignal.timeout(30000), headers: { 'User-Agent': UA } }) }
319
+ catch { throw new GhError('net', 'could not download the submission attachment') }
320
+ if (reply.status >= 300 && reply.status < 400 && reply.headers.get('location')) {
321
+ url = new URL(reply.headers.get('location'), url)
322
+ continue
323
+ }
324
+ if (reply.status !== 200 || !reply.body) throw new GhError('api', 'could not download the submission attachment', reply.status)
325
+ if (Number(reply.headers.get('content-length')) > ZIP_MAX) { await reply.body.cancel?.(); return false }
326
+ const chunks = []
327
+ let size = 0
328
+ try {
329
+ for await (const chunk of reply.body) {
330
+ size += chunk.length
331
+ if (size > ZIP_MAX) return false
332
+ chunks.push(Buffer.from(chunk))
333
+ }
334
+ } catch { throw new GhError('net', 'could not read the submission attachment') }
335
+ try { return packPrint(readZip(Buffer.concat(chunks)).files) === pack }
336
+ catch { return false }
337
+ }
338
+ return false
339
+ }
340
+
341
+ async function getIssue(number) {
342
+ const found = await call(null, 'GET', `/repos/${GALLERY}/issues/${number}`)
343
+ if (receipt(found)?.number !== number) throw new GhError('issueMismatch')
344
+ return found
345
+ }
346
+
347
+ async function verify({ issue, pack, manualRef, ref, previous }) {
348
+ const number = issueNumber(issue)
349
+ if (!number) throw new GhError('issueNumber')
350
+ const found = await getIssue(number)
351
+ if (number === previous?.number || hasMarker(found, pack)
352
+ || ((packTitle(found, manualRef) || packTitle(found, ref)) && await matchesAttachment(found, pack))) return receipt(found)
353
+ throw new GhError('issueMismatch')
354
+ }
355
+
356
+ async function findIssue({ api, login }, { pack, manualRef }, known) {
357
+ if (known) {
358
+ const found = await api('GET', `/repos/${GALLERY}/issues/${known.number}`)
359
+ if (receipt(found)?.number !== known.number) throw new GhError('issueMismatch')
360
+ return receipt(found)
361
+ }
362
+ // The bot also closes issues, including submissions already merged.
363
+ for (let page = 1; page <= 10; page++) {
364
+ const mine = await api('GET', `/repos/${GALLERY}/issues?creator=${encodeURIComponent(login)}&state=all&per_page=100&page=${page}`)
242
365
  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
366
+ for (const issue of mine) {
367
+ const got = receipt(issue)
368
+ if (got && (hasMarker(issue, pack) || (packTitle(issue, manualRef) && await matchesAttachment(issue, pack)))) return got
369
+ }
370
+ if (mine.length < 100) return null
245
371
  }
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
372
+ throw new GhError('api', 'too many issues to check for duplicates')
373
+ }
374
+
375
+ async function branchExists(api, r) {
376
+ try {
377
+ const ref = await api('GET', `/repos/${r.target}/git/ref/heads/${r.branch}`)
378
+ if (ref?.object?.sha !== r.sha) throw new GhError('branchChanged')
379
+ return true
380
+ } catch (e) {
381
+ if (e.status === 404) return false
382
+ throw e
254
383
  }
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)
384
+ }
385
+
386
+ async function upload(api, login, opts, saved, save) {
387
+ const r = saved.branchState === 'removed' ? { target: saved.target } : { ...saved }
388
+ if (!r.target) {
389
+ r.target = GALLERY
390
+ if (login.toLowerCase() !== GALLERY.split('/')[0].toLowerCase()) {
391
+ const fk = await api('POST', `/repos/${GALLERY}/forks`, { default_branch_only: true })
392
+ const owner = String(fk.owner?.login || '')
393
+ if (typeof fk.full_name !== 'string' || owner.toLowerCase() !== login.toLowerCase()
394
+ || fk.full_name.split('/')[0].toLowerCase() !== login.toLowerCase()
395
+ || !/^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9._-]{1,100}$/.test(fk.full_name)) throw new GhError('fork', String(fk.full_name || ''))
396
+ r.target = fk.full_name
264
397
  }
398
+ save(r)
399
+ }
400
+ const git = `/repos/${r.target}/git`
401
+ if (!r.blob) {
402
+ for (let i = 0; ; i++) {
403
+ try {
404
+ const blob = await api('POST', git + '/blobs', { content: opts.zip.toString('base64'), encoding: 'base64' })
405
+ if (!/^[0-9a-f]{40}$/.test(String(blob.sha))) throw new GhError('api', 'no blob')
406
+ r.blob = blob.sha
407
+ save(r)
408
+ break
409
+ } catch (e) {
410
+ if (i >= 14 || (e.status !== 404 && e.status !== 409)) throw e
411
+ await wait(5000)
412
+ }
413
+ }
414
+ }
415
+ if (!r.tree) {
416
+ const tree = await api('POST', git + '/trees', { tree: [{ path: 'submission.zip', mode: '100644', type: 'blob', sha: r.blob }] })
417
+ if (!/^[0-9a-f]{40}$/.test(String(tree.sha))) throw new GhError('api', 'no tree')
418
+ r.tree = tree.sha
419
+ save(r)
420
+ }
421
+ if (!r.sha) {
422
+ const commit = await api('POST', git + '/commits', { message: `design submission ${opts.ref}`, tree: r.tree, parents: [] })
423
+ if (!/^[0-9a-f]{40}$/.test(String(commit.sha))) throw new GhError('api', 'no commit')
424
+ r.sha = commit.sha
425
+ save(r)
426
+ }
427
+ const hadBranch = !!r.branch
428
+ if (!hadBranch) {
429
+ const ref = /^[a-z0-9-]{1,40}$/.test(opts.ref) ? opts.ref : opts.pack.slice(0, 12)
430
+ r.branch = `dsh-submit/${ref}-${crypto.randomBytes(8).toString('hex')}`
431
+ r.branchState = 'pending'
432
+ save(r) // A lost create-ref response must leave enough information to check the exact ref.
433
+ }
434
+ if (!hadBranch || !await branchExists(api, r)) {
435
+ try { await api('POST', git + '/refs', { ref: 'refs/heads/' + r.branch, sha: r.sha }) }
436
+ catch (e) {
437
+ if (!await branchExists(api, r)) throw e
438
+ }
439
+ }
440
+ r.branchState = 'public'
441
+ save(r)
442
+ return r
443
+ }
444
+
445
+ async function submitOnce({ zip, title, ref, slug, license, pack: fp = '', manualRef, as = '' }) {
446
+ if (!Buffer.isBuffer(zip) || !zip.length) throw new GhError('zip')
447
+ if (zip.length > ZIP_MAX) throw new GhError('big')
448
+ const who = await account(as)
449
+ const { api, login } = who
450
+ const pack = PACK_RE.test(fp) ? fp : digest(zip)
451
+ const key = uploadKey(who, pack)
452
+ let r = records.read(key) || {}
453
+ const save = next => { records.write(key, next); r = { ...next } }
454
+ try {
455
+ let match = await findIssue(who, { pack, manualRef }, r.issue)
456
+ if (!match && r.issueAttempt) {
457
+ // Give an accepted POST with a lost response a chance to appear in the issue list.
458
+ await wait(2000)
459
+ match = await findIssue(who, { pack, manualRef })
460
+ }
461
+ let issue = match
462
+ if (!issue) {
463
+ await upload(api, login, { zip, ref, pack }, r, save)
464
+ save({ ...r, issueAttempt: true })
465
+ const created = await api('POST', `/repos/${GALLERY}/issues`, {
466
+ title: `投稿 / Submission: ${String(title).replace(/\s+/g, ' ').trim().slice(0, 60)} · ${ref}`,
467
+ body: issueBody({ zipUrl: zipUrlOf(r), slug, license, pack }),
468
+ labels: ['submission'],
469
+ })
470
+ issue = receipt(created)
471
+ if (!issue) throw new GhError('api', 'no issue')
472
+ }
473
+ issue = { ...issue, login: issue.login || login }
474
+ save({ ...r, issue, issueAttempt: false })
475
+ return { ...issue, fork: r.target && r.target !== GALLERY ? r.target : '', again: !!match, progress: showProgress(r, login) }
476
+ } catch (e) {
477
+ e.progress = showProgress(r, login)
478
+ throw e
479
+ }
480
+ }
481
+
482
+ async function withdrawOnce({ pack, manualRef, as = '' }) {
483
+ if (!PACK_RE.test(pack)) throw new GhError('zip')
484
+ const who = await account(as)
485
+ const { api, login } = who
486
+ const key = uploadKey(who, pack)
487
+ let r = records.read(key)
488
+ if (!r?.branch) throw new GhError('notUploaded')
489
+ try {
490
+ const issue = await findIssue(who, { pack, manualRef }, r.issue)
491
+ if (issue) {
492
+ r = { ...r, issue }
493
+ records.write(key, r)
494
+ throw new GhError('alreadySubmitted')
495
+ }
496
+ if (r.branchState !== 'removed' && await branchExists(api, r)) {
497
+ try { await api('DELETE', `/repos/${r.target}/git/refs/heads/${r.branch}`) }
498
+ catch (e) { if (await branchExists(api, r)) throw e }
499
+ }
500
+ r = { ...r, branchState: 'removed' }
501
+ records.write(key, r)
502
+ return showProgress(r, login)
503
+ } catch (e) {
504
+ e.progress = showProgress(r, login)
505
+ throw e
265
506
  }
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
507
  }
280
508
 
281
- async function submit(opts) {
282
- if (busy) throw new GhError('busy')
283
- busy = submitOnce(opts)
284
- try { return await busy } finally { busy = null }
509
+ async function run(op, opts) {
510
+ if (activeSubmissions.has(busyKey)) throw new GhError('busy')
511
+ activeSubmissions.add(busyKey)
512
+ try { return await op(opts) } finally { activeSubmissions.delete(busyKey) }
285
513
  }
286
514
 
287
- return { status, start, cancel, logout, submit, token }
515
+ return { status, start, cancel, logout, submit: opts => run(submitOnce, opts), withdraw: opts => run(withdrawOnce, opts), verify, progress, token }
288
516
  }
@@ -13,6 +13,8 @@ import os from 'node:os'
13
13
  import path from 'node:path'
14
14
  import { checkPack, normalizeHtml, message, cleanPath } from './policy.js'
15
15
  import { sha256 } from '../works.js'
16
+ import { portablePages, savePages } from '../page-settings.js'
17
+ import { sizeFits } from '../kinds.js'
16
18
 
17
19
  /** 文件夹名:去掉路径和系统不让用的字符,限长;空了用 fallback */
18
20
  export function slugOf(name, fallback = 'template') {
@@ -52,7 +54,7 @@ class UseError extends Error {
52
54
  * 包([{ path, data: Buffer }])→ 检查过的、要写的文件 + 清单;不过关抛 UseError(errors 里是每条问题)
53
55
  * 规范化只做「去掉 / 改掉」的事(注释、站外链接、表单地址),别的照原样
54
56
  */
55
- export function preparePack(files, { lang = 'zh' } = {}) {
57
+ export function preparePack(files, { lang = 'zh', localZip = true } = {}) {
56
58
  const fixed = files.map((f) => {
57
59
  if (/\.html$/i.test(f.path) && Buffer.isBuffer(f.data)) {
58
60
  const r = normalizeHtml(f.data.toString('utf8'), { file: f.path })
@@ -60,13 +62,15 @@ export function preparePack(files, { lang = 'zh' } = {}) {
60
62
  }
61
63
  return f
62
64
  })
63
- const r = checkPack(fixed, { mode: 'install' })
65
+ const r = checkPack(fixed, { mode: 'install', localZip })
64
66
  if (!r.ok) {
65
67
  const errors = r.errors.map((p) => ({ ...p, msg: message(p, lang) }))
66
68
  throw new UseError(errors.some((e) => e.code === 'noManifest') ? 'noManifest' : 'check', errors)
67
69
  }
68
70
  if (r.type !== 'template') throw new UseError('type')
69
- return { files: fixed, manifest: r.manifest, screens: r.screens, kind: r.kind, flags: r.flags.map((p) => ({ ...p, msg: message(p, lang) })) }
71
+ // 清单写的画幅这个类型收不下(旧的网页模板写了 160x80):不拦导入,当没写,导入后用页面写的画幅
72
+ const manifest = r.manifest.size !== undefined && !sizeFits(String(r.manifest.size), r.manifest.kind) ? (({ size, ...rest }) => rest)(r.manifest) : r.manifest
73
+ return { files: fixed, manifest, screens: r.screens, kind: r.kind, flags: r.flags.map((p) => ({ ...p, msg: message(p, lang) })) }
70
74
  }
71
75
 
72
76
  /**
@@ -100,9 +104,14 @@ export function installPack(prepared, { base, name, trust, from, library, now =
100
104
  const parent = fs.realpathSync(path.dirname(abs))
101
105
  if (parent !== realDest && !inside(parent)) throw new UseError('path')
102
106
  fs.writeFileSync(abs, f.data, { flag: 'wx' }) // 新目录里不该已经有:有就是包里重名,出错
103
- if (/\.html$/i.test(rel)) hashes[rel] = sha256(f.data)
107
+ // 屏:原样没改就加硬规矩预览;rules.md(2.0 项目规矩):原样没改就是模板作者写的,不当成用户的要求
108
+ if (/\.html$/i.test(rel) || /^rules\.md$/i.test(rel)) hashes[rel] = sha256(f.data)
104
109
  }
110
+ // 包里没带 rules.md:记一笔空的(以后用户自己写的都算用户的,不当成包里的)
111
+ if (!Object.keys(hashes).some((k) => /^rules\.md$/i.test(k))) hashes['rules.md'] = ''
105
112
  const m = { ...manifest, from: { ...from, at: new Date(now).toISOString() } }
113
+ if (trust === 'zip' && m.pageSettings) savePages(realDest, portablePages(m.pageSettings, screens))
114
+ delete m.pageSettings
106
115
  delete m.shareToken
107
116
  delete m.shareHash // 别人分享时的记号,不是你的
108
117
  fs.writeFileSync(path.join(realDest, 'design.json'), JSON.stringify(m, null, 2) + '\n', { flag: 'wx' })