@blocklet/pages-kit-inner-components 0.4.44 → 0.4.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/_chunks/site-state-C0hyEwRs.js +57 -0
- package/lib/cjs/components.js +1 -1
- package/lib/cjs/project-html.js +1 -1
- package/lib/cjs/resources.js +1 -1
- package/lib/cjs/site-state.js +1 -1
- package/lib/es/_chunks/{site-state-4UkWXe7F.js → site-state-B5JbU9OF.js} +133 -117
- package/lib/es/components.js +1 -1
- package/lib/es/project-html.js +2 -2
- package/lib/es/resources.js +1 -1
- package/lib/es/site-state.js +1 -1
- package/package.json +3 -3
- package/lib/cjs/_chunks/site-state-Bm_4Xw-l.js +0 -57
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";var tt=Object.defineProperty;var st=(t,n,e)=>n in t?tt(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var A=(t,n,e)=>st(t,typeof n!="symbol"?n+"":n,e);const nt=require("@blocklet/pages-kit/builtin/utils"),se=require("@blocklet/pages-kit/types"),oe=require("@blocklet/pages-kit/utils/property"),V=require("@blocklet/quickjs"),ot=require("@blocklet/sdk/lib/config"),Ee=require("lru-cache"),Ne=require("node-fetch"),x=require("ufo"),ie=require("crypto"),rt=require("@blocklet/logger"),at=require("@blocklet/pages-kit/utils/builtin"),Ue=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),be=require("@blocklet/sdk/lib/component"),it=require("autoprefixer"),ct=require("esbuild"),E=require("fs"),lt=require("postcss"),pt=require("tailwindcss"),ut=require("typescript"),dt=require("@reactivedata/reactive"),ee=require("@syncedstore/core"),fe=require("glob"),ft=require("lib0/decoding"),mt=require("lib0/encoding"),L=require("lodash"),gt=require("nanoid"),ht=require("p-limit"),h=require("path"),yt=require("stream/promises"),St=require("tar"),wt=require("wait-on"),G=require("y-protocols/awareness"),le=require("y-protocols/sync"),Et=require("yaml"),bt=require("yjs"),Tt=require("lodash/isNil"),C=require("sequelize");require("sqlite3");const N=t=>t&&t.__esModule?t:{default:t};function X(t){if(t&&t.__esModule)return t;const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const e in t)if(e!=="default"){const s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,s.get?s:{enumerable:!0,get:()=>t[e]})}}return n.default=t,Object.freeze(n)}const w=N(ot),It=N(Ne),Ot=N(rt),Pt=N(it),Ct=X(ct),jt=N(lt),At=N(pt),D=N(ut),pe=X(ft),_=X(mt),_t=N(ht),vt=N(h),Dt=N(wt),J=X(Et),B=X(bt),xt=N(Tt);w.default.env.mode;const kt="image-bin";w.default.env.INIT_TEMPLATE_PATH;const Rt=process.env.DATABASE_URL||vt.default.join(w.default.env.dataDir,"db/pages-kit.db"),ve=w.default,Lt=()=>w.default.env.tenantMode==="multiple",Nt=()=>{var t;return(xt.default(ve.env.preferences.multiTenantAllProjectAccessPassports)?[]:(t=ve.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:t.split(","))||[]},O=Ot.default("pages-kit"),Ut=C.DataTypes.sqlite.DATE.parse;C.DataTypes.sqlite.DATE.parse=(t,n)=>typeof t=="number"?new Date(t):Ut(t,n);const Z=new C.Sequelize({dialect:"sqlite",storage:Rt,benchmark:process.env.ENABLE_SEQUELIZE_BENCHMARK==="true",retry:{match:[/SQLITE_BUSY/],name:"query",max:10},logging:process.env.ENABLE_SEQUELIZE_LOGGING==="true"?console.log:!1});Z.query("pragma journal_mode = WAL;");Z.query("pragma synchronous = normal;");Z.query("pragma journal_size_limit = 67108864;");class ce extends C.Model{}ce.init({id:{type:C.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:C.DataTypes.UUIDV4},projectId:{type:C.DataTypes.UUID,allowNull:!1},componentId:{type:C.DataTypes.STRING,allowNull:!1}},{sequelize:Z,tableName:"ProjectComponents",timestamps:!1});class $ extends C.Model{static async getProjectByIdOrSlug(n){return $.findOne({where:{[C.Op.or]:[{id:n},{slug:n}]}})}}$.init({id:{type:C.DataTypes.UUID,defaultValue:C.DataTypes.UUIDV4,primaryKey:!0},name:{type:C.DataTypes.STRING,allowNull:!1},description:C.DataTypes.TEXT,createdAt:C.DataTypes.DATE,updatedAt:C.DataTypes.DATE,createdBy:{type:C.DataTypes.STRING,allowNull:!1},updatedBy:{type:C.DataTypes.STRING,allowNull:!1},slug:C.DataTypes.STRING,icon:C.DataTypes.STRING,pinnedAt:C.DataTypes.DATE,useAllResources:C.DataTypes.BOOLEAN,relatedBlocklets:{type:C.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(t){this.setDataValue("relatedBlocklets",JSON.stringify(t||{}))}}},{sequelize:Z,paranoid:!0});$.hasMany(ce,{foreignKey:"projectId",as:"components"});const Mt=async(t,{componentId:n})=>{const e=`@tailwind components;
|
|
2
|
+
@tailwind utilities;
|
|
3
|
+
`,s=`.CustomComponent_${n}`;return(await jt.default([At.default({content:[{raw:t,extension:"tsx"}]}),Pt.default({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),r=>{r.walkRules(l=>{l.selectors=l.selectors.map(a=>a.replace(/\.(.+)/g,`${s}.$1,${s} .$1`))})}]).process(e)).css},Ft=async(t,{componentId:n})=>{const e=await Mt(t,{componentId:n});return`export const __PagesKit_CSS__ = ${JSON.stringify(e)};
|
|
4
|
+
|
|
5
|
+
${t}
|
|
6
|
+
`},De=V.memoize(async(t,n)=>{let e=D.default.transpileModule(t,{compilerOptions:{jsx:D.default.JsxEmit.React,target:D.default.ScriptTarget.ES2016,module:D.default.ModuleKind.ESNext},transformers:{before:[Ue.createBuiltinModuleTransformer(D.default)]}}).outputText;if(n.tailwind&&(e=await Ft(e,{componentId:n.componentId})),n.module===se.PreloadComponentScriptModule.ESM)return e;const s=D.default.transpileModule(e,{compilerOptions:{jsx:D.default.JsxEmit.React,target:D.default.ScriptTarget.ES2016,module:D.default.ModuleKind.CommonJS,moduleResolution:D.default.ModuleResolutionKind.Node16}}).outputText;return n.module===se.PreloadComponentScriptModule.CJS?s:$t(n.moduleName,s)},{keyGenerator:(t,n)=>{const e=ie.createHash("md5").update(t).digest("hex"),s={...n,componentId:n.componentId,module:n.module,...n.module!==se.PreloadComponentScriptModule.ESM?{moduleName:n.moduleName}:{},tailwind:n.tailwind};return JSON.stringify(["transpileModule",e,s])},lruOptions:{max:100,ttl:1e3*60*60}}),qt=async(t,n)=>{var l,a;const s=(a=(l=(await Ct.build({entryPoints:["index.tsx"],external:Object.keys(at.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(i){let c=null;i.onResolve({filter:/.*/},p=>p.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:p.path==="./component"?{path:"component.tsx",namespace:"vfs"}:null),i.onLoad({filter:/.*/,namespace:"vfs"},async p=>{var u;if(p.path==="index.tsx")return{contents:`export { ${n} } from './component'`,loader:"tsx"};if(p.path==="component.tsx")return{contents:t,loader:"tsx"};if(Ue.isRelativeModule(p.path)){const f=p.path.split("/").pop();if(c||(c=await Ae({ensureLoaded:!1})),(u=c==null?void 0:c.chunks)!=null&&u[f])try{const g=E.readFileSync(c.chunks[f],"utf-8");return O.info("get chunk from local file system",f),{contents:g,loader:"tsx"}}catch{}}return null})}}]})).outputFiles)==null?void 0:l[0])==null?void 0:a.contents;if(!s)throw new Error("Failed to build server code");const o=Buffer.from(s).toString();return D.default.transpileModule(o,{compilerOptions:{module:D.default.ModuleKind.ESNext,target:D.default.ScriptTarget.ES2020}}).outputText},Me=V.memoize(async(t,n)=>{const e=await qt(t,n);return new RegExp(`export\\s+\\{\\s+${n}\\s+\\}`,"m").test(e)?e:void 0},{keyGenerator:(t,n)=>{const e=ie.createHash("md5").update(t).digest("hex");return JSON.stringify(["extractExportValueSchema",e,n])},lruOptions:{max:100,ttl:1e3*60*60}}),$t=(t,n)=>{const e=/\bawait\b/.test(n);return`// GENERATED FILE. DO NOT EDIT.
|
|
7
|
+
var ${t} = ${e?"async":""} function () {
|
|
8
|
+
|
|
9
|
+
const exports = {};
|
|
10
|
+
let moduleExports = null;
|
|
11
|
+
|
|
12
|
+
// add commonjs module compatibility layer
|
|
13
|
+
const module = { exports: moduleExports };
|
|
14
|
+
|
|
15
|
+
// execute component code
|
|
16
|
+
${n}
|
|
17
|
+
|
|
18
|
+
// handle possible module.exports
|
|
19
|
+
if (module.exports && module.exports !== moduleExports) {
|
|
20
|
+
// if module.exports is used, use it first
|
|
21
|
+
return typeof module.exports === 'object' ? module.exports : { default: module.exports };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// ensure a default export
|
|
25
|
+
if (!('default' in exports) && Object.keys(exports).length === 0) {
|
|
26
|
+
// module has no exports, return null to indicate invalid
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return exports;
|
|
31
|
+
};
|
|
32
|
+
`},K=new Ee.LRUCache({max:100}),Fe=60*60,me=60;function qe(t){O.info("clear preload components cache",{cacheKey:t}),K.delete(t)}function $e(t){for(const n of K.keys())n.includes(t)&&(O.info("clear preload components cache",{cacheKey:n}),qe(n))}function Be({mode:t,instanceId:n,componentId:e,locale:s}){return["getPreloadComponents",t,n,e,s].join("-")}async function Bt({mode:t,req:n,state:e,locale:s,instances:o,module:r}){const{supportedLocales:l,config:{defaultLocale:a}}=e;if(!a)return null;const i=(await Promise.all(o.map(async g=>{try{const S=Be({mode:t,instanceId:g.id,componentId:g.componentId,locale:s});if(t!=="draft"&&g.useCache&&K.has(S))return O.info(`get preload component from cache: ${S}`),K.get(S);const j=W({state:e,componentId:g.componentId});if(!j)return null;const v=await Ve({req:n,state:e,componentId:j.id,locale:s,defaultLocale:a,properties:g.properties});if(!v)return null;const F={instanceId:g.id,preload:v};if(t!=="draft"&&g.useCache){let R=Fe;g.cacheDuration&&(R=g.cacheDuration),O.info(`set preload component to cache(${R}s): ${S}`),K.set(S,F,{ttl:R*1e3})}return F}catch(S){return O.error("get preload component error",{instanceId:g.id,componentId:g.componentId},{error:S}),null}}))).filter(g=>!!g),c=Object.values(i.reduce((g,S)=>({...g,...S.preload.components}),{}));async function p(){const g=await Promise.all(c.map(async S=>{const j=oe.componentUMDName({componentId:S.component.id}),v=r===se.PreloadComponentScriptModule.ESM?{module:r,script:await De(S.script,{componentId:S.component.id,module:r,tailwind:t!=="draft"})}:{module:r,script:await De(S.script,{componentId:S.component.id,module:r,moduleName:j,tailwind:t!=="draft"}),moduleName:j};return[S.component.id,{component:S.component,script:v}]}));return Object.fromEntries(g)}const u=await p();return{config:{defaultLocale:a,supportedLocales:l},components:u,instances:i.map(g=>({id:g.instanceId,componentId:g.preload.component.id,locales:{[g.preload.locale]:{props:g.preload.props}}}))}}async function Ve({req:t,state:n,componentId:e,locale:s,defaultLocale:o,properties:r}){const{supportedLocales:l}=n,a=W({state:n,componentId:e});if(!a)return null;const i=l.some(p=>p.locale===s)?s:o;if(!i)return null;const c=await He({req:t,state:n,componentId:e,locale:i,defaultLocale:o,properties:r});return c?{component:a,...c}:null}const Vt=20;async function He({req:t,depth:n=0,state:e,componentId:s,locale:o,defaultLocale:r,properties:l}){if(n>Vt)throw new RangeError("max component depth exceeded");const a=Ht({state:e,componentId:s,properties:l,locale:o});if(!a)return null;const{props:i}=a,c={locale:o||r,components:{[a.component.id]:{component:a.component,script:a.script}},props:{...i}};try{const p=await zt({...a,req:t});p!=null&&p.props&&Object.assign(c.props,p.props)}catch(p){O.error("preload data at server side error",{componentId:s,name:a.component.name},{error:p})}return await Promise.all(Object.entries(i).map(async([p,u])=>{if((u==null?void 0:u.type)===oe.RenderNestedComponent){const f=await He({req:t,depth:n+1,state:e,componentId:u.componentId,locale:o,defaultLocale:r,properties:u.properties});f&&(Object.assign(c.components,f.components),Object.assign(c.props,{[p]:{type:oe.RenderNestedComponent,componentId:u.componentId,props:f.props}}))}})),c}function Ht({state:t,componentId:n,locale:e,properties:s}){const o=W({state:t,componentId:n});if(!o)return null;const r=oe.mergeComponent({componentId:n,getComponent:l=>W({state:t,componentId:l}),locale:e,defaultLocale:t.config.defaultLocale,properties:s});return r?{component:o,script:r.script,props:{locale:e,...r.properties}}:null}function W({state:t,componentId:n}){var e,s,o;return((e=t.components[n])==null?void 0:e.data)??((o=(s=t.resources.components)==null?void 0:s[n])==null?void 0:o.component)}function Gt({state:t,name:n}){var s,o;const e=n.toLowerCase();return((s=Object.values(t.components).find(r=>{var l;return((l=r.data.name)==null?void 0:l.toLowerCase())===e}))==null?void 0:s.data)??((o=t.resources.components&&Object.values(t.resources.components).find(r=>{var l;return((l=r.component.name)==null?void 0:l.toLowerCase())===e}))==null?void 0:o.component)}async function zt({component:t,script:n,props:e,req:s}){if(!(n!=null&&n.includes("getServerSideProps")))return null;const o=await Me(n,"getServerSideProps");if(!o)return null;const r=new Promise((a,i)=>{setTimeout(()=>{i(new Error("getServerSideProps timeout in promise race"))},me*1e3)});return await Promise.race([r,V.Sandbox.callFunction({code:`${o}
|
|
33
|
+
|
|
34
|
+
export async function getServerSidePropsWrapper(props) {
|
|
35
|
+
const { location, fetch } = props;
|
|
36
|
+
// 使用局部变量而不是全局变量
|
|
37
|
+
const originalLocation = typeof window !== 'undefined' ? window.location : undefined;
|
|
38
|
+
const originalFetch = globalThis.fetch;
|
|
39
|
+
|
|
40
|
+
try {
|
|
41
|
+
globalThis.location = location;
|
|
42
|
+
globalThis.fetch = fetch;
|
|
43
|
+
return await getServerSideProps(props);
|
|
44
|
+
} finally {
|
|
45
|
+
// 清理全局状态
|
|
46
|
+
if (originalLocation) globalThis.location = originalLocation;
|
|
47
|
+
if (originalFetch) globalThis.fetch = originalFetch;
|
|
48
|
+
}
|
|
49
|
+
}`,filename:`${t.name||t.id}.js`,moduleLoader:a=>{if(a==="@blocklet/pages-kit/builtin/utils")return`const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
|
|
50
|
+
export { joinURL, withQuery, getQuery, getComponentMountPoint }
|
|
51
|
+
`;if(a==="@blocklet/pages-kit/builtin/dayjs")return V.BuiltinModules.dayjs},global:{console:{log:(...a)=>{O.info(...a)},warn:(...a)=>{O.warn(...a)},error:(...a)=>{O.error(...a)}},getComponentMountPoint:nt.getComponentMountPoint,joinURL:x.joinURL,withQuery:x.withQuery,getQuery:x.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:x.joinURL(x.withHttps(s.hostname),s.originalUrl)},fetch:(a,{...i}={})=>{const c=typeof a=="string"&&a.startsWith("/")?x.joinURL(w.default.env.appUrl,a):a;if(typeof c=="string"&&x.parseURL(c).host===x.parseURL(w.default.env.appUrl).host){const p=s.get("cookie");if(p){const u=new Ne.Headers(i.headers);u.set("cookie",p),i.headers=u}}return It.default(c,{...i,timeout:me*1e3}).then(p=>({ok:p.ok,status:p.status,statusText:p.statusText,headers:Object.fromEntries(p.headers.entries()),json:()=>p.json()}))},props:e}]})])}const Ge=V.memoize(async(t,n,e)=>{if(!(t!=null&&t.includes(n)))return null;const s=await Me(t,n);if(s)try{return await V.Sandbox.callFunction({code:`
|
|
52
|
+
${s}
|
|
53
|
+
|
|
54
|
+
export function get${n}SchemaWrapper() {
|
|
55
|
+
return ${n};
|
|
56
|
+
}
|
|
57
|
+
`,filename:`${e}.js`,functionName:`get${n}SchemaWrapper`})}catch(o){return O.error(`获取 ${n} 失败`,{componentId:e,error:o}),null}return null},{keyGenerator:(t,n,e)=>{const s=ie.createHash("md5").update(t).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",s,n,e])},lruOptions:{max:100,ttl:1e3*60*60}}),Jt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",ge="page",he="trigger-reload-project-resource",Te=Jt,Kt="z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV",{uploadToMediaKit:Yt}=require("@blocklet/uploader-server"),ye=gt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),Ie=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,Y=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,xe=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Wt=1e4,Qt=3e4,te=0,ue=1,Xt=0,Zt=1,Se=w.default,z=h.join(process.env.BLOCKLET_DATA_DIR,"site-state"),es=["production","draft"],ts=["production"];function ze(t){return(t==null?void 0:t.replace(/\//g,"|"))||""}function ss(){var e;const t=Se.env.languages.map(s=>({locale:s.code,name:s.name})),n=(e=t[0])==null?void 0:e.locale;return{pageIds:[],pages:{},components:{},supportedLocales:t,config:{defaultLocale:n},resources:{}}}const q=class q extends B.Doc{constructor(e){super();A(this,"states",{});A(this,"syncedStore");A(this,"conns",new Map);A(this,"awareness");A(this,"awarenessChangeHandler",({added:e,updated:s,removed:o},r)=>{const l=e.concat(s,o);if(r!==null){const c=this.conns.get(r);c&&(e.forEach(p=>{c.add(p)}),o.forEach(p=>{c.delete(p)}))}const a=_.createEncoder();_.writeVarUint(a,ue),_.writeVarUint8Array(a,G.encodeAwarenessUpdate(this.awareness,l));const i=_.toUint8Array(a);this.conns.forEach((c,p)=>this.send(p,i))});A(this,"updateHandler",e=>{const s=_.createEncoder();_.writeVarUint(s,te),le.writeUpdate(s,e);const o=_.toUint8Array(s);this.conns.forEach((r,l)=>this.send(l,o))});A(this,"ensureDataStructure",()=>{var l;const{supportedLocales:e,pages:s,pageIds:o,config:r}=this.syncedStore;{const a=new Set(Object.keys(s));let i=0;for(;i<o.length;){const c=o[i];a.has(c)?(a.delete(c),i++):o.splice(i,1)}}e.splice(0,e.length),e.push(...Se.env.languages.map(a=>({locale:a.code,name:a.name}))),r.defaultLocale=(l=e[0])==null?void 0:l.locale;{let a=0;const i=new Set;for(;a<e.length;){const{locale:c}=e[a];i.has(c)?e.splice(a,1):(a++,i.add(c))}}});A(this,"send",(e,s)=>{e.readyState!==Xt&&e.readyState!==Zt&&this.closeConn(e);try{e.send(s,o=>{o&&this.closeConn(e)})}catch{this.closeConn(e)}});A(this,"closeConn",e=>{if(e.removeAllListeners(),this.conns.has(e)){const s=this.conns.get(e);this.conns.delete(e),s&&G.removeAwarenessStates(this.awareness,Array.from(s),null)}e.close()});A(this,"autoSave",L.debounce(()=>{E.mkdirSync(h.dirname(this.draftYjsFilePath),{recursive:!0}),E.writeFileSync(this.draftYjsFilePath,B.encodeStateAsUpdate(this))},Wt));A(this,"save",({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()});A(this,"publish",async({mode:e,pages:s})=>{const o=await this.getState("draft"),r=await this.getState("production");await we(o,r,{pages:s,pageMergeMode:"replace",deletePages:!0,publishMode:e}),r.config.publishedAt=new Date().getTime();for(const l of s||Object.keys(this.syncedStore.pages))this.syncedStore.pages[l]&&(this.syncedStore.pages[l].publishedAt=new Date().toISOString());await this.setState(e,r)});A(this,"mergeState",async(e,s)=>{var a,i,c;const o=JSON.parse(JSON.stringify(s));(a=e.config).fontFamily??(a.fontFamily={});const r=(i=o.config)==null?void 0:i.fontFamily,l=(c=e.config)==null?void 0:c.fontFamily;e.config.fontFamily.title=(r==null?void 0:r.title)||(l==null?void 0:l.title),e.config.fontFamily.description=(r==null?void 0:r.description)||(l==null?void 0:l.description),await new Promise((p,u)=>{this.transact(async()=>{try{const f=await we(e,s);p(f)}catch(f){u(f)}})})});A(this,"addConnection",e=>{if(this.conns.has(e))return;e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",r=>this.messageListener(e,new Uint8Array(r)));let s=!0;const o=setInterval(()=>{if(!s)this.conns.has(e)&&this.closeConn(e),clearInterval(o);else if(this.conns.has(e)){s=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(o)}}},Qt);e.on("close",()=>{this.closeConn(e),clearInterval(o)}),e.on("pong",()=>{s=!0});{const r=_.createEncoder();_.writeVarUint(r,te),le.writeSyncStep1(r,this),this.send(e,_.toUint8Array(r));const l=this.awareness.getStates();if(l.size>0){const a=_.createEncoder();_.writeVarUint(a,ue),_.writeVarUint8Array(a,G.encodeAwarenessUpdate(this.awareness,Array.from(l.keys()))),this.send(e,_.toUint8Array(a))}}});A(this,"messageListener",(e,s)=>{try{const o=_.createEncoder(),r=pe.createDecoder(s),l=pe.readVarUint(r);switch(l){case te:_.writeVarUint(o,te),le.readSyncMessage(r,o,this,null),_.length(o)>1&&(this.ensureDataStructure(),this.send(e,_.toUint8Array(o)));break;case ue:{G.applyAwarenessUpdate(this.awareness,pe.readVarUint8Array(r),e);break}default:O.warn(`Unsupported messageType ${l}`)}}catch(o){O.error(o)}this.save()});this.options=e,E.existsSync(this.draftYjsFilePath)&&B.applyUpdate(this,E.readFileSync(this.draftYjsFilePath)),this.syncedStore=dt.reactive(ee.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new G.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const s=h.join(z,e),o=h.join(z,`@del-${e}`);E.renameSync(s,o)}catch(s){O.error("Failed to safe delete project state dir:",s)}}static get projectIds(){return fe.globSync("*/",{cwd:z,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(e=>q.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let s=this.sharedInstances.get(e);return s||(s=new q({path:h.join(z,e)}),this.sharedInstances.set(e,s),s)}destroy(){this.conns.forEach((e,s)=>this.closeConn(s)),this.awareness.destroy(),super.destroy()}initObserver(){const e=o=>{o.observeDeep(r=>{r.some(l=>l.changes.keys.has("updatedAt")||l.changes.keys.has("publishedAt"))||o.set("updatedAt",new Date().toISOString())})};this.syncedStore.pages&&Object.keys(this.syncedStore.pages).forEach(o=>{const r=ee.getYjsValue(this.syncedStore.pages[o]);r&&r instanceof B.Map&&e(r)});const s=ee.getYjsValue(this.syncedStore.pages);s&&s instanceof B.Map&&s.observe(o=>{o.changes.keys.forEach((r,l)=>{if(r.action==="add"){const a=ee.getYjsValue(this.syncedStore.pages[l]);a&&a instanceof B.Map&&e(a)}})})}get draftYjsFilePath(){return h.join(this.options.path,"draft.yjs")}async getState(e){var s,o,r,l;if(e==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[e]&&(this.states[e]=await Oe(this.getPublishDir(e),{includeResources:!0})??ss(),!((o=(s=this.states[e])==null?void 0:s.config)!=null&&o.defaultLocale))){(r=this.states[e]).config??(r.config={});const a=Se.env.languages.map(i=>({locale:i.code,name:i.name}));this.states[e].config.defaultLocale=(l=a[0])==null?void 0:l.locale}return{...this.states[e],resources:await Ae().then(async a=>{var u,f,g,S;const{pages:i,components:c}=L.pick(a,"pages","components");let p=c;if((f=(u=this.states[e])==null?void 0:u.resources)!=null&&f.components)p={...(S=(g=this.states[e])==null?void 0:g.resources)==null?void 0:S.components};else{const j=h.basename(this.options.path),v=await $.findByPk(j);if(v!=null&&v.useAllResources)p=c;else{const R=(await ce.findAll({where:{projectId:j}})).map(T=>T.componentId);p=Object.fromEntries(Object.entries(c||{}).filter(([T])=>R.includes(T)))}}return{pages:i,components:p}}).catch(()=>({}))}}async setState(e,s){const o=await Ye(s,{exportAssets:!1,includeResources:!0}),r=this.getPublishDir(e);E.mkdirSync(h.dirname(r),{recursive:!0}),E.rmSync(r,{force:!0,recursive:!0}),E.renameSync(o,r),this.states[e]=s}getPublishDir(e){return h.join(this.options.path,e)}static async pageUrlMap(e){const{projectIds:s}=this,o={};for(const r of s){const l=await $.findByPk(r);if(!l)continue;const a=await q.shared(r).getState(e),i=L.union(w.default.env.languages.map(c=>c.code),a.supportedLocales.map(c=>c.locale));for(const c of a.pageIds){const p=a.pages[c];if(!p||e==="production"&&!p.isPublic)continue;const u=p.slug,f=l.slug||r,g={projectId:r,projectSlug:f,pageSlug:u,pageId:c,defaultLocale:i==null?void 0:i[0],locales:i,publishedAt:a.config.publishedAt,isPublic:p.isPublic,isTemplate:p.isTemplate};f&&(o[x.joinURL("/",f,u)]={...g,shouldRedirect:!0,mainPage:!0}),o[x.joinURL("/",r,u)]={...g,shouldRedirect:!0,mainPage:!0};for(const S of i){const j={...g,locale:S};o[x.joinURL("/",S,r,u)]=j,f&&(o[x.joinURL("/",S,f,u)]=j)}}}return o}getDocumentSize(){return B.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const e=[];for(const[s,o]of this.sharedInstances.entries()){const r=o.getDocumentSize();e.push({projectId:s,sizeInBytes:r,sizeInMB:`${(r/(1024*1024)).toFixed(2)} MB`,activeConnections:o.conns.size})}return e}};A(q,"INSTANCE_TTL",30*60*1e3),A(q,"sharedInstances",new Ee.LRUCache({max:100,ttl:q.INSTANCE_TTL,dispose:e=>{e.destroy()}}));let Q=q;function Je(){return E.mkdtempSync(h.join(w.default.env.dataDir,"tmp-"))}function re(t,n,e=[]){return Array.isArray(t)?t.flatMap((s,o)=>re(s,n,[...e,o])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([s,o])=>re(o,n,[...e,s])):n(t)?[e]:[]}function M(t){return t.filter(n=>n!=null)}async function ns(t,n,e){if(!t||!E.existsSync(t)||!E.lstatSync(t).isFile())return null;let s=e[t];return s||(s=(async()=>{var o;try{const r=(o=await Yt({filePath:t,fileName:n}))==null?void 0:o.data;return r==null?void 0:r.filename}catch(r){return O.error(`Failed to upload asset ${t}:`,r),null}})(),e[t]=s),s}const os=async(t,n)=>{const e=h.basename(t),s=await be.call({name:Te,path:x.joinURL("/uploads",e),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const o=E.createWriteStream(n);await yt.pipeline(s.data,o)}else throw new Error(`download asset failed ${s.status}`)},rs=async(t,n)=>{await Promise.all(t.map(async e=>{try{await os(e,h.join(n,h.basename(e)))}catch(s){O.error(`Failed to export assets: ${e}, ${s}`)}}))};function Ke(t){return Ie.test(t)?[t]:Y.test(t)?(xe.lastIndex=0,Array.from(t.matchAll(xe)).map(e=>e[1]).filter(e=>!!e)):[]}async function de(t,n,e){const{getFilename:s,exportAssets:o}=e,r=h.join(n,s(t));if(E.mkdirSync(h.dirname(r),{recursive:!0}),E.writeFileSync(r,J.stringify(t)),o){const a=re(t,i=>typeof i=="string"&&(Ie.test(i)||Y.test(i))).map(i=>{const c=L.get(t,i);return Ke(c)}).flat().filter(Boolean);await rs(a,h.dirname(r))}}const ke=new Ee.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function Re(t,n,e){var a;const s=re(t,i=>typeof i=="string"&&(Ie.test(i)||Y.test(i))),o=_t.default(2),r=s.map(i=>o(async()=>{try{const c=L.get(t,i),p=Ke(c);for(const u of p){const f=h.basename(u),g=e.getFilePath(u,i),S=g?`${g}:${f}`:f,j=ke.get(S);if(j){Y.test(c)||L.set(t,i,j);return}const v=await ns(g,f,n);v&&(Y.test(c)||L.set(t,i,v),ke.set(S,v))}}catch(c){O.error(`Failed to process upload for path ${i.join(".")}:`,c.message||c.reason)}})),l=await Promise.allSettled(r);(a=e.onFinish)==null||a.call(e,l)}async function Ye(t,{exportAssets:n,pageIds:e="all",componentIds:s="all",rawConfig:o,includeResources:r=!1}={}){var F,R,y,T,I,P;const l=e==="all"?t.pageIds:e,a=as({state:t,pageIds:l,componentIds:s==="all"?Object.keys(t.components):s}),i=(m,d)=>{var b;return{id:m.id,name:m.name,isTemplateSection:m.isTemplateSection??!1,templateDescription:m.templateDescription,component:m.component,config:m.config,visibility:m.visibility,properties:((b=m.locales)==null?void 0:b[d])??{}}},c=(m,d)=>{var b;return{id:m.id,createdAt:m.createdAt,updatedAt:m.updatedAt,publishedAt:m.publishedAt,isPublic:m.isPublic??!0,isTemplate:m.isTemplate??!1,meta:((b=m.locales)==null?void 0:b[d])??{},sections:M(m.sectionIds.map(k=>{const U=m.sections[k];return U&&i(U,d)}))}},p=M(t.supportedLocales.map(m=>m.locale).flatMap(m=>l.map(d=>{const b=t.pages[d];return b&&{locale:m,slug:b.slug,page:c(b,m)}}))),u=Je(),f=h.join(u,"pages");E.mkdirSync(f,{recursive:!0});const g=h.join(u,"components");E.mkdirSync(g,{recursive:!0});for(const{locale:m,slug:d,page:b}of p)await de(b,f,{getFilename:()=>`${ze(d)||"index"}.${m}.yml`,exportAssets:n});for(const m of a){const d=(F=t.components[m])==null?void 0:F.data;d&&await de(d,g,{getFilename:b=>`${b.name||"unnamed"}.${b.id}.yml`,exportAssets:n})}const S=h.join(u,".blocklet/pages/pages.config.yml");E.mkdirSync(h.dirname(S),{recursive:!0});const j={pages:M(l.map(m=>{const d=t.pages[m];return d&&{id:m,slug:d.slug}})),components:M(a.map(m=>{var b;const d=(b=t.components[m])==null?void 0:b.data;return d&&{id:m,name:d.name}})),...r?{resources:{components:M(Object.keys(((R=t.resources)==null?void 0:R.components)||{}).map(m=>{var d,b,k,U;return{id:m,name:(U=(k=(b=(d=t.resources)==null?void 0:d.components)==null?void 0:b[m])==null?void 0:k.component)==null?void 0:U.name}}))}}:{},supportedLocales:t.supportedLocales,config:t.config};E.writeFileSync(S,J.stringify(j));const v=h.join(u,"config.source.json");if(o&&E.writeFileSync(v,JSON.stringify(o)),r){const m=h.join(u,"resources"),d=h.join(m,"components");E.mkdirSync(d,{recursive:!0});for(const b of Object.keys(((y=t==null?void 0:t.resources)==null?void 0:y.components)??{})){const k=(P=(I=(T=t.resources)==null?void 0:T.components)==null?void 0:I[b])==null?void 0:P.component;k&&await de(k,d,{getFilename:U=>`${U.name||"unnamed"}.${U.id}.yml`,exportAssets:n})}}return u}async function Oe(t,{importAssets:n,includeResources:e}={}){var r,l,a;if(!E.existsSync(t))return null;let s,o=!1;try{E.lstatSync(t).isDirectory()?s=t:/\.(tgz|gz|tar)$/.test(t)&&(o=!0,s=Je(),await St.x({file:t,C:s}));const i=fe.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}).at(0),c=i&&h.join(h.dirname(i),"../../pages"),p=i&&h.join(h.dirname(i),"../../components"),u=i&&h.join(h.dirname(i),"../../chunks");if(!i)return null;const f=J.parse(E.readFileSync(i).toString()),g=(y,T,I)=>{let P=h.join(y,`${T}${I?`.${I}`:""}.yml`);return(!E.existsSync(P)||!E.lstatSync(P).isFile())&&(P=h.join(y,T,`index${I?`.${I}`:""}.yml`),!E.existsSync(P)||!E.lstatSync(P))?null:J.parse(E.readFileSync(P).toString())},S=(y,T)=>{try{const I=fe.globSync(`*.${T}.yml`,{cwd:y,absolute:!0})[0];return I?J.parse(E.readFileSync(I).toString()):null}catch(I){O.error("parse component error",I)}return null},j=M(f.pages.map(({slug:y})=>{var m;const T=M(f.supportedLocales.map(({locale:d})=>{const b=c?g(c,ze(y),d):void 0;if(b)return{locale:d,page:b};const k=c?g(c,y,d):void 0;return k&&{locale:d,page:k}})),I=(m=T[0])==null?void 0:m.page;if(!I)return null;const P=I.sections.map(d=>{const b=d.id||ye();return{id:b,component:d.component,config:d.config,name:d.name,isTemplateSection:d.isTemplateSection??!1,templateDescription:d.templateDescription,visibility:d.visibility,locales:Object.fromEntries(M(T.map(({locale:k,page:U})=>{const _e=U.sections.find(et=>et.id===b);return _e&&[k,_e.properties]})))}});return{id:I.id||ye(),createdAt:I.createdAt,updatedAt:I.updatedAt,publishedAt:I.publishedAt,isPublic:I.isPublic??!0,isTemplate:I.isTemplate??!1,slug:y,sections:Object.fromEntries(P.map(d=>[d.id,d])),sectionIds:P.map(d=>d.id),locales:Object.fromEntries(T.map(({locale:d,page:b})=>[d,b.meta]))}})),v=p?M(((r=f.components)==null?void 0:r.map(({id:y})=>S(p,y)))??[]):[];if(n){const y=(...T)=>{O.info(`[${o?h.basename(t):h.basename(h.join(t,"../../../../"))}] importAssets:`,...T)};try{y("wait image-bin api ready"),await Dt.default({resources:[`${be.getComponentWebEndpoint(kt)}/api/sdk/uploads`],validateStatus:P=>P>=200&&P<=500}),y("image-bin api is ready");const T={},I={};y("start to upload assets"),await Promise.allSettled([Re(v,T,{getFilePath:P=>p&&h.join(p,P),onFinish:P=>{y(`upload ${P.length} component assets`)}}),Re(j,I,{getFilePath:(P,m)=>{const d=L.get(j,m.slice(0,1));return c&&h.join(c,h.dirname(d.slug),P)},onFinish:P=>{y(`upload ${P.length} page assets`)}})]),y("upload assets done"),global.gc&&global.gc()}catch(T){y("Error during asset import:",T)}}const F={};if(e){const y=i&&h.join(h.dirname(i),"../../resources/components"),T=M(((a=(l=f.resources)==null?void 0:l.components)==null?void 0:a.map(({id:I})=>S(y,I)))??[]);T.length>0&&(F.components=Object.fromEntries(T.map((I,P)=>[I.id,{index:P,component:I}])))}const R={};if(u&&E.existsSync(u)){const y=E.readdirSync(u);for(const T of y)R[T]=h.join(u,T)}return{supportedLocales:f.supportedLocales,pageIds:j.map(y=>y.id),components:Object.fromEntries(v.map((y,T)=>[y.id,{index:T,data:y}])),pages:Object.fromEntries(j.map(y=>[y.id,y])),config:f.config||{},resources:F,chunks:R}}finally{o&&s&&E.rmSync(s,{force:!0,recursive:!0})}}async function we(t,n,{pages:e,pageMergeMode:s="byUpdateTime",deletePages:o=!1,publishMode:r=void 0}={}){try{r&&$e(r)}catch(p){O.error("clear preload page cache error",{error:p})}const{pageIds:l,pages:a,supportedLocales:i}=t;for(const p of e??l){const u=a[p];if(!u){const f=n.pageIds.indexOf(p);f!==-1&&o&&(n.pageIds.splice(f,1),delete n.pages[p]);continue}if(n.pageIds.includes(u.id)){if(s==="replace")n.pages[u.id]=u;else if(s==="byUpdateTime"){const f=n.pages[u.id];(!f||u.updatedAt&&u.updatedAt>f.updatedAt)&&(n.pages[u.id]=u)}}else n.pageIds.push(u.id),n.pages[u.id]=u}if(o&&!e)for(const p of n.pageIds)t.pageIds.includes(p)||delete n.pages[p],n.pageIds=[...n.pageIds].filter(u=>t.pageIds.includes(u));if(n.supportedLocales.splice(0,n.supportedLocales.length),n.supportedLocales.push(...L.cloneDeep(i)),o)for(const p of Object.keys(n.components))delete n.components[p];let c=JSON.parse(JSON.stringify(t.components));c=Object.fromEntries(await Promise.all(Object.entries(c).map(async([p,u])=>{const f=await We(u==null?void 0:u.data);return[p,{...u,data:f}]}))),Object.assign(n.components,c),Object.assign(n.config,JSON.parse(JSON.stringify(t.config))),n.resources.components=JSON.parse(JSON.stringify(t.resources.components||{}))}const We=V.memoize(async t=>{var n;if(!L.isEmpty(t==null?void 0:t.properties))return t;if(((n=t==null?void 0:t.renderer)==null?void 0:n.type)==="react-component"){const{script:e}=(t==null?void 0:t.renderer)||{};if(e&&e.includes("PROPERTIES_SCHEMA"))try{const s=await Ge(e,"PROPERTIES_SCHEMA",t.id);s&&s.length>0&&t&&(t.properties={},s.forEach((o,r)=>{t!=null&&t.properties&&(t.properties[o.id]={index:r,data:o})}))}catch(s){O.error("checkPropertiesFromCode error",{componentId:t.id,name:t.name},{error:s})}}return t},{keyGenerator:t=>{var l;const n=(t==null?void 0:t.id)||"",e=(t==null?void 0:t.name)||"",s=((l=t==null?void 0:t.renderer)==null?void 0:l.type)||"",o=(t==null?void 0:t.properties)||{},r=ie.createHash("md5").update(JSON.stringify(o)).digest("hex");return JSON.stringify(["checkPropertiesFromCode",n,e,s,r])},lruOptions:{max:100,ttl:1e3*60*60}});function as({state:t,pageIds:n=[],componentIds:e=[]}){var l;const s=(a,i=new Set)=>(Array.isArray(a)&&a.forEach(c=>s(c,i)),a&&typeof a=="object"&&(typeof a.componentId=="string"&&i.add(a.componentId),Object.values(a).forEach(c=>s(c,i))),i),o=new Set(e);for(const a of n){const i=t.pages[a];s(i,o)}const r=[...o];for(;r.length;){const a=r.shift();o.has(a)||o.add(a);const i=(l=t.components[a])==null?void 0:l.data;if(i)for(const c of s(i))o.has(c)||r.push(c)}return[...o]}let ae,H,Pe,Ce,je;function Qe(){return ae=(async()=>{const t=be.getResources({types:[{did:Te,type:ge},{did:Kt,type:ge}]});H=(await Promise.all(t.map(async e=>{const s=e.path?await Oe(e.path,{importAssets:!1}):void 0;return s?{blockletId:e.did,state:s,blockletTitle:e.title}:void 0}))).filter(e=>!!e),Pe=H.reduce((e,s)=>Object.assign(e,Object.fromEntries(Object.values(s.state.pages).map(o=>o?[o==null?void 0:o.id,{page:o,blockletId:s.blockletId}]:[]))),{});const n=H.reduce((e,s)=>Object.assign(e,Object.fromEntries(Object.values(s.state.components).map(o=>[o.data.id,{blockletId:s.blockletId,component:o.data}]))),{});Ce=Object.fromEntries(await Promise.all(Object.entries(n).map(async([e,s])=>{const o=await We(s.component);return[e,{...s,component:o}]}))),je=H.reduce((e,s)=>Object.assign(e,s.state.chunks),{})})(),ae}function Xe(t){const n=L.debounce(async()=>{await Qe().catch(e=>{O.error("load resource states error",{error:e})}),await(t==null?void 0:t({states:H,pages:Pe,components:Ce,chunks:je}))},3e3,{leading:!1,trailing:!0});return n(),w.default.events.on(w.default.Events.componentAdded,n),w.default.events.on(w.default.Events.componentRemoved,n),w.default.events.on(w.default.Events.componentStarted,n),w.default.events.on(w.default.Events.componentStopped,n),w.default.events.on(w.default.Events.componentUpdated,n),w.default.events.on(he,n),()=>{w.default.events.off(w.default.Events.componentAdded,n),w.default.events.off(w.default.Events.componentRemoved,n),w.default.events.off(w.default.Events.componentStarted,n),w.default.events.off(w.default.Events.componentStopped,n),w.default.events.off(w.default.Events.componentUpdated,n),w.default.events.off(he,n)}}const Ze=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),ne=globalThis;var Le;(Le=ne[Ze])==null||Le.call(ne);ne[Ze]=Xe(async({pages:t,components:n})=>{const{projectIds:e}=Q;O.info(`start update resource states projects(${e.length})`,e),await Promise.race([Promise.all(e.map(async s=>{const o=Q.shared(s);o.syncedStore.resources.pages=t;const r=await $.findByPk(s);if(r!=null&&r.useAllResources)o.syncedStore.resources.components=n;else{const a=(await ce.findAll({where:{projectId:s}})).map(c=>c.componentId),i=Object.fromEntries(Object.entries(n||{}).filter(([c])=>a.includes(c)));o.syncedStore.resources.components=i}O.info(`update [${s}] resource states:`,{pages:Object.keys(o.syncedStore.resources.pages||{}).length,components:Object.keys(o.syncedStore.resources.components||{}).length})})),new Promise((s,o)=>{setTimeout(()=>{o(new Error("timeout to update resource states"))},30*1e3)})]).catch(s=>{O.error("update resource states failed:",s)})});async function is(){O.info("trigger reload all project resource"),w.default.events.emit(he)}async function Ae({ensureLoaded:t=!0}={}){return t&&(ae??(ae=Qe()),await ae),{states:H,pages:Pe,components:Ce,chunks:je}}exports.COMPONENT_DID=Te;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=Fe;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=me;exports.PUBLISH_MODES=ts;exports.Project=$;exports.RESOURCE_TYPE=ge;exports.SITE_STATE_PATH=z;exports.STATE_MODES=es;exports.SiteState=Q;exports.clearPreloadComponentsCache=qe;exports.clearPreloadComponentsCacheByMode=$e;exports.fromPackage=Oe;exports.getComponentFromState=W;exports.getComponentFromStateByName=Gt;exports.getExportSchemaValueFromCode=Ge;exports.getMultiTenantAllProjectAccessPassports=Nt;exports.getPreloadComponent=Ve;exports.getPreloadComponents=Bt;exports.getPreloadComponentsCacheKey=Be;exports.getResourceStates=Ae;exports.initPackResourceStates=Xe;exports.isMultiTenant=Lt;exports.logger=O;exports.mergeState=we;exports.nextId=ye;exports.toPackage=Ye;exports.triggerReloadAllProjectResource=is;
|
package/lib/cjs/components.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});require("@blocklet/pages-kit/builtin/utils");require("@blocklet/pages-kit/types");require("@blocklet/pages-kit/utils/property");require("@blocklet/quickjs");require("@blocklet/sdk/lib/config");require("lru-cache");require("node-fetch");require("ufo");require("crypto");const e=require("./_chunks/site-state-
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});require("@blocklet/pages-kit/builtin/utils");require("@blocklet/pages-kit/types");require("@blocklet/pages-kit/utils/property");require("@blocklet/quickjs");require("@blocklet/sdk/lib/config");require("lru-cache");require("node-fetch");require("ufo");require("crypto");const e=require("./_chunks/site-state-C0hyEwRs.js");exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=e.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=e.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS;exports.clearPreloadComponentsCache=e.clearPreloadComponentsCache;exports.clearPreloadComponentsCacheByMode=e.clearPreloadComponentsCacheByMode;exports.getComponentFromState=e.getComponentFromState;exports.getComponentFromStateByName=e.getComponentFromStateByName;exports.getExportSchemaValueFromCode=e.getExportSchemaValueFromCode;exports.getPreloadComponent=e.getPreloadComponent;exports.getPreloadComponents=e.getPreloadComponents;exports.getPreloadComponentsCacheKey=e.getPreloadComponentsCacheKey;
|
package/lib/cjs/project-html.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const k=require("./_chunks/site-state-
|
|
1
|
+
"use strict";const k=require("./_chunks/site-state-C0hyEwRs.js"),S=require("@blocklet/crawler/middlewares"),W=require("@blocklet/pages-kit/types"),J=require("@blocklet/pages-kit/utils/preload"),G=require("@blocklet/sdk/lib/component"),D=require("@blocklet/sdk/lib/config"),z=require("cheerio/slim"),K=require("express"),A=require("fs"),Q=require("mustache"),I=require("path"),j=require("ufo"),q=e=>e&&e.__esModule?e:{default:e};function V(e){if(e&&e.__esModule)return e;const l=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const t in e)if(t!=="default"){const p=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(l,t,p.get?p:{enumerable:!0,get:()=>e[t]})}}return l.default=e,Object.freeze(l)}const d=q(D),U=V(z),X=q(Q),Y=["/assets/"],R=()=>[!0,"true"].includes(d.default.env.preferences.allowCrawler);function x(){R()?S.initCronCrawlBlocklet({time:"30 30 */12 * * *",options:{}}):S.cancelCronCrawlBlocklet()}x();d.default.events.on(d.default.Events.envUpdate,x);function Z({app:e,viteDevServer:l,state:t}){let p;if(l){const r=A.readFileSync(I.resolve(process.cwd(),"./index.html"),"utf-8");e.use(async(b,T,y)=>{const v=b.originalUrl;p=await l.transformIndexHtml(v,r),y()})}else p=A.readFileSync(I.resolve(process.env.BLOCKLET_APP_DIR,"dist/index.html"),"utf-8");const C=K.Router();C.use(S.initSEOMiddleware({autoReturnHtml:!1,allowCrawler:R})),C.get("/:path(*)?",async(r,b,T)=>{var E,L,M;if(Y.some(c=>{var i;return(i=r.path)==null?void 0:i.startsWith(c)})){T();return}const y=performance.now(),v=()=>Math.round(performance.now()-y),B="production";let o,u,g=p;if(r.path.startsWith("/pages")){const c=r.params.lang,i=r.cookies.nf_lang,w=new Set([...d.default.env.languages.map(h=>h.code)]);let f=(c&&w.has(c)?c:void 0)||(w.has(i)?i:void 0)||[...w][0];if((!f||!((E=t.supportedLocales)!=null&&E.find(h=>h.locale===f)))&&(f=((M=(L=t.supportedLocales)==null?void 0:L[0])==null?void 0:M.locale)||""),f){const h=[];Object.values(t.pages).forEach(s=>{const P=Object.values((s==null?void 0:s.sections)??{}).filter(a=>{var _;return a.component==="custom-component"&&((_=a.config)==null?void 0:_.componentId)}).map(a=>{var _,O;return{id:a.id,componentId:a.config.componentId,useCache:a.config.useCache,cacheDuration:a.config.cacheDuration,properties:(O=(_=a.locales)==null?void 0:_[f])==null?void 0:O.properties}});h.push(...P)});const N=new Promise((s,P)=>{setTimeout(()=>{P(new Error("getPreloadComponents timeout in promise race, skip it"))},90*1e3)});try{await Promise.race([N,k.getPreloadComponents({mode:B,req:r,state:t,locale:f,instances:h,module:W.PreloadComponentScriptModule.UMD_FN}).then(s=>{s&&(u=J.injectPreloadComponents(s))})])}catch(s){k.logger.warn("getPreloadComponents timeout in promise race, skip inject html elements"),k.logger.warn(s)}}}try{const c=(o==null?void 0:o.title)||d.default.env.appName,i=(o==null?void 0:o.description)||d.default.env.appDescription,w=j.withQuery(j.joinURL(d.default.env.appUrl,"/.well-known/service/blocklet/og.png"),{title:c,description:i});g=X.default.render(p,{ogTitle:c,ogDescription:i,ogImage:F(o==null?void 0:o.image)||w,pagesPublishedAt:(t==null?void 0:t.config.publishedAt)||new Date().getTime()})}catch{}const n=t==null?void 0:t.config.fontFamily,H=r.query.mode==="draft"||r.url.includes("preview"),m=U.load(g);m("head").find("#injected-head-elements").replaceWith(`
|
|
2
2
|
${o!=null&&o.backgroundColor?`<meta name="theme-color" content="${o.backgroundColor}" /><style>html,body,#app {background-color: ${o.backgroundColor} !important;}</style>`:""}
|
|
3
3
|
${n!=null&&n.title?`<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${n.title}&display=swap">`:""}
|
|
4
4
|
${n!=null&&n.description&&(n==null?void 0:n.description)!==(n==null?void 0:n.title)?`<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${n.description}&display=swap">`:""}
|
package/lib/cjs/resources.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const c=require("./_chunks/site-state-
|
|
1
|
+
"use strict";const c=require("./_chunks/site-state-C0hyEwRs.js"),M=require("async_hooks"),U=require("express"),F=require("fs"),J=require("joi"),O=require("lodash"),b=require("path"),X=require("@blocklet/sdk/lib/middlewares/auth"),W=require("@blocklet/sdk/lib/component"),E=t=>t&&t.__esModule?t:{default:t},p=E(F),I=E(J),k=E(b),v=E(X);new M.AsyncLocalStorage;const $=async(t,e,o)=>{var n,s,r,a;try{const{projectId:u}=t.params;if(!u)return o();const f=await c.Project.findByPk(u);if(!f)return e==null?void 0:e.status(404).json({error:"Project not found"});const P=(n=t.user)==null?void 0:n.did,h=((s=t.user)==null?void 0:s.role)||"UNKNOWN_ROLE";if(!P)return e==null?void 0:e.status(401).json({error:"Authentication required"});if(c.isMultiTenant()){const w=f.createdBy===P,i=(a=(r=c.getMultiTenantAllProjectAccessPassports())==null?void 0:r.includes)==null?void 0:a.call(r,h);if(!w&&!i)return e==null?void 0:e.status(403).json({error:"No permission to access this project in multi-tenant mode"})}else if(!["owner","admin","pagesEditor"].includes(h))return e==null?void 0:e.status(403).json({error:"No permission to access this project in single-tenant mode"});t.project=f,t.projectId=u,o()}catch(u){c.logger.error("Project middleware error:",u),e==null||e.status(500).json({error:"Internal server error"})}};function N(t,e){return new Promise((o,n)=>{const s=p.default.createReadStream(t),r=p.default.createWriteStream(e);s.on("error",n),r.on("error",n),r.on("finish",o),s.pipe(r)})}async function T(t,e){await p.default.promises.mkdir(e,{recursive:!0});const o=await p.default.promises.readdir(t,{withFileTypes:!0});for(const n of o){const s=k.default.join(t,n.name),r=k.default.join(e,n.name);n.isDirectory()?await T(s,r):await N(s,r)}}async function G(t,e){(await p.default.promises.stat(t)).isDirectory()?await T(t,e):await N(t,e)}const D=(t,e,o)=>c.isMultiTenant()?v.default()(t,e,o):v.default({roles:["owner","admin","pagesEditor"]})(t,e,o),K=(t,e)=>{const o=W.getResourceExportDir({projectId:t,releaseId:e});return b.join(o,c.COMPONENT_DID,c.RESOURCE_TYPE)},S=U.Router(),B="@page",q="@component",y=":",_="ALL",L="@project",C=({pageId:t,projectId:e})=>[B,e,t].join(y),Y=t=>{const[e,o,n]=t.split(y);if(e===B)return{pageId:n,projectId:o}},A=({componentId:t,projectId:e})=>[q,e,t].join(y),z=t=>{const[e,o,n]=t.split(y);if(e===q)return{componentId:n,projectId:o}},H=t=>[L,t].join(y),Q=t=>{const[e,o]=t.split(y);if(e===L)return o},V=t=>{try{return JSON.parse(t)}catch{}return{}};async function x(t){const e=await c.SiteState.shared(t).getState("production"),o=await c.Project.findByPk(t),n=e.pageIds.map(r=>{const a=e.pages[r];if(a)return{id:C({pageId:r,projectId:t}),name:a.slug}}).filter(Boolean),s=O.sortBy(Object.values(e.components),r=>r.index).map(({data:r})=>({id:A({componentId:r.id,projectId:t}),name:r.name||r.id}));return{id:H(t),name:(o==null?void 0:o.name)||"Unnamed Project",children:[{id:C({pageId:_,projectId:t}),name:"Pages",children:n},{id:A({componentId:_,projectId:t}),name:"Components",children:s}]}}S.get("/resources",D,async(t,e)=>{const{projectId:o}=V(t.query.resourcesParams);if(o){t.params={...t.params,projectId:o},await $(t,e,()=>{});const r=await x(o);e.json({resources:[r]});return}const n=await c.Project.findAll({where:{}}),s=await Promise.all(n.map(r=>x(r.id)));e.json({resources:s})});const Z=I.default.object({projectId:I.default.string().required().min(1),releaseId:I.default.string().allow(""),resources:I.default.array().items(I.default.string()).required(),locale:I.default.string().allow("")});S.post("/resources",D,async(t,e)=>{const{resources:o,projectId:n,releaseId:s}=await Z.validateAsync(t.body),r="production",a=[],u=[];for(const i of o){if(Q(i))continue;const{pageId:m,projectId:j}=Y(i)||{};if(m)m===_||m&&j&&a.push({pageId:m,projectId:j});else{const{componentId:l,projectId:d}=z(i)||{};l===_||l&&d&&u.push({componentId:l,projectId:d})}}const f=O.groupBy(a,"projectId"),P=O.groupBy(u,"projectId"),h=new Set([...Object.keys(f),...Object.keys(P)]),w=K(n,s);p.default.rmSync(w,{recursive:!0,force:!0}),p.default.mkdirSync(w,{recursive:!0});for(const i of h){const m=await c.SiteState.shared(i).getState(r),j=f[i],l=P[i],d=j==null?void 0:j.map(g=>g.pageId),R=l==null?void 0:l.map(g=>g.componentId);if(d!=null&&d.length||R!=null&&R.length){const g=await c.toPackage(m,{exportAssets:!0,pageIds:d,componentIds:R});await G(g,w),p.default.rmSync(g,{recursive:!0,force:!0})}c.logger.info(`Exported resources for project ${i}`,{pageIds:d,componentIds:R})}e.json({})});S.get("/all-resources",D,async(t,e)=>{const{states:o}=await c.getResourceStates(),n=o==null?void 0:o.map(s=>{const r={blockletId:s.blockletId,blockletTitle:s.blockletTitle,components:{}};if(s.state.components&&(r.components=s.state.components),Object.keys(r.components).length!==0)return r}).filter(Boolean);e.json(n)});module.exports=S;
|
package/lib/cjs/site-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./_chunks/site-state-
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./_chunks/site-state-C0hyEwRs.js");require("@blocklet/quickjs");require("@blocklet/sdk/lib/component");require("@blocklet/sdk/lib/config");require("@reactivedata/reactive");require("@syncedstore/core");require("crypto");require("fs");require("glob");require("lib0/decoding");require("lib0/encoding");require("lodash");require("lru-cache");require("nanoid");require("p-limit");require("path");require("stream/promises");require("tar");require("ufo");require("wait-on");require("y-protocols/awareness");require("y-protocols/sync");require("yaml");require("yjs");exports.PUBLISH_MODES=e.PUBLISH_MODES;exports.SITE_STATE_PATH=e.SITE_STATE_PATH;exports.STATE_MODES=e.STATE_MODES;exports.default=e.SiteState;exports.fromPackage=e.fromPackage;exports.getResourceStates=e.getResourceStates;exports.initPackResourceStates=e.initPackResourceStates;exports.mergeState=e.mergeState;exports.nextId=e.nextId;exports.toPackage=e.toPackage;exports.triggerReloadAllProjectResource=e.triggerReloadAllProjectResource;
|
|
@@ -4,11 +4,11 @@ var P = (t, o, e) => tt(t, typeof o != "symbol" ? o + "" : o, e);
|
|
|
4
4
|
import { getComponentMountPoint as st } from "@blocklet/pages-kit/builtin/utils";
|
|
5
5
|
import { PreloadComponentScriptModule as X } from "@blocklet/pages-kit/types";
|
|
6
6
|
import { componentUMDName as ot, RenderNestedComponent as Oe, mergeComponent as nt } from "@blocklet/pages-kit/utils/property";
|
|
7
|
-
import { memoize as ae, Sandbox as
|
|
7
|
+
import { memoize as ae, Sandbox as _e, BuiltinModules as rt } from "@blocklet/quickjs";
|
|
8
8
|
import S from "@blocklet/sdk/lib/config";
|
|
9
9
|
import { LRUCache as he } from "lru-cache";
|
|
10
10
|
import at, { Headers as it } from "node-fetch";
|
|
11
|
-
import { joinURL as
|
|
11
|
+
import { joinURL as _, getQuery as ct, withQuery as lt, parseURL as Ae, withHttps as pt } from "ufo";
|
|
12
12
|
import { createHash as ie } from "crypto";
|
|
13
13
|
import ut from "@blocklet/logger";
|
|
14
14
|
import { BuiltinModules as dt } from "@blocklet/pages-kit/utils/builtin";
|
|
@@ -16,40 +16,40 @@ import { createBuiltinModuleTransformer as mt, isRelativeModule as ft } from "@b
|
|
|
16
16
|
import { getResources as gt, getComponentWebEndpoint as ht, call as yt } from "@blocklet/sdk/lib/component";
|
|
17
17
|
import St from "autoprefixer";
|
|
18
18
|
import * as wt from "esbuild";
|
|
19
|
-
import { readFileSync as H, existsSync as V, lstatSync as Z, readdirSync as Et, rmSync as $e, mkdtempSync as bt, renameSync as
|
|
19
|
+
import { readFileSync as H, existsSync as V, lstatSync as Z, readdirSync as Et, rmSync as $e, mkdtempSync as bt, renameSync as ve, mkdirSync as F, writeFileSync as te, createWriteStream as It } from "fs";
|
|
20
20
|
import Ot from "postcss";
|
|
21
21
|
import At from "tailwindcss";
|
|
22
22
|
import j from "typescript";
|
|
23
|
-
import { reactive as
|
|
24
|
-
import { syncedStore as
|
|
23
|
+
import { reactive as vt } from "@reactivedata/reactive";
|
|
24
|
+
import { syncedStore as Tt, getYjsValue as le } from "@syncedstore/core";
|
|
25
25
|
import { globSync as me } from "glob";
|
|
26
26
|
import * as pe from "lib0/decoding";
|
|
27
27
|
import * as C from "lib0/encoding";
|
|
28
|
-
import { get as ye, isEmpty as Pt, set as
|
|
28
|
+
import { get as ye, isEmpty as Pt, set as Te, pick as Ct, debounce as Fe, union as xt, cloneDeep as jt } from "lodash";
|
|
29
29
|
import { customAlphabet as kt } from "nanoid";
|
|
30
30
|
import Dt from "p-limit";
|
|
31
31
|
import Nt, { join as A, dirname as L, basename as J } from "path";
|
|
32
32
|
import { pipeline as Lt } from "stream/promises";
|
|
33
33
|
import { x as Rt } from "tar";
|
|
34
34
|
import Ut from "wait-on";
|
|
35
|
-
import { Awareness as
|
|
35
|
+
import { Awareness as Mt, encodeAwarenessUpdate as Pe, removeAwarenessStates as _t, applyAwarenessUpdate as $t } from "y-protocols/awareness";
|
|
36
36
|
import { writeUpdate as Ft, writeSyncStep1 as Bt, readSyncMessage as Vt } from "y-protocols/sync";
|
|
37
|
-
import * as
|
|
38
|
-
import * as
|
|
37
|
+
import * as z from "yaml";
|
|
38
|
+
import * as $ from "yjs";
|
|
39
39
|
import Gt from "lodash/isNil";
|
|
40
|
-
import { DataTypes as
|
|
40
|
+
import { DataTypes as T, Sequelize as Jt, Model as Be, Op as Ht } from "sequelize";
|
|
41
41
|
import "sqlite3";
|
|
42
42
|
S.env.mode;
|
|
43
|
-
const
|
|
43
|
+
const zt = "image-bin";
|
|
44
44
|
S.env.INIT_TEMPLATE_PATH;
|
|
45
|
-
const
|
|
45
|
+
const Kt = process.env.DATABASE_URL || Nt.join(S.env.dataDir, "db/pages-kit.db"), Ce = S, so = () => S.env.tenantMode === "multiple", oo = () => {
|
|
46
46
|
var t;
|
|
47
47
|
return (Gt(Ce.env.preferences.multiTenantAllProjectAccessPassports) ? [] : (t = Ce.env.preferences.multiTenantAllProjectAccessPassports) == null ? void 0 : t.split(",")) || [];
|
|
48
|
-
}, I = ut("pages-kit"),
|
|
49
|
-
|
|
48
|
+
}, I = ut("pages-kit"), Wt = T.sqlite.DATE.parse;
|
|
49
|
+
T.sqlite.DATE.parse = (t, o) => typeof t == "number" ? new Date(t) : Wt(t, o);
|
|
50
50
|
const Y = new Jt({
|
|
51
51
|
dialect: "sqlite",
|
|
52
|
-
storage:
|
|
52
|
+
storage: Kt,
|
|
53
53
|
benchmark: process.env.ENABLE_SEQUELIZE_BENCHMARK === "true",
|
|
54
54
|
retry: {
|
|
55
55
|
match: [/SQLITE_BUSY/],
|
|
@@ -69,59 +69,59 @@ class ce extends Be {
|
|
|
69
69
|
ce.init(
|
|
70
70
|
{
|
|
71
71
|
id: {
|
|
72
|
-
type:
|
|
72
|
+
type: T.UUID,
|
|
73
73
|
allowNull: !1,
|
|
74
74
|
primaryKey: !0,
|
|
75
|
-
defaultValue:
|
|
75
|
+
defaultValue: T.UUIDV4
|
|
76
76
|
},
|
|
77
77
|
projectId: {
|
|
78
|
-
type:
|
|
78
|
+
type: T.UUID,
|
|
79
79
|
allowNull: !1
|
|
80
80
|
},
|
|
81
81
|
componentId: {
|
|
82
|
-
type:
|
|
82
|
+
type: T.STRING,
|
|
83
83
|
allowNull: !1
|
|
84
84
|
}
|
|
85
85
|
},
|
|
86
86
|
{ sequelize: Y, tableName: "ProjectComponents", timestamps: !1 }
|
|
87
87
|
);
|
|
88
|
-
class
|
|
88
|
+
class B extends Be {
|
|
89
89
|
static async getProjectByIdOrSlug(o) {
|
|
90
|
-
return
|
|
90
|
+
return B.findOne({
|
|
91
91
|
where: {
|
|
92
92
|
[Ht.or]: [{ id: o }, { slug: o }]
|
|
93
93
|
}
|
|
94
94
|
});
|
|
95
95
|
}
|
|
96
96
|
}
|
|
97
|
-
|
|
97
|
+
B.init(
|
|
98
98
|
{
|
|
99
99
|
id: {
|
|
100
|
-
type:
|
|
101
|
-
defaultValue:
|
|
100
|
+
type: T.UUID,
|
|
101
|
+
defaultValue: T.UUIDV4,
|
|
102
102
|
primaryKey: !0
|
|
103
103
|
},
|
|
104
104
|
name: {
|
|
105
|
-
type:
|
|
105
|
+
type: T.STRING,
|
|
106
106
|
allowNull: !1
|
|
107
107
|
},
|
|
108
|
-
description:
|
|
109
|
-
createdAt:
|
|
110
|
-
updatedAt:
|
|
108
|
+
description: T.TEXT,
|
|
109
|
+
createdAt: T.DATE,
|
|
110
|
+
updatedAt: T.DATE,
|
|
111
111
|
createdBy: {
|
|
112
|
-
type:
|
|
112
|
+
type: T.STRING,
|
|
113
113
|
allowNull: !1
|
|
114
114
|
},
|
|
115
115
|
updatedBy: {
|
|
116
|
-
type:
|
|
116
|
+
type: T.STRING,
|
|
117
117
|
allowNull: !1
|
|
118
118
|
},
|
|
119
|
-
slug:
|
|
120
|
-
icon:
|
|
121
|
-
pinnedAt:
|
|
122
|
-
useAllResources:
|
|
119
|
+
slug: T.STRING,
|
|
120
|
+
icon: T.STRING,
|
|
121
|
+
pinnedAt: T.DATE,
|
|
122
|
+
useAllResources: T.BOOLEAN,
|
|
123
123
|
relatedBlocklets: {
|
|
124
|
-
type:
|
|
124
|
+
type: T.JSON,
|
|
125
125
|
allowNull: !1,
|
|
126
126
|
defaultValue: {},
|
|
127
127
|
get() {
|
|
@@ -134,7 +134,7 @@ F.init(
|
|
|
134
134
|
},
|
|
135
135
|
{ sequelize: Y, paranoid: !0 }
|
|
136
136
|
);
|
|
137
|
-
|
|
137
|
+
B.hasMany(ce, {
|
|
138
138
|
foreignKey: "projectId",
|
|
139
139
|
as: "components"
|
|
140
140
|
});
|
|
@@ -287,14 +287,14 @@ var ${t} = ${e ? "async" : ""} function () {
|
|
|
287
287
|
return exports;
|
|
288
288
|
};
|
|
289
289
|
`;
|
|
290
|
-
},
|
|
290
|
+
}, K = new he({
|
|
291
291
|
max: 100
|
|
292
292
|
}), Zt = 60 * 60, je = 60;
|
|
293
293
|
function es(t) {
|
|
294
|
-
I.info("clear preload components cache", { cacheKey: t }),
|
|
294
|
+
I.info("clear preload components cache", { cacheKey: t }), K.delete(t);
|
|
295
295
|
}
|
|
296
296
|
function ts(t) {
|
|
297
|
-
for (const o of
|
|
297
|
+
for (const o of K.keys())
|
|
298
298
|
o.includes(t) && (I.info("clear preload components cache", { cacheKey: o }), es(o));
|
|
299
299
|
}
|
|
300
300
|
function ss({
|
|
@@ -327,14 +327,14 @@ async function no({
|
|
|
327
327
|
componentId: g.componentId,
|
|
328
328
|
locale: s
|
|
329
329
|
});
|
|
330
|
-
if (t !== "draft" && g.useCache &&
|
|
331
|
-
return I.info(`get preload component from cache: ${y}`),
|
|
332
|
-
const
|
|
333
|
-
if (!
|
|
330
|
+
if (t !== "draft" && g.useCache && K.has(y))
|
|
331
|
+
return I.info(`get preload component from cache: ${y}`), K.get(y);
|
|
332
|
+
const v = se({ state: e, componentId: g.componentId });
|
|
333
|
+
if (!v) return null;
|
|
334
334
|
const x = await os({
|
|
335
335
|
req: o,
|
|
336
336
|
state: e,
|
|
337
|
-
componentId:
|
|
337
|
+
componentId: v.id,
|
|
338
338
|
locale: s,
|
|
339
339
|
defaultLocale: a,
|
|
340
340
|
properties: g.properties
|
|
@@ -343,7 +343,7 @@ async function no({
|
|
|
343
343
|
const U = { instanceId: g.id, preload: x };
|
|
344
344
|
if (t !== "draft" && g.useCache) {
|
|
345
345
|
let D = Zt;
|
|
346
|
-
g.cacheDuration && (D = g.cacheDuration), I.info(`set preload component to cache(${D}s): ${y}`),
|
|
346
|
+
g.cacheDuration && (D = g.cacheDuration), I.info(`set preload component to cache(${D}s): ${y}`), K.set(y, U, {
|
|
347
347
|
ttl: D * 1e3
|
|
348
348
|
});
|
|
349
349
|
}
|
|
@@ -358,7 +358,7 @@ async function no({
|
|
|
358
358
|
async function p() {
|
|
359
359
|
const g = await Promise.all(
|
|
360
360
|
c.map(async (y) => {
|
|
361
|
-
const
|
|
361
|
+
const v = ot({ componentId: y.component.id }), x = r === X.ESM ? {
|
|
362
362
|
module: r,
|
|
363
363
|
script: await xe(y.script, {
|
|
364
364
|
componentId: y.component.id,
|
|
@@ -370,10 +370,10 @@ async function no({
|
|
|
370
370
|
script: await xe(y.script, {
|
|
371
371
|
componentId: y.component.id,
|
|
372
372
|
module: r,
|
|
373
|
-
moduleName:
|
|
373
|
+
moduleName: v,
|
|
374
374
|
tailwind: t !== "draft"
|
|
375
375
|
}),
|
|
376
|
-
moduleName:
|
|
376
|
+
moduleName: v
|
|
377
377
|
};
|
|
378
378
|
return [y.component.id, { component: y.component, script: x }];
|
|
379
379
|
})
|
|
@@ -505,7 +505,7 @@ async function as({
|
|
|
505
505
|
});
|
|
506
506
|
return await Promise.race([
|
|
507
507
|
r,
|
|
508
|
-
|
|
508
|
+
_e.callFunction({
|
|
509
509
|
code: `${n}
|
|
510
510
|
|
|
511
511
|
export async function getServerSidePropsWrapper(props) {
|
|
@@ -548,7 +548,7 @@ export { joinURL, withQuery, getQuery, getComponentMountPoint }
|
|
|
548
548
|
}
|
|
549
549
|
},
|
|
550
550
|
getComponentMountPoint: st,
|
|
551
|
-
joinURL:
|
|
551
|
+
joinURL: _,
|
|
552
552
|
withQuery: lt,
|
|
553
553
|
getQuery: ct
|
|
554
554
|
},
|
|
@@ -557,9 +557,9 @@ export { joinURL, withQuery, getQuery, getComponentMountPoint }
|
|
|
557
557
|
{
|
|
558
558
|
// NOTE: IMPORTANT! place location and fetch (has side effect) at the args not global
|
|
559
559
|
// because the global is shared between all runtime and just init once
|
|
560
|
-
location: { href:
|
|
560
|
+
location: { href: _(pt(s.hostname), s.originalUrl) },
|
|
561
561
|
fetch: (a, { ...i } = {}) => {
|
|
562
|
-
const c = typeof a == "string" && a.startsWith("/") ?
|
|
562
|
+
const c = typeof a == "string" && a.startsWith("/") ? _(S.env.appUrl, a) : a;
|
|
563
563
|
if (typeof c == "string" && Ae(c).host === Ae(S.env.appUrl).host) {
|
|
564
564
|
const p = s.get("cookie");
|
|
565
565
|
if (p) {
|
|
@@ -591,7 +591,7 @@ const is = ae(
|
|
|
591
591
|
const s = await Ve(t, o);
|
|
592
592
|
if (s)
|
|
593
593
|
try {
|
|
594
|
-
return await
|
|
594
|
+
return await _e.callFunction({
|
|
595
595
|
code: `
|
|
596
596
|
${s}
|
|
597
597
|
|
|
@@ -617,7 +617,7 @@ const is = ae(
|
|
|
617
617
|
ttl: 1e3 * 60 * 60
|
|
618
618
|
}
|
|
619
619
|
}
|
|
620
|
-
), cs = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o", ke = "page", fe = "trigger-reload-project-resource", Je = cs, ls = "z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV", { uploadToMediaKit: ps } = require("@blocklet/uploader-server"), De = kt("abcdefghijklmnopqrstuvwxyz0123456789", 16), Se = /^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,
|
|
620
|
+
), cs = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o", ke = "page", fe = "trigger-reload-project-resource", Je = cs, ls = "z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV", { uploadToMediaKit: ps } = require("@blocklet/uploader-server"), De = kt("abcdefghijklmnopqrstuvwxyz0123456789", 16), Se = /^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/, W = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i, Ne = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi, us = 1e4, ds = 3e4, q = 0, ue = 1, ms = 0, fs = 1, ge = S, Q = A(process.env.BLOCKLET_DATA_DIR, "site-state"), ao = ["production", "draft"], io = ["production"];
|
|
621
621
|
function He(t) {
|
|
622
622
|
return (t == null ? void 0 : t.replace(/\//g, "|")) || "";
|
|
623
623
|
}
|
|
@@ -633,7 +633,7 @@ function gs() {
|
|
|
633
633
|
resources: {}
|
|
634
634
|
};
|
|
635
635
|
}
|
|
636
|
-
const
|
|
636
|
+
const M = class M extends $.Doc {
|
|
637
637
|
constructor(e) {
|
|
638
638
|
super();
|
|
639
639
|
P(this, "states", {});
|
|
@@ -695,12 +695,12 @@ const _ = class _ extends B.Doc {
|
|
|
695
695
|
P(this, "closeConn", (e) => {
|
|
696
696
|
if (e.removeAllListeners(), this.conns.has(e)) {
|
|
697
697
|
const s = this.conns.get(e);
|
|
698
|
-
this.conns.delete(e), s &&
|
|
698
|
+
this.conns.delete(e), s && _t(this.awareness, Array.from(s), null);
|
|
699
699
|
}
|
|
700
700
|
e.close();
|
|
701
701
|
});
|
|
702
702
|
P(this, "autoSave", Fe(() => {
|
|
703
|
-
|
|
703
|
+
F(L(this.draftYjsFilePath), { recursive: !0 }), te(this.draftYjsFilePath, $.encodeStateAsUpdate(this));
|
|
704
704
|
}, us));
|
|
705
705
|
P(this, "save", ({ flush: e = !1 } = {}) => {
|
|
706
706
|
this.autoSave(), e && this.autoSave.flush();
|
|
@@ -779,12 +779,12 @@ const _ = class _ extends B.Doc {
|
|
|
779
779
|
}
|
|
780
780
|
this.save();
|
|
781
781
|
});
|
|
782
|
-
this.options = e, V(this.draftYjsFilePath) &&
|
|
783
|
-
|
|
782
|
+
this.options = e, V(this.draftYjsFilePath) && $.applyUpdate(this, H(this.draftYjsFilePath)), this.syncedStore = vt(
|
|
783
|
+
Tt(
|
|
784
784
|
{ pages: {}, pageIds: [], components: {}, supportedLocales: [], config: {}, resources: {} },
|
|
785
785
|
this
|
|
786
786
|
)
|
|
787
|
-
), this.initObserver(), this.on("update", this.updateHandler), this.awareness = new
|
|
787
|
+
), this.initObserver(), this.on("update", this.updateHandler), this.awareness = new Mt(this), this.awareness.on("update", this.awarenessChangeHandler), this.ensureDataStructure();
|
|
788
788
|
}
|
|
789
789
|
// safe delete project state dir
|
|
790
790
|
static safeDeleteProjectStateDir(e) {
|
|
@@ -792,7 +792,7 @@ const _ = class _ extends B.Doc {
|
|
|
792
792
|
throw new Error("Should provide project context");
|
|
793
793
|
try {
|
|
794
794
|
const s = A(Q, e), n = A(Q, `@del-${e}`);
|
|
795
|
-
|
|
795
|
+
ve(s, n);
|
|
796
796
|
} catch (s) {
|
|
797
797
|
I.error("Failed to safe delete project state dir:", s);
|
|
798
798
|
}
|
|
@@ -805,13 +805,13 @@ const _ = class _ extends B.Doc {
|
|
|
805
805
|
});
|
|
806
806
|
}
|
|
807
807
|
static get allShared() {
|
|
808
|
-
return this.projectIds.map((e) =>
|
|
808
|
+
return this.projectIds.map((e) => M.shared(e));
|
|
809
809
|
}
|
|
810
810
|
static shared(e) {
|
|
811
811
|
if (!e)
|
|
812
812
|
throw new Error("Should provide project context");
|
|
813
813
|
let s = this.sharedInstances.get(e);
|
|
814
|
-
return s || (s = new
|
|
814
|
+
return s || (s = new M({
|
|
815
815
|
path: A(Q, e)
|
|
816
816
|
}), this.sharedInstances.set(e, s), s);
|
|
817
817
|
}
|
|
@@ -826,14 +826,14 @@ const _ = class _ extends B.Doc {
|
|
|
826
826
|
};
|
|
827
827
|
this.syncedStore.pages && Object.keys(this.syncedStore.pages).forEach((n) => {
|
|
828
828
|
const r = le(this.syncedStore.pages[n]);
|
|
829
|
-
r && r instanceof
|
|
829
|
+
r && r instanceof $.Map && e(r);
|
|
830
830
|
});
|
|
831
831
|
const s = le(this.syncedStore.pages);
|
|
832
|
-
s && s instanceof
|
|
832
|
+
s && s instanceof $.Map && s.observe((n) => {
|
|
833
833
|
n.changes.keys.forEach((r, l) => {
|
|
834
834
|
if (r.action === "add") {
|
|
835
835
|
const a = le(this.syncedStore.pages[l]);
|
|
836
|
-
a && a instanceof
|
|
836
|
+
a && a instanceof $.Map && e(a);
|
|
837
837
|
}
|
|
838
838
|
});
|
|
839
839
|
});
|
|
@@ -845,7 +845,7 @@ const _ = class _ extends B.Doc {
|
|
|
845
845
|
var s, n, r, l;
|
|
846
846
|
if (e === "draft")
|
|
847
847
|
return JSON.parse(JSON.stringify(this.syncedStore));
|
|
848
|
-
if (!this.states[e] && (this.states[e] = await
|
|
848
|
+
if (!this.states[e] && (this.states[e] = await We(this.getPublishDir(e), { includeResources: !0 }) ?? gs(), !((n = (s = this.states[e]) == null ? void 0 : s.config) != null && n.defaultLocale))) {
|
|
849
849
|
(r = this.states[e]).config ?? (r.config = {});
|
|
850
850
|
const a = ge.env.languages.map((i) => ({ locale: i.code, name: i.name }));
|
|
851
851
|
this.states[e].config.defaultLocale = (l = a[0]) == null ? void 0 : l.locale;
|
|
@@ -861,11 +861,11 @@ const _ = class _ extends B.Doc {
|
|
|
861
861
|
...(y = (g = this.states[e]) == null ? void 0 : g.resources) == null ? void 0 : y.components
|
|
862
862
|
};
|
|
863
863
|
else {
|
|
864
|
-
const
|
|
864
|
+
const v = J(this.options.path), x = await B.findByPk(v);
|
|
865
865
|
if (x != null && x.useAllResources)
|
|
866
866
|
p = c;
|
|
867
867
|
else {
|
|
868
|
-
const D = (await ce.findAll({ where: { projectId:
|
|
868
|
+
const D = (await ce.findAll({ where: { projectId: v } })).map((E) => E.componentId);
|
|
869
869
|
p = Object.fromEntries(
|
|
870
870
|
Object.entries(c || {}).filter(([E]) => D.includes(E))
|
|
871
871
|
);
|
|
@@ -877,7 +877,7 @@ const _ = class _ extends B.Doc {
|
|
|
877
877
|
}
|
|
878
878
|
async setState(e, s) {
|
|
879
879
|
const n = await ws(s, { exportAssets: !1, includeResources: !0 }), r = this.getPublishDir(e);
|
|
880
|
-
|
|
880
|
+
F(L(r), { recursive: !0 }), $e(r, { force: !0, recursive: !0 }), ve(n, r), this.states[e] = s;
|
|
881
881
|
}
|
|
882
882
|
getPublishDir(e) {
|
|
883
883
|
return A(this.options.path, e);
|
|
@@ -885,9 +885,9 @@ const _ = class _ extends B.Doc {
|
|
|
885
885
|
static async pageUrlMap(e) {
|
|
886
886
|
const { projectIds: s } = this, n = {};
|
|
887
887
|
for (const r of s) {
|
|
888
|
-
const l = await
|
|
888
|
+
const l = await B.findByPk(r);
|
|
889
889
|
if (!l) continue;
|
|
890
|
-
const a = await
|
|
890
|
+
const a = await M.shared(r).getState(e), i = xt(
|
|
891
891
|
S.env.languages.map((c) => c.code),
|
|
892
892
|
a.supportedLocales.map((c) => c.locale)
|
|
893
893
|
);
|
|
@@ -907,35 +907,51 @@ const _ = class _ extends B.Doc {
|
|
|
907
907
|
isPublic: p.isPublic,
|
|
908
908
|
isTemplate: p.isTemplate
|
|
909
909
|
};
|
|
910
|
-
m && (n[
|
|
910
|
+
m && (n[_("/", m, u)] = {
|
|
911
911
|
...g,
|
|
912
912
|
shouldRedirect: !0,
|
|
913
913
|
mainPage: !0
|
|
914
|
-
}), n[
|
|
914
|
+
}), n[_("/", r, u)] = {
|
|
915
915
|
...g,
|
|
916
916
|
shouldRedirect: !0,
|
|
917
917
|
mainPage: !0
|
|
918
918
|
};
|
|
919
919
|
for (const y of i) {
|
|
920
|
-
const
|
|
921
|
-
n[
|
|
920
|
+
const v = { ...g, locale: y };
|
|
921
|
+
n[_("/", y, r, u)] = v, m && (n[_("/", y, m, u)] = v);
|
|
922
922
|
}
|
|
923
923
|
}
|
|
924
924
|
}
|
|
925
925
|
return n;
|
|
926
926
|
}
|
|
927
|
+
getDocumentSize() {
|
|
928
|
+
return $.encodeStateAsUpdate(this).byteLength;
|
|
929
|
+
}
|
|
930
|
+
static getInstancesSizeInfo() {
|
|
931
|
+
const e = [];
|
|
932
|
+
for (const [s, n] of this.sharedInstances.entries()) {
|
|
933
|
+
const r = n.getDocumentSize();
|
|
934
|
+
e.push({
|
|
935
|
+
projectId: s,
|
|
936
|
+
sizeInBytes: r,
|
|
937
|
+
sizeInMB: `${(r / (1024 * 1024)).toFixed(2)} MB`,
|
|
938
|
+
activeConnections: n.conns.size
|
|
939
|
+
});
|
|
940
|
+
}
|
|
941
|
+
return e;
|
|
942
|
+
}
|
|
927
943
|
};
|
|
928
|
-
P(
|
|
929
|
-
P(
|
|
944
|
+
P(M, "INSTANCE_TTL", 30 * 60 * 1e3), // 30 minutes
|
|
945
|
+
P(M, "sharedInstances", new he({
|
|
930
946
|
max: 100,
|
|
931
947
|
// Maximum number of instances to store
|
|
932
|
-
ttl:
|
|
948
|
+
ttl: M.INSTANCE_TTL,
|
|
933
949
|
dispose: (e) => {
|
|
934
950
|
e.destroy();
|
|
935
951
|
}
|
|
936
952
|
}));
|
|
937
|
-
let oe =
|
|
938
|
-
function
|
|
953
|
+
let oe = M;
|
|
954
|
+
function ze() {
|
|
939
955
|
return bt(A(S.env.dataDir, "tmp-"));
|
|
940
956
|
}
|
|
941
957
|
function ne(t, o, e = []) {
|
|
@@ -964,7 +980,7 @@ async function hs(t, o, e) {
|
|
|
964
980
|
const ys = async (t, o) => {
|
|
965
981
|
const e = J(t), s = await yt({
|
|
966
982
|
name: Je,
|
|
967
|
-
path:
|
|
983
|
+
path: _("/uploads", e),
|
|
968
984
|
responseType: "stream",
|
|
969
985
|
method: "GET"
|
|
970
986
|
});
|
|
@@ -984,18 +1000,18 @@ const ys = async (t, o) => {
|
|
|
984
1000
|
})
|
|
985
1001
|
);
|
|
986
1002
|
};
|
|
987
|
-
function
|
|
988
|
-
return Se.test(t) ? [t] :
|
|
1003
|
+
function Ke(t) {
|
|
1004
|
+
return Se.test(t) ? [t] : W.test(t) ? (Ne.lastIndex = 0, Array.from(t.matchAll(Ne)).map((e) => e[1]).filter((e) => !!e)) : [];
|
|
989
1005
|
}
|
|
990
1006
|
async function de(t, o, e) {
|
|
991
1007
|
const { getFilename: s, exportAssets: n } = e, r = A(o, s(t));
|
|
992
|
-
if (
|
|
1008
|
+
if (F(L(r), { recursive: !0 }), te(r, z.stringify(t)), n) {
|
|
993
1009
|
const a = ne(
|
|
994
1010
|
t,
|
|
995
|
-
(i) => typeof i == "string" && (Se.test(i) ||
|
|
1011
|
+
(i) => typeof i == "string" && (Se.test(i) || W.test(i))
|
|
996
1012
|
).map((i) => {
|
|
997
1013
|
const c = ye(t, i);
|
|
998
|
-
return
|
|
1014
|
+
return Ke(c);
|
|
999
1015
|
}).flat().filter(Boolean);
|
|
1000
1016
|
await Ss(a, L(r));
|
|
1001
1017
|
}
|
|
@@ -1008,19 +1024,19 @@ async function Re(t, o, e) {
|
|
|
1008
1024
|
var a;
|
|
1009
1025
|
const s = ne(
|
|
1010
1026
|
t,
|
|
1011
|
-
(i) => typeof i == "string" && (Se.test(i) ||
|
|
1027
|
+
(i) => typeof i == "string" && (Se.test(i) || W.test(i))
|
|
1012
1028
|
), n = Dt(2), r = s.map(
|
|
1013
1029
|
(i) => n(async () => {
|
|
1014
1030
|
try {
|
|
1015
|
-
const c = ye(t, i), p =
|
|
1031
|
+
const c = ye(t, i), p = Ke(c);
|
|
1016
1032
|
for (const u of p) {
|
|
1017
|
-
const m = J(u), g = e.getFilePath(u, i), y = g ? `${g}:${m}` : m,
|
|
1018
|
-
if (
|
|
1019
|
-
|
|
1033
|
+
const m = J(u), g = e.getFilePath(u, i), y = g ? `${g}:${m}` : m, v = Le.get(y);
|
|
1034
|
+
if (v) {
|
|
1035
|
+
W.test(c) || Te(t, i, v);
|
|
1020
1036
|
return;
|
|
1021
1037
|
}
|
|
1022
1038
|
const x = await hs(g, m, o);
|
|
1023
|
-
x && (
|
|
1039
|
+
x && (W.test(c) || Te(t, i, x), Le.set(y, x));
|
|
1024
1040
|
}
|
|
1025
1041
|
} catch (c) {
|
|
1026
1042
|
I.error(`Failed to process upload for path ${i.join(".")}:`, c.message || c.reason);
|
|
@@ -1081,10 +1097,10 @@ async function ws(t, {
|
|
|
1081
1097
|
};
|
|
1082
1098
|
})
|
|
1083
1099
|
)
|
|
1084
|
-
), u =
|
|
1085
|
-
|
|
1100
|
+
), u = ze(), m = A(u, "pages");
|
|
1101
|
+
F(m, { recursive: !0 });
|
|
1086
1102
|
const g = A(u, "components");
|
|
1087
|
-
|
|
1103
|
+
F(g, { recursive: !0 });
|
|
1088
1104
|
for (const { locale: f, slug: d, page: w } of p)
|
|
1089
1105
|
await de(w, m, {
|
|
1090
1106
|
getFilename: () => `${He(d) || "index"}.${f}.yml`,
|
|
@@ -1098,8 +1114,8 @@ async function ws(t, {
|
|
|
1098
1114
|
});
|
|
1099
1115
|
}
|
|
1100
1116
|
const y = A(u, ".blocklet/pages/pages.config.yml");
|
|
1101
|
-
|
|
1102
|
-
const
|
|
1117
|
+
F(L(y), { recursive: !0 });
|
|
1118
|
+
const v = {
|
|
1103
1119
|
pages: R(
|
|
1104
1120
|
l.map((f) => {
|
|
1105
1121
|
const d = t.pages[f];
|
|
@@ -1132,11 +1148,11 @@ async function ws(t, {
|
|
|
1132
1148
|
supportedLocales: t.supportedLocales,
|
|
1133
1149
|
config: t.config
|
|
1134
1150
|
};
|
|
1135
|
-
te(y,
|
|
1151
|
+
te(y, z.stringify(v));
|
|
1136
1152
|
const x = A(u, "config.source.json");
|
|
1137
1153
|
if (n && te(x, JSON.stringify(n)), r) {
|
|
1138
1154
|
const f = A(u, "resources"), d = A(f, "components");
|
|
1139
|
-
|
|
1155
|
+
F(d, { recursive: !0 });
|
|
1140
1156
|
for (const w of Object.keys(((h = t == null ? void 0 : t.resources) == null ? void 0 : h.components) ?? {})) {
|
|
1141
1157
|
const k = (O = (b = (E = t.resources) == null ? void 0 : E.components) == null ? void 0 : b[w]) == null ? void 0 : O.component;
|
|
1142
1158
|
k && await de(k, d, {
|
|
@@ -1147,28 +1163,28 @@ async function ws(t, {
|
|
|
1147
1163
|
}
|
|
1148
1164
|
return u;
|
|
1149
1165
|
}
|
|
1150
|
-
async function
|
|
1166
|
+
async function We(t, { importAssets: o, includeResources: e } = {}) {
|
|
1151
1167
|
var r, l, a;
|
|
1152
1168
|
if (!V(t))
|
|
1153
1169
|
return null;
|
|
1154
1170
|
let s, n = !1;
|
|
1155
1171
|
try {
|
|
1156
|
-
Z(t).isDirectory() ? s = t : /\.(tgz|gz|tar)$/.test(t) && (n = !0, s =
|
|
1172
|
+
Z(t).isDirectory() ? s = t : /\.(tgz|gz|tar)$/.test(t) && (n = !0, s = ze(), await Rt({ file: t, C: s }));
|
|
1157
1173
|
const i = me("**/.blocklet/pages/pages.config.yml", { cwd: s, absolute: !0 }).at(0), c = i && A(L(i), "../../pages"), p = i && A(L(i), "../../components"), u = i && A(L(i), "../../chunks");
|
|
1158
1174
|
if (!i)
|
|
1159
1175
|
return null;
|
|
1160
|
-
const m =
|
|
1176
|
+
const m = z.parse(H(i).toString()), g = (h, E, b) => {
|
|
1161
1177
|
let O = A(h, `${E}${b ? `.${b}` : ""}.yml`);
|
|
1162
|
-
return (!V(O) || !Z(O).isFile()) && (O = A(h, E, `index${b ? `.${b}` : ""}.yml`), !V(O) || !Z(O)) ? null :
|
|
1178
|
+
return (!V(O) || !Z(O).isFile()) && (O = A(h, E, `index${b ? `.${b}` : ""}.yml`), !V(O) || !Z(O)) ? null : z.parse(H(O).toString());
|
|
1163
1179
|
}, y = (h, E) => {
|
|
1164
1180
|
try {
|
|
1165
1181
|
const b = me(`*.${E}.yml`, { cwd: h, absolute: !0 })[0];
|
|
1166
|
-
return b ?
|
|
1182
|
+
return b ? z.parse(H(b).toString()) : null;
|
|
1167
1183
|
} catch (b) {
|
|
1168
1184
|
I.error("parse component error", b);
|
|
1169
1185
|
}
|
|
1170
1186
|
return null;
|
|
1171
|
-
},
|
|
1187
|
+
}, v = R(
|
|
1172
1188
|
m.pages.map(({ slug: h }) => {
|
|
1173
1189
|
var f;
|
|
1174
1190
|
const E = R(
|
|
@@ -1222,7 +1238,7 @@ async function ze(t, { importAssets: o, includeResources: e } = {}) {
|
|
|
1222
1238
|
};
|
|
1223
1239
|
try {
|
|
1224
1240
|
h("wait image-bin api ready"), await Ut({
|
|
1225
|
-
resources: [`${ht(
|
|
1241
|
+
resources: [`${ht(zt)}/api/sdk/uploads`],
|
|
1226
1242
|
validateStatus: (O) => O >= 200 && O <= 500
|
|
1227
1243
|
}), h("image-bin api is ready");
|
|
1228
1244
|
const E = {}, b = {};
|
|
@@ -1233,9 +1249,9 @@ async function ze(t, { importAssets: o, includeResources: e } = {}) {
|
|
|
1233
1249
|
h(`upload ${O.length} component assets`);
|
|
1234
1250
|
}
|
|
1235
1251
|
}),
|
|
1236
|
-
Re(
|
|
1252
|
+
Re(v, b, {
|
|
1237
1253
|
getFilePath: (O, f) => {
|
|
1238
|
-
const d = ye(
|
|
1254
|
+
const d = ye(v, f.slice(0, 1));
|
|
1239
1255
|
return c && A(c, L(d.slug), O);
|
|
1240
1256
|
},
|
|
1241
1257
|
onFinish: (O) => {
|
|
@@ -1264,9 +1280,9 @@ async function ze(t, { importAssets: o, includeResources: e } = {}) {
|
|
|
1264
1280
|
}
|
|
1265
1281
|
return {
|
|
1266
1282
|
supportedLocales: m.supportedLocales,
|
|
1267
|
-
pageIds:
|
|
1283
|
+
pageIds: v.map((h) => h.id),
|
|
1268
1284
|
components: Object.fromEntries(x.map((h, E) => [h.id, { index: E, data: h }])),
|
|
1269
|
-
pages: Object.fromEntries(
|
|
1285
|
+
pages: Object.fromEntries(v.map((h) => [h.id, h])),
|
|
1270
1286
|
config: m.config || {},
|
|
1271
1287
|
resources: U,
|
|
1272
1288
|
chunks: D
|
|
@@ -1393,7 +1409,7 @@ function qe() {
|
|
|
1393
1409
|
});
|
|
1394
1410
|
G = (await Promise.all(
|
|
1395
1411
|
t.map(async (e) => {
|
|
1396
|
-
const s = e.path ? await
|
|
1412
|
+
const s = e.path ? await We(e.path, { importAssets: !1 }) : void 0;
|
|
1397
1413
|
return s ? { blockletId: e.did, state: s, blockletTitle: e.title } : void 0;
|
|
1398
1414
|
})
|
|
1399
1415
|
)).filter((e) => !!e), we = G.reduce(
|
|
@@ -1451,8 +1467,8 @@ function bs(t) {
|
|
|
1451
1467
|
};
|
|
1452
1468
|
}
|
|
1453
1469
|
const Qe = Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"), ee = globalThis;
|
|
1454
|
-
var
|
|
1455
|
-
(
|
|
1470
|
+
var Me;
|
|
1471
|
+
(Me = ee[Qe]) == null || Me.call(ee);
|
|
1456
1472
|
ee[Qe] = bs(async ({ pages: t, components: o }) => {
|
|
1457
1473
|
const { projectIds: e } = oe;
|
|
1458
1474
|
I.info(`start update resource states projects(${e.length})`, e), await Promise.race([
|
|
@@ -1460,7 +1476,7 @@ ee[Qe] = bs(async ({ pages: t, components: o }) => {
|
|
|
1460
1476
|
e.map(async (s) => {
|
|
1461
1477
|
const n = oe.shared(s);
|
|
1462
1478
|
n.syncedStore.resources.pages = t;
|
|
1463
|
-
const r = await
|
|
1479
|
+
const r = await B.findByPk(s);
|
|
1464
1480
|
if (r != null && r.useAllResources)
|
|
1465
1481
|
n.syncedStore.resources.components = o;
|
|
1466
1482
|
else {
|
|
@@ -1495,7 +1511,7 @@ async function Xe({
|
|
|
1495
1511
|
export {
|
|
1496
1512
|
Je as C,
|
|
1497
1513
|
je as G,
|
|
1498
|
-
|
|
1514
|
+
B as P,
|
|
1499
1515
|
ke as R,
|
|
1500
1516
|
oe as S,
|
|
1501
1517
|
Xe as a,
|
|
@@ -1515,7 +1531,7 @@ export {
|
|
|
1515
1531
|
Q as o,
|
|
1516
1532
|
ao as p,
|
|
1517
1533
|
io as q,
|
|
1518
|
-
|
|
1534
|
+
We as r,
|
|
1519
1535
|
Ue as s,
|
|
1520
1536
|
ws as t,
|
|
1521
1537
|
bs as u,
|
package/lib/es/components.js
CHANGED
|
@@ -7,7 +7,7 @@ import "lru-cache";
|
|
|
7
7
|
import "node-fetch";
|
|
8
8
|
import "ufo";
|
|
9
9
|
import "crypto";
|
|
10
|
-
import { c as _, G as E, d as i, e as d, j as l, k as N, m as O, h as P, b as c, f as g } from "./_chunks/site-state-
|
|
10
|
+
import { c as _, G as E, d as i, e as d, j as l, k as N, m as O, h as P, b as c, f as g } from "./_chunks/site-state-B5JbU9OF.js";
|
|
11
11
|
export {
|
|
12
12
|
_ as CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS,
|
|
13
13
|
E as GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS,
|
package/lib/es/project-html.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { b as H, l as P } from "./_chunks/site-state-
|
|
1
|
+
import { b as H, l as P } from "./_chunks/site-state-B5JbU9OF.js";
|
|
2
2
|
import { initCronCrawlBlocklet as W, cancelCronCrawlBlocklet as N, initSEOMiddleware as J } from "@blocklet/crawler/middlewares";
|
|
3
3
|
import { PreloadComponentScriptModule as G } from "@blocklet/pages-kit/types";
|
|
4
4
|
import { injectPreloadComponents as K } from "@blocklet/pages-kit/utils/preload";
|
|
5
5
|
import { getComponentMountPoint as Q } from "@blocklet/sdk/lib/component";
|
|
6
6
|
import a, { getBlockletJs as z } from "@blocklet/sdk/lib/config";
|
|
7
|
-
import * as I from "cheerio";
|
|
7
|
+
import * as I from "cheerio/slim";
|
|
8
8
|
import { Router as V } from "express";
|
|
9
9
|
import { readFileSync as j } from "fs";
|
|
10
10
|
import X from "mustache";
|
package/lib/es/resources.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as S, i as b, g as M, l as x, C as J, R as X, S as N, t as W, a as G } from "./_chunks/site-state-
|
|
1
|
+
import { P as S, i as b, g as M, l as x, C as J, R as X, S as N, t as W, a as G } from "./_chunks/site-state-B5JbU9OF.js";
|
|
2
2
|
import { AsyncLocalStorage as K } from "async_hooks";
|
|
3
3
|
import { Router as Y } from "express";
|
|
4
4
|
import d from "fs";
|
package/lib/es/site-state.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { q as x, o as D, p as H, S as M, r as O, a as j, u as q, s as v, n as B, t as L, v as U } from "./_chunks/site-state-
|
|
1
|
+
import { q as x, o as D, p as H, S as M, r as O, a as j, u as q, s as v, n as B, t as L, v as U } from "./_chunks/site-state-B5JbU9OF.js";
|
|
2
2
|
import "@blocklet/quickjs";
|
|
3
3
|
import "@blocklet/sdk/lib/component";
|
|
4
4
|
import "@blocklet/sdk/lib/config";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blocklet/pages-kit-inner-components",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.46",
|
|
4
4
|
"description": "Pages Kit inner components library",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -202,8 +202,8 @@
|
|
|
202
202
|
"yaml": "^2.5.0",
|
|
203
203
|
"yjs": "^13.6.18",
|
|
204
204
|
"zustand": "^4.5.5",
|
|
205
|
-
"@blocklet/pages-kit": "^0.4.
|
|
206
|
-
"@blocklet/pages-kit-block-studio": "^0.4.
|
|
205
|
+
"@blocklet/pages-kit": "^0.4.46",
|
|
206
|
+
"@blocklet/pages-kit-block-studio": "^0.4.46"
|
|
207
207
|
},
|
|
208
208
|
"devDependencies": {
|
|
209
209
|
"@trivago/prettier-plugin-sort-imports": "^5.2.1",
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
"use strict";var tt=Object.defineProperty;var st=(t,n,e)=>n in t?tt(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var A=(t,n,e)=>st(t,typeof n!="symbol"?n+"":n,e);const nt=require("@blocklet/pages-kit/builtin/utils"),se=require("@blocklet/pages-kit/types"),oe=require("@blocklet/pages-kit/utils/property"),B=require("@blocklet/quickjs"),ot=require("@blocklet/sdk/lib/config"),Ee=require("lru-cache"),Le=require("node-fetch"),D=require("ufo"),ie=require("crypto"),rt=require("@blocklet/logger"),at=require("@blocklet/pages-kit/utils/builtin"),Ue=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),be=require("@blocklet/sdk/lib/component"),it=require("autoprefixer"),ct=require("esbuild"),E=require("fs"),lt=require("postcss"),pt=require("tailwindcss"),ut=require("typescript"),dt=require("@reactivedata/reactive"),ee=require("@syncedstore/core"),fe=require("glob"),ft=require("lib0/decoding"),mt=require("lib0/encoding"),N=require("lodash"),gt=require("nanoid"),ht=require("p-limit"),h=require("path"),yt=require("stream/promises"),St=require("tar"),wt=require("wait-on"),G=require("y-protocols/awareness"),le=require("y-protocols/sync"),Et=require("yaml"),bt=require("yjs"),Tt=require("lodash/isNil"),I=require("sequelize");require("sqlite3");const L=t=>t&&t.__esModule?t:{default:t};function X(t){if(t&&t.__esModule)return t;const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const e in t)if(e!=="default"){const s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,s.get?s:{enumerable:!0,get:()=>t[e]})}}return n.default=t,Object.freeze(n)}const w=L(ot),Ot=L(Le),Pt=L(rt),Ct=L(it),It=X(ct),jt=L(lt),At=L(pt),x=L(ut),pe=X(ft),_=X(mt),_t=L(ht),vt=L(h),xt=L(wt),K=X(Et),V=X(bt),Dt=L(Tt);w.default.env.mode;const kt="image-bin";w.default.env.INIT_TEMPLATE_PATH;const Rt=process.env.DATABASE_URL||vt.default.join(w.default.env.dataDir,"db/pages-kit.db"),ve=w.default,Nt=()=>w.default.env.tenantMode==="multiple",Lt=()=>{var t;return(Dt.default(ve.env.preferences.multiTenantAllProjectAccessPassports)?[]:(t=ve.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:t.split(","))||[]},P=Pt.default("pages-kit"),Ut=I.DataTypes.sqlite.DATE.parse;I.DataTypes.sqlite.DATE.parse=(t,n)=>typeof t=="number"?new Date(t):Ut(t,n);const Z=new I.Sequelize({dialect:"sqlite",storage:Rt,benchmark:process.env.ENABLE_SEQUELIZE_BENCHMARK==="true",retry:{match:[/SQLITE_BUSY/],name:"query",max:10},logging:process.env.ENABLE_SEQUELIZE_LOGGING==="true"?console.log:!1});Z.query("pragma journal_mode = WAL;");Z.query("pragma synchronous = normal;");Z.query("pragma journal_size_limit = 67108864;");class ce extends I.Model{}ce.init({id:{type:I.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:I.DataTypes.UUIDV4},projectId:{type:I.DataTypes.UUID,allowNull:!1},componentId:{type:I.DataTypes.STRING,allowNull:!1}},{sequelize:Z,tableName:"ProjectComponents",timestamps:!1});class $ extends I.Model{static async getProjectByIdOrSlug(n){return $.findOne({where:{[I.Op.or]:[{id:n},{slug:n}]}})}}$.init({id:{type:I.DataTypes.UUID,defaultValue:I.DataTypes.UUIDV4,primaryKey:!0},name:{type:I.DataTypes.STRING,allowNull:!1},description:I.DataTypes.TEXT,createdAt:I.DataTypes.DATE,updatedAt:I.DataTypes.DATE,createdBy:{type:I.DataTypes.STRING,allowNull:!1},updatedBy:{type:I.DataTypes.STRING,allowNull:!1},slug:I.DataTypes.STRING,icon:I.DataTypes.STRING,pinnedAt:I.DataTypes.DATE,useAllResources:I.DataTypes.BOOLEAN,relatedBlocklets:{type:I.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(t){this.setDataValue("relatedBlocklets",JSON.stringify(t||{}))}}},{sequelize:Z,paranoid:!0});$.hasMany(ce,{foreignKey:"projectId",as:"components"});const Mt=async(t,{componentId:n})=>{const e=`@tailwind components;
|
|
2
|
-
@tailwind utilities;
|
|
3
|
-
`,s=`.CustomComponent_${n}`;return(await jt.default([At.default({content:[{raw:t,extension:"tsx"}]}),Ct.default({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),r=>{r.walkRules(l=>{l.selectors=l.selectors.map(a=>a.replace(/\.(.+)/g,`${s}.$1,${s} .$1`))})}]).process(e)).css},Ft=async(t,{componentId:n})=>{const e=await Mt(t,{componentId:n});return`export const __PagesKit_CSS__ = ${JSON.stringify(e)};
|
|
4
|
-
|
|
5
|
-
${t}
|
|
6
|
-
`},xe=B.memoize(async(t,n)=>{let e=x.default.transpileModule(t,{compilerOptions:{jsx:x.default.JsxEmit.React,target:x.default.ScriptTarget.ES2016,module:x.default.ModuleKind.ESNext},transformers:{before:[Ue.createBuiltinModuleTransformer(x.default)]}}).outputText;if(n.tailwind&&(e=await Ft(e,{componentId:n.componentId})),n.module===se.PreloadComponentScriptModule.ESM)return e;const s=x.default.transpileModule(e,{compilerOptions:{jsx:x.default.JsxEmit.React,target:x.default.ScriptTarget.ES2016,module:x.default.ModuleKind.CommonJS,moduleResolution:x.default.ModuleResolutionKind.Node16}}).outputText;return n.module===se.PreloadComponentScriptModule.CJS?s:$t(n.moduleName,s)},{keyGenerator:(t,n)=>{const e=ie.createHash("md5").update(t).digest("hex"),s={...n,componentId:n.componentId,module:n.module,...n.module!==se.PreloadComponentScriptModule.ESM?{moduleName:n.moduleName}:{},tailwind:n.tailwind};return JSON.stringify(["transpileModule",e,s])},lruOptions:{max:100,ttl:1e3*60*60}}),qt=async(t,n)=>{var l,a;const s=(a=(l=(await It.build({entryPoints:["index.tsx"],external:Object.keys(at.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(i){let c=null;i.onResolve({filter:/.*/},p=>p.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:p.path==="./component"?{path:"component.tsx",namespace:"vfs"}:null),i.onLoad({filter:/.*/,namespace:"vfs"},async p=>{var u;if(p.path==="index.tsx")return{contents:`export { ${n} } from './component'`,loader:"tsx"};if(p.path==="component.tsx")return{contents:t,loader:"tsx"};if(Ue.isRelativeModule(p.path)){const f=p.path.split("/").pop();if(c||(c=await Ae({ensureLoaded:!1})),(u=c==null?void 0:c.chunks)!=null&&u[f])try{const g=E.readFileSync(c.chunks[f],"utf-8");return P.info("get chunk from local file system",f),{contents:g,loader:"tsx"}}catch{}}return null})}}]})).outputFiles)==null?void 0:l[0])==null?void 0:a.contents;if(!s)throw new Error("Failed to build server code");const o=Buffer.from(s).toString();return x.default.transpileModule(o,{compilerOptions:{module:x.default.ModuleKind.ESNext,target:x.default.ScriptTarget.ES2020}}).outputText},Me=B.memoize(async(t,n)=>{const e=await qt(t,n);return new RegExp(`export\\s+\\{\\s+${n}\\s+\\}`,"m").test(e)?e:void 0},{keyGenerator:(t,n)=>{const e=ie.createHash("md5").update(t).digest("hex");return JSON.stringify(["extractExportValueSchema",e,n])},lruOptions:{max:100,ttl:1e3*60*60}}),$t=(t,n)=>{const e=/\bawait\b/.test(n);return`// GENERATED FILE. DO NOT EDIT.
|
|
7
|
-
var ${t} = ${e?"async":""} function () {
|
|
8
|
-
|
|
9
|
-
const exports = {};
|
|
10
|
-
let moduleExports = null;
|
|
11
|
-
|
|
12
|
-
// add commonjs module compatibility layer
|
|
13
|
-
const module = { exports: moduleExports };
|
|
14
|
-
|
|
15
|
-
// execute component code
|
|
16
|
-
${n}
|
|
17
|
-
|
|
18
|
-
// handle possible module.exports
|
|
19
|
-
if (module.exports && module.exports !== moduleExports) {
|
|
20
|
-
// if module.exports is used, use it first
|
|
21
|
-
return typeof module.exports === 'object' ? module.exports : { default: module.exports };
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
// ensure a default export
|
|
25
|
-
if (!('default' in exports) && Object.keys(exports).length === 0) {
|
|
26
|
-
// module has no exports, return null to indicate invalid
|
|
27
|
-
return null;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
return exports;
|
|
31
|
-
};
|
|
32
|
-
`},z=new Ee.LRUCache({max:100}),Fe=60*60,me=60;function qe(t){P.info("clear preload components cache",{cacheKey:t}),z.delete(t)}function $e(t){for(const n of z.keys())n.includes(t)&&(P.info("clear preload components cache",{cacheKey:n}),qe(n))}function Be({mode:t,instanceId:n,componentId:e,locale:s}){return["getPreloadComponents",t,n,e,s].join("-")}async function Bt({mode:t,req:n,state:e,locale:s,instances:o,module:r}){const{supportedLocales:l,config:{defaultLocale:a}}=e;if(!a)return null;const i=(await Promise.all(o.map(async g=>{try{const S=Be({mode:t,instanceId:g.id,componentId:g.componentId,locale:s});if(t!=="draft"&&g.useCache&&z.has(S))return P.info(`get preload component from cache: ${S}`),z.get(S);const j=W({state:e,componentId:g.componentId});if(!j)return null;const v=await Ve({req:n,state:e,componentId:j.id,locale:s,defaultLocale:a,properties:g.properties});if(!v)return null;const F={instanceId:g.id,preload:v};if(t!=="draft"&&g.useCache){let R=Fe;g.cacheDuration&&(R=g.cacheDuration),P.info(`set preload component to cache(${R}s): ${S}`),z.set(S,F,{ttl:R*1e3})}return F}catch(S){return P.error("get preload component error",{instanceId:g.id,componentId:g.componentId},{error:S}),null}}))).filter(g=>!!g),c=Object.values(i.reduce((g,S)=>({...g,...S.preload.components}),{}));async function p(){const g=await Promise.all(c.map(async S=>{const j=oe.componentUMDName({componentId:S.component.id}),v=r===se.PreloadComponentScriptModule.ESM?{module:r,script:await xe(S.script,{componentId:S.component.id,module:r,tailwind:t!=="draft"})}:{module:r,script:await xe(S.script,{componentId:S.component.id,module:r,moduleName:j,tailwind:t!=="draft"}),moduleName:j};return[S.component.id,{component:S.component,script:v}]}));return Object.fromEntries(g)}const u=await p();return{config:{defaultLocale:a,supportedLocales:l},components:u,instances:i.map(g=>({id:g.instanceId,componentId:g.preload.component.id,locales:{[g.preload.locale]:{props:g.preload.props}}}))}}async function Ve({req:t,state:n,componentId:e,locale:s,defaultLocale:o,properties:r}){const{supportedLocales:l}=n,a=W({state:n,componentId:e});if(!a)return null;const i=l.some(p=>p.locale===s)?s:o;if(!i)return null;const c=await He({req:t,state:n,componentId:e,locale:i,defaultLocale:o,properties:r});return c?{component:a,...c}:null}const Vt=20;async function He({req:t,depth:n=0,state:e,componentId:s,locale:o,defaultLocale:r,properties:l}){if(n>Vt)throw new RangeError("max component depth exceeded");const a=Ht({state:e,componentId:s,properties:l,locale:o});if(!a)return null;const{props:i}=a,c={locale:o||r,components:{[a.component.id]:{component:a.component,script:a.script}},props:{...i}};try{const p=await Jt({...a,req:t});p!=null&&p.props&&Object.assign(c.props,p.props)}catch(p){P.error("preload data at server side error",{componentId:s,name:a.component.name},{error:p})}return await Promise.all(Object.entries(i).map(async([p,u])=>{if((u==null?void 0:u.type)===oe.RenderNestedComponent){const f=await He({req:t,depth:n+1,state:e,componentId:u.componentId,locale:o,defaultLocale:r,properties:u.properties});f&&(Object.assign(c.components,f.components),Object.assign(c.props,{[p]:{type:oe.RenderNestedComponent,componentId:u.componentId,props:f.props}}))}})),c}function Ht({state:t,componentId:n,locale:e,properties:s}){const o=W({state:t,componentId:n});if(!o)return null;const r=oe.mergeComponent({componentId:n,getComponent:l=>W({state:t,componentId:l}),locale:e,defaultLocale:t.config.defaultLocale,properties:s});return r?{component:o,script:r.script,props:{locale:e,...r.properties}}:null}function W({state:t,componentId:n}){var e,s,o;return((e=t.components[n])==null?void 0:e.data)??((o=(s=t.resources.components)==null?void 0:s[n])==null?void 0:o.component)}function Gt({state:t,name:n}){var s,o;const e=n.toLowerCase();return((s=Object.values(t.components).find(r=>{var l;return((l=r.data.name)==null?void 0:l.toLowerCase())===e}))==null?void 0:s.data)??((o=t.resources.components&&Object.values(t.resources.components).find(r=>{var l;return((l=r.component.name)==null?void 0:l.toLowerCase())===e}))==null?void 0:o.component)}async function Jt({component:t,script:n,props:e,req:s}){if(!(n!=null&&n.includes("getServerSideProps")))return null;const o=await Me(n,"getServerSideProps");if(!o)return null;const r=new Promise((a,i)=>{setTimeout(()=>{i(new Error("getServerSideProps timeout in promise race"))},me*1e3)});return await Promise.race([r,B.Sandbox.callFunction({code:`${o}
|
|
33
|
-
|
|
34
|
-
export async function getServerSidePropsWrapper(props) {
|
|
35
|
-
const { location, fetch } = props;
|
|
36
|
-
// 使用局部变量而不是全局变量
|
|
37
|
-
const originalLocation = typeof window !== 'undefined' ? window.location : undefined;
|
|
38
|
-
const originalFetch = globalThis.fetch;
|
|
39
|
-
|
|
40
|
-
try {
|
|
41
|
-
globalThis.location = location;
|
|
42
|
-
globalThis.fetch = fetch;
|
|
43
|
-
return await getServerSideProps(props);
|
|
44
|
-
} finally {
|
|
45
|
-
// 清理全局状态
|
|
46
|
-
if (originalLocation) globalThis.location = originalLocation;
|
|
47
|
-
if (originalFetch) globalThis.fetch = originalFetch;
|
|
48
|
-
}
|
|
49
|
-
}`,filename:`${t.name||t.id}.js`,moduleLoader:a=>{if(a==="@blocklet/pages-kit/builtin/utils")return`const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
|
|
50
|
-
export { joinURL, withQuery, getQuery, getComponentMountPoint }
|
|
51
|
-
`;if(a==="@blocklet/pages-kit/builtin/dayjs")return B.BuiltinModules.dayjs},global:{console:{log:(...a)=>{P.info(...a)},warn:(...a)=>{P.warn(...a)},error:(...a)=>{P.error(...a)}},getComponentMountPoint:nt.getComponentMountPoint,joinURL:D.joinURL,withQuery:D.withQuery,getQuery:D.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:D.joinURL(D.withHttps(s.hostname),s.originalUrl)},fetch:(a,{...i}={})=>{const c=typeof a=="string"&&a.startsWith("/")?D.joinURL(w.default.env.appUrl,a):a;if(typeof c=="string"&&D.parseURL(c).host===D.parseURL(w.default.env.appUrl).host){const p=s.get("cookie");if(p){const u=new Le.Headers(i.headers);u.set("cookie",p),i.headers=u}}return Ot.default(c,{...i,timeout:me*1e3}).then(p=>({ok:p.ok,status:p.status,statusText:p.statusText,headers:Object.fromEntries(p.headers.entries()),json:()=>p.json()}))},props:e}]})])}const Ge=B.memoize(async(t,n,e)=>{if(!(t!=null&&t.includes(n)))return null;const s=await Me(t,n);if(s)try{return await B.Sandbox.callFunction({code:`
|
|
52
|
-
${s}
|
|
53
|
-
|
|
54
|
-
export function get${n}SchemaWrapper() {
|
|
55
|
-
return ${n};
|
|
56
|
-
}
|
|
57
|
-
`,filename:`${e}.js`,functionName:`get${n}SchemaWrapper`})}catch(o){return P.error(`获取 ${n} 失败`,{componentId:e,error:o}),null}return null},{keyGenerator:(t,n,e)=>{const s=ie.createHash("md5").update(t).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",s,n,e])},lruOptions:{max:100,ttl:1e3*60*60}}),Kt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",ge="page",he="trigger-reload-project-resource",Te=Kt,zt="z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV",{uploadToMediaKit:Yt}=require("@blocklet/uploader-server"),ye=gt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),Oe=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,Y=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,De=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Wt=1e4,Qt=3e4,te=0,ue=1,Xt=0,Zt=1,Se=w.default,J=h.join(process.env.BLOCKLET_DATA_DIR,"site-state"),es=["production","draft"],ts=["production"];function Je(t){return(t==null?void 0:t.replace(/\//g,"|"))||""}function ss(){var e;const t=Se.env.languages.map(s=>({locale:s.code,name:s.name})),n=(e=t[0])==null?void 0:e.locale;return{pageIds:[],pages:{},components:{},supportedLocales:t,config:{defaultLocale:n},resources:{}}}const q=class q extends V.Doc{constructor(e){super();A(this,"states",{});A(this,"syncedStore");A(this,"conns",new Map);A(this,"awareness");A(this,"awarenessChangeHandler",({added:e,updated:s,removed:o},r)=>{const l=e.concat(s,o);if(r!==null){const c=this.conns.get(r);c&&(e.forEach(p=>{c.add(p)}),o.forEach(p=>{c.delete(p)}))}const a=_.createEncoder();_.writeVarUint(a,ue),_.writeVarUint8Array(a,G.encodeAwarenessUpdate(this.awareness,l));const i=_.toUint8Array(a);this.conns.forEach((c,p)=>this.send(p,i))});A(this,"updateHandler",e=>{const s=_.createEncoder();_.writeVarUint(s,te),le.writeUpdate(s,e);const o=_.toUint8Array(s);this.conns.forEach((r,l)=>this.send(l,o))});A(this,"ensureDataStructure",()=>{var l;const{supportedLocales:e,pages:s,pageIds:o,config:r}=this.syncedStore;{const a=new Set(Object.keys(s));let i=0;for(;i<o.length;){const c=o[i];a.has(c)?(a.delete(c),i++):o.splice(i,1)}}e.splice(0,e.length),e.push(...Se.env.languages.map(a=>({locale:a.code,name:a.name}))),r.defaultLocale=(l=e[0])==null?void 0:l.locale;{let a=0;const i=new Set;for(;a<e.length;){const{locale:c}=e[a];i.has(c)?e.splice(a,1):(a++,i.add(c))}}});A(this,"send",(e,s)=>{e.readyState!==Xt&&e.readyState!==Zt&&this.closeConn(e);try{e.send(s,o=>{o&&this.closeConn(e)})}catch{this.closeConn(e)}});A(this,"closeConn",e=>{if(e.removeAllListeners(),this.conns.has(e)){const s=this.conns.get(e);this.conns.delete(e),s&&G.removeAwarenessStates(this.awareness,Array.from(s),null)}e.close()});A(this,"autoSave",N.debounce(()=>{E.mkdirSync(h.dirname(this.draftYjsFilePath),{recursive:!0}),E.writeFileSync(this.draftYjsFilePath,V.encodeStateAsUpdate(this))},Wt));A(this,"save",({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()});A(this,"publish",async({mode:e,pages:s})=>{const o=await this.getState("draft"),r=await this.getState("production");await we(o,r,{pages:s,pageMergeMode:"replace",deletePages:!0,publishMode:e}),r.config.publishedAt=new Date().getTime();for(const l of s||Object.keys(this.syncedStore.pages))this.syncedStore.pages[l]&&(this.syncedStore.pages[l].publishedAt=new Date().toISOString());await this.setState(e,r)});A(this,"mergeState",async(e,s)=>{var a,i,c;const o=JSON.parse(JSON.stringify(s));(a=e.config).fontFamily??(a.fontFamily={});const r=(i=o.config)==null?void 0:i.fontFamily,l=(c=e.config)==null?void 0:c.fontFamily;e.config.fontFamily.title=(r==null?void 0:r.title)||(l==null?void 0:l.title),e.config.fontFamily.description=(r==null?void 0:r.description)||(l==null?void 0:l.description),await new Promise((p,u)=>{this.transact(async()=>{try{const f=await we(e,s);p(f)}catch(f){u(f)}})})});A(this,"addConnection",e=>{if(this.conns.has(e))return;e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",r=>this.messageListener(e,new Uint8Array(r)));let s=!0;const o=setInterval(()=>{if(!s)this.conns.has(e)&&this.closeConn(e),clearInterval(o);else if(this.conns.has(e)){s=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(o)}}},Qt);e.on("close",()=>{this.closeConn(e),clearInterval(o)}),e.on("pong",()=>{s=!0});{const r=_.createEncoder();_.writeVarUint(r,te),le.writeSyncStep1(r,this),this.send(e,_.toUint8Array(r));const l=this.awareness.getStates();if(l.size>0){const a=_.createEncoder();_.writeVarUint(a,ue),_.writeVarUint8Array(a,G.encodeAwarenessUpdate(this.awareness,Array.from(l.keys()))),this.send(e,_.toUint8Array(a))}}});A(this,"messageListener",(e,s)=>{try{const o=_.createEncoder(),r=pe.createDecoder(s),l=pe.readVarUint(r);switch(l){case te:_.writeVarUint(o,te),le.readSyncMessage(r,o,this,null),_.length(o)>1&&(this.ensureDataStructure(),this.send(e,_.toUint8Array(o)));break;case ue:{G.applyAwarenessUpdate(this.awareness,pe.readVarUint8Array(r),e);break}default:P.warn(`Unsupported messageType ${l}`)}}catch(o){P.error(o)}this.save()});this.options=e,E.existsSync(this.draftYjsFilePath)&&V.applyUpdate(this,E.readFileSync(this.draftYjsFilePath)),this.syncedStore=dt.reactive(ee.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new G.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const s=h.join(J,e),o=h.join(J,`@del-${e}`);E.renameSync(s,o)}catch(s){P.error("Failed to safe delete project state dir:",s)}}static get projectIds(){return fe.globSync("*/",{cwd:J,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(e=>q.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let s=this.sharedInstances.get(e);return s||(s=new q({path:h.join(J,e)}),this.sharedInstances.set(e,s),s)}destroy(){this.conns.forEach((e,s)=>this.closeConn(s)),this.awareness.destroy(),super.destroy()}initObserver(){const e=o=>{o.observeDeep(r=>{r.some(l=>l.changes.keys.has("updatedAt")||l.changes.keys.has("publishedAt"))||o.set("updatedAt",new Date().toISOString())})};this.syncedStore.pages&&Object.keys(this.syncedStore.pages).forEach(o=>{const r=ee.getYjsValue(this.syncedStore.pages[o]);r&&r instanceof V.Map&&e(r)});const s=ee.getYjsValue(this.syncedStore.pages);s&&s instanceof V.Map&&s.observe(o=>{o.changes.keys.forEach((r,l)=>{if(r.action==="add"){const a=ee.getYjsValue(this.syncedStore.pages[l]);a&&a instanceof V.Map&&e(a)}})})}get draftYjsFilePath(){return h.join(this.options.path,"draft.yjs")}async getState(e){var s,o,r,l;if(e==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[e]&&(this.states[e]=await Pe(this.getPublishDir(e),{includeResources:!0})??ss(),!((o=(s=this.states[e])==null?void 0:s.config)!=null&&o.defaultLocale))){(r=this.states[e]).config??(r.config={});const a=Se.env.languages.map(i=>({locale:i.code,name:i.name}));this.states[e].config.defaultLocale=(l=a[0])==null?void 0:l.locale}return{...this.states[e],resources:await Ae().then(async a=>{var u,f,g,S;const{pages:i,components:c}=N.pick(a,"pages","components");let p=c;if((f=(u=this.states[e])==null?void 0:u.resources)!=null&&f.components)p={...(S=(g=this.states[e])==null?void 0:g.resources)==null?void 0:S.components};else{const j=h.basename(this.options.path),v=await $.findByPk(j);if(v!=null&&v.useAllResources)p=c;else{const R=(await ce.findAll({where:{projectId:j}})).map(T=>T.componentId);p=Object.fromEntries(Object.entries(c||{}).filter(([T])=>R.includes(T)))}}return{pages:i,components:p}}).catch(()=>({}))}}async setState(e,s){const o=await Ye(s,{exportAssets:!1,includeResources:!0}),r=this.getPublishDir(e);E.mkdirSync(h.dirname(r),{recursive:!0}),E.rmSync(r,{force:!0,recursive:!0}),E.renameSync(o,r),this.states[e]=s}getPublishDir(e){return h.join(this.options.path,e)}static async pageUrlMap(e){const{projectIds:s}=this,o={};for(const r of s){const l=await $.findByPk(r);if(!l)continue;const a=await q.shared(r).getState(e),i=N.union(w.default.env.languages.map(c=>c.code),a.supportedLocales.map(c=>c.locale));for(const c of a.pageIds){const p=a.pages[c];if(!p||e==="production"&&!p.isPublic)continue;const u=p.slug,f=l.slug||r,g={projectId:r,projectSlug:f,pageSlug:u,pageId:c,defaultLocale:i==null?void 0:i[0],locales:i,publishedAt:a.config.publishedAt,isPublic:p.isPublic,isTemplate:p.isTemplate};f&&(o[D.joinURL("/",f,u)]={...g,shouldRedirect:!0,mainPage:!0}),o[D.joinURL("/",r,u)]={...g,shouldRedirect:!0,mainPage:!0};for(const S of i){const j={...g,locale:S};o[D.joinURL("/",S,r,u)]=j,f&&(o[D.joinURL("/",S,f,u)]=j)}}}return o}};A(q,"INSTANCE_TTL",30*60*1e3),A(q,"sharedInstances",new Ee.LRUCache({max:100,ttl:q.INSTANCE_TTL,dispose:e=>{e.destroy()}}));let Q=q;function Ke(){return E.mkdtempSync(h.join(w.default.env.dataDir,"tmp-"))}function re(t,n,e=[]){return Array.isArray(t)?t.flatMap((s,o)=>re(s,n,[...e,o])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([s,o])=>re(o,n,[...e,s])):n(t)?[e]:[]}function M(t){return t.filter(n=>n!=null)}async function ns(t,n,e){if(!t||!E.existsSync(t)||!E.lstatSync(t).isFile())return null;let s=e[t];return s||(s=(async()=>{var o;try{const r=(o=await Yt({filePath:t,fileName:n}))==null?void 0:o.data;return r==null?void 0:r.filename}catch(r){return P.error(`Failed to upload asset ${t}:`,r),null}})(),e[t]=s),s}const os=async(t,n)=>{const e=h.basename(t),s=await be.call({name:Te,path:D.joinURL("/uploads",e),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const o=E.createWriteStream(n);await yt.pipeline(s.data,o)}else throw new Error(`download asset failed ${s.status}`)},rs=async(t,n)=>{await Promise.all(t.map(async e=>{try{await os(e,h.join(n,h.basename(e)))}catch(s){P.error(`Failed to export assets: ${e}, ${s}`)}}))};function ze(t){return Oe.test(t)?[t]:Y.test(t)?(De.lastIndex=0,Array.from(t.matchAll(De)).map(e=>e[1]).filter(e=>!!e)):[]}async function de(t,n,e){const{getFilename:s,exportAssets:o}=e,r=h.join(n,s(t));if(E.mkdirSync(h.dirname(r),{recursive:!0}),E.writeFileSync(r,K.stringify(t)),o){const a=re(t,i=>typeof i=="string"&&(Oe.test(i)||Y.test(i))).map(i=>{const c=N.get(t,i);return ze(c)}).flat().filter(Boolean);await rs(a,h.dirname(r))}}const ke=new Ee.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function Re(t,n,e){var a;const s=re(t,i=>typeof i=="string"&&(Oe.test(i)||Y.test(i))),o=_t.default(2),r=s.map(i=>o(async()=>{try{const c=N.get(t,i),p=ze(c);for(const u of p){const f=h.basename(u),g=e.getFilePath(u,i),S=g?`${g}:${f}`:f,j=ke.get(S);if(j){Y.test(c)||N.set(t,i,j);return}const v=await ns(g,f,n);v&&(Y.test(c)||N.set(t,i,v),ke.set(S,v))}}catch(c){P.error(`Failed to process upload for path ${i.join(".")}:`,c.message||c.reason)}})),l=await Promise.allSettled(r);(a=e.onFinish)==null||a.call(e,l)}async function Ye(t,{exportAssets:n,pageIds:e="all",componentIds:s="all",rawConfig:o,includeResources:r=!1}={}){var F,R,y,T,O,C;const l=e==="all"?t.pageIds:e,a=as({state:t,pageIds:l,componentIds:s==="all"?Object.keys(t.components):s}),i=(m,d)=>{var b;return{id:m.id,name:m.name,isTemplateSection:m.isTemplateSection??!1,templateDescription:m.templateDescription,component:m.component,config:m.config,visibility:m.visibility,properties:((b=m.locales)==null?void 0:b[d])??{}}},c=(m,d)=>{var b;return{id:m.id,createdAt:m.createdAt,updatedAt:m.updatedAt,publishedAt:m.publishedAt,isPublic:m.isPublic??!0,isTemplate:m.isTemplate??!1,meta:((b=m.locales)==null?void 0:b[d])??{},sections:M(m.sectionIds.map(k=>{const U=m.sections[k];return U&&i(U,d)}))}},p=M(t.supportedLocales.map(m=>m.locale).flatMap(m=>l.map(d=>{const b=t.pages[d];return b&&{locale:m,slug:b.slug,page:c(b,m)}}))),u=Ke(),f=h.join(u,"pages");E.mkdirSync(f,{recursive:!0});const g=h.join(u,"components");E.mkdirSync(g,{recursive:!0});for(const{locale:m,slug:d,page:b}of p)await de(b,f,{getFilename:()=>`${Je(d)||"index"}.${m}.yml`,exportAssets:n});for(const m of a){const d=(F=t.components[m])==null?void 0:F.data;d&&await de(d,g,{getFilename:b=>`${b.name||"unnamed"}.${b.id}.yml`,exportAssets:n})}const S=h.join(u,".blocklet/pages/pages.config.yml");E.mkdirSync(h.dirname(S),{recursive:!0});const j={pages:M(l.map(m=>{const d=t.pages[m];return d&&{id:m,slug:d.slug}})),components:M(a.map(m=>{var b;const d=(b=t.components[m])==null?void 0:b.data;return d&&{id:m,name:d.name}})),...r?{resources:{components:M(Object.keys(((R=t.resources)==null?void 0:R.components)||{}).map(m=>{var d,b,k,U;return{id:m,name:(U=(k=(b=(d=t.resources)==null?void 0:d.components)==null?void 0:b[m])==null?void 0:k.component)==null?void 0:U.name}}))}}:{},supportedLocales:t.supportedLocales,config:t.config};E.writeFileSync(S,K.stringify(j));const v=h.join(u,"config.source.json");if(o&&E.writeFileSync(v,JSON.stringify(o)),r){const m=h.join(u,"resources"),d=h.join(m,"components");E.mkdirSync(d,{recursive:!0});for(const b of Object.keys(((y=t==null?void 0:t.resources)==null?void 0:y.components)??{})){const k=(C=(O=(T=t.resources)==null?void 0:T.components)==null?void 0:O[b])==null?void 0:C.component;k&&await de(k,d,{getFilename:U=>`${U.name||"unnamed"}.${U.id}.yml`,exportAssets:n})}}return u}async function Pe(t,{importAssets:n,includeResources:e}={}){var r,l,a;if(!E.existsSync(t))return null;let s,o=!1;try{E.lstatSync(t).isDirectory()?s=t:/\.(tgz|gz|tar)$/.test(t)&&(o=!0,s=Ke(),await St.x({file:t,C:s}));const i=fe.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}).at(0),c=i&&h.join(h.dirname(i),"../../pages"),p=i&&h.join(h.dirname(i),"../../components"),u=i&&h.join(h.dirname(i),"../../chunks");if(!i)return null;const f=K.parse(E.readFileSync(i).toString()),g=(y,T,O)=>{let C=h.join(y,`${T}${O?`.${O}`:""}.yml`);return(!E.existsSync(C)||!E.lstatSync(C).isFile())&&(C=h.join(y,T,`index${O?`.${O}`:""}.yml`),!E.existsSync(C)||!E.lstatSync(C))?null:K.parse(E.readFileSync(C).toString())},S=(y,T)=>{try{const O=fe.globSync(`*.${T}.yml`,{cwd:y,absolute:!0})[0];return O?K.parse(E.readFileSync(O).toString()):null}catch(O){P.error("parse component error",O)}return null},j=M(f.pages.map(({slug:y})=>{var m;const T=M(f.supportedLocales.map(({locale:d})=>{const b=c?g(c,Je(y),d):void 0;if(b)return{locale:d,page:b};const k=c?g(c,y,d):void 0;return k&&{locale:d,page:k}})),O=(m=T[0])==null?void 0:m.page;if(!O)return null;const C=O.sections.map(d=>{const b=d.id||ye();return{id:b,component:d.component,config:d.config,name:d.name,isTemplateSection:d.isTemplateSection??!1,templateDescription:d.templateDescription,visibility:d.visibility,locales:Object.fromEntries(M(T.map(({locale:k,page:U})=>{const _e=U.sections.find(et=>et.id===b);return _e&&[k,_e.properties]})))}});return{id:O.id||ye(),createdAt:O.createdAt,updatedAt:O.updatedAt,publishedAt:O.publishedAt,isPublic:O.isPublic??!0,isTemplate:O.isTemplate??!1,slug:y,sections:Object.fromEntries(C.map(d=>[d.id,d])),sectionIds:C.map(d=>d.id),locales:Object.fromEntries(T.map(({locale:d,page:b})=>[d,b.meta]))}})),v=p?M(((r=f.components)==null?void 0:r.map(({id:y})=>S(p,y)))??[]):[];if(n){const y=(...T)=>{P.info(`[${o?h.basename(t):h.basename(h.join(t,"../../../../"))}] importAssets:`,...T)};try{y("wait image-bin api ready"),await xt.default({resources:[`${be.getComponentWebEndpoint(kt)}/api/sdk/uploads`],validateStatus:C=>C>=200&&C<=500}),y("image-bin api is ready");const T={},O={};y("start to upload assets"),await Promise.allSettled([Re(v,T,{getFilePath:C=>p&&h.join(p,C),onFinish:C=>{y(`upload ${C.length} component assets`)}}),Re(j,O,{getFilePath:(C,m)=>{const d=N.get(j,m.slice(0,1));return c&&h.join(c,h.dirname(d.slug),C)},onFinish:C=>{y(`upload ${C.length} page assets`)}})]),y("upload assets done"),global.gc&&global.gc()}catch(T){y("Error during asset import:",T)}}const F={};if(e){const y=i&&h.join(h.dirname(i),"../../resources/components"),T=M(((a=(l=f.resources)==null?void 0:l.components)==null?void 0:a.map(({id:O})=>S(y,O)))??[]);T.length>0&&(F.components=Object.fromEntries(T.map((O,C)=>[O.id,{index:C,component:O}])))}const R={};if(u&&E.existsSync(u)){const y=E.readdirSync(u);for(const T of y)R[T]=h.join(u,T)}return{supportedLocales:f.supportedLocales,pageIds:j.map(y=>y.id),components:Object.fromEntries(v.map((y,T)=>[y.id,{index:T,data:y}])),pages:Object.fromEntries(j.map(y=>[y.id,y])),config:f.config||{},resources:F,chunks:R}}finally{o&&s&&E.rmSync(s,{force:!0,recursive:!0})}}async function we(t,n,{pages:e,pageMergeMode:s="byUpdateTime",deletePages:o=!1,publishMode:r=void 0}={}){try{r&&$e(r)}catch(p){P.error("clear preload page cache error",{error:p})}const{pageIds:l,pages:a,supportedLocales:i}=t;for(const p of e??l){const u=a[p];if(!u){const f=n.pageIds.indexOf(p);f!==-1&&o&&(n.pageIds.splice(f,1),delete n.pages[p]);continue}if(n.pageIds.includes(u.id)){if(s==="replace")n.pages[u.id]=u;else if(s==="byUpdateTime"){const f=n.pages[u.id];(!f||u.updatedAt&&u.updatedAt>f.updatedAt)&&(n.pages[u.id]=u)}}else n.pageIds.push(u.id),n.pages[u.id]=u}if(o&&!e)for(const p of n.pageIds)t.pageIds.includes(p)||delete n.pages[p],n.pageIds=[...n.pageIds].filter(u=>t.pageIds.includes(u));if(n.supportedLocales.splice(0,n.supportedLocales.length),n.supportedLocales.push(...N.cloneDeep(i)),o)for(const p of Object.keys(n.components))delete n.components[p];let c=JSON.parse(JSON.stringify(t.components));c=Object.fromEntries(await Promise.all(Object.entries(c).map(async([p,u])=>{const f=await We(u==null?void 0:u.data);return[p,{...u,data:f}]}))),Object.assign(n.components,c),Object.assign(n.config,JSON.parse(JSON.stringify(t.config))),n.resources.components=JSON.parse(JSON.stringify(t.resources.components||{}))}const We=B.memoize(async t=>{var n;if(!N.isEmpty(t==null?void 0:t.properties))return t;if(((n=t==null?void 0:t.renderer)==null?void 0:n.type)==="react-component"){const{script:e}=(t==null?void 0:t.renderer)||{};if(e&&e.includes("PROPERTIES_SCHEMA"))try{const s=await Ge(e,"PROPERTIES_SCHEMA",t.id);s&&s.length>0&&t&&(t.properties={},s.forEach((o,r)=>{t!=null&&t.properties&&(t.properties[o.id]={index:r,data:o})}))}catch(s){P.error("checkPropertiesFromCode error",{componentId:t.id,name:t.name},{error:s})}}return t},{keyGenerator:t=>{var l;const n=(t==null?void 0:t.id)||"",e=(t==null?void 0:t.name)||"",s=((l=t==null?void 0:t.renderer)==null?void 0:l.type)||"",o=(t==null?void 0:t.properties)||{},r=ie.createHash("md5").update(JSON.stringify(o)).digest("hex");return JSON.stringify(["checkPropertiesFromCode",n,e,s,r])},lruOptions:{max:100,ttl:1e3*60*60}});function as({state:t,pageIds:n=[],componentIds:e=[]}){var l;const s=(a,i=new Set)=>(Array.isArray(a)&&a.forEach(c=>s(c,i)),a&&typeof a=="object"&&(typeof a.componentId=="string"&&i.add(a.componentId),Object.values(a).forEach(c=>s(c,i))),i),o=new Set(e);for(const a of n){const i=t.pages[a];s(i,o)}const r=[...o];for(;r.length;){const a=r.shift();o.has(a)||o.add(a);const i=(l=t.components[a])==null?void 0:l.data;if(i)for(const c of s(i))o.has(c)||r.push(c)}return[...o]}let ae,H,Ce,Ie,je;function Qe(){return ae=(async()=>{const t=be.getResources({types:[{did:Te,type:ge},{did:zt,type:ge}]});H=(await Promise.all(t.map(async e=>{const s=e.path?await Pe(e.path,{importAssets:!1}):void 0;return s?{blockletId:e.did,state:s,blockletTitle:e.title}:void 0}))).filter(e=>!!e),Ce=H.reduce((e,s)=>Object.assign(e,Object.fromEntries(Object.values(s.state.pages).map(o=>o?[o==null?void 0:o.id,{page:o,blockletId:s.blockletId}]:[]))),{});const n=H.reduce((e,s)=>Object.assign(e,Object.fromEntries(Object.values(s.state.components).map(o=>[o.data.id,{blockletId:s.blockletId,component:o.data}]))),{});Ie=Object.fromEntries(await Promise.all(Object.entries(n).map(async([e,s])=>{const o=await We(s.component);return[e,{...s,component:o}]}))),je=H.reduce((e,s)=>Object.assign(e,s.state.chunks),{})})(),ae}function Xe(t){const n=N.debounce(async()=>{await Qe().catch(e=>{P.error("load resource states error",{error:e})}),await(t==null?void 0:t({states:H,pages:Ce,components:Ie,chunks:je}))},3e3,{leading:!1,trailing:!0});return n(),w.default.events.on(w.default.Events.componentAdded,n),w.default.events.on(w.default.Events.componentRemoved,n),w.default.events.on(w.default.Events.componentStarted,n),w.default.events.on(w.default.Events.componentStopped,n),w.default.events.on(w.default.Events.componentUpdated,n),w.default.events.on(he,n),()=>{w.default.events.off(w.default.Events.componentAdded,n),w.default.events.off(w.default.Events.componentRemoved,n),w.default.events.off(w.default.Events.componentStarted,n),w.default.events.off(w.default.Events.componentStopped,n),w.default.events.off(w.default.Events.componentUpdated,n),w.default.events.off(he,n)}}const Ze=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),ne=globalThis;var Ne;(Ne=ne[Ze])==null||Ne.call(ne);ne[Ze]=Xe(async({pages:t,components:n})=>{const{projectIds:e}=Q;P.info(`start update resource states projects(${e.length})`,e),await Promise.race([Promise.all(e.map(async s=>{const o=Q.shared(s);o.syncedStore.resources.pages=t;const r=await $.findByPk(s);if(r!=null&&r.useAllResources)o.syncedStore.resources.components=n;else{const a=(await ce.findAll({where:{projectId:s}})).map(c=>c.componentId),i=Object.fromEntries(Object.entries(n||{}).filter(([c])=>a.includes(c)));o.syncedStore.resources.components=i}P.info(`update [${s}] resource states:`,{pages:Object.keys(o.syncedStore.resources.pages||{}).length,components:Object.keys(o.syncedStore.resources.components||{}).length})})),new Promise((s,o)=>{setTimeout(()=>{o(new Error("timeout to update resource states"))},30*1e3)})]).catch(s=>{P.error("update resource states failed:",s)})});async function is(){P.info("trigger reload all project resource"),w.default.events.emit(he)}async function Ae({ensureLoaded:t=!0}={}){return t&&(ae??(ae=Qe()),await ae),{states:H,pages:Ce,components:Ie,chunks:je}}exports.COMPONENT_DID=Te;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=Fe;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=me;exports.PUBLISH_MODES=ts;exports.Project=$;exports.RESOURCE_TYPE=ge;exports.SITE_STATE_PATH=J;exports.STATE_MODES=es;exports.SiteState=Q;exports.clearPreloadComponentsCache=qe;exports.clearPreloadComponentsCacheByMode=$e;exports.fromPackage=Pe;exports.getComponentFromState=W;exports.getComponentFromStateByName=Gt;exports.getExportSchemaValueFromCode=Ge;exports.getMultiTenantAllProjectAccessPassports=Lt;exports.getPreloadComponent=Ve;exports.getPreloadComponents=Bt;exports.getPreloadComponentsCacheKey=Be;exports.getResourceStates=Ae;exports.initPackResourceStates=Xe;exports.isMultiTenant=Nt;exports.logger=P;exports.mergeState=we;exports.nextId=ye;exports.toPackage=Ye;exports.triggerReloadAllProjectResource=is;
|