@heycys/gallery 0.2.1 → 0.2.3
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/THIRD-PARTY-NOTICES.md +1 -1
- package/browser/editor/page/annotate/index.mjs +3 -2
- package/browser/editor/page/board/index.mjs +2 -1
- package/browser/editor/page/board/settings.mjs +2 -1
- package/browser/editor/page/core.mjs +3 -2
- package/browser/editor/page/custom-page.mjs +4 -3
- package/browser/editor/page/editor.mjs +13 -7
- package/browser/editor/page/emoji-picker/support.mjs +3 -2
- package/browser/editor/page/links/index.mjs +1 -12
- package/browser/editor/page/links/pages.mjs +3 -2
- package/browser/editor/page/outline/folds.mjs +3 -0
- package/browser/editor/page/post.mjs +2 -1
- package/browser/editor/page/present-links.mjs +4 -3
- package/browser/editor/page/present-shell.mjs +3 -58
- package/browser/editor/page/session.mjs +3 -37
- package/browser/editor/page/storage.mjs +5 -5
- package/browser/shared/component-catalog.mjs +2 -2
- package/browser/shared/drafts.mjs +26 -51
- package/browser/shared/emoji/icon-value.mjs +2 -1
- package/browser/shared/extension-manifest.mjs +90 -0
- package/browser/shared/extensions.mjs +26 -16
- package/browser/shared/http.mjs +1 -1
- package/browser/shared/i18n/en.mjs +46 -15
- package/browser/shared/media.mjs +2 -1
- package/browser/shared/outline.mjs +11 -51
- package/browser/shared/page-address.mjs +8 -15
- package/browser/shared/paths.mjs +2 -1
- package/browser/shared/preferences.mjs +3 -1
- package/browser/shared/preview-server.mjs +51 -63
- package/browser/shared/service-location.mjs +18 -0
- package/browser/shared/session.mjs +3 -6
- package/browser/shared/workspace-address.mjs +22 -0
- package/browser/shared/workspace-columns.mjs +1 -2
- package/browser/shared/workspace-registry.mjs +6 -40
- package/browser/shared/workspace.mjs +3 -6
- package/browser/shared/writing-preferences.mjs +6 -4
- package/dist/{chunk-5MEXZ2UF.mjs → chunk-225ALKYI.mjs} +1 -1
- package/dist/{chunk-7N2LPG33.mjs → chunk-2HS7ZBPU.mjs} +1 -1
- package/dist/chunk-3F57LEN5.mjs +2 -0
- package/dist/{chunk-MKTX5PGV.mjs → chunk-43B75J5T.mjs} +1 -1
- package/dist/{chunk-VKSRM7EY.mjs → chunk-4B2TB5K2.mjs} +1 -1
- package/dist/{chunk-LV24RY2E.mjs → chunk-4K5KC6V2.mjs} +1 -1
- package/dist/chunk-5GK7HS62.mjs +2 -0
- package/dist/chunk-6GV3CBB2.mjs +2 -0
- package/dist/{chunk-TOE6DPLH.mjs → chunk-6NLXUKAY.mjs} +1 -1
- package/dist/{chunk-ZCP7BTOZ.mjs → chunk-6QBHU4DF.mjs} +1 -1
- package/dist/{chunk-QXVNUASA.mjs → chunk-6QWQXHAV.mjs} +1 -1
- package/dist/chunk-6XD6U3QA.mjs +5 -0
- package/dist/{chunk-DKR7LFIY.mjs → chunk-6Y3HYOBM.mjs} +1 -1
- package/dist/{chunk-36FIRJIF.mjs → chunk-742D2WWJ.mjs} +2 -2
- package/dist/{chunk-7M7UPWU6.mjs → chunk-7EFHNQ5B.mjs} +1 -1
- package/dist/{chunk-2GKGEVMR.mjs → chunk-7UZUQQ7Q.mjs} +25 -24
- package/dist/{chunk-VPVOAJ7X.mjs → chunk-AGDILNWB.mjs} +1 -1
- package/dist/{chunk-5IIH335D.mjs → chunk-ALZ6ZENZ.mjs} +1 -1
- package/dist/{chunk-G4YP7GVC.mjs → chunk-BFJGHSQN.mjs} +1 -1
- package/dist/{chunk-AMDGVDNV.mjs → chunk-BQNTTFPL.mjs} +1 -1
- package/dist/chunk-BX5AKINW.mjs +15 -0
- package/dist/{chunk-PAFSFVYB.mjs → chunk-BYNPEUDS.mjs} +1 -1
- package/dist/{chunk-74RPP2M2.mjs → chunk-C564NU2H.mjs} +1 -1
- package/dist/{chunk-DH6GMDNN.mjs → chunk-CRDG6EF2.mjs} +1 -1
- package/dist/{chunk-7XDYK3UC.mjs → chunk-E7656LR7.mjs} +1 -1
- package/dist/{chunk-KFZBYDIS.mjs → chunk-ECZBLQKK.mjs} +1 -1
- package/dist/{chunk-ZEY2RLBT.mjs → chunk-ERLAIBOA.mjs} +2 -2
- package/dist/{chunk-YFJU3O7G.mjs → chunk-FJLM7YE7.mjs} +1 -1
- package/dist/{chunk-AFGUR7SY.mjs → chunk-FNCCVGKX.mjs} +1 -1
- package/dist/{chunk-VNUWREXU.mjs → chunk-FOJ3K5Z3.mjs} +1 -1
- package/dist/{chunk-WCWYNFDF.mjs → chunk-FQ72LZHB.mjs} +1 -1
- package/dist/chunk-G7N7YFVD.mjs +2 -0
- package/dist/chunk-GIRXJBGC.mjs +2 -0
- package/dist/{chunk-VA3KAQZD.mjs → chunk-GKOBB6DH.mjs} +1 -1
- package/dist/chunk-GMJD7ID3.mjs +2 -0
- package/dist/chunk-GQJMVSSN.mjs +2 -0
- package/dist/{chunk-QZ35UAB4.mjs → chunk-GRAXKKG4.mjs} +1 -1
- package/dist/{chunk-SAHS56QM.mjs → chunk-HX4DLE3J.mjs} +1 -1
- package/dist/{chunk-2RKIHJI2.mjs → chunk-HYMEEXKN.mjs} +1 -1
- package/dist/{chunk-QK3VISCA.mjs → chunk-IA4PSIMD.mjs} +1 -1
- package/dist/chunk-IS7N3N6Q.mjs +168 -0
- package/dist/{chunk-CZ5KJSGK.mjs → chunk-JJNHKGTD.mjs} +1 -1
- package/dist/chunk-JPG2LBQM.mjs +11 -0
- package/dist/chunk-JYK5WJPM.mjs +2 -0
- package/dist/{chunk-LE44MD3O.mjs → chunk-KLQP46Y3.mjs} +1 -1
- package/dist/chunk-L55NOXBE.mjs +4 -0
- package/dist/{chunk-FXQBADMN.mjs → chunk-LCB6MARS.mjs} +1 -1
- package/dist/{chunk-SOD23RGL.mjs → chunk-LJLVCU6W.mjs} +8 -8
- package/dist/{chunk-NAGMRVW4.mjs → chunk-LKX55H76.mjs} +1 -1
- package/dist/chunk-LMUZQK5O.mjs +2 -0
- package/dist/{chunk-CG3UHDKH.mjs → chunk-M4NRDYI5.mjs} +1 -1
- package/dist/{chunk-HM4E43VM.mjs → chunk-MAFIGVXY.mjs} +1 -1
- package/dist/chunk-NLDF35P5.mjs +2 -0
- package/dist/{chunk-3OFXMN6N.mjs → chunk-NMF3IPYA.mjs} +1 -1
- package/dist/chunk-ONKC4BCC.mjs +2 -0
- package/dist/{chunk-CPS4SRPF.mjs → chunk-OU6ZZVBX.mjs} +2 -2
- package/dist/{chunk-NWRZXELO.mjs → chunk-PAREWQGB.mjs} +1 -1
- package/dist/{chunk-BYSF5UMM.mjs → chunk-PKVK6WFC.mjs} +2 -2
- package/dist/{chunk-4AMTKWDO.mjs → chunk-PUOQ65NC.mjs} +1 -1
- package/dist/{chunk-L7W624FD.mjs → chunk-QJAVCTY7.mjs} +1 -1
- package/dist/{chunk-6MPKCH3P.mjs → chunk-QNECWMGR.mjs} +1 -1
- package/dist/{chunk-HBAUKKQH.mjs → chunk-QP7BOHE4.mjs} +1 -1
- package/dist/chunk-QVGOPHOF.mjs +2 -0
- package/dist/{chunk-NFABH3QW.mjs → chunk-RRKJMHNX.mjs} +2 -2
- package/dist/chunk-S3SX3COT.mjs +20 -0
- package/dist/chunk-SQ3FQCCN.mjs +8 -0
- package/dist/{chunk-ZO7SFB2E.mjs → chunk-SQ6Y2ZMA.mjs} +2 -2
- package/dist/{chunk-3A5I2GJK.mjs → chunk-T4Y2ZSVX.mjs} +1 -1
- package/dist/{chunk-VG5JEIUQ.mjs → chunk-TKWEX4FD.mjs} +2 -2
- package/dist/{chunk-CCSGFCLZ.mjs → chunk-U3SSPL4K.mjs} +1 -1
- package/dist/{chunk-DHB7UZ7F.mjs → chunk-U5XL7D6A.mjs} +1 -1
- package/dist/{chunk-JXLSHVJ2.mjs → chunk-UMHUSOPJ.mjs} +1 -1
- package/dist/chunk-UTF7GBQU.mjs +4 -0
- package/dist/chunk-UTMAY3WK.mjs +2 -0
- package/dist/{chunk-S2Y7VI4H.mjs → chunk-V4ZHRALW.mjs} +2 -2
- package/dist/{chunk-GWOYMENX.mjs → chunk-V6XZ4VIR.mjs} +1 -1
- package/dist/{chunk-WTEGUPFG.mjs → chunk-VRPVVMRB.mjs} +1 -1
- package/dist/{chunk-XKOHV4H6.mjs → chunk-W5NPH5UA.mjs} +1 -1
- package/dist/{chunk-VGTMLQWZ.mjs → chunk-WD4U6XXT.mjs} +1 -1
- package/dist/{chunk-4DNHHJSL.mjs → chunk-XBNFXWAW.mjs} +1 -1
- package/dist/chunk-XZV72SQ4.mjs +2 -0
- package/dist/{chunk-QJ3TFJLQ.mjs → chunk-Y34NR5JL.mjs} +1 -1
- package/dist/{chunk-YBB5LWZK.mjs → chunk-YFJB534W.mjs} +1 -1
- package/dist/{chunk-V5JRSGZF.mjs → chunk-YN37ZDLW.mjs} +1 -1
- package/dist/chunk-Z6OKLRHC.mjs +2 -0
- package/dist/chunk-ZLS2FRS6.mjs +3 -0
- package/dist/{chunk-JI6T3A4Y.mjs → chunk-ZMHUDYLV.mjs} +1 -1
- package/dist/{chunk-KH24LWAT.mjs → chunk-ZTHICSSF.mjs} +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/server.mjs +1 -1
- package/dist/worker.mjs +1 -1
- package/kit/math.js +1 -1
- package/kit/runtime.js +13 -2
- package/kit/state.js +2 -0
- package/kit/ui.js +5 -1
- package/package.json +1 -1
- package/release.json +7 -7
- package/skill/SKILL.md +13 -13
- package/skill/references/building-blocks.md +1 -1
- package/skill/references/extensions.md +45 -9
- package/web/assets/index-D8P8uhDW.js +15 -0
- package/web/assets/{index-xP0uw3a0.css → index-FLb9jCfl.css} +1 -1
- package/web/index.html +2 -2
- package/dist/chunk-46ACXOU5.mjs +0 -2
- package/dist/chunk-5DPABPBI.mjs +0 -2
- package/dist/chunk-5L26JUYA.mjs +0 -2
- package/dist/chunk-AEMVZYZQ.mjs +0 -166
- package/dist/chunk-ASAXY2DJ.mjs +0 -2
- package/dist/chunk-DAMVDXR3.mjs +0 -2
- package/dist/chunk-DLFZJJEE.mjs +0 -2
- package/dist/chunk-EKNHM3P4.mjs +0 -2
- package/dist/chunk-FCK6NXON.mjs +0 -3
- package/dist/chunk-FX42XU6J.mjs +0 -2
- package/dist/chunk-HATA2W7X.mjs +0 -2
- package/dist/chunk-JJNRIFND.mjs +0 -8
- package/dist/chunk-JL6R4FG4.mjs +0 -4
- package/dist/chunk-KUILYI7H.mjs +0 -4
- package/dist/chunk-NIW7F7LU.mjs +0 -4
- package/dist/chunk-OU3S466R.mjs +0 -20
- package/dist/chunk-QCEATQC4.mjs +0 -2
- package/dist/chunk-TDWJKOLN.mjs +0 -2
- package/dist/chunk-UGO5N3EI.mjs +0 -15
- package/dist/chunk-XMKHCUI6.mjs +0 -15
- package/dist/chunk-XQRUG4G3.mjs +0 -2
- package/dist/chunk-YPPJVDQI.mjs +0 -2
- package/dist/chunk-ZANMKAWS.mjs +0 -2
- package/web/assets/index-BHC5ZOMh.js +0 -15
- /package/dist/{chunk-N3DSBH5S.mjs → chunk-A55HN5OK.mjs} +0 -0
- /package/dist/{chunk-KNZJT4ET.mjs → chunk-QAIHRH3I.mjs} +0 -0
- /package/dist/{chunk-ZW2A6GBW.mjs → chunk-QR6A54KJ.mjs} +0 -0
- /package/dist/{chunk-74UW7QSL.mjs → chunk-UH4SIXTR.mjs} +0 -0
- /package/dist/{chunk-EKGYYOSP.mjs → chunk-W7XHE4CT.mjs} +0 -0
- /package/dist/{chunk-5MMN3N5J.mjs → chunk-YEY3RSFQ.mjs} +0 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
|
|
2
|
+
import{a as Gn,b as Kn}from"./chunk-6GV3CBB2.mjs";import{a as Jn}from"./chunk-DR73Y2UJ.mjs";import{b as zn}from"./chunk-M4NRDYI5.mjs";import{a as Un,i as Hn,j as Bn}from"./chunk-PUOQ65NC.mjs";import{a as Wn,b as Mn}from"./chunk-6QWQXHAV.mjs";import{k as Qe}from"./chunk-ZLS2FRS6.mjs";import{h as Rn,i as Fn}from"./chunk-S3SX3COT.mjs";import{a as An}from"./chunk-JJNHKGTD.mjs";import{a as Dn}from"./chunk-JPG2LBQM.mjs";import{a as In,b as Nn}from"./chunk-ALZ6ZENZ.mjs";import{a as Ln}from"./chunk-2OHANJ6Q.mjs";import{a as Cn,b as qe,d as _n,e as Pn,f as jn,g as Tn}from"./chunk-7M2BQQGZ.mjs";import{b as Et,e as ln,g as Ot,h as dn,j as fn,k as mn}from"./chunk-4B2TB5K2.mjs";import{a as qt,d as en,e as tn,f as nn,k as on,l as an,m as rn,r as sn,t as bt,u as cn}from"./chunk-KLQP46Y3.mjs";import{b as kn,c as vn,d as Pe,e as xn,f as $n,g as Ze,i as Sn,m as bn,p as En,q as On}from"./chunk-BX5AKINW.mjs";import{d as wn,e as Fe,f as Xe,g as Ct,h as yn,k as Ve}from"./chunk-FJLM7YE7.mjs";import{b as un,c as pn}from"./chunk-PAREWQGB.mjs";import{i as Ke,j as Je,k as Ye}from"./chunk-BFJGHSQN.mjs";import{d as gn}from"./chunk-U5XL7D6A.mjs";import{a as hn}from"./chunk-HYMEEXKN.mjs";import{a as We}from"./chunk-E7656LR7.mjs";import{c as $t,g as se,j as Yt,k as Xt,p as Vt,q as Zt,v as Qt,w as St}from"./chunk-TKWEX4FD.mjs";import wt from"node:fs";import oi from"node:fs/promises";import ai from"node:http";import{kitPublicDirectory as ri,release as si,releaseFile as yt,vendorDirectory as ii,workbenchDirectory as ci}from"../browser/shared/paths.mjs";import{serviceLocation as li}from"../browser/shared/service-location.mjs";import{serve as ga}from"../browser/shared/http.mjs";import{defaultWorkspace as di,ensureWorkspace as fi,layoutOf as mi}from"../browser/shared/workspace.mjs";import Yn from"node:fs";import Sa from"node:fs/promises";import _t from"node:path";import ba from"node:http";import Zn from"node:net";import{spawn as Xn}from"node:child_process";import{extensionDirectory as Ea,extensionFile as Oa,listCapabilities as et,setExtensionEnabled as Ca}from"../browser/shared/extension-manifest.mjs";import{serviceLocation as _a}from"../browser/shared/service-location.mjs";import{sendJson as ie,serve as Pa}from"../browser/shared/http.mjs";var Vn=e=>new Promise(a=>setTimeout(a,e)),ja=()=>new Promise((e,a)=>{let t=Zn.createServer();t.once("error",a),t.listen(0,"127.0.0.1",()=>{let{port:o}=t.address();t.close(()=>e(o))})}),Ta=e=>new Promise(a=>{let t=Zn.connect(e,"127.0.0.1");t.setTimeout(250),t.once("connect",()=>{t.destroy(),a(!0)}),t.once("error",()=>a(!1)),t.once("timeout",()=>{t.destroy(),a(!1)})}),Ra={".js":"text/javascript",".mjs":"text/javascript",".css":"text/css",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".woff2":"font/woff2"};function Qn({edits:e}){let a=new Map,t=Promise.resolve(),o=0,i=n=>{o++;let c=t.then(n);return t=c.catch(()=>{}),c.finally(()=>{o--})},f=!1,s=async n=>{let c=a.get(n);c&&(await l(c),a.delete(n))},m=setInterval(()=>{et().then(async n=>{for(let c of a.values()){let v=n.find(P=>P.id===c.id);(!v?.enabled||v.manifest.revision!==c.revision)&&await s(c.id)}}).catch(()=>{})},1e3);m.unref();function l(n){return n.stopping??=p(n)}async function p(n){n.stopped=!0,clearTimeout(n.timer),await n.starting?.catch(()=>{});let c=n.child;c&&c.exitCode===null&&c.signalCode===null&&(process.platform==="win32"?await new Promise(v=>{let P=Xn("taskkill",["/pid",String(c.pid),"/t","/f"],{windowsHide:!0,stdio:"ignore"});P.once("error",v),P.once("exit",v)}):(c.kill("SIGTERM"),await Promise.race([new Promise(v=>c.once("exit",v)),Vn(1500)]),c.exitCode===null&&c.kill("SIGKILL"))),n.log?.end()}async function k(n){if(f||n.stopped)return;let c=(await et()).find(C=>C.id===n.id);if(!c?.enabled||c.manifest.revision!==n.revision){n.stopped=!0,n.log.end(),a.delete(n.id);return}if(n.port=await ja(),f||n.stopped)return;let[v,...P]=c.manifest.server.command,h=Xn(v==="node"?process.execPath:v,P,{cwd:c.folder,windowsHide:!0,shell:!1,env:{...process.env,PORT:String(n.port),GALLERY_EXTENSION_PORT:String(n.port),GALLERY_EXTENSION_HOST:"127.0.0.1",GALLERY_EXTENSION_ID:n.id},stdio:["ignore","pipe","pipe"]});n.child=h;let M=Date.now();h.stdout?.pipe(n.log,{end:!1}),h.stderr?.pipe(n.log,{end:!1});let x=!1,$=C=>{x||(x=!0,n.log.write(`[${new Date().toISOString()}] ${C?.message??"Backend exited"}
|
|
3
|
+
`),!(f||n.stopped)&&(n.failures=Date.now()-M>3e4?0:n.failures+1,n.timer=setTimeout(()=>{n.starting=k(n).finally(()=>{n.starting=null}),n.starting.catch(w=>n.log.write(w.message+`
|
|
4
|
+
`))},Math.min(3e4,500*2**Math.min(n.failures,6))),n.timer.unref()))};h.once("error",$),h.once("exit",()=>$())}async function S(n){if(o||f)throw new Error("\u6269\u5C55\u6B63\u5728\u66F4\u65B0\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");let c=a.get(n.id);if(c&&c.revision!==n.manifest.revision&&(await l(c),a.delete(n.id),c=null),!c){let P=_t.join(_a().data,"logs","extensions",`${n.id}.log`);Yn.mkdirSync(_t.dirname(P),{recursive:!0}),c={id:n.id,revision:n.manifest.revision,failures:0,stopped:!1,log:Yn.createWriteStream(P,{flags:"a"})},c.log.on("error",()=>{}),a.set(n.id,c),c.starting=k(c).finally(()=>{c.starting=null})}await c.starting;let v=Date.now()+1e4;for(;!f&&!c.stopped&&Date.now()<v;){if(c.child?.exitCode===null&&!c.child.signalCode&&await Ta(c.port))return c.port;await Vn(100)}throw new Error("\u6269\u5C55\u540E\u53F0\u6682\u672A\u5C31\u7EEA\uFF0C\u8BF7\u67E5\u770B\u6269\u5C55\u65E5\u5FD7")}async function b(n,c){let v=new URL(n.url,"http://localhost");if(!v.pathname.startsWith("/__gallery/extensions"))return!1;let P=`127.0.0.1:${n.socket.localPort}`;if(n.headers.host!==P)return ie(c,403,{ok:!1,reason:"host"}),!0;try{if(v.pathname==="/__gallery/extensions"&&n.method==="GET")return ie(c,200,{ok:!0,extensions:await et()}),!0;let h=/^\/__gallery\/extensions\/(install|remove)$/.exec(v.pathname)?.[1];if(h){let T=await e.check(n,65536);if(T.error)ie(c,...T.error);else if(h==="install"){let G=await i(()=>Gn(T.body.path,{inService:!0,beforeReplace:s}));ie(c,200,{ok:!0,installed:G})}else await i(()=>Kn(T.body.id,{inService:!0,beforeReplace:s})),ie(c,200,{ok:!0});return!0}if(v.pathname==="/__gallery/extensions"&&n.method==="POST"){let T=await e.check(n,65536);return T.error?ie(c,...T.error):(await i(async()=>{await Ca(T.body),T.body.enabled||await s(T.body.id)}),ie(c,200,{ok:!0})),!0}let M=/^\/__gallery\/extensions\/([^/]+)\/(files|api)\/(.*)$/.exec(v.pathname);if(!M)return ie(c,404,{ok:!1}),!0;if(o||f)return ie(c,503,{ok:!1,message:"\u6269\u5C55\u6B63\u5728\u66F4\u65B0\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5"}),!0;let[,x,$,C]=M,w=(await et()).find(T=>T.id===x);if(!w?.enabled)return ie(c,403,{ok:!1,reason:"disabled"}),!0;if($==="files"){if(n.method!=="GET"&&n.method!=="HEAD")return ie(c,405,{ok:!1}),!0;let T=await Oa(Ea(x),decodeURIComponent(C));return Pa(c,{type:Ra[_t.extname(T)]??"application/octet-stream",headers:{"X-Content-Type-Options":"nosniff","Cache-Control":"no-cache"},body:n.method==="HEAD"?void 0:await Sa.readFile(T)}),!0}let j={...n.headers};if(!j.origin&&["GET","HEAD"].includes(n.method))try{j.origin=new URL(j.referer).origin}catch{}let L=e.checkHeaders({method:"POST",headers:j,socket:n.socket});if(L)return ie(c,...L),!0;if(!w.manifest.server)return ie(c,404,{ok:!1,reason:"backend"}),!0;let E=await S(w),U={...n.headers,host:`127.0.0.1:${E}`};delete U["x-gallery-token"],delete U.cookie;let J=ba.request({host:"127.0.0.1",port:E,method:n.method,path:"/"+C+v.search,headers:U},T=>{let G={...T.headers};delete G["access-control-allow-origin"],delete G["set-cookie"],c.writeHead(T.statusCode,G),T.pipe(c)});return J.setTimeout(3e4,()=>J.destroy(new Error("\u6269\u5C55\u540E\u53F0\u8BF7\u6C42\u8D85\u65F6"))),J.once("error",T=>{c.headersSent?c.destroy():ie(c,502,{ok:!1,message:T.message})}),c.once("close",()=>J.destroy()),n.pipe(J),!0}catch(h){return ie(c,400,{ok:!1,message:h.message}),!0}}return{handle:b,async close(){f=!0,clearInterval(m),await t,await Promise.all([...a.values()].map(l)),a.clear()}}}import ca from"node:fs";import{serviceLocation as Gs}from"../browser/shared/service-location.mjs";import we from"node:fs/promises";import X from"node:path";import{assetFile as Fa,referencedFile as qn}from"../browser/shared/media.mjs";import{pageAssetAddress as La}from"../browser/shared/pages.mjs";function Pt(e,a){if(!/assets\//i.test(e))return e;let t=Je(e,o=>qn(o)!==null);return Ke(e,Ye(t,o=>{let i=qn(o.value);return Fa(i)?`${La(a,i)}${/[?#].*$/.exec(o.value.trim())?.[0]??""}`:null}))}function eo(e,{reportsDirectory:a,kit:t,slug:o=null}={}){let{html:i,packages:f}=$n(o?Pt(e,o):e,{reportsDirectory:a,kit:t,page:!0});return{html:i,packages:f}}import{Z as Aa}from"../browser/shared/layers.mjs";import{escapeMarkup as jt}from"../browser/shared/escape.mjs";import{layoutNotesScript as Ia}from"../browser/shared/qa-levels.mjs";var tt=30,Na=`
|
|
5
|
+
[data-doc-dev].doc-checks { position: fixed; z-index: ${Aa.checks}; left: 12px; bottom: 12px; max-width: min(520px, calc(100vw - 24px));
|
|
6
|
+
font: 13px/1.5 system-ui, sans-serif; color: light-dark(#37352f, #e3e2e0); }
|
|
7
|
+
[data-doc-dev].doc-checks[hidden] { display: none; }
|
|
8
|
+
[data-doc-dev].doc-checks > summary { display: inline-flex; gap: 6px; align-items: center; padding: 4px 10px; border-radius: 999px; cursor: pointer;
|
|
9
|
+
list-style: none; color: light-dark(#a1352b, #f19c92); background: light-dark(#fce9e7, #3b2321);
|
|
10
|
+
box-shadow: 0 0 0 1px light-dark(rgb(161 53 43 / 18%), rgb(241 156 146 / 22%)); user-select: none; }
|
|
11
|
+
[data-doc-dev].doc-checks > summary::-webkit-details-marker { display: none; }
|
|
12
|
+
[data-doc-dev].doc-checks > div { margin-top: 6px; padding: 8px 12px; max-height: 50vh; overflow: auto; border-radius: 10px;
|
|
13
|
+
background: light-dark(#ffffff, #252525); box-shadow: 0 0 0 1px light-dark(rgb(42 28 0 / 7%), #383836), 0 20px 24px light-dark(rgb(25 25 25 / 5%), rgb(0 0 0 / 20%)); }
|
|
14
|
+
[data-doc-dev].doc-checks ul { margin: 0; padding-left: 18px; }
|
|
15
|
+
[data-doc-dev].doc-checks li { margin: 2px 0; overflow-wrap: anywhere; }
|
|
16
|
+
[data-doc-dev].doc-checks p { margin: 6px 0 0; color: light-dark(#787774, #9b9a97); }
|
|
17
|
+
[data-doc-dev].doc-checks .doc-checks-live:not(:first-child) { margin-top: 8px; }
|
|
18
|
+
@media print { [data-doc-dev].doc-checks { display: none; } }`,Da=`(() => {
|
|
19
|
+
document.currentScript.remove();
|
|
20
|
+
${Ia()}
|
|
21
|
+
const panel = document.querySelector("details.doc-checks[data-doc-dev]");
|
|
22
|
+
if (!panel) return;
|
|
23
|
+
const failures = Number(panel.dataset.failures) || 0;
|
|
24
|
+
const live = panel.querySelector(".doc-checks-live ul");
|
|
25
|
+
// The note's words in the UI's language (the root's data-ge-language).
|
|
26
|
+
const english = document.documentElement.getAttribute("data-ge-language") === "en";
|
|
27
|
+
const WORDS = english
|
|
28
|
+
? { card: "Chart card", table: "Table", named: (kind, name) => kind + " \u201C" + name + "\u201D", first: (name) => "Table (first column \u201C" + name + "\u201D)", colon: ": ",
|
|
29
|
+
failing: (count) => "Checks failed \xB7 " + count, more: (count) => count + " more", all: (slug) => "gallery check " + slug + " runs every check (TypeScript too)." }
|
|
30
|
+
: { card: "\u56FE\u8868\u5361\u7247", table: "\u8868\u683C", named: (kind, name) => kind + "\u300C" + name + "\u300D", first: (name) => "\u8868\u683C\uFF08\u9996\u5217\u300C" + name + "\u300D\uFF09", colon: "\uFF1A",
|
|
31
|
+
failing: (count) => "\u68C0\u67E5\u672A\u901A\u8FC7 \xB7 " + count + " \u9879", more: (count) => "\u8FD8\u6709 " + count + " \u9879", all: (slug) => "gallery check " + slug + " \u8DD1\u5168\u90E8\u68C0\u67E5\uFF08\u542B TypeScript\uFF09\u3002" };
|
|
32
|
+
const more = panel.querySelector("[data-more]");
|
|
33
|
+
if (more) more.textContent = WORDS.more(more.dataset.more);
|
|
34
|
+
const all = panel.querySelector("[data-all]");
|
|
35
|
+
if (all) all.textContent = WORDS.all(all.dataset.all);
|
|
36
|
+
const tidy = (node) => (node?.textContent ?? "").replace(/\\s+/g, " ").trim().slice(0, 40);
|
|
37
|
+
const what = (host) => {
|
|
38
|
+
const card = host.closest("figure");
|
|
39
|
+
const title = card?.querySelector(":scope > h3, :scope > figcaption");
|
|
40
|
+
const table = host.closest(".doc-table-wrap, table");
|
|
41
|
+
const caption = table?.querySelector("caption");
|
|
42
|
+
const header = table?.querySelector("th");
|
|
43
|
+
return title ? WORDS.named(WORDS.card, tidy(title)) : card ? WORDS.card : caption && tidy(caption) ? WORDS.named(WORDS.table, tidy(caption)) : header ? WORDS.first(tidy(header)) : host.localName;
|
|
44
|
+
};
|
|
45
|
+
// A chart that drew nothing says why in its card (the kit's line, in the same language): that line, else the note in words.
|
|
46
|
+
const said = (host, name, note) => (name === "data-missing" && tidy(host.querySelector(".doc-chart-message"))) || noteInWords(note, { english });
|
|
47
|
+
let shown = "";
|
|
48
|
+
let frame = 0;
|
|
49
|
+
const draw = () => {
|
|
50
|
+
frame = 0;
|
|
51
|
+
const notes = [...document.querySelectorAll("[data-doc-layout]")].filter((host) => !host.closest("[data-doc-dev]"))
|
|
52
|
+
.flatMap((host) => layoutNotesOf(host.getAttribute("data-doc-layout"), document.documentElement.clientWidth)
|
|
53
|
+
.filter(({ level }) => level === "fail")
|
|
54
|
+
.map(({ note, name }) => ({ line: what(host) + WORDS.colon + said(host, name, note), note })));
|
|
55
|
+
const key = notes.map(({ line }) => line).join("\\n");
|
|
56
|
+
if (key === shown) return;
|
|
57
|
+
shown = key;
|
|
58
|
+
live.replaceChildren(...notes.map(({ line, note }) => Object.assign(document.createElement("li"), { textContent: line, title: note })));
|
|
59
|
+
live.parentElement.hidden = notes.length === 0;
|
|
60
|
+
const failing = failures + notes.length;
|
|
61
|
+
panel.querySelector("summary").textContent = failing ? WORDS.failing(failing) : "";
|
|
62
|
+
panel.hidden = failing === 0;
|
|
63
|
+
};
|
|
64
|
+
const later = (records) => {
|
|
65
|
+
if (!globalThis.document?.defaultView) return; // the page is gone
|
|
66
|
+
if (!frame && records.some((record) => !record.target.closest?.("[data-doc-dev]"))) frame = requestAnimationFrame(draw);
|
|
67
|
+
};
|
|
68
|
+
new MutationObserver(later).observe(document.documentElement, { subtree: true, childList: true, attributes: true, attributeFilter: ["data-doc-layout"] });
|
|
69
|
+
addEventListener("resize", () => { if (!frame) frame = requestAnimationFrame(draw); });
|
|
70
|
+
draw();
|
|
71
|
+
})();`;function to(e,a,t={},{directory:o}={}){let i=Sn({slug:e,html:a,metadata:t,...o?{directory:o}:{}}),f=i.slice(0,tt).map(p=>`<li>${jt(p)}</li>`).join(""),s=i.length>tt?`<p data-more="${i.length-tt}">\u8FD8\u6709 ${i.length-tt} \u9879</p>`:"",m=i.length?`<ul>${f}</ul>${s}<p data-all="${jt(e)}">gallery check ${jt(e)} \u8DD1\u5168\u90E8\u68C0\u67E5\uFF08\u542B TypeScript\uFF09\u3002</p>`:"";return`<details class="doc-checks" data-doc-dev data-failures="${i.length}"${i.length?"":" hidden"}><summary>${i.length?`\u68C0\u67E5\u672A\u901A\u8FC7 \xB7 ${i.length} \u9879`:""}</summary><div>${m}<div class="doc-checks-live" hidden><ul></ul></div></div><style>${Na}</style></details>
|
|
72
|
+
<script data-doc-dev>${Da}</script>`}import{browserDirectory as ds,kitSourceDirectory as na,release as fs,reportsDirectory as ms}from"../browser/shared/paths.mjs";import{FRAMED_BY as us,sendJson as Ho,serve as zt,serveFound as Ie}from"../browser/shared/http.mjs";import{languageScript as Bo}from"../browser/shared/i18n/index.mjs";import{announcePreviewServer as ps,galleryVersion as hs,sameDirectory as gs}from"../browser/shared/preview-server.mjs";import{registerQuietly as ws}from"../browser/shared/workspace-registry.mjs";import{lookWord as zo}from"../browser/shared/document-look.mjs";import{documentLook as Go,ownLookAt as ys}from"../browser/shared/workspace-look.mjs";import{slugPattern as oa}from"../browser/shared/reports.mjs";import{ATTRIBUTE as pt,PACKAGE_ID as ks}from"../browser/shared/components/installed.mjs";import{COMPONENTS_FOLDER as Ko,DOCUMENT_FOLDERS as Jo,EXTENSIONS_FOLDER as vs,PAGES_FOLDER as xs,WORKSPACE_FILE as ht,defaultWorkspace as Te,documentDirectory as ft,documentFiles as $s,isDocumentFile as Ss,isDocumentSource as Yo,isSlugName as aa,layoutOf as Me}from"../browser/shared/workspace.mjs";import{PAGE_FILES as Xo,homeCardsNew as bs,isBlankPage as Es,isPageFile as Os,pageFiles as Vo,pageHintShown as Cs,pageMetaNow as _s,pageVersion as Zo}from"../browser/shared/pages.mjs";import{LINK_FILE as Ps}from"../browser/shared/web-links.mjs";import{SIDEBAR_FILE as mt}from"../browser/shared/extension-sidebar.mjs";import{extensionColumnIds as Qo}from"../browser/shared/extensions.mjs";import{isExtensionId as js}from"../browser/shared/outline-shape.mjs";import{createHash as Qa,randomBytes as qa}from"node:crypto";import ee from"node:fs";import Tt from"node:os";import ge from"node:path";import{Transform as er}from"node:stream";import{pipeline as tr}from"node:stream/promises";import{exportSourceOf as nr}from"../browser/shared/export-wrap.mjs";import{writeAtomic as Rt}from"../browser/shared/files.mjs";import{sendJson as V}from"../browser/shared/http.mjs";import{said as Ft,saying as or}from"../browser/shared/i18n/index.mjs";import{IMPORT_LIMIT as so}from"../browser/shared/import-types.mjs";import{mediaUrl as ar}from"../browser/shared/media.mjs";import{fullAddress as rr}from"../browser/shared/page-address.mjs";import{documentLinks as io,slugPattern as co}from"../browser/shared/reports.mjs";import{documentDirectory as sr,documentFiles as lo,newDocSlug as ir,pageSlug as cr}from"../browser/shared/workspace.mjs";import{readWritingPreferences as lr,saysAnything as dr,unshownLines as fr}from"../browser/shared/writing-preferences.mjs";import no from"node:fs/promises";import Ka from"node:path";import{Worker as Wa}from"node:worker_threads";import{refusal as Ma,said as Ua}from"../browser/shared/i18n/index.mjs";var Ha=6e4,me=null,Ba=0,nt=0,je=new Map;function za(){me=new Wa(new URL("./worker.mjs",import.meta.url)),me.on("message",({id:a,result:t,error:o})=>{let i=je.get(a);i&&(je.delete(a),o?i.reject(Object.assign(new Error(o.message),o)):i.resolve(t),je.size===0&&(me?.unref(),Ga()))});let e=a=>{for(let t of je.values())t.reject(a);je.clear(),me=null};me.on("error",e),me.on("exit",a=>e(Ma(Ua("\u8F6C\u6362\u8FDB\u7A0B\u610F\u5916\u9000\u51FA\uFF08{0}\uFF09",a))))}function Ga(){clearTimeout(nt),nt=setTimeout(()=>{if(je.size===0&&me){let e=me;me=null,e.removeAllListeners("exit"),e.terminate()}},Ha),nt.unref?.()}function ve(e,a){clearTimeout(nt),me||za();let t=++Ba;return new Promise((o,i)=>{je.set(t,{resolve:o,reject:i}),me.ref(),me.postMessage({id:t,type:e,payload:a})})}import{pageLanguage as Ja}from"../browser/shared/components/page.mjs";function ot(e){return String(e??"").replace(/[\\/:*?"<>|\u0000-\u001f\u007f]/g," ").replace(/\s+/g," ").trim().slice(0,100).trim()||"Untitled"}function at(e,a){let t=e.lastIndexOf("."),[o,i]=t>0?[e.slice(0,t),e.slice(t)]:[e,""];for(let f=0;;f+=1){let s=f===0?e:`${o} ${f}${i}`;if(!a.has(s.toLowerCase()))return a.add(s.toLowerCase()),s}}function rt(e,a){let t=e.split("/").slice(0,-1),o=a.split("/"),i=0;for(;i<t.length&&i<o.length-1&&t[i]===o[i];)i+=1;return[...t.slice(i).map(()=>".."),...o.slice(i)].map(s=>s===".."?s:encodeURIComponent(s).replace(/\(/g,"%28").replace(/\)/g,"%29")).join("/")}import{documentDirectory as Ya,documentFiles as Xa}from"../browser/shared/workspace.mjs";var oo={markdown:"md",html:"html",pdf:"pdf"},Va={markdown:"text/markdown; charset=utf-8",html:"text/html; charset=utf-8",pdf:"application/pdf"},Za=e=>typeof e=="number"&&e>.1&&e<2;function ao(e){let{format:a,content:t="everything",subpages:o=!1,folders:i=!0,paper:f="A4",scale:s=1}=e??{};return Object.hasOwn(oo,a)&&["everything","no_files"].includes(t)&&typeof o=="boolean"&&typeof i=="boolean"&&["A4","A3","Letter","Legal","Tabloid"].includes(f)&&Za(s)}async function ro(e,a,t){let{format:o,content:i="everything",subpages:f=!1,folders:s=!0,paper:m="A4",scale:l=1}=a,p=oo[o],k=i==="everything",S=[],b=new Map,n=$=>b.get($)??b.set($,new Set).get($),c=async($,C)=>{let w=await t.titleOf($),j=at(`${ot(w)}.${p}`,n(C)),L=C?`${C}/${j}`:j,E=s?L.slice(0,-(p.length+1)):"";if(S.push({slug:$,title:w,file:L,folder:E,files:C?`${C}/assets`:"assets"}),f)for(let U of await t.childrenOf($))await c(U,E)};await c(e,"");let{links:v}=await t.links(),P=($,C)=>vn(C,$.slug,w=>{let j=o==="pdf"?null:S.find(L=>L.slug===w)?.file??null;return j&&rt($.file,j)},{blocks:o!=="markdown",links:v}),h=[],M=[];for(let $ of S)if(o==="markdown"){await t.check($.slug);let C=Ya($.slug,t.reportsDirectory),w=Pe(await no.readFile(Xa(C).html,"utf8"),{slug:$.slug,mode:"words",reportsDirectory:t.reportsDirectory}),j=P($,w),L=k&&!!Un(),{text:E,files:U,charts:J,charted:T}=await ve("markdown",{source:j,title:$.title,pictures:L}),G=E,Z=new Map;if(U.forEach(({src:g,name:y},A)=>{Z.has(g)||(Z.set(g,`${$.files}/${at(ot(y),n($.files))}`),k&&M.push({from:Ka.join(C,g),name:Z.get(g)}));let R=Z.get(g);G=G.replace(`\0F${A}\0`,()=>rt($.file,R))}),L&&J>0&&G.includes("\0C")){let g=await Bn(await t.offline($.slug,{files:!0})).catch(()=>[]);G=G.replace(/^.*\u0000C(\d+)\u0000.*$/gm,(y,A)=>{let R=g[Number(A)];if(!R)return"\0gone\0";let I=`${$.files}/${at(Ja(j)==="en"?T[Number(A)]?"Chart.png":"Figure.png":T[Number(A)]?"\u56FE\u8868.png":"\u56FE.png",n($.files))}`;return h.push({name:I,data:R,later:!0}),y.replace(`\0C${A}\0`,()=>rt($.file,I))}).replace(/\n*\u0000gone\u0000\n*/g,`
|
|
73
|
+
|
|
74
|
+
`).replace(/^\n+|\n+$/g,"")}h.push({name:$.file,data:G})}else o==="html"?h.push({name:$.file,data:P($,await t.offline($.slug,{files:k}))}):h.push({name:$.file,data:await Hn(P($,await t.offline($.slug,{files:k})),{paper:m,scale:l})});for(let $ of M){let C=await no.readFile($.from).catch(()=>null);C&&h.push({name:$.name,data:C})}let x=[...h.filter($=>!$.later&&S.some(C=>C.file===$.name)),...h.filter($=>$.later||!S.some(C=>C.file===$.name))];return x.length===1?{name:x[0].name,type:Va[o],data:Buffer.isBuffer(x[0].data)?x[0].data:Buffer.from(x[0].data,"utf8")}:{name:`${ot(S[0].title)}.zip`,type:"application/zip",data:Ln(x)}}var mr=3600*1e3,Lt=new Set,fo=!1,ur=e=>{Lt.add(e),!fo&&(fo=!0,process.once("exit",()=>{for(let a of Lt)try{ee.rmSync(a,{recursive:!0,force:!0})}catch{}}))},pr=/^u-[a-f0-9]{16}$/;function mo({edits:e,workspace:a,reports:t,reportsDirectory:o,offline:i}){let f=null,s=()=>f??=ee.promises.mkdtemp(ge.join(Tt.tmpdir(),"gallery-uploads-")).then(g=>(ur(g),g)),m=new Map,l=(g,y,A)=>[g,{ok:!1,reason:y,...or(A)}],p=g=>ee.promises.access(g).then(()=>!0,()=>!1),k=g=>sr(g,o),S=g=>lo(k(g)),b=async g=>{try{return JSON.parse(await ee.promises.readFile(S(g).json,"utf8")).title||g}catch{return g}};function n(g){if(g.method!=="POST")return[405,{ok:!1,reason:"method"}];let y=g.headers.host??"",A=g.socket.localPort;return y!==`127.0.0.1:${A}`&&y!==`localhost:${A}`?[403,{ok:!1,reason:"host"}]:g.headers.origin!==`http://${y}`?[403,{ok:!1,reason:"origin"}]:g.headers["x-gallery-token"]!==e.token?[403,{ok:!1,reason:"token"}]:/^application\/octet-stream\b/i.test(g.headers["content-type"]??"")?Number(g.headers["content-length"]??0)>so?l(413,"size","\u6587\u4EF6\u592A\u5927\uFF08\u6700\u591A 5GB\uFF09"):null:[415,{ok:!1,reason:"type"}]}async function c(){for(let[g,y]of m)Date.now()-y.at<mr||(m.delete(g),await ee.promises.rm(y.file,{force:!0}).catch(()=>{}))}async function v(g,y){let A=n(g);if(A)return g.resume(),V(y,...A);let R=new URL(g.url,"http://localhost").searchParams.get("name")?.replace(/[\u0000-\u001f]/g,"").trim()??"";if(!R||R.length>255)return g.resume(),V(y,...l(400,"name","\u6587\u4EF6\u540D\u4E0D\u5BF9"));await c();let I=`u-${qa(8).toString("hex")}`,N=ge.join(await s(),I),B=0,z=new er({transform(H,Q,q){B+=H.length,q(B>so?Object.assign(new Error("too-large"),{reason:"size"}):null,H)}});try{await tr(g,z,ee.createWriteStream(N))}catch(H){return await ee.promises.rm(N,{force:!0}).catch(()=>{}),H.reason==="size"?V(y,...l(413,"size","\u6587\u4EF6\u592A\u5927\uFF08\u6700\u591A 5GB\uFF09")):V(y,...l(400,"body","\u6587\u4EF6\u6CA1\u6709\u4F20\u5B8C"))}return m.set(I,{file:N,name:R,at:Date.now()}),V(y,200,{ok:!0,id:I})}async function P(g,y){let A=await e.check(g);if(A.error)return V(y,...A.error);let{slug:R,options:I}=A.body??{};if(typeof R!="string"||!co.test(R)||!await p(S(R).html))return V(y,...l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"));if(!ao(I))return V(y,...l(400,"options","\u5BFC\u51FA\u9009\u9879\u4E0D\u5BF9"));try{let N=await i(),B=new Map,z=D=>(B.has(D)||B.set(D,e.handIn(D,{reader:!0}).then(Y=>{if(!Y.ok)throw Object.assign(new Error(Y.message??Y.reason),{reason:Y.reason});if(Y.repeated.length)throw Object.assign(new Error("check"),{reason:"check",slug:D,failures:Ze(Y.repeated)})})),B.get(D)),H=new Map,Q={reportsDirectory:o,titleOf:b,childrenOf:async D=>{let{children:Y,links:re=[]}=await a.outline(),ne=ye=>(Y[ye]??[]).flatMap(pe=>re.includes(pe)||pe.startsWith("~")?ne(pe):[pe]);return ne(D)},links:()=>io(o),offline:async(D,Y)=>{await z(D);let re=await N(D,Y),ne=I.format==="markdown"?null:nr(re);return ne&&H.set(D,ne),re},check:async D=>(await z(D),N.check(D))},{name:q,type:te,data:K}=await ro(R,I,Q);H.size&&await(await Qe([...H.keys()],o)).keep([...H.keys()],H),y.writeHead(200,{"Content-Type":te,"Content-Length":K.length,"Content-Disposition":`attachment; filename*=UTF-8''${encodeURIComponent(q)}`,"X-File-Name":encodeURIComponent(q),"Cache-Control":"no-store"}),y.end(K)}catch(N){if(N.reason==="check"){let B=await b(N.slug),z=N.component?Ft("\u300C{0}\u300D\u91CC\u7684\u7EC4\u4EF6 {1} \u6709\u9519\u8BEF\uFF0C\u6CA1\u6709\u751F\u6210\u6587\u4EF6\uFF1A\u53EF\u4EE5\u8BA9 AI \u68C0\u67E5\u8FD9\u4EFD\u6587\u6863\u5E76\u4FEE\u597D",B,N.component):N.failures.length>1?Ft("\u300C{0}\u300D\u6CA1\u6709\u901A\u8FC7\u5BFC\u51FA\u524D\u7684\u68C0\u67E5\uFF0C\u6CA1\u6709\u751F\u6210\u6587\u4EF6\uFF1A{1}\uFF08\u5171 {2} \u5904\uFF1A\u53EF\u4EE5\u8BA9 AI \u68C0\u67E5\u8FD9\u4EFD\u6587\u6863\uFF0C\u5217\u51FA\u5168\u90E8\u5E76\u4FEE\u597D\uFF09",B,N.failures[0],N.failures.length):Ft("\u300C{0}\u300D\u6CA1\u6709\u901A\u8FC7\u5BFC\u51FA\u524D\u7684\u68C0\u67E5\uFF0C\u6CA1\u6709\u751F\u6210\u6587\u4EF6\uFF1A{1}",B,N.failures[0]);return V(y,...l(422,"check",z))}V(y,...l(N.reason==="browser"?422:N.reason==="busy"?409:N.reason==="missing"?404:500,N.reason??"export",N))}}async function h(g,y){let A=await e.check(g);if(A.error)return V(y,...A.error);let{slug:R}=A.body??{},I=(await e.readTaken(R,{wait:0}))?.text??null;if(I===null)return V(y,...l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"));let N=`http://${g.headers.host}`,{named:B}=await io(o),z=kn(Pe(I,{slug:R,mode:"words",reportsDirectory:o}),R,te=>te.slug&&rr(N,te,B),B),{text:H,files:Q}=await ve("markdown",{source:z,title:await b(R),pictures:!1}),q=H.replace(/\u0000F(\d+)\u0000/g,(te,K)=>{let{src:D,kind:Y}=Q[Number(K)];return encodeURI(`${N}${ar(Y==="image"?"asset":"file",R,D)}`)});return V(y,200,{ok:!0,text:q})}let M=async g=>{let y=await e.readTaken(g,{wait:0});return{source:y?.text??"",version:y?.version??null}},x=async(g,y=null)=>{let{source:A,version:R}=y??await M(g),I="\u5199\u4F5C\u504F\u597D",{text:N,files:B}=await ve("markdown",{source:A,title:I,pictures:!1}),z=N.split(`
|
|
75
|
+
`).slice(1).join(`
|
|
76
|
+
`).replace(/^[\s>]*(?:```.*|\d+\.|- \[x\])/gm,"").replace(/<\/?aside>/g,"");if(!/[\p{L}\p{N}]|\u0000F\d+\u0000/u.test(z))return{markdown:`# ${I}
|
|
77
|
+
`,empty:!0,version:R};let H=ge.relative(o,k(g)).split(ge.sep).join("/");return{markdown:`${N.replace(/\u0000F(\d+)\u0000/g,(Q,q)=>encodeURI(`${H}/${B[Number(q)].src}`))}
|
|
78
|
+
`,empty:!1,version:R}},$=g=>S(g).json,C=async g=>{try{let y=JSON.parse(await ee.promises.readFile($(g),"utf8"));return y&&typeof y=="object"?y:null}catch{return null}},w=g=>Qa("sha256").update(g).digest("hex").slice(0,16);async function j(g,y,A,R){let I=await C(g);if(!I||A===null)return;let{synced:N,...B}=I,z={file:w(y),page:A,unshown:R},H=I.madeSame;N===void 0&&H?.file===z.file&&H?.page===z.page&&JSON.stringify(H?.unshown)===JSON.stringify(R)||await Rt($(g),`${JSON.stringify({...B,madeSame:z},null,2)}
|
|
79
|
+
`)}async function L(g,y){let A=await ee.promises.mkdtemp(ge.join(Tt.tmpdir(),"gallery-preferences-"));try{let I=(await ve("import",{uploads:[{file:y,name:"preferences.md"}],scratch:A})).pages[0]??{nodes:[],raws:[],files:[],icon:null,lang:null},N=k(g),B=await C(g)??{},z=lo(N).html,H=await ee.promises.readFile(z,"utf8").catch(()=>""),Q=/<html\b[^>]*\slang="([^"]*)"/i.exec(H)?.[1]??null,{html:q}=await pn(g,B.title||"\u5199\u4F5C\u504F\u597D",B.description||"",{blank:!0,lang:Q}),te=typeof B.icon=="string"&&B.icon?B.icon:null,K=await ve("fill",{source:q,nodes:I.nodes,icon:te,raws:I.raws,lang:I.lang});I.files.length&&await ee.promises.mkdir(ge.join(N,"assets"),{recursive:!0});for(let{from:Y,name:re}of I.files){let ne=ge.join(N,"assets",re);await p(ne)||await ee.promises.copyFile(Y,ne)}let D=await ee.promises.readFile(z,"utf8").catch(()=>null);D!==null&&e.keepVersion?.(g,D),await Rt(z,Ve(K))}finally{await ee.promises.rm(A,{recursive:!0,force:!0}).catch(()=>{})}}async function E(g,y){let A=await e.check(g);if(A.error)return V(y,...A.error);let R=A.body?.opening===!0,I=await cr(o);if(!I)return V(y,...l(404,"missing","\u8FD8\u6CA1\u6709\u5199\u4F5C\u504F\u597D"));let N=null,B=(z,H)=>[200,{ok:!0,path:ge.resolve(N),remade:z,unshown:H}];return e.respond(async()=>{let z;({file:N,text:z}=await lr(o));let H=await M(I),Q=(await C(I))?.madeSame??null,q=Q===null||Q.page===H.version,te=Q!==null&&q&&Q.file===w(z);if(R&&te&&Array.isArray(Q.unshown))return B(!1,Q.unshown);let[K,D,Y,re]=[z,"",H.version,!1];if(R&&!q)await L(I,N),{markdown:D,version:Y}=await x(I),re=!0;else{let ye=await x(I,H),pe=z.trim()===ye.markdown.trim()||ye.empty&&!dr(z);D=ye.markdown,R?!pe&&!te&&(await L(I,N),{markdown:D,version:Y}=await x(I),re=!0):pe||(await Rt(N,ye.markdown),K=ye.markdown)}let ne=fr(K,D);return await j(I,K,Y,ne),B(re,ne)})(g,y)}async function U(g,y){let A=await e.check(g);if(A.error)return V(y,...A.error);let{uploads:R,parent:I="",from:N,language:B}=A.body??{},z={said:typeof N=="string"&&N.includes("{0}")&&N.length<=60?N:"\u5BFC\u5165\u81EA {0}",lang:B==="en"?"en":null};if(!Array.isArray(R)||R.length===0||R.length>1e3||!R.every(D=>typeof D=="string"&&pr.test(D)))return V(y,...l(400,"body"));let H=R.map(D=>m.get(D)).filter(Boolean);if(H.length!==R.length)return V(y,...l(410,"gone","\u4E0A\u4F20\u7684\u6587\u4EF6\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u5BFC\u5165"));for(let D of R)m.delete(D);let Q=typeof I=="string"&&co.test(I)&&await p(ge.join(o,I))?I:"",q=await ee.promises.mkdtemp(ge.join(Tt.tmpdir(),"gallery-import-")),te=()=>Promise.all([ee.promises.rm(q,{recursive:!0,force:!0}),...H.map(({file:D})=>ee.promises.rm(D,{force:!0}))]).catch(()=>{}),K;try{K=await ve("import",{uploads:H.map(({file:D,name:Y})=>({file:D,name:Y})),scratch:q})}catch(D){return await te(),V(y,...l(500,"convert",D))}return e.respond(async()=>{try{let{made:D,top:Y}=await An(K.pages,{create:t.create,slugOf:()=>ir(o),folderOf:k,fill:re=>ve("fill",re),place:a.place,under:Q,...z});return[200,{ok:!0,pages:D.length,reports:Y,skipped:K.skipped,missing:J(K.pages)}]}finally{await te()}})(g,y)}let J=g=>[...new Set(g.flatMap(function y(A){return[...(A.notes??[]).filter(R=>R.kind==="picture-missing").map(R=>R.name),...A.children.flatMap(y)]}))],T={export:P,markdown:h,upload:v,import:U,preferences:E};function G(g,y,A){return Object.hasOwn(T,A)?T[A](g,y).catch(R=>{y.headersSent||V(y,...l(500,"transfer",R))}):V(y,404,{ok:!1,reason:"unknown"})}async function Z(){let g=f;f=null,m.clear();let y=await g?.catch(()=>null);y&&(Lt.delete(y),await ee.promises.rm(y,{recursive:!0,force:!0}).catch(()=>{}))}return{handle:G,close:Z}}import{FACT_KINDS as Ts,QUERY_ROUTE as Rs,WORKSPACE_GLOBAL as Fs}from"../browser/shared/workspace-query.mjs";function uo({settled:e,tell:a,delay:t=120,recheck:o=1e3}){let i=new Map,f=(s,m=t)=>{clearTimeout(i.get(s));let l=setTimeout(async()=>{let p=await e(s).catch(()=>({source:null,held:!1,wait:0}));if(i.get(s)===l){if(p.held)return f(s,Math.min(Math.max(p.wait,50),o));if(p.wait>0)return f(s,p.wait);await a(s,p)}},m);i.set(s,l)};return f}import xe from"node:fs";import Ce from"node:path";import{isExtensionId as hr}from"../browser/shared/outline-shape.mjs";import{DOCUMENT_FOLDERS as po,isSlugName as At,layoutOf as ho}from"../browser/shared/workspace.mjs";function gr(e,a=!1,t=!1){let{components:o,gallery:i,preferencesPage:f,customPages:s,extensions:m}=ho(e),l=(n,c)=>{try{return xe.readdirSync(n,{withFileTypes:!0}).filter(v=>v.isDirectory()&&c(v.name)).map(v=>Ce.join(n,v.name))}catch{return[]}},p=l(m,n=>hr(n)&&!po.includes(n));if(a){let n=Ce.dirname(e);for(;!xe.existsSync(n)&&Ce.dirname(n)!==n;)n=Ce.dirname(n);return[n,e,...t?[i]:[],m,...p].filter(c=>xe.existsSync(c))}let k=[...l(e,n=>At(n)),...l(f,n=>At(n))],S=n=>[n,...l(n,c=>!c.startsWith(".")).flatMap(S)],b=l(s,n=>At(n)&&!po.includes(n));return[...new Set([e,...[i,f,s,m].filter(n=>xe.existsSync(n)),...b,...p,...k,...k.map(n=>Ce.join(n,"assets")).filter(n=>xe.existsSync(n)),...xe.existsSync(o)?S(o):[]])]}function Le(e,a,{folders:t=process.platform==="linux",extensionsOnly:o=!1,outline:i=!1}={}){let f=It(e),s=(b,n)=>{!(i&&n===ho(e).outline)&&(f(n)||Ce.basename(n).startsWith("."))||xe.stat(n,(v,P)=>{if(v)return a(v.code==="ENOENT"?"unlink":"change",n);let h=P.isDirectory();a(b==="rename"?h?"addDir":"add":h?"addDir":"change",n)})},m=()=>{};if(!t&&!o)try{let b=xe.watch(e,{recursive:!0},(n,c)=>c?s(n,Ce.join(e,c.toString())):a("reset",e));return b.on("error",m),{close:()=>b.close()}}catch(b){if(b.code!=="ERR_FEATURE_UNAVAILABLE_ON_PLATFORM")throw b}let l=new Map,p=null,k=()=>{let b=new Set(gr(e,o,i));for(let[n,c]of l)b.has(n)||(c.close(),l.delete(n));for(let n of b)if(!l.has(n))try{let c=xe.watch(n,(v,P)=>{if(!P)return a("reset",n);v==="rename"&&S(),s(v,Ce.join(n,P.toString()))});c.on("error",m),l.set(n,c)}catch{}},S=()=>{p??=setTimeout(()=>{p=null,k()},50)};return k(),{close(){clearTimeout(p);for(let b of l.values())b.close();l.clear()},get folders(){return[...l.keys()]}}}import wr from"node:fs/promises";import{packageScript as yr}from"../browser/shared/export-wrap.mjs";import{serveFound as kr}from"../browser/shared/http.mjs";import{extensionOf as vr,mediaTypeOf as xr}from"../browser/shared/media.mjs";var $r="/__gallery/components/",Sr=/^\/__gallery\/components\/([a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*)\/(.+)$/,br={js:"text/javascript; charset=utf-8",mjs:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",wasm:"application/wasm"};async function go(e,a,t,{root:o}){if(!e.startsWith($r))return!1;let[,i,f]=Sr.exec(e)??[],s=i?se(o).packages.get(i):null,m=s?.files.includes(f)?Vt(s,f):null,l=m?await wr.readFile(m).catch(()=>null):null,p=l&&f==="kit.js"?Buffer.from(yr(l.toString("utf8").replace(/^\uFEFF/,""))):l,k=p&&a===s.stamp&&a===Zt(s);return kr(t,p,{type:p?br[vr(f)]??xr(f):void 0,headers:{"X-Content-Type-Options":"nosniff","Cache-Control":k?"max-age=31536000, immutable":"no-store"}}),!0}import{BLOCK_ICON as Er}from"../browser/editor/components/icons.mjs";import{LISTED_BLOCKS as wo}from"../browser/editor/components/registry.mjs";import{PACKAGE_ID as Or}from"../browser/shared/components/installed.mjs";import{netHostsOf as yo}from"../browser/shared/net-policy.mjs";import{inLanguage as ko,refusal as st,said as _e}from"../browser/shared/i18n/index.mjs";function vo({root:e,taken:a}){let t=()=>{let s=se(e);return{packages:Qt(s).map(m=>{let l=nn(m.id)?tn(m.id):null;return{...m,newer:l?on(e,l):null,...l?{addAs:l.pack===qt?l.name:l.id}:{}}}),packs:bt(e,{settings:s.settings}),packageIcon:Er,blocks:wo.map(({id:m,name:l,icon:p,hideable:k})=>({id:m,name:{zh:ko("zh",l),en:ko("en",l)},icon:p,hidden:k&&s.settings.hidden.includes(m),hideable:k})),problem:Xt(s)}},o=({id:s,hidden:m,shown:l,disabled:p,unlisted:k,net:S})=>{if(![m,l,p,k,S].every(n=>n===void 0||typeof n=="boolean"))return _e("\u5F00\u5173\u7684\u503C\u4E0D\u5BF9");let b=wo.find(n=>n.id===s);return b?p!==void 0||l!==void 0||k!==void 0||S!==void 0?_e("\u5185\u7F6E\u5757\u53EA\u80FD\u9690\u85CF\uFF0C\u4E0D\u80FD\u505C\u7528"):m&&!b.hideable?_e("\u8FD9\u4E2A\u5757\u4E0D\u80FD\u9690\u85CF"):null:typeof s=="string"&&Or.test(s)?S&&yo(se(e).packages.get(s)?.needs).length===0?_e("\u8FD9\u4E2A\u5757\u4E0D\u8054\u7F51"):null:_e("\u6CA1\u6709\u8FD9\u4E2A\u7EC4\u4EF6")};return{read:t,write:async s=>{if(s?.pack!==void 0){let{pack:S,enabled:b}=s;if(typeof b!="boolean")throw st(_e("\u5F00\u5173\u7684\u503C\u4E0D\u5BF9"));if(typeof S!="string"||!bt(e,{settings:se(e).settings}).some(({id:n})=>n===S))throw st(_e("\u6CA1\u6709\u8FD9\u4E2A\u5757\u5305"));return await $t(e,{pack:S,enabled:b}),a(),t()}let m=o(s);if(m)throw st(m);let{net:l,...p}=s,k=l===void 0?void 0:l?yo(se(e).packages.get(s.id)?.needs):[];return await $t(e,{...p,...k?{net:k}:{}}),a(),t()},install:({path:s,zip:m}={})=>{let l=typeof m=="string"?Mn(Buffer.from(m,"base64")):typeof s=="string"&&s.trim()?Wn(s):null;if(!l)throw st(_e("\u7C98\u8D34\u5757\u5305\u7684\u6587\u4EF6\u5939\u6216 zip \u7684\u8DEF\u5F84"),{code:"path"});let p=sn(e,l);return a(),{...t(),installed:p}}}}import Cr from"node:path";import{reportsDirectory as _r}from"../browser/shared/paths.mjs";import{layoutOf as Pr}from"../browser/shared/workspace.mjs";async function xo(e,a,{root:t=_r,workspace:o=null}={}){let{exports:i}=Pr(t),f=Cr.join(i,`${a}.html`),s=await Qe([a],t),m=await e.handInReport(a,{reader:!0});if(!m.ok)return{problems:[],refused:{reason:m.reason,message:m.message},file:f};if(m.repeated.length)return{problems:Ze(m.repeated),file:f};let{exported:l,failures:p}=await On([a],{workspace:o,directory:t});return await s.keep(l.map(k=>k.slug)),{problems:p.get(a)??[],file:f}}import $o from"node:fs/promises";import So from"node:path";import{MEDIA_ROUTES as bo,assetFile as jr,extensionOf as Tr,imageFile as Rr,mediaTypeOf as Fr}from"../browser/shared/media.mjs";import{serveFound as Eo}from"../browser/shared/http.mjs";import{slugPattern as Oo}from"../browser/shared/reports.mjs";import{pageFiles as Lr}from"../browser/shared/pages.mjs";import{documentDirectory as Ar}from"../browser/shared/workspace.mjs";var Nt={asset:e=>({"Content-Type":Fr(e),"Cache-Control":"no-cache"}),file:()=>({"Content-Type":"application/octet-stream","Content-Disposition":"attachment","X-Content-Type-Options":"nosniff","Cache-Control":"no-cache"}),embed:e=>/\.pdf$/i.test(e)?{"Content-Type":"application/pdf","X-Content-Type-Options":"nosniff","Cache-Control":"no-cache"}:{"Content-Type":"text/html; charset=utf-8","Content-Security-Policy":"sandbox allow-scripts allow-popups allow-forms allow-modals","X-Content-Type-Options":"nosniff","Cache-Control":"no-cache"}},Ir=new RegExp(`^/__gallery/edit/(${Object.keys(bo).join("|")})/([^/]+)/(assets/[^/]+)$`);async function Co(e,a,{reportsDirectory:t}){let[,o,i,f]=Ir.exec(e)??[];if(!o)return!1;let s=Oo.test(i)&&bo[o](f)?await $o.readFile(So.join(Ar(i,t),f)).catch(()=>null):null;return Eo(a,s,{headers:Nt[o](f)}),!0}var Nr={css:"text/css; charset=utf-8",js:"text/javascript; charset=utf-8",mjs:"text/javascript; charset=utf-8"},Dr=/^\/pages\/([^/]+)\/(assets\/[^/]+)$/;async function _o(e,a,{reportsDirectory:t}){let[,o,i]=Dr.exec(e)??[];if(!o)return!1;let f=Oo.test(o)&&jr(i)?await $o.readFile(So.join(Lr(o,t).folder,i)).catch(()=>null):null,s=Nr[Tr(i??"")];return Eo(a,f,{headers:s?{"Content-Type":s,"X-Content-Type-Options":"nosniff","Cache-Control":"no-cache"}:(Rr(i)?Nt.asset:Nt.file)(i)}),!0}import Wr from"node:dns";import{sendJson as Ae}from"../browser/shared/http.mjs";import{createNetCache as Mr,dataOf as Ur}from"../browser/shared/net-cache.mjs";import{readKeys as Hr}from"../browser/shared/net-keys.mjs";import{addressKind as ct,addressOf as Io,hostIn as Po,keptHere as jo,keyIn as To,mapsHere as Br,netHostsOf as zr,proxyHere as Gr,withKey as Kr}from"../browser/shared/net-policy.mjs";import{galleryVersion as Jr}from"../browser/shared/preview-server.mjs";var it=512*1024,Yr=6e4,Ro=20,Fo=5,Lo=1e4,Xr=16*1024,Vr=new Set([301,302,303,307,308]),Zr=/^(?:application\/(?:[\w.-]+\+)?json|text\/[\w.+-]+)$/i,$e=(e,a={})=>({ok:!1,code:e,...a}),ae=(e,a={},t)=>Object.assign(new Error(e),{refusal:$e(e,a),...t===void 0?{}:{detail:t}});function Qr(e,a){let t;try{t=new URL(e,a)}catch{return{code:"url",why:"a redirect to an address that does not parse"}}let o=Io(t.href);return o.code?{code:"url",why:`a redirect to ${t.host?`${t.protocol}//${t.host}`:t.protocol}: ${o.why}`}:o}function Ao(e,a){let t=[...new Set([a,encodeURIComponent(a)])].filter(Boolean),o=i=>typeof i=="string"?t.reduce((f,s)=>f.split(s).join("{key}"),i):i;return Object.fromEntries(Object.entries(e).map(([i,f])=>[i,o(f)]))}var qr=e=>Wr.promises.lookup(e,{all:!0,verbatim:!0}),Dt=e=>URL.parse(e)?.host||"?",Wt=e=>ct(e)==="fake-ip"?"an address a fake-ip proxy's DNS gives":"an address of this computer or of a private network";async function es(e,{resolve:a,proxy:t}){let o=e.hostname,i=Gr(t),f=c=>{let v=ct(c);return v==="public"||v==="fake-ip"&&i},s=o.replace(/^\[|\]$/g,"");if(ct(s)!=="none"){if(f(s))return{address:s};throw ae("private",{host:o,address:s,why:`${s} is ${Wt(s)}`})}let m;try{m=(await a(o)).map(c=>typeof c=="string"?c:c.address)}catch(c){throw ae("offline",{why:`${o} did not resolve (${c.code??c.message})`})}if(m.length===0)throw ae("offline",{why:`${o} did not resolve`});let l=m.filter(c=>!f(c));if(l.length===0)return{address:m[0]};let p=l.filter(c=>!Br(c)),k=p.length?p:l,S=k.find(c=>!c.includes(":"))??k[0],b=`${o} resolved to ${S}, ${Wt(S)}`,n=jo(o)?"and its name is one kept for this computer (localhost)":t?i?e.protocol!=="https:"?"and an http address is never handed to a proxy by its name (no TLS to check the site)":p.length?"and a private network's address is never handed to a proxy by its name (that network's own machines are there)":null:"and the proxy it goes through is not on this computer":"and no proxy of this computer goes between to reach it by its name";if(n===null)return{address:null,resolved:S,said:b};throw ae("private",{host:o,address:S,why:`${b}, ${n}`},i||!t||jo(o)?void 0:`${b}, and the proxy it goes through (${Dt(t)}) is not on this computer`)}var ts=({resolve:e=qr,proxyFor:a=Cn,connect:t,ca:o}={})=>async(i,{headers:f,signal:s})=>{let m=await a(i.href),l=await es(i,{resolve:e,proxy:m}),{address:p}=l,k={...t?{connect:t}:{},...o?{ca:o}:{}};try{return await qe(i,{address:p,proxy:m,headers:f,signal:s,...k})}catch(S){if(!(m&&S.proxyFailed&&(p!==null||S.code==="ECONNREFUSED")))throw p===null&&!s?.aborted?ae("offline",{why:`${l.said}, and no site the proxy of this computer reached by its name proved to be it`},`${l.said}, handed by its name to the proxy (${Dt(m)}): ${S.code??S.message}`):S;let b=c=>`and the proxy of this computer that would reach it${c?` (${Dt(m)})`:""} is not running`,n=p===null?l.said:`${i.hostname.replace(/^\[|\]$/g,"")===p?p:`${i.hostname} resolved to ${p}`}, ${Wt(p)}`;if(p===null||ct(p)!=="public")throw ae("private",{host:i.hostname,address:p??l.resolved,why:`${n}, ${b(!1)}`},`${n}, ${b(!0)}`);return qe(i,{address:p,proxy:null,headers:f,signal:s,...k})}},No=e=>(a,{headers:t,signal:o})=>qe(new URL(`http://127.0.0.1:${e}/${a.protocol.slice(0,-1)}/${a.host}${a.pathname}${a.search}`),{address:"127.0.0.1",headers:t,signal:o});async function ns(e){let a=0,t=[];for await(let o of e){if(a+=o.length,a>Xr)throw Object.assign(new Error("too-large"),{status:413});t.push(o)}return JSON.parse(Buffer.concat(t).toString("utf8"))}function os(e,a){let t=/;\s*charset="?([^";]+)"?/i.exec(a)?.[1];try{return new TextDecoder(t||"utf-8").decode(e)}catch{return new TextDecoder("utf-8").decode(e)}}function Do({root:e,catalog:a=()=>se(e),hop:t=null,now:o=Date.now,cache:i=Mr(e),log:f=()=>{}}){let s=t??ts(),m=new Map,l=c=>{let v=o(),P=(m.get(c)??[]).filter(h=>v-h<6e4);return P.length>=Ro?(m.set(c,P),!1):(m.set(c,[...P,v]),!0)},p={accept:"application/json, text/plain;q=0.9, text/*;q=0.8","user-agent":`Gallery/${Jr} (a custom block's card)`};async function k(c,{hosts:v,allowed:P,key:h}){let M=AbortSignal.timeout(Lo),x=c;for(let $=0;;$++){let C;try{C=await s(h===void 0?x:new URL(Kr(x.href,h)),{headers:p,signal:M})}catch(E){throw E.refusal?E:ae("offline",{why:M.aborted?`no answer within ${Lo/1e3} s`:String(E.code??E.message)})}if(Vr.has(C.status)&&C.headers.get("location")){if(C.body?.cancel().catch(()=>{}),$>=Fo)throw ae("status",{status:C.status,why:`more than ${Fo} redirects`});let E=Qr(C.headers.get("location"),x);if(E.code)throw ae("url",{why:E.why});let U=Po(E.url.hostname,v);if(!U)throw ae("host",{host:E.url.hostname,why:`a redirect to ${E.url.hostname}, which the block's needs do not name`});if(!P.includes(U))throw ae("consent",{hosts:v.filter(J=>!P.includes(J))});x=E.url,h=To(x.href)?h:void 0;continue}if(C.status<200||C.status>299)throw C.body?.cancel().catch(()=>{}),ae("status",{status:C.status});let w=C.headers.get("content-type")??"",j=w.split(";")[0].trim();if(j&&!Zr.test(j))throw C.body?.cancel().catch(()=>{}),ae("type",{type:j});if(Number(C.headers.get("content-length"))>it)throw C.body?.cancel().catch(()=>{}),ae("too-large",{limit:it});let L;try{L=C.body?await _n(C,it):Buffer.alloc(0)}catch(E){throw ae("offline",{why:String(E.code??E.message)})}if(L===null)throw ae("too-large",{limit:it});return{type:j||"text/plain",text:os(L,w)}}}let S=(c,v,P)=>{let h=Ur(c,v);return h===void 0?$e("type",{why:"the answer is no JSON"}):{ok:!0,data:h,at:c.at,cached:P}};async function b(c){let{block:v,url:P,as:h="json",doc:M=null}=c??{},x=typeof v=="string"?a().packages.get(v):null;if(!x)return $e("missing",{why:"no custom block of that id loads in this workspace"});let $=zr(x.needs);if(h!=="json"&&h!=="text")return $e("url",{why:'as is "json" or "text"'});let C=Io(P);if(C.code)return $e("url",{why:C.why});let{url:w}=C,j=Po(w.hostname,$);if(!j)return $e("host",{host:w.hostname,why:$.length?`its needs name ${$.join(", ")}`:"its needs name no host of the net"});let L=a().settings.net?.[v]??[];if(!L.includes(j))return $e("consent",{hosts:$.filter(T=>!L.includes(T))});let E;if(To(w.href)){let T=Hr(e);if(E=T[w.hostname]??T[j],E===void 0)return $e("key",{host:w.hostname})}let U=w.href,J=i.get(U);if(i.used(U,M,h),J&&o()-Date.parse(J.at)<Yr)return S(J,h,!0);if(!l(v))return J?S(J,h,!0):$e("rate",{why:`more than ${Ro} fetches in a minute`});try{let{type:T,text:G}=await k(w,{hosts:$,allowed:L,key:E});return S(i.put(U,{type:T,text:G,at:new Date(o()).toISOString()}),h,!1)}catch(T){if(!T.refusal)throw T;if(J&&T.refusal.code!=="consent")return S(J,h,!0);let G=E===void 0?T.refusal:Ao(T.refusal,E),Z=T.detail===void 0?G.why:E===void 0?T.detail:Ao({why:T.detail},E).why;return(G.code!=="offline"||T.detail!==void 0)&&f(`${v}: ${w.hostname} refused (${G.code}${Z?`: ${Z}`:""})`),G}}async function n(c,v){if(c.method!=="POST")return Ae(v,405,{ok:!1,reason:"method"});if(c.headers.origin!==`http://${c.headers.host}`)return Ae(v,403,{ok:!1,reason:"origin"});if(!/^application\/json\b/i.test(c.headers["content-type"]??""))return Ae(v,415,{ok:!1,reason:"type"});let P;try{P=await ns(c)}catch(h){return Ae(v,h.status??400,{ok:!1,reason:"body"})}try{return Ae(v,200,await b(P))}catch(h){return Ae(v,500,{ok:!1,code:"offline",why:h.message})}}return{handle:n,answer:b,cache:i}}import{walk as as,attr as Mt}from"../browser/shared/html-tree.mjs";import{workspaceAddress as Ut}from"../browser/shared/workspace-address.mjs";function lt(e,a){if(!a)return e;let t=hn(e),o=Je(e,s=>Ut(s,a)!==s,t),i=Ye(o,s=>Ut(s.value,a)),f=s=>s.replace(/(["'`])(\/(?:__gallery\/(?:edit\/(?:v\/[a-f0-9]{16}\/)?src\/|components\/)|__gallery\/|generated\/|pages\/))/g,(m,l,p)=>l+Ut(p,a));return as(t,s=>{if(s.tagName==="script"&&(Mt(s,"data-doc-dev")!==void 0||Mt(s,"data-doc-package")!==void 0)&&!Mt(s,"src")){let m=s.sourceCodeLocation?.startTag?.endOffset,l=s.sourceCodeLocation?.endTag?.startOffset;m!==void 0&&l!==void 0&&i.push({start:m,end:l,text:f(e.slice(m,l))})}}),Ke(e,i)}function Wo({max:e=20}={}){let a=new Map;return{get(t,o,i){let f=`${t} ${o}`,s=a.get(f);return!s||s.text!==i?null:(a.delete(f),a.set(f,s),s.page)},set(t,o,i,f){let s=`${t} ${o}`;for(a.delete(s),a.set(s,{slug:t,text:i,page:f});a.size>e;)a.delete(a.keys().next().value)},clear(){a.clear()},forget(t){for(let[o,i]of a)i.slug===t&&a.delete(o)},get size(){return a.size}}}import{createHash as rs}from"node:crypto";import{readFileSync as ss}from"node:fs";import Mo from"node:fs/promises";import is from"node:path";import{release as cs,releaseFile as ls}from"../browser/shared/paths.mjs";async function dt(e){let a=await Promise.all(e.map(o=>Mo.stat(o).then(({mtimeMs:i,size:f})=>`${i} ${f}`,()=>"none"))),t=rs("sha256");return e.forEach((o,i)=>t.update(`${o}\0${a[i]}
|
|
80
|
+
`)),t.digest("hex").slice(0,16)}function Uo(e,a){let t=null,o=async()=>(await Promise.all(e.map(async i=>(await Mo.readdir(i,{recursive:!0,withFileTypes:!0}).catch(()=>[])).filter(s=>s.isFile()).map(s=>is.join(s.parentPath,s.name))))).flat().filter(a).sort();return{files:()=>t??=o(),changed:()=>{t=null}}}var Ht=cs?JSON.parse(ss(ls,"utf8")).stamps:null;var gt=oa.source.slice(1,-1),Ls=new RegExp(`^/generated/(${gt})\\.html$`),As=new RegExp(`^/(${gt})/(?:doc|report)\\.html$`),Is=new RegExp(`^/pages/(${gt})$`),Ns=new RegExp(`^/__gallery/pages/(${gt})/(cards|library|hint)$`),Gt="/__gallery/events",Re=ds,ra=/^\/__gallery\/edit\/(v\/[a-f0-9]{16}\/)?src\/((?:shared(?:\/components|\/emoji|\/i18n)?\/|editor\/(?:page|components)(?:\/[a-z]+(?:-[a-z]+)*){0,2}\/(?!files?\.mjs))[a-z]+(?:-[a-z]+)*\.mjs)$/,Ds=/^\/__gallery\/edit\/(?:v\/[a-f0-9]{16}\/)?src\/(shared\/emoji\/data\/[a-z]+(?:-[a-z]+)*\.(json|bin))$/,ut=[X.join(Re,"editor","page"),X.join(Re,"editor","components"),X.join(Re,"shared")],Ws=e=>ra.test(`/__gallery/edit/src/${X.relative(Re,e).split(X.sep).join("/")}`);var Ms=[na,X.join(Re,"shared","components")],vd=[na,...ut],Ue={"Cache-Control":"no-store"},qo={"Cache-Control":"max-age=31536000, immutable"},Bt=(e,a,t)=>zt(e,{type:a,headers:{...Ue,...us},body:t});function Us(e){let a=e.headers?.host??"",t=e.socket?.localPort;return!!t&&(a===`127.0.0.1:${t}`||a===`localhost:${t}`)}function Hs(e){if(e.method!=="GET"&&e.method!=="HEAD")return null;let a=e.socket?.localPort;if(!a||e.headers?.host!==`localhost:${a}`)return null;let t=new URL(e.url||"/","http://localhost");return t.pathname==="/"||t.pathname==="/index.html"?`http://127.0.0.1:${a}${t.pathname}${t.search}`:null}var sa=`window.addEventListener("doc-net-fetch", (event) => {
|
|
81
|
+
event.preventDefault();
|
|
82
|
+
event.detail.answer(fetch("/__gallery/net", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(event.detail.ask) }).then((response) => response.json()));
|
|
83
|
+
});`,ia=`let lost = false;
|
|
84
|
+
events.onerror = () => { lost = true; };
|
|
85
|
+
events.onopen = () => {
|
|
86
|
+
if (!lost) return;
|
|
87
|
+
lost = false;
|
|
88
|
+
for (const kind of ${JSON.stringify(Ts)}) window.dispatchEvent(new CustomEvent("doc-workspace-change", { detail: kind }));
|
|
89
|
+
};`,Bs=(e,a,t)=>`<script data-doc-dev>
|
|
90
|
+
(() => {
|
|
91
|
+
document.currentScript.remove();
|
|
92
|
+
${sa}
|
|
93
|
+
const solo = new URLSearchParams(location.search).has("solo");
|
|
94
|
+
let catalog = "${t}";
|
|
95
|
+
const holds = (ids) => document.querySelector(ids === undefined ? "[${pt}]" : ids.split(",").map((id) => '[${pt}="' + id + '"]').join());
|
|
96
|
+
const events = new EventSource("${Gt}?slug=${e}");
|
|
97
|
+
${ia}
|
|
98
|
+
events.onmessage = (event) => {
|
|
99
|
+
const [kind, next, ids, more, consents, unlisted, packs] = event.data.split(" ");
|
|
100
|
+
if (kind === "notes") return void window.dispatchEvent(new CustomEvent("doc-annotations-changed", { detail: { version: next ?? "" } }));
|
|
101
|
+
if (kind === "changes") return void window.dispatchEvent(new CustomEvent("doc-changes-changed", { detail: { stamp: next ?? "" } }));
|
|
102
|
+
if (kind === "look") return void window.dispatchEvent(new CustomEvent("doc-look-request", { detail: { look: Object.fromEntries(new URLSearchParams(next ?? "")), from: "file" } }));
|
|
103
|
+
if (kind === "settings") return void window.dispatchEvent(new CustomEvent("doc-settings-changed", { detail: { hidden: next ? next.split(",") : [], disabled: ids ? ids.split(",") : [], shown: more ? more.split(",") : [], net: consents ? consents.split(",") : [], unlisted: unlisted ? unlisted.split(",") : [], packsOff: packs ? packs.split(",") : [] } }));
|
|
104
|
+
if (kind === "data") return void window.dispatchEvent(new CustomEvent("doc-workspace-change", { detail: next ?? "" }));
|
|
105
|
+
if (kind !== "report" && kind !== "assets" && kind !== "components") return;
|
|
106
|
+
if (kind === "components") {
|
|
107
|
+
if (document.readyState === "loading") return void document.addEventListener("DOMContentLoaded", () => events.onmessage(event), { once: true });
|
|
108
|
+
if (solo || next === catalog) return;
|
|
109
|
+
catalog = next;
|
|
110
|
+
if (!holds(ids)) return void window.dispatchEvent(new CustomEvent("doc-catalog-changed", { detail: { ids: ids === undefined ? null : ids.split(",").filter(Boolean) } }));
|
|
111
|
+
}
|
|
112
|
+
if (window.__galleryEditBusy) {
|
|
113
|
+
window.dispatchEvent(new CustomEvent({ report: "doc-source-changed", assets: "doc-assets-changed", components: "doc-components-changed" }[kind], { detail: { version: next ?? null } }));
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (kind === "report" && next === "${a}") return;
|
|
117
|
+
if (window.__galleryEditReload) return window.__galleryEditReload(); // in a workbench: swapped in, no reload seen
|
|
118
|
+
location.reload();
|
|
119
|
+
};
|
|
120
|
+
})();
|
|
121
|
+
</script>`,zs=(e,a,t)=>`<script>
|
|
122
|
+
(() => {
|
|
123
|
+
document.currentScript.remove();
|
|
124
|
+
${sa}
|
|
125
|
+
let catalog = "${t}";
|
|
126
|
+
const holds = (ids) => {
|
|
127
|
+
const named = ids === undefined ? "[${pt}]" : ids.split(",").filter(Boolean).map((id) => '[${pt}="' + id + '"]').join() || ":not(*)";
|
|
128
|
+
return Boolean(document.querySelector(named)) || [...document.querySelectorAll("template[data-ge-held]")].some((held) => held.content.querySelector(named));
|
|
129
|
+
};
|
|
130
|
+
const again = () => (window.__galleryEditReload ? window.__galleryEditReload() : location.reload());
|
|
131
|
+
const events = new EventSource("${Gt}?page=${e}");
|
|
132
|
+
${ia}
|
|
133
|
+
events.onmessage = (event) => {
|
|
134
|
+
const [kind, next, ids, more, consents, unlisted, packs] = event.data.split(" ");
|
|
135
|
+
if (kind === "page") return void (window.__galleryPageChanged ? window.__galleryPageChanged(next) : next !== "${a}" && again());
|
|
136
|
+
if (kind === "assets") return void again();
|
|
137
|
+
if (kind === "settings") return void window.dispatchEvent(new CustomEvent("doc-settings-changed", { detail: { hidden: next ? next.split(",") : [], disabled: ids ? ids.split(",") : [], shown: more ? more.split(",") : [], net: consents ? consents.split(",") : [], unlisted: unlisted ? unlisted.split(",") : [], packsOff: packs ? packs.split(",") : [] } }));
|
|
138
|
+
if (kind === "data") return void window.dispatchEvent(new CustomEvent("doc-workspace-change", { detail: next ?? "" }));
|
|
139
|
+
if (kind !== "components") return;
|
|
140
|
+
if (document.readyState === "loading") return void document.addEventListener("DOMContentLoaded", () => events.onmessage(event), { once: true });
|
|
141
|
+
if (next === catalog) return;
|
|
142
|
+
catalog = next;
|
|
143
|
+
if (holds(ids)) again();
|
|
144
|
+
};
|
|
145
|
+
})();
|
|
146
|
+
</script>`;function ea(e,a){let t=X.relative(e,a).split(X.sep);if(t[0]===".."||X.isAbsolute(t[0])||t[0]==="")return null;if(t.length===1&&t[0]===ht)return{slug:null,name:ht,packages:!0};let o=l=>process.platform==="win32"?l.toLowerCase():l;if(o(t[0])===vs&&t.length>=2&&js(t[1])&&!Jo.includes(t[1])){let l=t.slice(2);return l.some(p=>p.startsWith("."))?null:{extension:t[1],name:l.length===1?l[0]:null}}if(o(t[0])===xs&&t.length>=2&&aa(t[1])&&!Jo.includes(t[1])){let l=t.slice(2);return l.some(p=>p.startsWith("."))?null:{page:t[1],name:l.length===1?l[0]:null}}let i=t[0]===".gallery"&&t[1]==="pages"&&t.length>=3,[f,...s]=i?t.slice(2):t,m=!i&&o(f)===Ko;return!(m||oa.test(f))||f==="exports"||s.some(l=>l.startsWith("."))?null:{slug:m?Ko:f,name:s.length===1?s[0]:null,...m?{packages:m}:{}}}function It(e){let a=S=>process.platform==="win32"?X.resolve(S).toLowerCase():X.resolve(S),{gallery:t,preferencesPage:o,exports:i,extensions:f}=Me(e),[s,m,l,p]=[a(t),a(o),a(i),a(f)],k=(S,b)=>S===b||S.startsWith(b+X.sep);return S=>{let b=a(S);return k(b,p)&&b!==p&&b.slice(p.length+1).split(X.sep).some((n,c)=>c>0&&(n==="node_modules"||n===".git"))?!0:k(b,s)&&b!==s&&!k(b,m)||k(b,l)}}var ta=`<script data-doc-dev>document.currentScript.remove(); globalThis.${Fs} = ${JSON.stringify(Rs)};</script>`,ue=(e,a,t)=>new RegExp(`</${a}>`,"i").test(e)?e.replace(new RegExp(`</${a}>`,"i"),()=>` ${t}
|
|
147
|
+
</${a}>`):`${e}
|
|
148
|
+
${t}`;function Kt({token:e=null,unified:a=!1,base:t="",reportsDirectory:o=ms,stateDirectory:i=Me(o).state,projects:f=void 0,onWorkspaceChange:s=()=>{},announceServer:m=!0,logger:l=console,kind:p="dev",workbenchPage:k=null,closeServer:S=async()=>{},exit:b=()=>process.exit(0)}={}){let n=new Set,c=(r,d="",u="report")=>{for(let _ of n)(!r||_.slug===r)&&_.response.write(`data: ${r?`${u} ${d}`:"assets"}
|
|
149
|
+
|
|
150
|
+
`)},v=(r,d)=>{for(let u of n)u.page===r&&u.response.write(`data: page ${d}
|
|
151
|
+
|
|
152
|
+
`)},P=()=>{K("workspace",()=>{for(let r of n)r.workspace&&r.response.write(`data: workspace ${Date.now()}
|
|
153
|
+
|
|
154
|
+
`)})},h=()=>{P(),s(o)},M=r=>c(r,String(Date.now()),"changes"),x=Fn({base:t,token:e,reportsDirectory:o,stateDirectory:i,finish:Ve,log:r=>l.info?.(`[gallery] ${r}`),onChanges:M}),$=(r,d,u,{lang:_=null,page:W=!1}={})=>un(r,d,u,{directory:o,blank:!0,lang:_,page:W}),C=i?Jn({file:X.join(i,"activity.json")}):null,w=Nn({root:o,read:In(x),activity:C,draw:(r,d)=>Pe(r,{slug:d,mode:"words",reportsDirectory:o})}),j=new Set,L=r=>{for(let d of r)j.add(d);j.size!==0&&K("data",()=>{let d=[...j];j.clear();for(let u of n)if(u.slug||u.page)for(let _ of d)u.response.write(`data: data ${_}
|
|
155
|
+
|
|
156
|
+
`)})},E=r=>X.resolve(X.dirname(ft(r,o)))===X.resolve(o),U=null,J=null,T=()=>J??=(async()=>{for(let r of n)r.response.end();n.clear(),await Promise.race([S().catch(()=>{}),new Promise(r=>setTimeout(r,3e3))]),await C?.close(),await U?.().catch(()=>{}),await Z.close(),b()})(),G=Dn({reportsDirectory:o,projects:f,unified:a,server:{kind:p,version:hs,stop:T},edits:x,reports:{create:$,export:r=>xo(x,r,{root:o,workspace:d=>w.snapshot(d)}),words:(r,d)=>Pe(r,{slug:d,mode:"words",reportsDirectory:o})},components:vo({root:Te(),taken:()=>ne.taken()}),changed:h,index:w,web:{frameable:Pn,title:jn,icon:r=>Tn(r)}}),Z=mo({edits:x,workspace:G,reports:{create:$},reportsDirectory:o,offline:r=>En({...r,directory:o,workspace:d=>w.snapshot(d)})}),g=Do({root:Te(),hop:process.env.GALLERY_TEST_NET?No(Number(process.env.GALLERY_TEST_NET)):null,log:r=>l.info?.(`[gallery] ${r}`)}),y=dn({root:Te(),edits:x,stateDirectory:Me(Te()).state,catalogTaken:()=>ne.taken(),log:r=>l.info?.(`[gallery] ${r}`),shown:(r,d)=>lt(Pt(r,d),t)}),A=(r,d,{present:u=!1,editorModule:_,kit:W}={})=>{let O=d,ce="",oe="",de=!0;try{u||({html:O,snippet:ce,head:oe}=x.preview(r,d,{editor:_,kitTags:fe=>yn(fe,W)}))}catch(fe){de=!1,l.warn(`[gallery] text editing unavailable for ${r}: ${fe.message}`)}if({html:O}=xn(O,{slug:r,mode:"preview",reportsDirectory:o,kit:W}),O=ue(O,"head",Bs(r,We(d),se().stamp)),O=ue(O,"head",`<script data-doc-dev>${Bo()}</script>`),O=ue(O,"head",ta),oe&&(O=ue(O,"head",oe)),u)return{html:ue(O,"head",`<style data-doc-present>.doc-display { display: none !important; }</style>
|
|
157
|
+
<script type="module" src="/__gallery/edit/src/editor/page/present-links.mjs" data-doc-dev></script>`),whole:de};let ke="";try{ke=to(r,d,{},{directory:ft(r,o)})}catch(fe){de=!1,l.warn(`[gallery] checks unavailable for ${r}: ${fe.message}`)}return ke&&(O=ue(O,"body",ke)),{html:ce?ue(O,"body",ce):O,whole:de}},R=Wo(),I=Uo(ut,Ws),N=r=>{let d=ft(r,o);return[d,X.join(d,"assets")]},B=()=>Ht?.editor??I.files().then(dt),z=r=>Ht?.kit?.[r.id]??dt([Ct(r)]),H=async(r,d,{present:u})=>{let[_,W,O]=await Promise.all([u?"":B(),Promise.all(Fe.map(z)),dt(N(r))]),ce=[u?"present":_,...W,O,se().stamp,`look:${zo(Go(r,o))}`].join(" "),oe=R.get(r,ce,d);if(oe!==null)return u||x.opened(d),oe;let de=new Map(Fe.map((he,be)=>[he,W[be]])),ke=u?void 0:`/__gallery/edit/v/${_}/src/editor/page/editor.mjs`,{html:fe,whole:le}=A(r,d,{present:u,editorModule:ke,kit:he=>`${Xe(he)}?v=${de.get(he)}`}),Se=lt(fe,t);return le&&R.set(r,ce,d,Se),Se},Q=async r=>{let d=Vo(r,o),[u,_]=await Promise.all([we.readFile(d.html,"utf8").catch(()=>null),we.readFile(d.json,"utf8").catch(()=>"")]);if(u===null)return null;let[W,O]=await Promise.all([B(),Promise.all(Fe.map(z))]),ce=new Map(Fe.map((F,Oe)=>[F,O[Oe]])),oe=se(),de=Zo(u,_),ke=ln(u,{blockOf:F=>Ot(oe,F)}),fe=Object.fromEntries([...new Set(Et(u).cards.map(({block:F})=>F).filter(Boolean))].map(F=>[F,Ot(oe,F)])),{html:le}=eo(ke,{reportsDirectory:o,slug:r,kit:F=>`${Xe(F)}?v=${ce.get(F)}`}),Se=_s(r,o),he=Cs(r,o),be=Se?.defaultCards===!0,ze=Es(u),Ge=F=>oe.packages.get(F)?.name??en().find(Oe=>Oe.id===F)?.title??null,Ee=be?bs(o,Et(u).cards.map(({block:F})=>F)).map(F=>({block:F,name:Ge(F)})):[],De=JSON.stringify({slug:r,title:Se?.title??r,token:x.token,version:de,blocks:fe,...he?{hint:he}:{},...be?{defaults:be}:{},...Ee.length?{news:Ee}:{},...ze?{blank:ze}:{}}).replace(/</g,"\\u003c");return le=ue(le,"head",`<script type="application/json" data-ge-page data-doc-dev>${De}</script>`),le=ue(le,"head",zs(r,de,oe.stamp)),le=ue(le,"head",`<script data-doc-dev>${Bo()}</script>`),le=ue(le,"head",ta),ue(le,"head",`<script type="module" src="/__gallery/edit/v/${W}/src/editor/page/custom-page.mjs" data-doc-dev></script>`)};async function q(r,d,u){try{if(!Us(r))return Ho(d,403,{ok:!1,reason:"host"});let _=Hs(r);if(_)return zt(d,{status:302,headers:{Location:_,...Ue}});let W=new URL(r.url||"/","http://localhost"),O=decodeURI(W.pathname);if(O===Gt){d.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-store",Connection:"keep-alive"}),d.write(`retry: 3000
|
|
158
|
+
|
|
159
|
+
`);let F={slug:W.searchParams.get("slug"),page:W.searchParams.get("page"),workspace:W.searchParams.has("workspace"),response:d};n.add(F);let{stamp:Oe,settings:$a}=se();d.write(`data: components ${Oe}
|
|
160
|
+
|
|
161
|
+
`),d.write(`data: ${St($a)}
|
|
162
|
+
|
|
163
|
+
`),r.on("close",()=>n.delete(F));return}if(O==="/__gallery/net")return g.handle(r,d);if(O==="/__gallery/edit/commit")return x.commit(r,d);if(O==="/__gallery/edit/reverted")return x.reverted(r,d);if(O==="/__gallery/edit/hand-in")return x.handInRequest(r,d);if(O==="/__gallery/edit/settle")return x.settleRequest(r,d);if(O==="/__gallery/edit/round")return x.roundRequest(r,d);if(O==="/__gallery/edit/upload")return x.upload(r,d);if(O==="/__gallery/edit/unfurl")return x.unfurl(r,d);if(O==="/__gallery/edit/emoji-library"){if(r.method==="POST")return x.addEmoji(r,d);let[F,Oe]=await x.listEmojis();return Ho(d,F,Oe)}if(O==="/__gallery/edit/icon"){let F=gn({value:W.searchParams.get("value")??"",slug:W.searchParams.get("slug"),tab:W.searchParams.has("tab")});return Ie(d,F?.body,{type:F?.type,headers:{"Cache-Control":"max-age=31536000, immutable"}})}if(await Co(O,d,{reportsDirectory:o})||await _o(O,d,{reportsDirectory:o})||await go(O,W.searchParams.get("v"),d,{root:Te()}))return;let ce=O.match(/^\/__gallery\/edit\/emoji-library\/([^/]+)$/)?.[1];if(ce){let F=await x.readEmoji(ce);return Ie(d,F?.body,{type:F?.type,headers:{"Cache-Control":"no-cache"}})}if(O==="/__gallery/edit/frameable")return x.frameable(r,d);if(O==="/__gallery/edit/annotations")return x.annotations(r,d);if(O==="/__gallery/edit/changes")return x.changes(r,d);let oe=O.match(/^\/__gallery\/transfer\/([a-z]+)$/)?.[1];if(oe)return Z.handle(r,d,oe);let[,de,ke]=O.match(Ns)??[];if(de)return y.handle(r,d,de,ke);let fe=O.match(/^\/__gallery\/workspace\/([a-z]+(?:-[a-z]+)*)$/)?.[1];if(fe)return G.handle(r,d,fe);let[,le,Se]=O.match(ra)??[];if(Se){let F=await we.readFile(X.join(Re,Se),"utf8").catch(()=>null);return Ie(d,F,{type:"text/javascript; charset=utf-8",headers:le?qo:Ue})}let he=W.searchParams.has("v")&&Fe.find(F=>Xe(F)===O);if(he){let F=await we.readFile(Ct(he)).catch(()=>null);return Ie(d,F,{type:O.endsWith(".css")?"text/css; charset=utf-8":"text/javascript; charset=utf-8",headers:qo})}if(O==="/__gallery/edit/mhchem.js"){let F=await we.readFile(wn).catch(()=>null);return Ie(d,F,{type:"text/javascript; charset=utf-8",headers:Ue})}let[,be,ze]=O.match(Ds)??[];if(be){let F=await we.readFile(X.join(Re,be)).catch(()=>null);return Ie(d,F,{type:ze==="json"?"application/json; charset=utf-8":"application/octet-stream",headers:{"Cache-Control":"max-age=86400"}})}if(k&&(O==="/"||O==="/index.html"))return Bt(d,"text/html; charset=utf-8",await k(W.pathname,r));let Ge=O.match(Is)?.[1];if(Ge){let F=await Q(Ge);return F===null?u():Bt(d,"text/html; charset=utf-8",lt(F,t))}let Ee=O.match(Ls)?.[1];if(!Ee){let F=O.match(As)?.[1];return aa(F)&&await we.access($s(ft(F,o)).html).then(()=>!0,()=>!1)?zt(d,{status:302,headers:{Location:`${t}/generated/${F}.html${W.search}`,...Ue}}):u()}let De=await x.readTaken(Ee);if(De===null)return u();W.searchParams.has("present")||x.noteTaken(Ee,De.source).then(F=>F&&M(Ee),()=>{}),Bt(d,"text/html; charset=utf-8",await H(Ee,De.text,{present:W.searchParams.has("present")}))}catch(_){u(_)}}let te=new Map,K=(r,d)=>{clearTimeout(te.get(r)),te.set(r,setTimeout(d,120))},D=r=>{ys(r,o).reads&&c(r,zo(Go(r,o)),"look")},Y=uo({settled:x.settled,async tell(r,d){let u=await x.read(r,d.source).catch(_=>(l.error(`[gallery] ${r}: ${_.message}`),{version:We(d.source??"")}));if(c(r,u?.version??We("")),E(r)){let _=x.writerOf(r,d.source)??"agent";w.changed(r,{source:d.source??null,text:u?.text??null,by:_}).then(L,W=>l.error(`[gallery] ${r}: its facts not read: ${W.message}`))}x.noteTaken(r,d.source).then(_=>_&&M(r),_=>l.error(`[gallery] ${r}: the Agent's changes not kept: ${_.message}`)),x.checkAnnotations(r).catch(_=>l.error(`[gallery] ${r}: annotations not checked: ${_.message}`))}}),re=({id:r,problem:d,off:u})=>u||l.warn(`[gallery] custom block ${r} does not load: ${Yt("en",d)}`),ne=zn({root:Te(),tell({stamp:r,problems:d,settings:u},_){for(let W of _)d.has(W)&&re(d.get(W));for(let{response:W}of n)W.write(`data: components ${r} ${_.filter(O=>ks.test(O)).join(",")}
|
|
164
|
+
|
|
165
|
+
`),W.write(`data: ${St(u)}
|
|
166
|
+
|
|
167
|
+
`)}});for(let r of se().problems.values())re(r);w.start().then(r=>r>0&&L(["activity"]));let ye=It(o),pe=Qo(o).then(r=>r.join("/"),()=>""),kt=!1,vt=r=>{kt||=r===mt,K("extensions",async()=>{let d=kt;kt=!1;let u=await pe;pe=Qo(o).then(_=>_.join("/"),()=>u),(d||await pe!==u)&&h()})},Be=Te(),wa=Me(Be).extensions,ya=t?null:Le(Be,(r,d)=>{if(gs(d,Me(Be).outline)){h();return}let u=X.relative(d,wa);if(r==="reset"||u===""||!u.startsWith("..")&&!X.isAbsolute(u)){vt(mt);return}let _=ea(Be,d);_?.extension&&(_.name===mt||_.name===null)&&vt(_.name)},{extensionsOnly:!0,outline:!0}),xt=(r,d)=>!fs&&d.some(u=>r.startsWith(u+X.sep));function ka(r,d){if(r==="reset"){R.clear(),I.changed(),ne.changed(),h();return}if(ye(d))return;let u=ea(o,d);if(u?.page){let{page:_,name:W}=u;W&&Os(W)&&K(`page:${_}`,async()=>{let O=Vo(_,o),[ce,oe]=await Promise.all([we.readFile(O.html,"utf8").catch(()=>null),we.readFile(O.json,"utf8").catch(()=>"")]);ce!==null&&v(_,Zo(ce,oe))}),(W===Xo.json||W===Xo.html&&/^(add|unlink)$/.test(r)||W===null&&/^(add|unlink)Dir$/.test(r))&&h();return}if(u?.extension){(u.name===mt||u.name===null)&&vt(u.name);return}if(u?.packages&&ne.changed(),u?.name===ht&&u.slug===null&&K("look:*",()=>new Set([...n].map(({slug:_})=>_).filter(Boolean)).forEach(D)),u?.name===ht&&u.slug===null&&h(),u?.slug&&!(u.name&&Ss(u.name))&&R.forget(u.slug),u&&(/^(doc|report)\.json$/.test(u.name??"")||/^(add|unlink)Dir$/.test(r)&&u.name===null)&&R.clear(),u?.slug&&!u.packages&&u.name===null&&/^(add|unlink)Dir$/.test(r)&&E(u.slug)&&(w.forget(u.slug),L(["todos","recent","stats"])),u?.slug&&!(u.packages&&u.name===null)&&(/^(doc|report)\.json$/.test(u.name??"")||/^(add|unlink)Dir$/.test(r)&&u.name===null||/^(add|unlink)$/.test(r)&&Yo(u.name??""))&&h(),u?.slug&&!u.packages&&u.name===Ps&&h(),/^(add|unlink)(Dir)?$/.test(r)&&xt(d,ut)&&I.changed(),u?.name&&(Yo(u.name)||/^(doc|report)\.json$/.test(u.name))){if(Y(u.slug),/^(doc|report)\.json$/.test(u.name)){let{slug:_}=u;K(`look:${_}`,()=>D(_))}}else if(u?.name==="annotations.json"){let{slug:_}=u;K(`notes:${_}`,async()=>{let W=await we.readFile(d,"utf8").catch(()=>null);c(_,W===null?"":We(W),"notes")})}else xt(d,Ms)?K("kit",async()=>{try{await bn({fresh:!0}),c()}catch(_){l.error(`[gallery] shared kit rebuild failed: ${_.message}`)}}):xt(d,ut)&&K("editor",()=>c())}async function va(r){m&&(U=await ps({home:o,port:r,token:x.token,kind:p})),await ws(o)}async function xa(){for(let r of n)r.response.end();n.clear(),ya?.close();for(let r of te.values())clearTimeout(r);ne.close(),await C?.close(),await U?.().catch(()=>{}),U=null,await Z.close(),await x.drain()}return{handle:q,changed:ka,listening:va,close:xa,stop:T,edits:x,workspace:G,transfer:Z,refresh:P,get listeners(){return n.size},get workbenchListeners(){return[...n].filter(r=>r.workspace).length}}}import{forgetSnapshot as Ks,idsOf as Jt}from"../browser/shared/workspace-columns.mjs";import{isWorkspace as la,readRegistry as Js,registryFile as da,workspaceId as Ys,workspaceKey as He}from"../browser/shared/workspace-registry.mjs";import{layoutOf as Xs}from"../browser/shared/workspace.mjs";import{projectBase as fa,projectOfPath as Vs,localPath as Zs}from"../browser/shared/workspace-address.mjs";import{sendJson as ma}from"../browser/shared/http.mjs";function ua({reportsDirectory:e,watch:a=!0,...t}){let o=Rn(Gs().data),i=new Map,f=new Map,s=new Map,m=!1,l=He(e),p=w=>{Ks(w);for(let j of i.values())j.refresh()},k=new Map,S=new Map,b={touch:w=>{let j=Jt();for(let L of w.values())v(L,j).catch(E=>t.logger?.warn?.(`[gallery] ${E.message}`))},indexOf:async w=>(await v(w))?.workspace.index??null},n=Kt({...t,token:o,reportsDirectory:e,unified:!0,projects:b,onWorkspaceChange:p,closeServer:async()=>{await $(),await t.closeServer?.()}}),c=Qn({edits:n.edits});n.base="",i.set(l,n);async function v(w,j=null){if(m)return null;let L=Ys(w),E=He(w);if(E!==l){let U=(j??Jt()).get(L);if(!la(w)||U?.length!==1||He(U[0])!==E)return null}return k.set(E,Date.now()),i.has(E)?i.get(E):(f.has(E)||f.set(E,(async()=>{let U=Kt({...t,token:o,reportsDirectory:w,stateDirectory:Xs(w).state,base:fa(L),projects:b,onWorkspaceChange:p,announceServer:!1,workbenchPage:null});return U.base=fa(L),m?(await U.close(),null):(i.set(E,U),a&&s.set(E,Le(w,U.changed)),U)})().finally(()=>f.delete(E))),f.get(E))}let P=null;function h(){return m?Promise.resolve():P??=(async()=>{let w=Js().workspaces.map(({root:L})=>L),j=new Set([l,...w.filter(la).map(L=>He(L))]);for(let[L,E]of i)j.has(L)||(i.delete(L),s.get(L)?.close(),s.delete(L),await E.close())})().catch(w=>t.logger?.warn?.(`[gallery] ${w.message}`)).finally(()=>{P=null})}async function M(w,j,L){try{if(m)return ma(j,503,{ok:!1,reason:"closing"});let E=new URL(w.url??"/","http://localhost");if(await c.handle(w,j))return;let U=Vs(E.pathname);if(!U)return n.handle(w,j,L);let J=Jt(),T=J.get(U),G=T?.length===1?await v(T[0],J):null;if(!G)return ma(j,404,{ok:!1,reason:"workspace"});let Z=Zs(E.pathname);if(G===n||/^\/pages(?:\/|$)|^\/__gallery\/(?:pages?|components|net)(?:\/|$)|^\/__gallery\/workspace\/(?:stop|head|new-page|instructions|extension-edit|components)(?:\/|$)/.test(Z)){j.writeHead(307,{Location:Z+E.search}),j.end();return}let y=He(T[0]);return S.set(y,(S.get(y)??0)+1),j.once("close",()=>{S.set(y,S.get(y)-1),k.set(y,Date.now())}),w.url=Z+E.search,G.handle(w,j,A=>{w.url=E.pathname+E.search,L(A)})}catch(E){L(E)}}let x=setInterval(()=>{for(let[w,j]of i)w!==l&&!n.workbenchListeners&&!S.get(w)&&!j.listeners&&Date.now()-k.get(w)>12e4&&(i.delete(w),s.get(w)?.close(),s.delete(w),k.delete(w),S.delete(w),j.close().catch(L=>t.logger?.warn?.(`[gallery] ${L.message}`)))},3e4);x.unref();async function $(){if(!m){m=!0,clearInterval(x),ca.unwatchFile(da(),C),await c.close();for(let w of s.values())w?.close();await Promise.all([...f.values()]),await Promise.all([...i.values()].map(w=>w.close())),i.clear()}}let C=()=>{p(e),h()};return{handle:M,resolve:v,edits:n.edits,workspace:n.workspace,stop:n.stop,changed(w,j){for(let L of i.values())L.changed(w,j)},async listening(w){await n.listening(w),await h(),ca.watchFile(da(),{interval:500,persistent:!1},C)},close:$}}import Qs from"node:fs/promises";import Ne from"node:path";import{FRAMED_BY as qs,serve as pa}from"../browser/shared/http.mjs";var ei={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff",".ttf":"font/ttf",".txt":"text/plain; charset=utf-8"},ti=e=>ei[Ne.extname(e).toLowerCase()]??"application/octet-stream";function ni(e,a){if(/%(?:2f|5c|00)/i.test(a)||/[\\\0]/.test(a))return null;let t;try{t=decodeURIComponent(a)}catch{return null}let o=t.split("/");if(o.some(s=>s===""||s==="."||s===".."||/[\\\0:]/.test(s)))return null;let i=Ne.resolve(e,...o),f=Ne.relative(e,i);return f&&!f.startsWith("..")&&!Ne.isAbsolute(f)?i:null}async function ha(e,a,{web:t,kit:o,vendor:i}){if(e.method!=="GET"&&e.method!=="HEAD")return!1;let f=new URL(e.url||"/","http://localhost").pathname,s=null,m=null;if(f==="/"||f==="/index.html"){if(!t)return!1;[s,m]=[Ne.join(t,"index.html"),{"Cache-Control":"no-store",...qs}]}else{let k=[["/assets/",t&&Ne.join(t,"assets"),"max-age=31536000, immutable"],["/kit/",o,"no-cache"],["/vendor/",i,"no-cache"]].find(([S,b])=>b&&f.startsWith(S));if(!k)return!1;s=ni(k[1],f.slice(k[0].length)),m={"Cache-Control":k[2]}}let l=s?await Qs.readFile(s).catch(()=>null):null;return l?(pa(a,{type:ti(s),headers:{...m,"X-Content-Type-Options":"nosniff"},body:e.method==="HEAD"?void 0:l}),!0):(pa(a,{status:404}),!0)}async function qd({reportsDirectory:e=di(),port:a,web:t=ci,kind:o=process.env.GALLERY_SERVER_KIND==="dev"?"dev":"cli",stateDirectory:i=mi(e).state,exit:f=(p=0)=>process.exit(p),watch:s=!0,signals:m=!0,log:l=console}={}){await fi(e),await cn(e,{log:h=>l.log(`[gallery] ${new Date().toISOString()} ${h}`)}),rn(e,h=>l.log(`[gallery] ${new Date().toISOString()} ${h}`)),an(e);let p=await fn(e,{stateDirectory:i});p.did==="made"?l.log(`[gallery] ${new Date().toISOString()} the default home page made: ${p.file} (${p.cards.length} cards)`):p.did==="failed"&&l.warn(`[gallery] ${new Date().toISOString()} ${mn(p)}`);let k=null,S=null,b=null,n=li(),c=async()=>{S?.close(),b&&wt.unwatchFile(yt,b),await oi.writeFile(n.lastPortFile,`${a}
|
|
168
|
+
`).catch(()=>{}),await new Promise(h=>{k.close(()=>h()),k.closeAllConnections()})},P=ua({reportsDirectory:e,watch:s,stateDirectory:i,logger:{info:h=>l.log(h),warn:h=>l.warn(h),error:h=>l.error(h)},kind:o,closeServer:c,exit:()=>f(0)});k=ai.createServer((h,M)=>{P.handle(h,M,async x=>{if(x){l.error(`[gallery] ${h.method} ${h.url}: ${x.stack??x.message}`),M.headersSent?M.end():ga(M,{status:500});return}try{if(await ha(h,M,{web:t,kit:ri,vendor:ii}))return}catch($){l.error(`[gallery] ${h.url}: ${$.message}`)}M.headersSent||ga(M,{status:404})})}),k.keepAliveTimeout=5e3,await new Promise((h,M)=>{k.once("error",M),k.listen(a,"127.0.0.1",()=>{k.off("error",M),h()})}),a=k.address().port;try{await P.listening(a)}catch(h){throw await c(),await P.close(),h}if(s&&(S=Le(e,P.changed)),si){let h=wt.readFileSync(yt,"utf8");b=()=>{let M=null;try{M=wt.readFileSync(yt,"utf8")}catch{}M!==h&&(l.log("[gallery] The package was replaced (another version installed): this server stops; the next gallery command starts the new one."),P.stop())},wt.watchFile(yt,{interval:3e3,persistent:!1},b)}if(m)for(let h of["SIGINT","SIGTERM","SIGHUP"])process.once(h,()=>P.stop());return{server:k,port:a,routes:P,async close(){await c(),await P.close()}}}export{qd as a};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
|
|
2
|
-
import{k as u}from"./chunk-
|
|
2
|
+
import{k as u}from"./chunk-FJLM7YE7.mjs";import n from"node:fs/promises";import d from"node:path";import{writeAtomic as h}from"../browser/shared/files.mjs";import{documentFiles as A}from"../browser/shared/workspace.mjs";var I=s=>n.access(s).then(()=>!0,()=>!1);async function q(s,{create:y,slugOf:F,folderOf:j,fill:p,place:x,under:N="",said:J="\u5BFC\u5165\u81EA {0}",lang:O=null}){let e=[],c=[];async function f(t,r,S){let i=await F(t,S);await y(i,t.title,J.replace("{0}",()=>t.from),{lang:O});let a=j(i),{html:l,json:m}=A(a),k=await n.readFile(l,"utf8");await h(l,u(await p({source:k,nodes:t.nodes,icon:t.icon,own:t.own,raws:t.raws,lang:t.lang}))),t.files.length&&await n.mkdir(d.join(a,"assets"),{recursive:!0});for(let{from:o,name:v}of t.files){let w=d.join(a,"assets",v);await I(w)||await n.copyFile(o,w)}if(t.icon){let o=JSON.parse(await n.readFile(m,"utf8"));await h(m,`${JSON.stringify({...o,icon:t.icon},null,2)}
|
|
3
3
|
`)}await x(i,r),e.push(i);for(let o of t.children??[])await f(o,i,null);return i}for(let[t,r]of s.entries())c.push(await f(r,N,t));return{made:e,top:c}}export{q as a};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
|
|
2
|
+
import{a as Qt,b as Xt}from"./chunk-ALZ6ZENZ.mjs";import{a as mt}from"./chunk-UMHUSOPJ.mjs";import{b as Vt,e as Ae}from"./chunk-A55HN5OK.mjs";import{randomBytes as kt}from"node:crypto";import h from"node:fs/promises";import{serviceLocation as Be}from"../browser/shared/service-location.mjs";import w from"node:path";import{writeAtomic as R}from"../browser/shared/files.mjs";import{sendJson as G}from"../browser/shared/http.mjs";import{said as B,saying as Et}from"../browser/shared/i18n/index.mjs";import{reportsDirectory as He}from"../browser/shared/paths.mjs";import{moveDocument as Ue,outlineAndFile as ze,ownsOutline as Ke,placeIn as nt,readOutline as te,validOutline as ee,withOutlineLock as ne,writeHead as Ve,writeOutline as Qe,writtenAs as Xe}from"../browser/shared/outline.mjs";Ae();import et from"node:fs/promises";import pt from"node:path";import{attr as Fe,walk as $e}from"../browser/shared/html-tree.mjs";import{escapeAttribute as Re}from"../browser/shared/escape.mjs";import{COMPONENTS_FOLDER as Je,DOCUMENT_FOLDERS as Te,SHARED_FOLDERS as Ce,documentFiles as Zt,packageFolders as _e,readLink as Me}from"../browser/shared/workspace.mjs";async function Pt(O,m){let k=await et.readdir(pt.join(O,m),{withFileTypes:!0});if(!Ce.includes(m))return k.map(({name:j})=>j);let c=m===Je?new Set(_e(O).map(({id:j})=>j.split("/")[0])):new Set;return k.filter(j=>j.isFile()||Te.includes(j.name)&&!c.has(j.name)).map(({name:j})=>j)}async function Nt(O,m,k,c,{names:j=new Map}={}){let x=pt.join(O,m),vt=await et.access(Zt(x).html).then(()=>!0,()=>!1)?null:await Me(x),C=new Set(["",...await Pt(O,m)]);if(await et.cp(x,k,{recursive:!0,errorOnExist:!0,force:!1,filter:N=>C.has(pt.relative(x,N).split(pt.sep)[0])}),vt)return[];let Z=Zt(k).html,v=await et.readFile(Z,"utf8"),ct=mt(v),q=new Map,H=new Set;$e(Vt(ct.replace(/^\uFEFF/," "),{sourceCodeLocationInfo:!0}),N=>{let A=Fe(N,"data-doc-component");A&&H.add(A);for(let{name:E,value:S}of N.attrs??[]){let F=N.sourceCodeLocation?.attrs?.[E];if(!F)continue;let _=/^(\.\.\/)([a-z0-9]+(?:-[a-z0-9]+)*)(\/.*)$/.exec(S),lt=E==="data-doc-id"&&S===m?c:["href","src","poster"].includes(E)&&_&&j.has(_[2])?`../${j.get(_[2])}${_[3]}`:S;lt!==S&&q.set(F.startOffset,{to:F.endOffset,text:`${E}="${Re(lt)}"`})}});let l=[...q].sort(([N],[A])=>A-N).reduce((N,[A,E])=>N.slice(0,A)+E.text+N.slice(E.to),ct);return await et.writeFile(Z,l),[...H]}import{storedHead as Ze}from"../browser/shared/sidebar-head.mjs";import{DOCS as ht,columnWorkspaceId as qe,entryWorkspace as De,entryPattern as tn,isForeign as ie,isTop as V,topOf as X}from"../browser/shared/outline-shape.mjs";import{addDraft as en,addWorkspace as nn,draftEntry as re,draftFacts as oe,draftOf as it,findDraft as rn,foreignMarker as on,projectChoices as an,registeredIds as gt,workspaceNames as sn,workspaceOf as rt}from"../browser/shared/drafts.mjs";import{forgetSnapshot as It,shownWorkspaces as cn}from"../browser/shared/workspace-columns.mjs";import{nameStops as ln}from"../browser/shared/workspace-name.mjs";import{registerWorkspace as un,workspaceId as Lt,workspaceKey as ae}from"../browser/shared/workspace-registry.mjs";import{spawn as We}from"node:child_process";import qt from"node:path";var Ge=O=>!["","0",void 0].includes(O);function Ye(O,{platform:m=process.platform,env:k=process.env}={}){return Ge(k.GALLERY_NO_BROWSER)?{skip:"GALLERY_NO_BROWSER is set"}:m==="win32"?{command:qt.join(k.SystemRoot||k.windir||"C:\\Windows","explorer.exe"),args:[`/select,"${O}"`],verbatim:!0}:m==="darwin"?{command:"open",args:["-R",O]}:!k.DISPLAY&&!k.WAYLAND_DISPLAY?{skip:"no display here (neither DISPLAY nor WAYLAND_DISPLAY is set)"}:{command:"xdg-open",args:[qt.dirname(O)]}}function Dt(O,m){let k=Ye(O,m);return k.skip?Promise.resolve({opened:!1,why:k.skip}):new Promise(c=>{let j;try{j=We(k.command,k.args,{detached:!0,stdio:"ignore",windowsHide:!1,windowsVerbatimArguments:!!k.verbatim})}catch(x){return c({opened:!1,why:x.code??x.message})}j.once("error",x=>c({opened:!1,why:x.code??x.message})),j.once("spawn",()=>{j.unref(),c({opened:!0})})})}import{LINK_FILE as At,linkStem as fn,linkValue as ot,ownAddress as Ft,readLinkText as dn}from"../browser/shared/web-links.mjs";import{sameDirectory as at}from"../browser/shared/preview-server.mjs";import{listReportSlugs as wn,slugPattern as P}from"../browser/shared/reports.mjs";import{PAGE_SLUG as mn,SHARED_FOLDERS as se,defaultWorkspace as yt,documentDirectory as pn,documentFiles as Ot,ensureWorkspace as kn,idHolder as hn,isDocSlug as gn,layoutOf as $t,listTrash as ce,newDocSlug as jt,pageSlug as yn,readLink as Rt,slugTaken as On,trashIdPattern as le}from"../browser/shared/workspace.mjs";import{createPage as jn,headOf as ue,listPages as fe,newPageSlug as Sn,pageFiles as st,readPageMeta as Jt,renamePage as vn}from"../browser/shared/pages.mjs";import{editExtension as xn,extensionSource as bn,listExtensions as Pn}from"../browser/shared/extensions.mjs";import{effectiveLook as Tt,ownLookFor as Nn,ownLookOf as En,sameLook as In,withLookField as de}from"../browser/shared/document-look.mjs";import{workspaceLook as Ct,writeWorkspaceLook as Ln}from"../browser/shared/workspace-look.mjs";import{findIn as An,tidyQuery as Fn}from"../browser/shared/search.mjs";var $n=([O,m,k,...c])=>c.length?B("\u68C0\u67E5\u6CA1\u6709\u901A\u8FC7\uFF1A{0}\uFF1B{1}\uFF1B{2} \u7B49 {3} \u6761",O,m,k,c.length+3):k!==void 0?B("\u68C0\u67E5\u6CA1\u6709\u901A\u8FC7\uFF1A{0}\uFF1B{1}\uFF1B{2}",O,m,k):m!==void 0?B("\u68C0\u67E5\u6CA1\u6709\u901A\u8FC7\uFF1A{0}\uFF1B{1}",O,m):B("\u68C0\u67E5\u6CA1\u6709\u901A\u8FC7\uFF1A{0}",O),St=O=>O==="en"?"en":null,Rn=32*1024*1024;async function Y(O,m){for(let k=0;;k++)try{return await h.rename(O,m)}catch(c){if(!["EPERM","EBUSY","EACCES"].includes(c.code))throw c;if(k>=5)break;await new Promise(j=>setTimeout(j,60*(k+1)))}await h.cp(O,m,{recursive:!0,errorOnExist:!0,force:!1}),await h.rm(O,{recursive:!0,force:!0,maxRetries:5})}var Jn=O=>w.resolve(O);function xi({unified:O=!1,edits:m,reports:k,reportsDirectory:c=He,server:j={kind:"dev",version:null,stop:null},components:x=null,changed:J=()=>{},index:vt=null,web:C=null,projects:Z={touch(){},indexOf:async()=>null}}){let{trash:v}=$t(c),ct=null,q=()=>ct??=ln(),H=vt??Xt({root:c,read:Qt(m),draw:(t,e)=>k.words(t,e)}),l=(t,e,n)=>[t,{ok:!1,reason:e,...Et(n)}],N=t=>h.readFile(t,"utf8").then(JSON.parse).catch(()=>null),A=t=>pn(t,c),E=t=>Ot(A(t)),S=t=>w.join(c,t),F=t=>D(Ot(S(t)).html),_=t=>Promise.resolve(m.forgetChanges?.(t)).catch(()=>{}),lt=t=>Pt(c,t),_t=async(t,e,n)=>{await h.mkdir(n,{recursive:!0});let i=[];try{for(let r of t)await Y(w.join(e,r),w.join(n,r)),i.push(r)}catch(r){for(let o of i)await Y(w.join(n,o),w.join(e,o));throw r}},we=async(t,e)=>{if(!se.includes(t))return Y(S(t),e);await _t(await lt(t),S(t),e),await h.rmdir(S(t)).catch(()=>{})},me=async(t,e)=>se.includes(t)&&!await F(t)&&(await Promise.all((await h.readdir(e)).map(n=>D(w.join(S(t),n))))).every(n=>!n),Mt=async t=>await N(Ot(t).json)??{},$=async t=>{let{title:e=t,description:n="",type:i,instructions:r,icon:o,look:a}=await Mt(A(t)),s=r===!0?{}:Tt(a,Ct(c));return{slug:t,title:e,description:n,...i?{type:i}:{},...typeof o=="string"&&o?{icon:o}:{},...r===!0?{instructions:!0}:{},...Object.keys(s).length?{look:s}:{}}},ut=async t=>{let e=await Rt(S(t));return e&&{slug:t,title:e.title,description:"",kind:"link",url:e.url,...e.icon?{icon:e.icon}:{},...e.siteIcon?{siteIcon:e.siteIcon}:{}}},pe=async(t,e,n=[])=>{let i=it(t),r=i&&n.find(({id:W})=>W===i.ws),o=r?.facts.get(i.slug);if(o){let W=w.join(r.root,i.slug);return{slug:t,title:o.title,description:o.description,kind:o.kind==="link"?"link":"draft",workspace:i.ws,...o.icon?{icon:o.icon}:{},...o.kind==="link"?{url:o.url,siteIcon:o.siteIcon}:{},path:o.path,folder:W,root:r.root}}let{ws:a,title:s,description:u,icon:p,path:g,folder:f,root:d,missing:y,kind:L,url:Q,siteIcon:K}=await oe(t,e);return{slug:t,title:s,description:u,kind:L==="link"?"link":"draft",workspace:a,...L==="link"?{url:Q,siteIcon:K}:{},...p?{icon:p}:{},...g?{path:g,folder:f,root:d}:{},...y?{missing:y}:{}}},Wt=async(t,e,n,i)=>ie(t)?pe(t,n,i):e.includes(t)?await ut(t)??{slug:t,title:t,description:"",kind:"link",url:""}:$(t),b=Lt(c),ke=()=>ae(yt())===ae(c),he=(t,e)=>{let n=t.shown.find(({isDefault:s})=>s)?.id??(ke()?b:null),i=new Set([...t.drafts.map(s=>it(s)?.ws),...t.groups.map(({workspace:s})=>s),...t.shown.map(({id:s})=>s)].filter(Boolean)),r=new Set(t.groups.filter(({workspace:s,title:u})=>s&&!u).map(({workspace:s})=>s));t.groups.find(({id:s})=>s===ht)?.title||r.add(b),r.delete(n);let o=sn(new Set([...i,b]),{ids:new Map([...e,[b,[c]]]),stops:q(),among:r});Z.touch(new Map([...o].filter(([s])=>s!==b).map(([s,{root:u}])=>[s,u])));let a=Object.fromEntries([...i].map(s=>[s,{...o.get(s)??{missing:rt(s,e).refused??"unknown"},...s===n?{default:!0}:{}}]));return a[b]={...o.get(b),there:!0,self:!0,...b===n?{default:!0}:{}},a},U=()=>yn(c),ge=async(t,e)=>{let n=await Mt(A(t));await R(E(t).json,`${JSON.stringify({...n,[e]:!0},null,2)}
|
|
3
|
+
`)},D=t=>h.access(t).then(()=>!0,()=>!1),ft=async(t,{own:e=null}={})=>{let n=new Set((await wt()).map(({slug:i})=>i));n.delete(e);for(let i=1;;i++){let r=i===1?t:`${t}-${i}`;if(!On(r,c)&&!n.has(r))return r}},xt=async t=>{let e=await ft(t.slug,{own:t.slug});return gn(t.slug)?e===t.slug&&!await hn(t.slug,c)?e:jt(c):e},ye=async(t,e)=>{let n=E(t).html,i=await h.readFile(n,"utf8"),r=mt(i).replace(`data-doc-id="${e}"`,`data-doc-id="${t}"`);r!==i&&await R(n,r)},I=()=>te(c),M=async t=>{await Qe(c,t),J()},T=t=>ne(c,t);async function dt(t,e="",n=1/0){await T(async()=>{let i=await I();nt(i,t,e,n),await M(i)})}async function Oe(t,{parent:e="",after:n=null,first:i=!1}={}){await T(async()=>{let r=await I();for(let a of Object.values(r.children))a.includes(t)&&a.splice(a.indexOf(t),1);let o=typeof n=="string"?Object.keys(r.children).find(a=>r.children[a].includes(n)):void 0;o!==void 0?nt(r,t,o,r.children[o].indexOf(n)+1):nt(r,t,typeof e=="string"?e:"",i===!0?0:1/0),await M(r)})}function je(t,e){let n=new Set(Object.values(t.children).flat()),i={...t.children};for(let{id:r}of e.groups){if(r===ht)continue;let o=a=>{let s=(e.children[a]??[]).filter(u=>!n.has(u));(V(a)||s.length)&&(i[a]=s),s.forEach(o)};o(X(r))}return{groups:e.groups,children:i}}function Gt(t){return T(async()=>{let e=await I();for(let[n,i]of Object.entries(e.children)){let r=i.indexOf(t);if(!(r<0))return i.splice(r,1,...e.children[t]??[]),delete e.children[t],await M(e),{parent:n,index:r}}return{parent:"",index:1/0}})}let Se=(t,e)=>H.lines(t,e),Yt=t=>N(w.join(v,t,"entry.json")),wt=()=>ce(c),ve=()=>O?[...gt()].filter(([t,e])=>t!==b&&e.length===1).map(([t,e])=>({id:t,root:e[0]})):[],Bt=async()=>[...await wt(),...(await Promise.all(ve().map(async({id:t,root:e})=>(await ce(e)).map(n=>({...n,id:re(t,n.id),slug:re(t,n.slug)}))))).flat()];async function xe(t){let e=await Jt(t,c);if(!e)return l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4E2A\u9875\u9762");let n=`${Date.now().toString(36)}-${kt(3).toString("hex")}`;try{await h.mkdir(w.join(v,n),{recursive:!0}),await Y(st(t,c).folder,w.join(v,n,"page"))}catch(r){throw await h.rm(w.join(v,n),{recursive:!0,force:!0}).catch(()=>{}),r}let i={id:n,kind:"page",slug:t,title:e.title,at:Date.now(),parent:"",index:-1};return await R(w.join(v,n,"entry.json"),`${JSON.stringify(i,null,2)}
|
|
4
|
+
`),[200,{ok:!0,entry:i}]}async function be(t){let e=w.join(v,t.id,"page"),n=await xt(t);if(await h.mkdir($t(c).customPages,{recursive:!0}),await Y(e,st(n,c).folder),n!==t.slug){let{html:i}=st(n,c),r=await h.readFile(i,"utf8").catch(()=>null),o=r?.replace(`data-page-id="${t.slug}"`,`data-page-id="${n}"`);r!==null&&o!==r&&await R(i,o)}return await h.rm(w.join(v,t.id),{recursive:!0,force:!0}),[200,{ok:!0,page:await Jt(n,c),entry:{...t,slug:n}}]}async function Pe(t){let e=await Rt(S(t));if(!e)return l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4E2A\u94FE\u63A5");let n=`${Date.now().toString(36)}-${kt(3).toString("hex")}`,i=await I(),{parent:r,index:o}=await Gt(t);try{await h.mkdir(w.join(v,n),{recursive:!0}),await Y(S(t),w.join(v,n,"link"))}catch(s){throw await T(()=>M(i)),await h.rm(w.join(v,n),{recursive:!0,force:!0}).catch(()=>{}),s}let a={id:n,kind:"link",slug:t,title:e.title,at:Date.now(),parent:r,index:Number.isFinite(o)?o:-1};return await R(w.join(v,n,"entry.json"),`${JSON.stringify(a,null,2)}
|
|
5
|
+
`),[200,{ok:!0,entry:a}]}async function Ne(t){let e=w.join(v,t.id,"link"),n=await xt(t);return await Y(e,S(n)),await h.rm(w.join(v,t.id),{recursive:!0,force:!0}),await dt(n,t.parent,t.index<0?1/0:t.index),[200,{ok:!0,report:await ut(n),entry:{...t,slug:n}}]}function Ee(t,{parent:e,after:n,first:i}){let r=a=>V(a)?Object.hasOwn(t.children,a):Object.values(t.children).some(s=>s.includes(a));if(n!=null){let a=Object.keys(t.children).find(s=>t.children[s].includes(n));return a===void 0?{refused:[404,"after","\u627E\u4E0D\u5230\u8981\u653E\u5728\u5B83\u540E\u9762\u7684\u6761\u76EE"]}:e!=null&&e!==a?{refused:[409,"level","\u8981\u653E\u5728\u5B83\u540E\u9762\u7684\u6761\u76EE\u4E0D\u5728\u8FD9\u4E00\u5C42"]}:{parent:a,index:t.children[a].indexOf(n)+1}}let o=e??X(ht);return V(o)&&t.groups.some(a=>a.extension&&X(a.id)===o)?{refused:[409,"extension","\u6269\u5C55\u7684\u680F\u91CC\u653E\u4E0D\u4E86\u522B\u7684\u6761\u76EE"]}:r(o)?{parent:o,index:i?0:(t.children[o]??[]).length}:{refused:[404,"parent",V(o)?"\u627E\u4E0D\u5230\u8FD9\u4E00\u680F":"\u627E\u4E0D\u5230\u8981\u653E\u5230\u5B83\u4E0B\u9762\u7684\u6761\u76EE"]}}let z=new Map;function Ie(t){let e=z.get(t);if(e&&Date.now()-e.at<36e5)return e.answer;let n=C?C.frameable(t).catch(()=>({frameable:!0,reason:"unknown"})):Promise.resolve({frameable:!0,reason:"unknown"});return z.size>=500&&z.delete(z.keys().next().value),z.set(t,{at:Date.now(),answer:n}),n.then(i=>{["auth","unknown"].includes(i.reason)&&z.get(t)?.answer===n&&z.delete(t)}),n}function Ht(t,e){return C?.icon?(async()=>{let n=await C.icon(e).catch(()=>null);if(!n)return null;let i=w.join(S(t),At),r=await h.readFile(i,"utf8").catch(()=>null),o=r===null?null:dn(r);if(!o||o.url!==e||o.siteIcon===n)return null;let a=ot({...o,siteIcon:n});return a.refused||!a.value.siteIcon||!await R(i,`${JSON.stringify(a.value,null,2)}
|
|
6
|
+
`,{expect:r})?null:(J(),n)})().catch(()=>null):Promise.resolve(null)}let Ut={info:async()=>[200,{ok:!0,version:1,gallery:j.version,token:m.token,commands:[...Object.keys(tt)],server:{pid:process.pid,home:w.resolve(yt()),data:Be().data,version:j.version,kind:j.kind}}],async outline(){let{outline:t,others:e}=await ze(c),n=await U(),i=[...Object.values(t.children).flat(),...n?[n]:[]],r=gt(),o=async d=>[d,await Wt(d,t.links,r,e)],[a,s,u,p]=await Promise.all([Promise.all(i.map(o)),fe(yt()),Bt(),Pn(c)]),g=p.map(({id:d,file:y,revision:L,title:Q,icon:K,entries:W,count:bt,error:Kt})=>({id:d,file:y,revision:L,title:Q,...K?{icon:K}:{},entries:W,count:bt,...Kt?{error:Et(Kt)}:{}})),f=await ue(c,s);return[200,{ok:!0,outline:t,instructions:n,reports:Object.fromEntries(a),pages:s,head:f,trash:u,workspaces:he(t,r),self:b,shared:!0,extensions:g}]},trash:async()=>[200,{ok:!0,entries:await Bt()}],async stats(t){let e=t.get("slug")??"",n=P.test(e)?await H.facts(e).catch(()=>null):null;return n?[200,{ok:!0,edited:n.edited,words:n.words}]:l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863")},async query(t){let e;try{e=JSON.parse(t.get("options")??"{}")}catch{return[400,{ok:!1,reason:"options",message:"options is JSON"}]}return H.query(t.get("kind")??"",e,{doc:t.get("doc")})},components:async()=>[200,{ok:!0,...x.read()}],async source(t){let e=t.get("slug")??"",n=t.get("kind")==="page";if(!P.test(e))return l(404,"missing",n?"\u627E\u4E0D\u5230\u8FD9\u4E2A\u9875\u9762":"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");let i=w.resolve(n?st(e,c).html:E(e).html);return await D(i)?[200,{ok:!0,path:i}]:l(404,"missing",n?"\u627E\u4E0D\u5230\u8FD9\u4E2A\u9875\u9762":"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863")},projects:async()=>[200,{ok:!0,workspaces:await an(c,{stops:q()})}],async search(t){let e=Fn(t.get("q")??"");if(!e)return[200,{ok:!0,results:[]}];let{children:n,groups:i,links:r}=await I(),o=[],a=f=>(n[f]??[]).forEach(d=>{!r.includes(d)&&(!ie(d)||it(d))&&o.push(d),a(d)});for(let{id:f}of i)a(X(f));let s=e.toLowerCase(),u=new Map(await Promise.all(o.map(async f=>[f,await Wt(f,r,gt())]))),p=JSON.stringify([...u].map(([f,{title:d}])=>[f,d])),g=(await Promise.all(o.map(async f=>{let d=it(f),y=d?rt(d.ws):null,L=y&&!y.refused?await Z.indexOf(y.root):null,Q=d?await L?.lines(d.slug,p):await Se(f,p);if(!Q)return null;let K=String(u.get(f).title).toLowerCase().includes(s),{count:W,hits:bt}=An(Q,e);return K||W?{slug:f,title:K,count:W,hits:bt}:null}))).filter(Boolean);return g.sort((f,d)=>Number(d.title)-Number(f.title)||d.count-f.count),[200,{ok:!0,results:g.slice(0,50)}]}},tt={async"extension-edit"({id:t,...e}){let n=await bn(c,t),i=await ne(n?.root??c,()=>xn(n?.root??c,t,e),{local:!0});return i.ok?(i.written&&J(),[200,{ok:!0}]):l(i.status,i.reason,i.error)},async outline({outline:t,base:e}){return!ee(t)||e!==void 0&&!ee(e)?l(400,"outline","\u6587\u6863\u76EE\u5F55\u7684\u7ED3\u6784\u4E0D\u5BF9\uFF1A\u6BCF\u4EFD\u6587\u6863\u53EA\u80FD\u51FA\u73B0\u4E00\u6B21"):Ke(c,t)?await T(async()=>{let i=await I();return e!==void 0&&!Xe(e,i)?!1:(await M(t.groups?t:je(t,i)),!0)})?[200,{ok:!0,outline:await I()}]:l(409,"stale","\u6587\u6863\u76EE\u5F55\u521A\u5728\u522B\u5904\u6539\u8FC7"):l(409,"cross-workspace","\u8DE8\u5DE5\u4F5C\u533A\u8BF7\u590D\u5236\uFF0C\u4E0D\u80FD\u53EA\u79FB\u52A8\u76EE\u5F55\u4F4D\u7F6E")},async move({slug:t,parent:e,after:n=null,first:i=!1,workspace:r}){if(typeof r=="string"&&!at(r,c))return l(409,"elsewhere","\u8FD9\u4E2A\u9884\u89C8\u670D\u52A1\u5668\u7BA1\u7684\u662F\u53E6\u4E00\u4E2A\u76EE\u5F55\u7684\u6587\u6863");let o=u=>typeof u=="string"&&P.test(u);if(!o(t)||e!==void 0&&e!==""&&!o(e)||n!==null&&!o(n)||typeof i!="boolean")return l(400,"body","\u8BF7\u6C42\u683C\u5F0F\u4E0D\u5BF9");let a=await U();if(a!==null&&[t,e,n].includes(a))return l(409,"instructions","\u5199\u4F5C\u504F\u597D\u4E0D\u5728\u6587\u6863\u76EE\u5F55\u91CC\uFF0C\u4E0D\u80FD\u79FB\u52A8\uFF0C\u4E0B\u9762\u4E5F\u4E0D\u80FD\u653E\u6587\u6863");let s=await Ue(c,t,{parent:e,after:n,first:i});if(s.written&&J(),!s.ok){let[u,p]={missing:[404,"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"],parent:[404,"\u627E\u4E0D\u5230\u8981\u653E\u5230\u5B83\u4E0B\u9762\u7684\u6587\u6863"],after:[404,"\u627E\u4E0D\u5230\u8981\u653E\u5728\u5B83\u540E\u9762\u7684\u6587\u6863"],level:[409,"\u8981\u653E\u5728\u5B83\u540E\u9762\u7684\u6587\u6863\u4E0D\u5728\u8FD9\u4E00\u5C42"],itself:[409,"\u6587\u6863\u4E0D\u80FD\u653E\u5728\u5B83\u81EA\u5DF1\u540E\u9762"],inside:[409,"\u6587\u6863\u4E0D\u80FD\u79FB\u5230\u5B83\u81EA\u5DF1\u6216\u5B83\u4E0B\u9762\u7684\u6587\u6863\u4E0B\u9762"],"cross-workspace":[409,"\u8DE8\u5DE5\u4F5C\u533A\u8BF7\u590D\u5236\uFF0C\u4E0D\u80FD\u53EA\u79FB\u52A8\u76EE\u5F55\u4F4D\u7F6E"]}[s.reason];return l(u,s.reason,p)}return[200,{ok:!0,...s,outline:await I()}]},async create({title:t,description:e,parent:n="",after:i=null,first:r=!1,language:o}){let a=typeof t=="string"?t.replace(/\s+/g," ").trim().slice(0,200):"",s=await jt(c);return await _(s),await k.create(s,a,typeof e=="string"&&e.trim()?e.trim():"\u65B0\u6587\u6863",{lang:St(o)}),await Oe(s,{parent:n,after:i,first:r}),[200,{ok:!0,report:await $(s)}]},async instructions({title:t,description:e,language:n}){let i=await U();if(i)return[200,{ok:!0,report:await $(i)}];let r=await ft(mn),o=(a,s)=>typeof a=="string"&&a.trim()?a.trim().slice(0,200):s;return await k.create(r,o(t,"\u5199\u4F5C\u504F\u597D"),o(e,"Agent \u6BCF\u6B21\u5199\u62A5\u544A\u524D\u90FD\u4F1A\u5148\u8BFB\u7684\u5199\u4F5C\u504F\u597D"),{lang:St(n),page:!0}),await ge(r,"instructions"),[200,{ok:!0,report:await $(r)}]},async components({id:t,hidden:e,shown:n,disabled:i,unlisted:r,net:o,pack:a,enabled:s}){try{return[200,{ok:!0,...await x.write(a!==void 0?{pack:a,enabled:s}:{id:t,hidden:e,shown:n,disabled:i,unlisted:r,net:o})}]}catch(u){return l(409,"components",u)}},async duplicate({slug:t,suffix:e,untitled:n}){if(typeof t!="string"||!P.test(t)||!await F(t))return l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");let i=await jt(c);await _(i),await Nt(c,t,S(i),i);let{title:r}=await $(t),o=r||(typeof n=="string"&&n.trim()?n.trim().slice(0,50):"\u672A\u547D\u540D\u6587\u6863"),a=await m.renameReport(i,`${o}${typeof e=="string"&&e.length>0&&e.length<=20?e:"\uFF08\u526F\u672C\uFF09"}`),s=await I(),[u,p]=Object.entries(s.children).find(([,g])=>g.includes(t))??["",null];return await dt(i,u,p?p.indexOf(t)+1:1/0),[200,{ok:!0,report:await $(i),notes:a.notes??[]}]},async"copy-from"({sourceWs:t,slug:e,parent:n="",index:i=0}){let r=typeof t=="string"?rt(t):{};if(!r.root||t===b||typeof e!="string"||!P.test(e)||typeof n!="string"||!V(n)&&!tn.test(n)||!Number.isInteger(i)||i<0)return l(400,"body","\u8BF7\u6C42\u683C\u5F0F\u4E0D\u5BF9");let o=await te(r.root);if(!Object.values(o.children).some(f=>f.includes(e)))return l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");let a=[],s=f=>{if(!P.test(f)||a.includes(f))throw new Error("\u6587\u6863\u76EE\u5F55\u7684\u7ED3\u6784\u4E0D\u5BF9\uFF1A\u6BCF\u4EFD\u6587\u6863\u53EA\u80FD\u51FA\u73B0\u4E00\u6B21");a.push(f);for(let d of o.children[f]??[])s(d)};s(e);let u=new Map;for(let f of a){let d;do d=await jt(c);while([...u.values()].includes(d));u.set(f,d)}let p=w.join($t(c).gallery,`copy-${kt(8).toString("hex")}`),g=[];try{await h.mkdir(p,{recursive:!0});for(let f of a)await Nt(r.root,f,w.join(p,u.get(f)),u.get(f),{names:u});return await T(async()=>{let f=await I();if((V(n)?qe(f.groups.find(y=>X(y.id)===n),b):De(n,b))!==b||(V(n)?!f.groups.some(y=>X(y.id)===n&&!y.extension):!Object.values(f.children).some(y=>y.includes(n))))throw new Error("\u627E\u4E0D\u5230\u8981\u653E\u5230\u5B83\u4E0B\u9762\u7684\u6587\u6863");for(let y of a){let L=u.get(y);await h.rename(w.join(p,L),S(L)),g.push(S(L))}It(c),nt(f,u.get(e),n,i);for(let y of a)o.children[y]?.length&&(f.children[u.get(y)]=o.children[y].map(L=>u.get(L)));await M(f)}),[200,{ok:!0,slug:u.get(e),count:a.length}]}catch(f){for(let d of g)await h.rm(d,{recursive:!0,force:!0});return It(c),l(409,"copy",f.text?f:f.message)}finally{await h.rm(p,{recursive:!0,force:!0})}},async look({slug:t,look:e}){if(typeof t!="string"||!P.test(t)||!await F(t))return l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");if(t===await U())return l(409,"instructions","\u5199\u4F5C\u504F\u597D\u6CA1\u6709\u5B57\u4F53\u4E0E\u5E03\u5C40");if(e!==null&&(typeof e!="object"||Array.isArray(e)))return l(400,"look","\u5B57\u4F53\u4E0E\u5E03\u5C40\u4E0D\u5BF9");let n=E(t).json,i=null;try{i=JSON.parse(await h.readFile(n,"utf8"))}catch{}if(!i||typeof i!="object"||Array.isArray(i))return l(409,"metadata","\u8FD9\u4EFD\u6587\u6863\u7684\u6807\u9898\u548C\u8BF4\u660E\u8BFB\u4E0D\u51FA\u6765");let r=de(i,Nn(e,Ct(c)));return JSON.stringify(r)!==JSON.stringify(i)&&await R(n,`${JSON.stringify(r,null,2)}
|
|
7
|
+
`),[200,{ok:!0,report:await $(t)}]},async looks({slug:t}){if(typeof t!="string"||!P.test(t)||!await F(t))return l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");let e=await U();if(t===e)return l(409,"instructions","\u5199\u4F5C\u504F\u597D\u6CA1\u6709\u5B57\u4F53\u4E0E\u5E03\u5C40");let n=await N(E(t).json);if(!n||typeof n!="object"||Array.isArray(n))return l(409,"metadata","\u8FD9\u4EFD\u6587\u6863\u7684\u6807\u9898\u548C\u8BF4\u660E\u8BFB\u4E0D\u51FA\u6765");let i=Ct(c),r=Tt(n.look,i);try{await Ln(c,r)}catch(u){return l(409,"workspace",u)}let o=0,a=(await wn(c)).filter(u=>u!==e).map(u=>({json:E(u).json,self:u===t})),s=(await wt()).filter(({kind:u})=>u==="document").map(({id:u})=>({json:Ot(w.join(v,u,"report")).json,self:!1}));for(let{json:u,self:p}of[...a,...s])for(let g=0;g<3;g++){let f=await h.readFile(u,"utf8").catch(()=>null),d=null;try{d=JSON.parse(f??"")}catch{}if(!d||typeof d!="object"||Array.isArray(d)||!Object.hasOwn(d,"look")||d.instructions===!0)break;let y=await R(u,`${JSON.stringify(de(d,{}),null,2)}
|
|
8
|
+
`,{expect:f}).catch(()=>null);if(y===null)break;if(y){!p&&Object.keys(En(d.look)).length>0&&!In(Tt(d.look,i),r)&&o++;break}}return[200,{ok:!0,look:r,replaced:o,report:await $(t)}]},async head({order:t}){let e=Ze(t);return e?(await T(()=>Ve(c,e)),J(),[200,{ok:!0,head:await ue(c,await fe(yt()))}]):l(400,"head","\u4FA7\u680F\u5934\u90E8\u7684\u987A\u5E8F\u4E0D\u5BF9")},async"new-page"({title:t,after:e=null,language:n}){let i=typeof t=="string"?t.replace(/\s+/g," ").trim():"";if(!i||i.length>200)return l(400,"title","\u6807\u9898\u4E0D\u80FD\u662F\u7A7A\u7684\uFF0C\u4E5F\u4E0D\u80FD\u8D85\u8FC7 200 \u4E2A\u5B57");if(e!==null&&(typeof e!="string"||!P.test(e)))return l(400,"body","\u8BF7\u6C42\u683C\u5F0F\u4E0D\u5BF9");let r=await Sn(c);return await jn(r,i,{root:c,blank:!0,after:e,...St(n)?{lang:St(n)}:{}}),J(),[200,{ok:!0,page:await Jt(r,c)}]},async rename({slug:t,title:e,kind:n="document"}){if(typeof t!="string"||!P.test(t))return l(400,"slug","\u6587\u6863\u540D\u4E0D\u5BF9");if(n==="page"){let r;try{r=await vn(t,e,c)}catch{return l(400,"title","\u6807\u9898\u4E0D\u80FD\u662F\u7A7A\u7684\uFF0C\u4E5F\u4E0D\u80FD\u8D85\u8FC7 200 \u4E2A\u5B57")}return r?[200,{ok:!0,page:r}]:l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4E2A\u9875\u9762")}let i=await m.renameReport(t,e);return i.ok?[200,{ok:!0,report:await $(t),notes:i.notes}]:l({title:400,missing:404}[i.reason]??409,i.reason,i.message??"\u6539\u540D\u6CA1\u6709\u6210\u529F")},async trash({slug:t,kind:e="document"}){if(typeof t!="string"||!P.test(t))return l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");if(e==="page")return xe(t);if(e==="link")return Pe(t);if(t===await U())return l(409,"instructions","\u5199\u4F5C\u504F\u597D\u4E0D\u80FD\u79FB\u5230\u56DE\u6536\u533A");if(!await F(t))return l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");let{title:n}=await $(t),i=`${Date.now().toString(36)}-${kt(3).toString("hex")}`,r=await I(),{parent:o,index:a}=await Gt(t);try{await h.mkdir(w.join(v,i),{recursive:!0}),await we(t,w.join(v,i,"report"))}catch(u){throw await T(()=>M(r)),await h.rm(w.join(v,i),{recursive:!0,force:!0}).catch(()=>{}),u}let s={id:i,kind:"document",slug:t,title:n,at:Date.now(),parent:o,index:Number.isFinite(a)?a:-1};return await R(w.join(v,i,"entry.json"),`${JSON.stringify(s,null,2)}
|
|
9
|
+
`),[200,{ok:!0,entry:s}]},async restore({id:t}){let e=typeof t=="string"&&le.test(t)?await Yt(t):null;if(!e)return l(404,"missing","\u56DE\u6536\u533A\u91CC\u6CA1\u6709\u8FD9\u4E00\u9879");if(e.kind==="page")return be(e);if(e.kind==="link")return Ne(e);let n=w.join(v,t,"report"),i=await me(e.slug,n),r=i?e.slug:await xt(e);return i?await _t(await h.readdir(n),n,S(r)):await Y(n,S(r)),r!==e.slug&&await ye(r,e.slug),await h.rm(w.join(v,t),{recursive:!0,force:!0}),await dt(r,e.parent,e.index<0?1/0:e.index),[200,{ok:!0,report:await $(r),entry:{...e,kind:"document",slug:r}}]},async destroy({id:t}){let e=typeof t=="string"&&le.test(t)?await Yt(t):null;return e?((e.kind??"document")==="document"&&!await F(e.slug)&&await _(e.slug),await h.rm(w.join(v,t),{recursive:!0,force:!0}),[200,{ok:!0}]):l(404,"missing","\u56DE\u6536\u533A\u91CC\u6CA1\u6709\u8FD9\u4E00\u9879")},async link({url:t,title:e,icon:n=null,parent:i,after:r=null,first:o=!1},{port:a,wait:s=!1}={}){let u=ot({url:t,title:e,icon:n});if(u.refused)return l(400,u.refused,u.message);if(Ft(u.value.url,a))return l(409,"own","\u8FD9\u662F Gallery \u81EA\u5DF1\u7684\u5730\u5740\uFF0C\u8BF7\u76F4\u63A5\u94FE\u63A5\u6587\u6863");if(i!=null&&typeof i!="string"||r!==null&&typeof r!="string"||typeof o!="boolean")return l(400,"body","\u8BF7\u6C42\u683C\u5F0F\u4E0D\u5BF9");let p=await T(async()=>{let f=await I(),d=Ee(f,{parent:i,after:r,first:o||i==null&&r===null});if(d.refused)return d;let y=await ft(fn(u.value.title,u.value.url));return await h.mkdir(S(y),{recursive:!0}),await R(w.join(S(y),At),`${JSON.stringify(u.value,null,2)}
|
|
10
|
+
`),nt(f,y,d.parent,d.index),await M(f),{slug:y,parent:d.parent,index:d.index}});if(p.refused)return l(...p.refused);let g=Ht(p.slug,u.value.url);return s&&await g,[200,{ok:!0,link:await ut(p.slug),parent:p.parent,index:p.index,outline:await I()}]},async"link-set"({slug:t,url:e,title:n,icon:i},{port:r,wait:o=!1}={}){let a=typeof t=="string"&&P.test(t)?await Rt(S(t)):null;if(!a)return l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4E2A\u94FE\u63A5");let s=e??a.url,u=ot({url:s,title:n??a.title,icon:i===void 0?a.icon??null:i,siteIcon:a.siteIcon??null});if(u.refused)return l(400,u.refused,u.message);let p=u.value.url!==a.url;if(p&&Ft(u.value.url,r))return l(409,"own","\u8FD9\u662F Gallery \u81EA\u5DF1\u7684\u5730\u5740\uFF0C\u8BF7\u76F4\u63A5\u94FE\u63A5\u6587\u6863");if(p&&delete u.value.siteIcon,JSON.stringify(u.value)!==JSON.stringify(a)&&await R(w.join(S(t),At),`${JSON.stringify(u.value,null,2)}
|
|
11
|
+
`),p){let g=Ht(t,u.value.url);o&&await g}return[200,{ok:!0,link:await ut(t)}]},async"draft-add"({path:t,confirm:e=!1,after:n=null}){let i=await rn(t),r=typeof n=="string"?n:null;if(i.kind==="missing")return l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4E2A\u6587\u4EF6\u6216\u6587\u4EF6\u5939");if(i.kind==="plain")return l(409,"plain","\u8FD9\u4E0D\u662F Gallery \u7684\u5E95\u7A3F\u6216\u5DE5\u4F5C\u533A\uFF0C\u53EF\u4EE5\u7528\u300C\u5BFC\u5165\u300D\u628A\u6587\u4EF6\u590D\u5236\u8FDB\u6765");if(i.kind==="nested")return l(409,"nested","\u8FD9\u4EFD\u5E95\u7A3F\u4E0D\u5728\u5B83\u5DE5\u4F5C\u533A\u7684\u7B2C\u4E00\u5C42\uFF08\u5728\u56DE\u6536\u533A\u91CC\uFF0C\u6216\u662F\u5199\u4F5C\u504F\u597D\uFF09\uFF0C\u4E0D\u80FD\u6DFB\u52A0");if(i.kind==="name")return l(409,"name","\u8FD9\u4E2A\u6587\u4EF6\u5939\u7684\u540D\u5B57\u4E0D\u662F Gallery \u6587\u6863\u7684\u5199\u6CD5\uFF08\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26\uFF09\uFF0C\u4E0D\u80FD\u6DFB\u52A0");let o=i.kind==="workspace"?i.root:i.kind==="folder"?null:i.root,a=!o||!cn(c).some(g=>at(g.root,o));if(!o){let g=i.kind==="folder"?i.folder:i.parent;if(on(g))return l(409,"marker",B("{0} \u91CC\u7684 gallery.json \u662F\u522B\u7684\u7A0B\u5E8F\u7684\uFF0C\u4E0D\u80FD\u628A\u5B83\u767B\u8BB0\u6210\u5DE5\u4F5C\u533A",g));if(e!==!0)return[409,{ok:!1,reason:"unregistered",folder:g,...Et(B("\u4F1A\u628A {0} \u767B\u8BB0\u6210\u4E00\u4E2A\u5DE5\u4F5C\u533A\uFF08\u5728\u91CC\u9762\u653E gallery.json \u548C .gallery/\uFF09",g))}];if(!(await kn(g)).ours)return l(409,"marker",B("{0} \u91CC\u7684 gallery.json \u662F\u522B\u7684\u7A0B\u5E8F\u7684\uFF0C\u4E0D\u80FD\u628A\u5B83\u767B\u8BB0\u6210\u5DE5\u4F5C\u533A",g));o=g}let s=i.kind==="workspace"||i.kind==="folder";if(at(o,c))return[200,{ok:!0,kind:s?"workspace":"draft",own:!0,existing:!0,...s?{column:ht}:{entry:i.slug}}];let u=await un(o,{force:!0}).catch(()=>"failed"),p=rt(Lt(o));return p.refused==="ambiguous"?l(409,"ambiguous",B("\u672C\u673A\u767B\u8BB0\u7684 {0} \u4E2A\u5DE5\u4F5C\u533A\u7F16\u53F7\u76F8\u540C\uFF08{1}\uFF09\uFF0C\u5148\u7528 gallery workspaces --forget \u53BB\u6389\u5176\u4E2D\u4E00\u4E2A",p.roots.length,Lt(o))):!p.root||!at(p.root,o)?u==="temporary"?l(409,"temporary","\u8FD9\u4E2A\u5DE5\u4F5C\u533A\u5728\u7CFB\u7EDF\u7684\u4E34\u65F6\u6587\u4EF6\u5939\u91CC\uFF0C\u4E0D\u80FD\u6DFB\u52A0"):l(409,"registry","\u6CA1\u80FD\u628A\u5B83\u7684\u5DE5\u4F5C\u533A\u8BB0\u8FDB\u672C\u673A\u7684\u767B\u8BB0\u8868"):(It(o),s?[200,{ok:!0,kind:"workspace",...await nn(c,o,{changed:J,after:r})}]:[200,{ok:!0,kind:"draft",...await en(c,o,i.slug,{changed:J,pick:!0,after:r,fresh:a})}])},async export({slug:t}){if(typeof t!="string"||!P.test(t)||!await D(A(t)))return l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863");let{problems:e=[],file:n,refused:i}=await k.export(t);return i?l(i.reason==="missing"?404:409,i.reason,i.message):e.length?l(422,"check",$n(e)):[200,{ok:!0,path:Jn(n)}]}},zt={async frameable({url:t},{port:e}){let n=typeof t=="string"?ot({url:t,title:"-"}):{refused:"url"};return n.refused?l(400,"url","\u8FD9\u4E0D\u662F\u4E00\u4E2A\u7F51\u5740"):Ft(n.value.url,e)?[200,{ok:!0,frameable:!1,reason:"own"}]:[200,{ok:!0,...await Ie(n.value.url)}]},async reveal({entry:t,ws:e,page:n}){let i=gt(),r=null;return typeof n=="string"?r=P.test(n)?st(n,c).folder:null:typeof t=="string"&&it(t)?r=(await oe(t,i)).folder:e===b?r=w.resolve(c):typeof e=="string"&&(r=rt(e,i).root??null),!r||!await D(r)?l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4E2A\u6587\u4EF6\u5939"):[200,{ok:!0,path:r,...await Dt(r)}]},async title({url:t}){let e=typeof t=="string"?ot({url:t,title:"-"}):{refused:"url"};if(e.refused)return l(400,"url","\u8FD9\u4E0D\u662F\u4E00\u4E2A\u7F51\u5740");let n=C?await C.title(e.value.url).catch(()=>""):"",i=typeof n=="string"?n:n?.title,r=["auth","unknown"].includes(n?.reason)?n.reason:void 0;return[200,{ok:!0,title:typeof i=="string"?i.slice(0,200):"",...r?{reason:r}:{}}]}};function Le(t,e,n){if(t.method==="GET"&&Object.hasOwn(Ut,n)){let r=t.headers.host??"",o=t.socket.localPort;return r!==`127.0.0.1:${o}`&&r!==`localhost:${o}`?G(e,403,{ok:!1,reason:"host"}):Ut[n](new URL(t.url??"/","http://localhost").searchParams).then(([a,s])=>G(e,a,s),a=>G(e,...l(500,"read",a)))}if(t.method==="POST"&&n==="stop")return m.respond(async r=>{let o=await m.check(r);return o.error?o.error:j.kind!=="cli"||typeof j.stop!="function"?l(409,"dev","\u8FD9\u662F npm run dev \u7684\u670D\u52A1\u5668\uFF1A\u5728\u8FD0\u884C\u5B83\u7684\u5730\u65B9\u505C\u6B62\u5B83"):(e.once("finish",()=>j.stop()),[200,{ok:!0,pid:process.pid}])})(t,e);if(t.method==="POST"&&n==="pack-install")return m.respond(async r=>{let o=await m.check(r,Rn);if(o.error)return o.error;if(!x?.install)return l(404,"unknown");try{return[200,{ok:!0,...x.install(o.body??{})}]}catch(a){if(!a.code)throw a;return l(409,a.code,a)}})(t,e);if(t.method==="POST"&&n==="todo")return(async()=>{let r=await m.check(t);if(r.error)return r.error;let{slug:o,items:a}=r.body??{};return typeof o!="string"||!P.test(o)||!Array.isArray(a)?[400,{ok:!1,reason:"body"}]:!await F(o)||o===await U()?l(404,"missing","\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"):m.setTodos(o,a)})().then(([r,o])=>G(e,r,o),r=>G(e,...l(500,"write",r.message)));let i={port:t.socket.localPort};return t.method==="POST"&&Object.hasOwn(tt,n)?m.respond(async r=>{let o=await m.check(r);if(o.error)return o.error;let a=o.body&&typeof o.body=="object"?o.body:{};return typeof a.workspace=="string"&&!at(a.workspace,c)?l(409,"elsewhere","\u8FD9\u4E2A\u9884\u89C8\u670D\u52A1\u5668\u7BA1\u7684\u662F\u53E6\u4E00\u4E2A\u76EE\u5F55\u7684\u6587\u6863"):tt[n](a,i)})(t,e):t.method==="POST"&&Object.hasOwn(zt,n)?(async()=>{let r=await m.check(t);return r.error?r.error:zt[n](r.body&&typeof r.body=="object"?r.body:{},i)})().then(([r,o])=>G(e,r,o),r=>G(e,...l(500,"read",r))):G(e,404,{ok:!1,reason:"unknown"})}return{handle:Le,outline:I,trashEntries:wt,place:dt,freeSlug:ft,index:H,run:(t,e,n={})=>Object.hasOwn(tt,t)?tt[t](e??{},{wait:!0,...n}):Promise.resolve(l(404,"unknown","\u6CA1\u6709\u8FD9\u4E2A\u547D\u4EE4"))}}export{xi as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
|
|
2
|
+
import{a}from"./chunk-IS7N3N6Q.mjs";import"./chunk-6GV3CBB2.mjs";import"./chunk-DR73Y2UJ.mjs";import"./chunk-M4NRDYI5.mjs";import"./chunk-PUOQ65NC.mjs";import"./chunk-6QWQXHAV.mjs";import"./chunk-ZLS2FRS6.mjs";import"./chunk-S3SX3COT.mjs";import"./chunk-JJNHKGTD.mjs";import"./chunk-JPG2LBQM.mjs";import"./chunk-ALZ6ZENZ.mjs";import"./chunk-IA4PSIMD.mjs";import"./chunk-2OHANJ6Q.mjs";import"./chunk-F4ZA6JRZ.mjs";import"./chunk-7M2BQQGZ.mjs";import"./chunk-6NLXUKAY.mjs";import"./chunk-VRPVVMRB.mjs";import"./chunk-4B2TB5K2.mjs";import"./chunk-KLQP46Y3.mjs";import"./chunk-BX5AKINW.mjs";import"./chunk-HX4DLE3J.mjs";import"./chunk-ZTHICSSF.mjs";import"./chunk-FJLM7YE7.mjs";import"./chunk-PAREWQGB.mjs";import"./chunk-BFJGHSQN.mjs";import"./chunk-U5XL7D6A.mjs";import"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-W5NPH5UA.mjs";import"./chunk-ECZBLQKK.mjs";import"./chunk-E7656LR7.mjs";import"./chunk-TKWEX4FD.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";export{a as startProductionServer};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
|
|
2
|
-
import{b as V,c as ce,e as le,j as X}from"./chunk-
|
|
2
|
+
import{b as V,c as ce,e as le,j as X}from"./chunk-TKWEX4FD.mjs";import{createHash as $e}from"node:crypto";import v from"node:fs";import h from"node:path";import{packsDirectory as T}from"../browser/shared/paths.mjs";import{PACKAGE_MANIFEST as M,layoutOf as Q}from"../browser/shared/workspace.mjs";var je="gallery",ee=/^(?:\.DS_Store|\._.*|Thumbs\.db|ehthumbs\.db|desktop\.ini)$/i,W=n=>ee.test(n);function G(n){return v.readdirSync(n,{recursive:!0,withFileTypes:!0}).filter(e=>e.isFile()&&!ee.test(e.name)).map(e=>h.relative(n,h.join(e.parentPath,e.name)).split(h.sep).join("/")).sort()}var Y=n=>[...n.filter(e=>e!==M),...n.includes(M)?[M]:[]];function E(n){return v.existsSync(n)?z(G(n).map(e=>({name:e,data:v.readFileSync(h.join(n,e))}))):null}function z(n){let e=$e("sha256"),t=n.filter(({name:i})=>!ee.test(i.split("/").at(-1))).sort((i,s)=>i.name<s.name?-1:i.name>s.name?1:0);for(let{name:i,data:s}of t)e.update(`${i}\0`).update(s).update(`
|
|
3
3
|
`);return e.digest("hex").slice(0,16)}var Z=n=>{try{return v.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}},_=(n=T)=>Z(n);function D(n=T){return Z(n).flatMap(e=>Z(h.join(n,e)).flatMap(t=>{let i=h.join(n,e,t);try{let s=JSON.parse(v.readFileSync(h.join(i,M),"utf8"));return s.id!==`${e}/${t}`?[]:[{name:t,id:s.id,pack:e,folder:i,version:s.version,title:s.name,description:s.description,places:s.places??["document"]}]}catch{return[]}}))}function Ue(n,e=T){let t=n.includes("/")?n:`${je}/${n}`;return D(e).find(i=>i.id===t)??null}var Ve=(n,e=T)=>_(e).includes(String(n).split("/")[0]);function P(n){try{let e=JSON.parse(v.readFileSync(Q(n).blocks,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function K(n,e){let t=Q(n).blocks;v.mkdirSync(h.dirname(t),{recursive:!0}),v.writeFileSync(t,`${JSON.stringify(e,null,2)}
|
|
4
4
|
`)}var he=(n,e)=>h.join(Q(n).components,...e.split("/"));function ne(n,e){let t=he(n,e.id),i=E(t);if(i===null)return{added:!1,version:null,changed:!1,behind:!1};let s=null;try{s=JSON.parse(v.readFileSync(h.join(t,M),"utf8")).version??null}catch{}let a=P(n)[e.id],c=E(e.folder),o=i!==c&&i!==a?.fingerprint;return{added:!0,version:s,changed:o,behind:!o&&i!==c}}function xe(n,e){let t=he(n,e.id),i=ne(n,e);if(i.changed)throw Object.assign(new Error(`${e.id} was changed after it was added`),{code:"changed",folder:t});let s=E(e.folder),a=P(n);if(i.added&&!i.behind)return a[e.id]?.fingerprint!==s&&K(n,{...a,[e.id]:{version:e.version,fingerprint:s}}),{did:"same",folder:t};let c=G(e.folder);if(i.added)for(let o of G(t))c.includes(o)||v.rmSync(h.join(t,o));for(let o of Y(c))v.mkdirSync(h.dirname(h.join(t,o)),{recursive:!0}),v.copyFileSync(h.join(e.folder,o),h.join(t,o));return K(n,{...a,[e.id]:{version:e.version,fingerprint:s}}),{did:i.added?"updated":"added",from:i.version,folder:t}}var ae=n=>/^\d+\.\d+\.\d+$/.test(String(n??""))?n.split(".").map(Number):null;function L(n,e){let[t,i]=[ae(n),ae(e)];if(!t||!i)return n!==e;let s=t.findIndex((a,c)=>a!==i[c]);return s!==-1&&t[s]>i[s]}function Xe(n,e){let t=ne(n,e);return t.changed&&L(e.version,t.version)?e.version:null}var fe=new Map,me=()=>{};function Oe(n,{updated:e,kept:t,failed:i}){let s=[];e.length&&s.push(`Gallery's own blocks in ${n}, as they were added, updated to this Gallery's: ${e.map(({id:a,from:c,to:o})=>`${a} ${c??"?"} -> ${o}`).join(", ")}`);for(let{id:a,version:c,shipped:o}of t)s.push(`${a} in ${n} was changed after it was added, so it stays at ${c??"its version"}: Gallery's is ${o} (\u8BBE\u7F6E \u203A \u7EC4\u4EF6\u5217\u8868 says how to take it)`);for(let{id:a,to:c,why:o}of i)s.push(`${a} in ${n} could not be updated to Gallery's ${c}: ${o}`);return s}function Fe(n,{ids:e=null,directory:t=T,log:i=null}={}){let s={updated:[],kept:[],failed:[]},a=h.resolve(n);for(let c of D(t)){if(e&&!e.includes(c.id))continue;let o=`${a}\0${h.resolve(c.folder)}`;if(fe.get(o)!==c.version){fe.set(o,c.version);try{let r=ne(n,c);if(r.changed&&L(c.version,r.version)&&s.kept.push({id:c.id,version:r.version,shipped:c.version}),!r.behind)continue;xe(n,c).did==="updated"&&s.updated.push({id:c.id,from:r.version,to:c.version})}catch(r){s.failed.push({id:c.id,to:c.version,why:r?.message??String(r)})}}}for(let c of Oe(a,s))(i??me)(c);return s}var de=new Set,pe=n=>process.platform==="win32"?h.resolve(n).toLowerCase():h.resolve(n);function Ze(n,e){de.add(pe(n)),me=e,le((t,i)=>{de.has(pe(t))&&Fe(t,{ids:i})},_())}var ue=n=>[n,n.replace("/","-")],be=n=>n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Qe(n,e,t=T){for(let i of D(t)){if(i.id===e)continue;let s;try{s=v.readFileSync(h.join(i.folder,"preview.svg"))}catch{continue}if(s.equals(n)||Buffer.from(Ae(i,e)["preview.svg"]??"").equals(n))return i}return null}function Ae(n,e){let[t,i]=[ue(n.id),ue(e)],s=new RegExp(t.map(be).join("|"),"g"),a={};for(let c of G(n.folder)){let o=v.readFileSync(h.join(n.folder,c));if(/\.(?:json|html|md|css|js|svg)$/.test(c)){let r=o.toString("utf8").replace(s,f=>i[t.indexOf(f)]);c===M&&(r=r.replace(/"version":\s*"[^"]*"/,'"version": "0.1.0"')),a[c]=r}else a[c]=o}return Object.fromEntries(Y(Object.keys(a)).map(c=>[c,a[c]]))}import m from"node:fs";import u from"node:path";import{refusal as Pe,said as k}from"../browser/shared/i18n/index.mjs";import{DEFAULT_PACK as Ee,OWN_SCOPE as te,PACK_FILE as F,PACK_ID as ye,readPackManifest as ie}from"../browser/shared/pack-manifest.mjs";import{packsDirectory as ge}from"../browser/shared/paths.mjs";import{DEVICE_NAMES as _e,PACKAGE_MANIFEST as R,layoutOf as H,markerOf as Ne,packageFolders as Ie}from"../browser/shared/workspace.mjs";var oe=Object.freeze(["gallery-soft"]);function fn(n,e={}){let t=P(n).packs;return oe.filter(i=>e?.[i]===void 0&&!b(t?.[i]))}var Me="GALLERY_NO_PACKS",Ge=(n=process.env)=>!["","0","false",void 0].includes(n[Me]),q=2e3,re=64*1024*1024,Se=/^[a-z0-9][a-z0-9-]*$/,b=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),j=(n,e)=>{throw Pe(e,{code:n})};function Te(n){let e=[];for(let t of m.readdirSync(n,{recursive:!0,withFileTypes:!0})){if(!t.isFile())continue;e.length>=q&&j("size",k("\u5757\u5305\u592A\u5927\uFF1A\u6700\u591A {0} \u4E2A\u6587\u4EF6\u3001{1} MB",q,re/1024/1024));let i=u.relative(n,u.join(t.parentPath,t.name)).split(u.sep).join("/");e.push({name:i,data:m.readFileSync(u.join(n,...i.split("/")))})}return e}function Ce(n,{refuse:e=()=>{}}={}){let t=[],i=0;for(let{name:r,data:f}of n){let d=String(r).replace(/\\/g,"/");if(d.endsWith("/"))continue;let y=d.split("/");(d.startsWith("/")||/^[A-Za-z]:/.test(d)||d.includes("\0")||y.some(l=>l===""||l==="."||l===".."))&&j("path",k("{0} \u6307\u5411\u5757\u5305\u5916\u9762\uFF0C\u4E0D\u80FD\u88C5",String(r))),!(y[0]==="__MACOSX"||W(y.at(-1)))&&(i+=f.length,t.push({name:d,data:f}))}(t.length>q||i>re)&&j("size",k("\u5757\u5305\u592A\u5927\uFF1A\u6700\u591A {0} \u4E2A\u6587\u4EF6\u3001{1} MB",q,re/1024/1024));let s=t;if(!t.some(({name:r})=>r===F)){let r=new Set(t.map(({name:d})=>d.split("/")[0])),[f]=r;(r.size!==1||!t.some(({name:d})=>d===`${f}/${F}`))&&j("manifest",k("\u6700\u4E0A\u4E00\u5C42\u6CA1\u6709 pack.json\uFF1A\u5757\u5305\u662F\u4E00\u4E2A\u6587\u4EF6\u5939\uFF0C\u6700\u4E0A\u4E00\u5C42\u653E pack.json\uFF0C\u6BCF\u4E2A\u5757\u4E00\u4E2A\u6587\u4EF6\u5939")),s=t.map(({name:d,data:y})=>({name:d.slice(f.length+1),data:y}))}let a=ie(s.find(({name:r})=>r===F).data.toString("utf8"));e(a);let c=new Map,o=[];for(let r of s){let[f,...d]=r.name.split("/");if(d.length===0){o.push(r);continue}c.has(f)||c.set(f,[]),c.get(f).push({name:d.join("/"),data:r.data})}for(let[r,f]of c){(!Se.test(r)||_e.has(r))&&j("block",k("{0} \u4E0D\u662F\u5757\u7684\u6587\u4EF6\u5939\u540D\uFF1A\u53EA\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26",r));let d=f.find(l=>l.name===R);d||j("block",k("{0}/ \u91CC\u6CA1\u6709 component.json",r));let y;try{y=JSON.parse(d.data.toString("utf8").replace(/^/,"")).id}catch{j("block",k("{0}/component.json \u4E0D\u662F JSON",r))}y!==`${a.id}/${r}`&&j("block",k("{0}/component.json \u7684 id \u8981\u5199\u6210 {1}",r,`${a.id}/${r}`))}return{manifest:a,blocks:c,own:o}}function Ke(n){try{let e=JSON.parse(n.find(({name:t})=>t===R).data.toString("utf8").replace(/^/,"")).version;return typeof e=="string"?e:null}catch{return null}}function ve(n){try{return m.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isFile()&&!W(e.name)).map(e=>e.name).sort()}catch{return[]}}function ke(n){let e=ve(n);return e.length?z(e.map(t=>({name:t,data:m.readFileSync(u.join(n,t))}))):null}function ze(n){try{return m.readdirSync(n).some(e=>!W(e))}catch{return!1}}function se(n,e,{replacing:t=!1,last:i=R}={}){let s=e.map(({name:o})=>o);if(t)for(let o of G(n))s.includes(o)||m.rmSync(u.join(n,...o.split("/")),{force:!0});let a=new Map(e.map(o=>[o.name,o.data])),c=i===R?Y(s):[...s.filter(o=>o!==i),...s.includes(i)?[i]:[]];for(let o of c){let r=u.join(n,...o.split("/"));m.mkdirSync(u.dirname(r),{recursive:!0}),m.writeFileSync(r,a.get(o))}}function De(n,e,{official:t=!1,shippedIds:i=_()}={}){let{manifest:s,blocks:a,own:c}=Ce(e,{refuse:({id:g})=>{!t&&i.includes(g)&&j("official",k("{0} \u662F Gallery \u81EA\u5E26\u7684\u5757\u5305\u7528\u7684 id\uFF1A\u6362\u4E00\u4E2A id \u518D\u88C5",g))}}),{id:o}=s,r=u.join(H(n).components,o),f=P(n),d=b(f.packs)?f.packs:{},y=b(d[o])?d[o]:null;!t&&!y&&ze(r)&&j("taken",k("\u5DE5\u4F5C\u533A\u91CC\u5DF2\u7ECF\u6709 components/{0}\uFF1A\u8FD9\u4E2A\u540D\u5B57\u88AB\u522B\u7684\u5757\u5305\u6216\u522B\u4EBA\u5199\u7684\u5757\u7528\u7740\uFF0C\u6362\u4E00\u4E2A id\uFF0C\u6216\u5148\u628A\u90A3\u4E2A\u6587\u4EF6\u5939\u632A\u8D70",o));let l={id:o,name:s.name,version:s.version,from:y?.version??null,folder:r,added:[],updated:[],same:[],kept:[],removed:[],skipped:[],ownKept:!1},w=[...a.keys()].sort();for(let g of w){let p=`${o}/${g}`,O=a.get(g),$=u.join(r,g),B=z(O),I=E($),J=b(f[p])?f[p]:null;if(I===null){if(t&&J){l.skipped.push(p);continue}se($,O),l.added.push(p)}else if(I===B)l.same.push(p);else if(J&&I===J.fingerprint)se($,O,{replacing:!0}),l.updated.push(p);else{l.kept.push(p);continue}f[p]={version:Ke(O),fingerprint:B}}for(let g of Array.isArray(y?.blocks)?y.blocks:[]){let p=String(g).split("/")[1];if(!p||a.has(p)||!Se.test(p))continue;let O=u.join(r,p),$=E(O);if($!==null&&$!==f[g]?.fingerprint){l.kept.push(g);continue}$!==null&&(m.rmSync(O,{recursive:!0,force:!0,maxRetries:5,retryDelay:100}),l.removed.push(g)),delete f[g]}let x=ke(r),A=z(c);if(x!==A)if(x===null||x===y?.fingerprint){let g=c.map(({name:p})=>p);for(let p of ve(r))g.includes(p)||m.rmSync(u.join(r,p),{force:!0});m.mkdirSync(r,{recursive:!0}),se(r,c,{last:F})}else l.ownKept=!0;let N=l.added.length+l.updated.length+l.removed.length>0||x!==A&&!l.ownKept;return l.did=y?N?"updated":"same":"installed",f.packs={...d,[o]:{version:s.version,fingerprint:l.ownKept?y.fingerprint:A,blocks:w.map(g=>`${o}/${g}`),...t?{official:!0}:{}}},K(n,f),l}function dn(n,e,{shippedIds:t=_()}={}){t.includes(e)&&j("official",k("{0} \u662F Gallery \u81EA\u5E26\u7684\u5757\u5305\uFF0C\u4E0D\u80FD\u5220\u9664\uFF1A\u5728 \u8BBE\u7F6E \u203A \u7EC4\u4EF6\u5217\u8868 \u91CC\u628A\u5B83\u5173\u6389",e));let i=u.join(H(n).components,e);(!ye.test(e)||!m.existsSync(i))&&j("missing",k("\u5DE5\u4F5C\u533A\u91CC\u6CA1\u6709\u5757\u5305 {0}",e));let s=P(n),a=b(s.packs)&&b(s.packs[e])?s.packs[e]:null;a||j("own",k("components/{0} \u4E0D\u662F\u88C5\u8FDB\u6765\u7684\u5757\u5305\uFF0C\u91CC\u9762\u7684\u5757\u662F\u6709\u4EBA\u5728\u8FD9\u4E2A\u5DE5\u4F5C\u533A\u5199\u7684\uFF1A\u8981\u5220\u5C31\u81EA\u5DF1\u5220\u6389\u8FD9\u4E2A\u6587\u4EF6\u5939",e)),m.rmSync(i,{recursive:!0,force:!0,maxRetries:5,retryDelay:100});for(let r of Object.keys(s))r.startsWith(`${e}/`)&&delete s[r];let{[e]:c,...o}=s.packs;return K(n,{...s,packs:o}),{id:e,version:a.version??null,blocks:Array.isArray(a.blocks)?a.blocks:[]}}var Le=n=>({zh:X("zh",n),en:X("en",n)});function pn(n,{settings:e=null,shippedIds:t=_(),directory:i=ge}={}){let{components:s}=H(n),a=P(n),c=b(a.packs)?a.packs:{},o=Ie(n),r=new Set([te,...o.map(({id:l})=>l.split("/")[0])]);try{for(let l of m.readdirSync(s))ye.test(l)&&m.existsSync(u.join(s,l,F))&&r.add(l)}catch{}let f=(e??V(n)).packs??{},d=[...r].map(l=>{let w=u.join(s,l),x=null,A=null;if(m.existsSync(u.join(w,F)))try{x=ie(m.readFileSync(u.join(w,F),"utf8")),x.id!==l&&(A=k("pack.json \u7684 id \u662F {0}\uFF0C\u5B83\u7684\u6587\u4EF6\u5939\u5374\u662F components/{1}",x.id,l),x=null)}catch(S){A=S}let N=b(c[l])?c[l]:null,g=o.filter(S=>S.id.startsWith(`${l}/`)),p=N?g.filter(S=>b(a[S.id])&&E(S.folder)!==a[S.id].fingerprint).map(S=>S.id):[];N&&ke(w)!==N.fingerprint&&p.push(`${l}/${F}`);let O=t.includes(l),$=null;if(O)try{$=ie(m.readFileSync(u.join(i,l,F),"utf8"))}catch{}let B=S=>{try{return JSON.parse(m.readFileSync(u.join(s,...S.split("/"),R),"utf8")).version??null}catch{return null}},I=O?D(i):[],we=O&&$&&p.some(S=>S.endsWith(`/${F}`)?L($.version,x?.version??null):I.some(U=>U.id===S)&&L(I.find(U=>U.id===S).version,B(S)))?$.version:null,C=l===te?Ee:x??(A?null:$);return{id:l,name:C?.name??{zh:l,en:l},description:C?.description??null,version:x?.version??null,author:C?.author??null,homepage:C?.homepage??null,icon:C?.icon??null,kind:l===te?"default":O?"official":N?"installed":"own",problem:A?Le(A):null,blocks:g.length,enabled:f[l]!==!1,changed:p,newer:we}}),y=({id:l,kind:w})=>w==="default"?-1:w==="official"?t.indexOf(l):w==="installed"?1e3:2e3;return d.sort((l,w)=>y(l)-y(w)||(l.id<w.id?-1:1))}function Re(n,e,t){let i=[],s=u.resolve(n);return t?i.push(`Gallery's pack ${e.id} ${e.version} installed in ${s} (${e.added.length+e.same.length+e.updated.length} blocks)${oe.includes(e.id)?", switched off: \u8BBE\u7F6E \u203A \u7EC4\u4EF6\u5217\u8868 turns it on":""}`):(e.added.length&&i.push(`Gallery's pack ${e.id} in ${s} has new blocks: ${e.added.join(", ")}`),e.updated.length&&i.push(`Gallery's pack ${e.id} in ${s}, its blocks as they were installed, updated to this Gallery's: ${e.updated.join(", ")}`),e.removed.length&&i.push(`Gallery's pack ${e.id} in ${s}: ${e.removed.join(", ")} no longer in it, taken out`)),i}async function un(n,{directory:e=ge,env:t=process.env,log:i=()=>{}}={}){if(Ge(t))return{did:"off",packs:[]};let s={ours:!1};try{s=Ne(m.readFileSync(H(n).marker,"utf8"))}catch{}if(!s.ours)return{did:"unread",packs:[]};let a=_(e),c=[];for(let o of a)try{let r=!b(P(n).packs?.[o]);r&&oe.includes(o)&&V(n).packs[o]===void 0&&await ce(n,{pack:o,enabled:!1});let f=De(n,Te(u.join(e,o)),{official:!0,shippedIds:a});c.push({...f,first:r});for(let d of Re(n,f,r))i(d)}catch(r){i(`Gallery's pack ${o} could not be installed in ${u.resolve(n)}: ${r?.message??r}`),c.push({id:o,failed:r?.message??String(r)})}return{did:"done",packs:c}}export{je as a,Y as b,_ as c,D as d,Ue as e,Ve as f,P as g,ne as h,xe as i,L as j,Xe as k,Fe as l,Ze as m,Qe as n,Ae as o,fn as p,Te as q,De as r,dn as s,pn as t,un as u};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
|
|
2
|
+
import{a as w,b as k,c as f,g as u}from"./chunk-7UZUQQ7Q.mjs";import{readFileSync as E,realpathSync as S}from"node:fs";import p from"node:path";import{fileURLToPath as $}from"node:url";var j=p.dirname($(import.meta.url));function v(r=j){for(let o=r;;o=p.dirname(o)){try{let n=JSON.parse(E(p.join(o,"package.json"),"utf8"));if(n.name==="@heycys/gallery")return n.version}catch{}if(p.dirname(o)===o)return"0.0.0"}}var x={init:()=>import("./chunk-UTMAY3WK.mjs"),new:()=>import("./chunk-GQJMVSSN.mjs"),import:()=>import("./chunk-FOJ3K5Z3.mjs"),open:()=>import("./chunk-QJAVCTY7.mjs"),serve:()=>import("./chunk-UTF7GBQU.mjs"),stop:()=>import("./chunk-QVGOPHOF.mjs"),check:()=>import("./chunk-G7N7YFVD.mjs"),export:()=>import("./chunk-FQ72LZHB.mjs"),qa:()=>import("./chunk-FNCCVGKX.mjs"),list:()=>import("./chunk-QNECWMGR.mjs"),workspaces:()=>import("./chunk-BYNPEUDS.mjs"),move:()=>import("./chunk-GKOBB6DH.mjs"),set:()=>import("./chunk-7EFHNQ5B.mjs"),link:()=>import("./chunk-LMUZQK5O.mjs"),extension:()=>import("./chunk-6XD6U3QA.mjs"),block:()=>import("./chunk-YFJB534W.mjs"),page:()=>import("./chunk-ONKC4BCC.mjs"),skill:()=>import("./chunk-WD4U6XXT.mjs")},N=new Set(["stop","init","skill","workspaces"]),A=(r,o)=>`${r.split(`
|
|
3
|
+
`)[0]} (gallery ${o?`${o} --help`:"help"} says more)`,g=r=>/^--.|^-[A-Za-z]/.test(r);function L(r){let o=r.indexOf("--"),n=o===-1?r:r.slice(0,o),h=o===-1?[]:r.slice(o),i=[],a=null;for(let e=0;e<n.length;e++){let s=n[e];if(s==="--workspace"||s.startsWith("--workspace=")){let t=s.includes("=")?s.slice(s.indexOf("=")+1):e+1<n.length&&!g(n[e+1])?n[++e]:"";if(!t)return{error:"--workspace takes a folder: --workspace <dir>",usage:u};if(a!==null&&p.resolve(a)!==p.resolve(t))return{error:`Two workspaces named: ${a} and ${t}.`,usage:u};a=t;continue}i.push(s)}if(i[0]==="--version"||i[0]==="-v"||i[0]==="-V")return i.length===1&&h.length===0?{version:!0}:{error:"--version takes nothing else.",usage:u};if(i.length===0||i[0]==="help"||i[0]==="--help"||i[0]==="-h"){let e=i[0]==="help"?i[1]:void 0;return e===void 0?{help:u}:Object.hasOwn(f,e)?{help:f[e]}:{error:`No such command: ${e} (${w.join(", ")}).`,usage:u}}let[c,...m]=i,l=k[c]??c;if(!Object.hasOwn(x,l))return{error:g(l)?`Unknown option: ${l} (the command comes first: gallery <command> [options]).`:`No such command: ${l} (${w.join(", ")}).`,usage:u};let d=[...m,...h];if(m.some(e=>e==="--help"||e==="-h"))return{help:f[l]};if(l==="init"){let e=new Set(["--from","--name"]),s=[];for(let t=0;t<m.length;t++)e.has(m[t])?t++:g(m[t])||s.push(m[t]);if(s.push(...h.slice(1)),s.length>1)return{error:"Name one folder at most.",usage:f.init,command:l};if(s.length===1){if(a!==null&&p.resolve(a)!==p.resolve(s[0]))return{error:`Two workspaces named: ${s[0]} and --workspace ${a}.`,usage:f.init,command:l};a=s[0]}}return{command:l,argv:d,flag:a}}var G=(r,o)=>`Cannot write the workspace ${r} (${o}): allow Gallery to write there, or pass --workspace <a folder you may write>.`,b=(r,o=!0)=>o?`${p.join(r,"gallery.json")} is not Gallery's (another program's file of that name): pass --workspace <another folder> for Gallery's documents.`:`${p.join(r,"gallery.json")} does not read as JSON: mend the file, or pass --workspace <another folder> for Gallery's documents.`;async function W(r=process.argv.slice(2)){process.stdout.on("error",e=>{throw e.code==="EPIPE"&&process.exit(process.exitCode??0),e});let o=L(r);if(o.version){let e=v();console.log(e);try{let{versionNotes:s}=await import("./chunk-TANZRINB.mjs");for(let t of s(e))console.log(t)}catch{}return}if(o.help)return void console.log(o.help);o.error&&(console.error(`${o.error}
|
|
4
|
+
${A(o.usage,o.command)}`),process.exit(2));let{command:n,flag:h}=o,{findWorkspace:i,defaultWorkspace:a}=await import("../browser/shared/workspace.mjs"),c=["page","block","extension"].includes(n)?{root:a(),how:"default"}:i({flag:h});if(process.env.GALLERY_WORKSPACE=c.root,!N.has(n)){let{ensureWorkspace:e}=await import("../browser/shared/workspace.mjs");try{await e(a());let{ours:t,reads:O}=await e(c.root,{state:n!=="init"||c.root===a()});t||(console.error(b(c.root,O)),process.exit(1))}catch(t){if(!t.code)throw t;console.error(G(c.root,t.code)),process.exit(1)}let{registerQuietly:s}=await import("../browser/shared/workspace-registry.mjs");await s(c.root)}let{UsageError:m,usageFailureText:l}=await import("./chunk-GPIWQ4X4.mjs"),d=await x[n]();try{await d.run(o.argv,{command:n,workspace:c.root,how:c.how,version:v()})}catch(e){if(!(e instanceof m))throw e;console.error(l(f[n],e.message,e.synopsis)),process.exit(2)}}var y=r=>{try{return S.native(r)}catch{return null}};process.argv[1]&&y(process.argv[1])===y($(import.meta.url))&&W();export{v as a,L as b,G as c,b as d,W as e};
|