dsh-design-studio 0.17.0 → 0.18.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/client.js CHANGED
@@ -854,7 +854,7 @@ window.__ModuleLoader__.load({
854
854
  exShare: '分享到设计市场',
855
855
  shTitle: '分享到设计市场',
856
856
  shGh: '投稿要有 GitHub 账号',
857
- shTip: '交上去的东西是公开的:别人能看、能拿去用。先查一遍,过了打成 zip,再到 GitHub 上交。',
857
+ shTip: '交上去的东西是公开的:别人能看、能拿去用。先查一遍,过了就能投。',
858
858
  shName: '名字',
859
859
  shDesc: '一句话介绍',
860
860
  shDescPh: '比如:街角茶饮店的三屏点单 App',
@@ -867,12 +867,39 @@ window.__ModuleLoader__.load({
867
867
  shChecking: '在查…',
868
868
  shOk: '查过了,打好了:{name}(在「下载」里)',
869
869
  shSteps: '还差三步:',
870
- shStep1: '点下面「打开投稿页」(先登录 GitHub)',
870
+ shStep1: '点「打开投稿页」(先登录 GitHub)',
871
871
  shStep2: '把这个 zip 拖进「设计包」那一栏',
872
872
  shStep3: '勾上四个确认,点「Submit new issue」',
873
873
  shOpen: '打开投稿页',
874
874
  shAfter: '几分钟后机器人会在那条 issue 里回复结果;上架后「我的作品」里这套会显示「已上架」。投稿记号:{ref}',
875
875
  shAgain: '改好了,再查一遍',
876
+ shGhWhy: '连一次 GitHub,以后点一下就能投:插件替你把 zip 放进你自己的 GitHub 仓库、开好投稿 issue。',
877
+ shGhConnect: '连上 GitHub',
878
+ shGhCode: '到 GitHub 输这个码:',
879
+ shGhCopy: '复制',
880
+ shGhOpen: '打开 GitHub 输码',
881
+ shGhCancel: '取消',
882
+ shGhWaiting: '输完点「Authorize」,这里会自动接着走。',
883
+ shGhAs: '用 GitHub 账号 {login} 投稿',
884
+ shGhLogout: '断开',
885
+ shGhErr_denied: '你在 GitHub 上点了拒绝。想投的话再连一次。',
886
+ shGhErr_expired: '码过期了,再连一次。',
887
+ shGhErr_net: '连不上 GitHub,等会儿再试,或者用网页表单交。',
888
+ shGhErr_noApp: '这个版本还不能一键投稿,用网页表单交。',
889
+ shGhErr_device: 'GitHub 没连上,再试一次,或者用网页表单交。',
890
+ shSubmit: '一键投稿',
891
+ shSubmittingShort: '在投…',
892
+ shSubmitting: '在投…第一次会在你的 GitHub 里建一个副本放 zip,要一两分钟。',
893
+ shSubmitted: '交上去了:机器人几分钟内会在投稿 issue 里回复检查结果。',
894
+ shSubmittedLink: '看投稿进度',
895
+ shManual: '不想连 GitHub?用网页表单交',
896
+ shSubErr_auth: 'GitHub 授权失效了,重新连一次。',
897
+ shSubErr_net: '连不上 GitHub,等会儿再试,或者用网页表单交。',
898
+ shSubErr_big: '包太大(超过 8MB),投不上去:删掉用不到的大图再查一遍。',
899
+ shSubErr_notShared: '找不到刚打好的包了,再点一次「检查并投稿」。',
900
+ shSubErr_busy: '正在投,稍等。',
901
+ shSubErr_who: '现在连着的 GitHub 账号换成了 {msg}(别的窗口里换的)。没投,确认用这个账号的话再点一次。',
902
+ shSubErr_api: 'GitHub 没接住({msg}):再试一次,或者用网页表单交。',
876
903
  wkShare: '分享到设计市场',
877
904
  wkListed: '已上架 · 去市场看',
878
905
  wkShared: '分享过 · 还没上架',
@@ -1692,7 +1719,7 @@ window.__ModuleLoader__.load({
1692
1719
  exShare: 'Share to the gallery',
1693
1720
  shTitle: 'Share to the gallery',
1694
1721
  shGh: 'You need a GitHub account to submit',
1695
- shTip: 'What you share is public: anyone can see and reuse it. It is checked first, saved as a zip, then you submit it on GitHub.',
1722
+ shTip: 'What you share is public: anyone can see and reuse it. It is checked first; once it passes you can submit it.',
1696
1723
  shName: 'Name',
1697
1724
  shDesc: 'One-line description',
1698
1725
  shDescPh: 'e.g. A three-screen ordering app for a corner tea shop',
@@ -1705,12 +1732,39 @@ window.__ModuleLoader__.load({
1705
1732
  shChecking: 'Checking…',
1706
1733
  shOk: 'Checked and saved: {name} (in Downloads)',
1707
1734
  shSteps: 'Three more steps:',
1708
- shStep1: 'Click “Open the submission page” below (sign in to GitHub first)',
1735
+ shStep1: 'Click “Open the submission page” (sign in to GitHub first)',
1709
1736
  shStep2: 'Drag this zip into the “Design pack” box',
1710
1737
  shStep3: 'Tick the four boxes and click “Submit new issue”',
1711
1738
  shOpen: 'Open the submission page',
1712
1739
  shAfter: 'A bot replies on that issue within minutes; once it is listed, My work shows “Listed”. Submission ref: {ref}',
1713
1740
  shAgain: 'Fixed, check again',
1741
+ shGhWhy: 'Connect GitHub once and submitting is one click: the plugin puts the zip in your own GitHub repository and opens the submission issue for you.',
1742
+ shGhConnect: 'Connect GitHub',
1743
+ shGhCode: 'Enter this code on GitHub:',
1744
+ shGhCopy: 'Copy',
1745
+ shGhOpen: 'Open GitHub to enter the code',
1746
+ shGhCancel: 'Cancel',
1747
+ shGhWaiting: 'After entering it, click “Authorize”; this continues by itself.',
1748
+ shGhAs: 'Submitting as GitHub user {login}',
1749
+ shGhLogout: 'Disconnect',
1750
+ shGhErr_denied: 'You declined on GitHub. Connect again if you want to submit.',
1751
+ shGhErr_expired: 'The code expired. Connect again.',
1752
+ shGhErr_net: 'Could not reach GitHub. Try again later, or use the web form.',
1753
+ shGhErr_noApp: 'One-click submission is not available in this version; use the web form.',
1754
+ shGhErr_device: 'Could not connect GitHub. Try again, or use the web form.',
1755
+ shSubmit: 'Submit',
1756
+ shSubmittingShort: 'Submitting…',
1757
+ shSubmitting: 'Submitting… The first time, a copy of the gallery is made in your GitHub to hold the zip; this takes a minute or two.',
1758
+ shSubmitted: 'Submitted: a bot replies on the submission issue with the check results within minutes.',
1759
+ shSubmittedLink: 'See progress',
1760
+ shManual: 'Rather not connect GitHub? Use the web form',
1761
+ shSubErr_auth: 'GitHub access expired. Connect again.',
1762
+ shSubErr_net: 'Could not reach GitHub. Try again later, or use the web form.',
1763
+ shSubErr_big: 'The pack is too big (over 8 MB): remove large images you do not use and check again.',
1764
+ shSubErr_notShared: 'The pack just made is gone; click “Check and submit” again.',
1765
+ shSubErr_busy: 'Already submitting, one moment.',
1766
+ shSubErr_who: 'The connected GitHub account changed to {msg} (in another window). Nothing was sent; click again to submit with this account.',
1767
+ shSubErr_api: 'GitHub did not accept it ({msg}): try again, or use the web form.',
1714
1768
  wkShare: 'Share to the gallery',
1715
1769
  wkListed: 'Listed · view in gallery',
1716
1770
  wkShared: 'Shared · not listed yet',
@@ -2645,6 +2699,9 @@ window.__ModuleLoader__.load({
2645
2699
  .ddp-share .steps{margin:10px 6px 0;line-height:1.6}
2646
2700
  .ddp-share .steps p{margin:0}
2647
2701
  .ddp-share .steps ol{margin:4px 0 6px;padding-left:20px}
2702
+ .ddp-share .steps.gh1{display:flex;flex-direction:column;gap:6px}
2703
+ .ddp-share .steps .code b{font:600 20px/1.3 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;letter-spacing:2px;color:var(--dsw-alias-label-primary);user-select:all}
2704
+ .ddp-share .steps .lk{padding:0}
2648
2705
  .ddp-share footer a.go{display:flex;flex:1;align-items:center;justify-content:center;height:30px;padding:0 10px;border-radius:8px;font:inherit;text-decoration:none}
2649
2706
  .ddp-share footer a.go:hover{opacity:.88}
2650
2707
  .ddp-pack .okbox{display:flex;flex-direction:column;align-items:flex-start;gap:6px;margin:10px 4px 0;padding:10px;border-radius:10px;background:color-mix(in srgb,#16a34a 11%,transparent);color:var(--dsw-alias-label-primary);line-height:1.5}
@@ -7603,34 +7660,132 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
7603
7660
  const [agree, setAgree] = useState({})
7604
7661
  const [res, setRes] = useState(null)
7605
7662
  const [busy, setBusy] = useState(false)
7663
+ const packSeq = useRef(0) // 每次查、每次换作品都加一:晚到的回包对不上就不认(不然 B 的面板会拿到 A 的包去投)
7664
+ const edited = useRef({}) // 用户自己改过的栏:预填回来不覆盖
7606
7665
  useEffect(() => {
7666
+ // 换了作品:上一套填的名字、介绍、授权和四个确认都不带过来,等这一套的预填
7667
+ packSeq.current++
7668
+ edited.current = {}
7669
+ setBusy(false)
7607
7670
  setRes(null)
7608
7671
  setInfo(null)
7672
+ setTitle('')
7673
+ setDesc('')
7674
+ setLic('CC0-1.0')
7675
+ setAgree({})
7609
7676
  if (!root) return undefined
7610
7677
  let on = true
7678
+ const my = packSeq.current
7611
7679
  post('pack', { session: sid, dir: root, info: true, lang: L }).then((d) => {
7612
- if (!on) return
7680
+ if (!on || packSeq.current !== my) return // 预填晚到、用户已经点了检查:不改正在查的表单
7613
7681
  setInfo(d)
7614
- setTitle(d.title && d.title !== baseName(root) ? d.title : brand || d.title || '')
7615
- setDesc(d.description || '')
7616
- setLic(d.license === 'CC-BY-4.0' ? 'CC-BY-4.0' : 'CC0-1.0')
7617
- }, (e) => { if (on) setInfo({ error: e.message }) })
7682
+ if (!edited.current.title) setTitle(d.title && d.title !== baseName(root) ? d.title : brand || d.title || '')
7683
+ if (!edited.current.desc) setDesc(d.description || '')
7684
+ if (!edited.current.lic) setLic(d.license === 'CC-BY-4.0' ? 'CC-BY-4.0' : 'CC0-1.0')
7685
+ }, (e) => { if (on && packSeq.current === my) setInfo({ error: e.message }) })
7618
7686
  return () => { on = false }
7619
7687
  }, [root])
7620
- const ready = !!root && !!title.trim() && !!desc.trim() && SHARE_AGREE.every(([k]) => agree[k])
7688
+ // 预填回来之前不能查(不然用的是没对上这一套的表单)
7689
+ const ready = !!root && !!info && !!title.trim() && !!desc.trim() && SHARE_AGREE.every(([k]) => agree[k])
7621
7690
  const go = async () => {
7691
+ const my = ++packSeq.current
7622
7692
  setBusy(true)
7623
7693
  setRes(null)
7624
- try { setRes(await post('pack', { session: sid, dir: root, share: true, title: title.trim(), description: desc.trim(), license: lic, agree, lang: L })) } catch (e) { setRes({ error: e.message }) } finally { setBusy(false) }
7694
+ setLost(false)
7695
+ let r
7696
+ try { r = await post('pack', { session: sid, dir: root, share: true, title: title.trim(), description: desc.trim(), license: lic, agree, lang: L }) } catch (e) { r = { error: e.message } }
7697
+ if (packSeq.current !== my) return
7698
+ setRes(r)
7699
+ setBusy(false)
7625
7700
  }
7626
7701
  const formUrl = (r) => {
7627
- const q = new URLSearchParams({ template: 'submit-design.yml', title: `投稿 / Submission: ${r.share.title || title.trim()} · ${r.share.ref}`, license: FORM_LIC[lic] })
7702
+ const q = new URLSearchParams({ template: 'submit-design.yml', title: `投稿 / Submission: ${r.share.title || title.trim()} · ${r.share.ref}`, license: FORM_LIC[r.share.license] || FORM_LIC[lic] })
7628
7703
  if (r.share.slug) q.set('slug', r.share.slug)
7629
7704
  return `${GALLERY_REPO}/issues/new?${q}`
7630
7705
  }
7631
7706
  const aiN = (res && res.aiPhotos) || 0
7632
7707
  const fixed = res && res.notes ? Object.entries(res.notes.reduce((m, n) => { m[n.code] = (m[n.code] || 0) + 1; return m }, {})).map(([k, n]) => t('pkNote_' + k, { n })).join(t('sep')) : ''
7633
7708
  const done = res && res.ok && res.share
7709
+ // 一键投稿:连 GitHub(设备授权,输个码)→ 插件替你放 zip、开投稿 issue;不想连的走网页表单
7710
+ const [gh, setGh] = useState(null)
7711
+ const [ghBusy, setGhBusy] = useState(false)
7712
+ const [sub, setSub] = useState(null) // { busy } / { url } / { error, msg }
7713
+ const [manual, setManual] = useState(false)
7714
+ const [lost, setLost] = useState(false) // 打好的包找不到了(插件重启过、zip 被删了):回到表单重新查
7715
+ const resNow = useRef(res) // 投稿回来时核对:还是投的那个包(中间换了作品、重新查过就不认这次的回包)
7716
+ resNow.current = res
7717
+ useEffect(() => { setSub(null); setManual(false) }, [res])
7718
+ const ghSeq = useRef(0) // 连、取消、断开、投稿发现授权失效都加一:之前发出去还没回来的查状态作废(不然断开后又显示连着)
7719
+ useEffect(() => {
7720
+ if (!done) return undefined
7721
+ let on = true
7722
+ const my = ghSeq.current
7723
+ getJson('ghauth').then((s) => { if (on && ghSeq.current === my) setGh(s) }, () => { if (on && ghSeq.current === my) setGh({ ready: false }) })
7724
+ return () => { on = false }
7725
+ }, [done])
7726
+ const waiting = !!(gh && gh.flow && !gh.flow.error && !gh.login)
7727
+ useEffect(() => {
7728
+ if (!waiting) return undefined
7729
+ let on = true
7730
+ const id = setInterval(() => {
7731
+ const my = ghSeq.current
7732
+ getJson('ghauth').then((s) => { if (on && ghSeq.current === my) setGh(s) }, () => {})
7733
+ }, 2500)
7734
+ return () => { on = false; clearInterval(id) }
7735
+ }, [waiting])
7736
+ const ghOp = async (op) => {
7737
+ const my = ++ghSeq.current
7738
+ setGhBusy(true)
7739
+ try {
7740
+ const s = await post('ghauth', { op })
7741
+ if (ghSeq.current === my) setGh(s)
7742
+ } catch (e) {
7743
+ if (ghSeq.current === my) setGh((g) => ({ ...(g || {}), ready: true, login: '', flow: { error: e.message } }))
7744
+ } finally { setGhBusy(false) }
7745
+ }
7746
+ const submit = async () => {
7747
+ const mine = res
7748
+ const still = () => resNow.current === mine
7749
+ setSub({ busy: true })
7750
+ try {
7751
+ const r = await fetch(API + 'submit', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: mine.path, login: (gh && gh.login) || '' }) })
7752
+ const d = await r.json().catch(() => ({}))
7753
+ if (!still()) return
7754
+ if (r.ok && d.url) setSub({ url: d.url })
7755
+ else if (d.error === 'notShared') { setLost(true); setRes(null) }
7756
+ else {
7757
+ setSub({ error: d.error || 'net', msg: d.msg || '' })
7758
+ if (d.error === 'auth') { ghSeq.current++; setGh((g) => ({ ...(g || {}), login: '', flow: null })) }
7759
+ // 别的窗口换了账号:面板换成现在连着的那个,用户看清楚再点
7760
+ if (d.error === 'who') { ghSeq.current++; setGh((g) => ({ ...(g || {}), login: d.msg || '', flow: null })) }
7761
+ }
7762
+ } catch { if (still()) setSub({ error: 'net' }) }
7763
+ }
7764
+ const ghErr = (code) => t(['denied', 'expired', 'net', 'noApp'].includes(code) ? 'shGhErr_' + code : 'shGhErr_device')
7765
+ const subErr = (s) => t(['auth', 'net', 'big', 'notShared', 'busy', 'who'].includes(s.error) ? 'shSubErr_' + s.error : 'shSubErr_api', { msg: s.msg || s.error })
7766
+ const canOne = !!(gh && gh.ready)
7767
+ const steps = h('div', { className: 'steps' },
7768
+ h('p', null, t('shSteps')),
7769
+ h('ol', null, h('li', null, t('shStep1')), h('li', null, t('shStep2')), h('li', null, t('shStep3'))),
7770
+ h('a', { className: 'lk', href: done ? formUrl(res) : '#', target: '_blank', rel: 'noopener noreferrer' }, t('shOpen')))
7771
+ const oneClick = !done || !canOne ? null : sub && sub.url
7772
+ ? h('div', { className: 'okbox' }, h('div', null, h(I.check), h('span', null, t('shSubmitted'))), h('a', { className: 'lk', href: sub.url, target: '_blank', rel: 'noopener noreferrer' }, t('shSubmittedLink')))
7773
+ : h('div', { className: 'steps gh1' },
7774
+ gh.login
7775
+ ? h('p', null, t('shGhAs', { login: gh.login }), ' ', h('button', { className: 'lk', disabled: !!(sub && sub.busy), onClick: () => ghOp('logout') }, t('shGhLogout')))
7776
+ : waiting
7777
+ ? [
7778
+ h('p', { key: 'c' }, t('shGhCode')),
7779
+ h('p', { key: 'v', className: 'code' }, h('b', null, gh.flow.code), ' ', h('button', { className: 'lk', onClick: () => { try { navigator.clipboard.writeText(gh.flow.code).catch(() => {}) } catch { /* 能选中自己复制 */ } } }, t('shGhCopy'))),
7780
+ h('p', { key: 'o' }, h('a', { className: 'lk', href: gh.flow.uri, target: '_blank', rel: 'noopener noreferrer' }, t('shGhOpen')), ' · ', h('button', { className: 'lk', onClick: () => ghOp('cancel') }, t('shGhCancel'))),
7781
+ h('p', { key: 'w', className: 'note' }, t('shGhWaiting')),
7782
+ ]
7783
+ : [
7784
+ h('p', { key: 'y' }, t('shGhWhy')),
7785
+ gh.flow && gh.flow.error ? h('p', { key: 'e', className: 'note' }, ghErr(gh.flow.error)) : null,
7786
+ ],
7787
+ sub && sub.busy ? h('p', { className: 'note' }, t('shSubmitting')) : null,
7788
+ sub && sub.error ? h('p', { className: 'note' }, subErr(sub)) : null)
7634
7789
  return h('div', { className: 'ddp-tokens ddp-pack ddp-share', onPointerDown: (e) => e.stopPropagation() },
7635
7790
  h('header', null, h(I.share), h('b', null, t('shTitle')), h('button', { className: 'ddp-btn', title: '×', onClick: onClose }, h(I.close))),
7636
7791
  h('p', { className: 'tip gh' }, h(I.info), h('span', null, t('shGh'))),
@@ -7640,25 +7795,27 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
7640
7795
  info && info.error ? h('div', { className: 'none' }, info.error === 'noScreens' ? t('pkNoDesign') : t('libFail', { msg: info.error })) : null,
7641
7796
  done ? null : [
7642
7797
  h('h4', { key: 'n' }, t('shName')),
7643
- h('input', { key: 'ni', className: 'who', value: title, maxLength: 24, 'aria-label': t('shName'), onChange: (e) => setTitle(e.target.value) }),
7798
+ h('input', { key: 'ni', className: 'who', value: title, maxLength: 24, disabled: busy, 'aria-label': t('shName'), onChange: (e) => { edited.current.title = true; setTitle(e.target.value) } }),
7644
7799
  h('h4', { key: 'd' }, t('shDesc')),
7645
- h('input', { key: 'di', className: 'who', value: desc, maxLength: 120, placeholder: t('shDescPh'), 'aria-label': t('shDesc'), onChange: (e) => setDesc(e.target.value) }),
7800
+ h('input', { key: 'di', className: 'who', value: desc, maxLength: 120, disabled: busy, placeholder: t('shDescPh'), 'aria-label': t('shDesc'), onChange: (e) => { edited.current.desc = true; setDesc(e.target.value) } }),
7646
7801
  h('h4', { key: 'l' }, t('pkLicense')),
7647
7802
  h('div', { key: 'li', className: 'lic' }, ...[['CC0-1.0', 'pkCC0'], ['CC-BY-4.0', 'pkBY']].map(([k, label]) => h('label', { key: k, className: lic === k ? 'on' : '' },
7648
- h('input', { type: 'radio', name: 'ddp-shlic', checked: lic === k, onChange: () => setLic(k) }), h('span', null, t(label))))),
7803
+ h('input', { type: 'radio', name: 'ddp-shlic', checked: lic === k, disabled: busy, onChange: () => { edited.current.lic = true; setLic(k) } }), h('span', null, t(label))))),
7649
7804
  lic === 'CC-BY-4.0' ? h('p', { key: 'by', className: 'note' }, t('shBYNote')) : null,
7650
7805
  h('div', { key: 'ag', className: 'agree' }, ...SHARE_AGREE.map(([k, label]) => h('label', { key: k },
7651
- h('input', { type: 'checkbox', checked: !!agree[k], onChange: (e) => setAgree((a) => ({ ...a, [k]: e.target.checked })) }), h('span', null, t(label))))),
7806
+ h('input', { type: 'checkbox', checked: !!agree[k], disabled: busy, onChange: (e) => setAgree((a) => ({ ...a, [k]: e.target.checked })) }), h('span', null, t(label))))),
7652
7807
  ],
7653
7808
  busy ? h('div', { className: 'none' }, t('shChecking')) : null,
7809
+ lost && !res && !busy ? h('p', { className: 'note' }, t('shSubErr_notShared')) : null,
7654
7810
  res && res.error ? h('div', { className: 'none' }, res.error === 'noScreens' ? t('pkNoDesign') : t('libFail', { msg: res.error })) : null,
7655
7811
  done ? h('div', { className: 'okbox' },
7656
7812
  h('div', null, h(I.check), h('span', null, t('shOk', { name: baseName(res.path) }))),
7657
7813
  h('button', { className: 'lk', onClick: () => post('reveal', { path: res.path }).catch(() => {}) }, t('pkReveal'))) : null,
7658
- done ? h('div', { className: 'steps' },
7659
- h('p', null, t('shSteps')),
7660
- h('ol', null, h('li', null, t('shStep1')), h('li', null, t('shStep2')), h('li', null, t('shStep3'))),
7661
- h('p', { className: 'note' }, t('shAfter', { ref: res.share.ref }))) : null,
7814
+ done && res.share.license ? h('p', { className: 'note' }, h('b', null, t('pkLicense')), ' ', t(res.share.license === 'CC-BY-4.0' ? 'pkBY' : 'pkCC0')) : null,
7815
+ oneClick,
7816
+ done && (!canOne || manual) && !(sub && sub.url) ? steps : null,
7817
+ done && canOne && !manual && !(sub && sub.url) ? h('button', { className: 'lk', onClick: () => setManual(true) }, t('shManual')) : null,
7818
+ done ? h('p', { className: 'note' }, t('shAfter', { ref: res.share.ref })) : null,
7662
7819
  res && res.ok === false ? h('div', { className: 'errs' },
7663
7820
  h('p', null, t('pkFail', { n: res.errors.length + (res.more || 0) })),
7664
7821
  h('ol', null, ...res.errors.slice(0, 30).map((e, i) => h('li', { key: i }, e.msg))),
@@ -7669,9 +7826,14 @@ ${Object.entries(CHIP_ICON).map(([k, d]) => `[data-composer-chip="${chipSrc(k)}"
7669
7826
  res.flags.length > 8 || res.flagsMore ? h('p', null, t('pkMore', { n: res.flags.length - 8 + (res.flagsMore || 0) })) : null) : null),
7670
7827
  h('footer', { className: 'row' },
7671
7828
  res && res.ok === false ? h('button', { onClick: () => onFix(res.errors) }, h('span', null, t('pkFix'))) : null,
7672
- done
7673
- ? h('a', { className: 'go', href: formUrl(res), target: '_blank', rel: 'noopener noreferrer' }, h('span', null, t('shOpen')))
7674
- : h('button', { className: 'go', disabled: busy || !ready, onClick: go }, h('span', null, t(res && res.ok === false ? 'shAgain' : 'shGo')))))
7829
+ !done
7830
+ ? h('button', { className: 'go', disabled: busy || !ready, onClick: go }, h('span', null, t(res && res.ok === false ? 'shAgain' : 'shGo')))
7831
+ : !gh ? null
7832
+ : !canOne ? h('a', { className: 'go', href: formUrl(res), target: '_blank', rel: 'noopener noreferrer' }, h('span', null, t('shOpen')))
7833
+ : sub && sub.url ? null
7834
+ : gh.login ? h('button', { className: 'go', disabled: !!(sub && sub.busy), onClick: submit }, h('span', null, t(sub && sub.busy ? 'shSubmittingShort' : 'shSubmit')))
7835
+ : waiting ? null
7836
+ : h('button', { className: 'go', disabled: ghBusy, onClick: () => ghOp('start') }, h('span', null, t('shGhConnect')))))
7675
7837
  }
7676
7838
 
7677
7839
  /** 拖进来的设计包没过检查:说清哪几条 */
@@ -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
+ }
package/lib/index.js CHANGED
@@ -1373,7 +1373,7 @@ export function apply(ctx) {
1373
1373
  const lib = createLibraryRoutes({ admit, readBody, json, tracker, library, inspiration, studio, open, storeLoad: fileStore.load, version: VERSION, exported, log, sessionCwd })
1374
1374
  const mk = createMarketRoutes({ admit, readBody, json, tracker, library, market, open, systemsDir: SYSTEMS_DIR, log, sessionCwd })
1375
1375
 
1376
- const routes = { works: lib.works, workthumb: lib.workthumb, pack: lib.pack, usezip: lib.usezip, inspire: lib.inspire, inspimg: lib.inspimg, ...mk, state, open: openRoute, view: viewRoute, close: closeRoute, history: historyRoute, restore: restoreRoute, edit: editRoute, style: styleRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, systems: systemsRoute, systhumb: systhumbRoute, project: projectRoute }
1376
+ const routes = { works: lib.works, workthumb: lib.workthumb, pack: lib.pack, usezip: lib.usezip, ghauth: lib.ghauth, submit: lib.submit, inspire: lib.inspire, inspimg: lib.inspimg, ...mk, state, open: openRoute, view: viewRoute, close: closeRoute, history: historyRoute, restore: restoreRoute, edit: editRoute, style: styleRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, systems: systemsRoute, systhumb: systhumbRoute, project: projectRoute }
1377
1377
  for (const [key, handler] of Object.entries(routes)) {
1378
1378
  ctx.effect(() => ctx.webServer.register({
1379
1379
  kind: 'exact',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-design-studio",
3
- "version": "0.17.0",
3
+ "version": "0.18.0",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "node --test --test-concurrency=1 test/*.mjs"