@blocklet/pages-kit-inner-components 0.4.24 → 0.4.26
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-B57sn0Rr.js → site-state-DNRKik3e.js} +4 -4
- package/lib/cjs/components.js +1 -1
- package/lib/cjs/project-html.js +12 -7
- package/lib/cjs/resources.js +1 -1
- package/lib/cjs/site-state.js +1 -1
- package/lib/es/_chunks/{site-state-D28bWM8J.js → site-state-B0nM69Rk.js} +137 -142
- package/lib/es/components.js +1 -1
- package/lib/es/project-html.js +92 -86
- package/lib/es/resources.js +1 -1
- package/lib/es/site-state.js +1 -1
- package/package.json +3 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const st=require("vite-plugin-node-polyfills/shims/process"),nt=require("vite-plugin-node-polyfills/shims/global"),ot=require("@blocklet/pages-kit/builtin/utils"),te=require("@blocklet/pages-kit/types"),ne=require("@blocklet/pages-kit/utils/property"),$=require("@blocklet/quickjs"),rt=require("@blocklet/sdk/lib/config"),Te=require("lru-cache"),Me=require("node-fetch"),v=require("ufo"),ie=require("crypto"),at=require("@blocklet/logger"),it=require("vite-plugin-node-polyfills/shims/buffer"),ct=require("@blocklet/pages-kit/utils/builtin"),me=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),ce=require("@blocklet/sdk/lib/component"),lt=require("autoprefixer"),ut=require("esbuild"),E=require("fs"),pt=require("postcss"),dt=require("tailwindcss"),ft=require("typescript"),mt=require("@reactivedata/reactive"),Z=require("@syncedstore/core"),ge=require("glob"),gt=require("lib0/decoding"),ht=require("lib0/encoding"),R=require("lodash"),yt=require("nanoid"),St=require("p-limit"),m=require("path"),wt=require("stream/promises"),Et=require("tar"),bt=require("wait-on"),G=require("y-protocols/awareness"),ue=require("y-protocols/sync"),Tt=require("yaml"),Ot=require("yjs"),
|
|
1
|
+
"use strict";const st=require("vite-plugin-node-polyfills/shims/process"),nt=require("vite-plugin-node-polyfills/shims/global"),ot=require("@blocklet/pages-kit/builtin/utils"),te=require("@blocklet/pages-kit/types"),ne=require("@blocklet/pages-kit/utils/property"),$=require("@blocklet/quickjs"),rt=require("@blocklet/sdk/lib/config"),Te=require("lru-cache"),Me=require("node-fetch"),v=require("ufo"),ie=require("crypto"),at=require("@blocklet/logger"),it=require("vite-plugin-node-polyfills/shims/buffer"),ct=require("@blocklet/pages-kit/utils/builtin"),me=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),ce=require("@blocklet/sdk/lib/component"),lt=require("autoprefixer"),ut=require("esbuild"),E=require("fs"),pt=require("postcss"),dt=require("tailwindcss"),ft=require("typescript"),mt=require("@reactivedata/reactive"),Z=require("@syncedstore/core"),ge=require("glob"),gt=require("lib0/decoding"),ht=require("lib0/encoding"),R=require("lodash"),yt=require("nanoid"),St=require("p-limit"),m=require("path"),wt=require("stream/promises"),Et=require("tar"),bt=require("wait-on"),G=require("y-protocols/awareness"),ue=require("y-protocols/sync"),Tt=require("yaml"),Ot=require("yjs"),jt=require("lodash/isNil"),C=require("sequelize");require("sqlite3");const x=e=>e&&e.__esModule?e:{default:e};function Q(e){if(e&&e.__esModule)return e;const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const t in e)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(s,t,n.get?n:{enumerable:!0,get:()=>e[t]})}}return s.default=e,Object.freeze(s)}const oe=x(st),xe=x(nt),w=x(rt),Ct=x(Me),It=x(at),Pt=x(it),At=x(lt),_t=Q(ut),vt=x(pt),xt=x(dt),D=x(ft),pe=Q(gt),A=Q(ht),Dt=x(St),kt=x(m),Rt=x(bt),J=Q(Tt),B=Q(Ot),Nt=x(jt);w.default.env.mode;const Lt="image-bin";w.default.env.INIT_TEMPLATE_PATH;const Ut=oe.default.env.DATABASE_URL||kt.default.join(w.default.env.dataDir,"db/pages-kit.db"),De=w.default,Mt=()=>w.default.env.tenantMode==="multiple",Ft=()=>{var e;return(Nt.default(De.env.preferences.multiTenantAllProjectAccessPassports)?[]:(e=De.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:e.split(","))||[]},I=It.default("pages-kit"),qt=C.DataTypes.sqlite.DATE.parse;C.DataTypes.sqlite.DATE.parse=(e,s)=>typeof e=="number"?new Date(e):qt(e,s);const X=new C.Sequelize({dialect:"sqlite",storage:Ut,benchmark:oe.default.env.ENABLE_SEQUELIZE_BENCHMARK==="true",retry:{match:[/SQLITE_BUSY/],name:"query",max:10},logging:oe.default.env.ENABLE_SEQUELIZE_LOGGING==="true"?console.log:!1});X.query("pragma journal_mode = WAL;");X.query("pragma synchronous = normal;");X.query("pragma journal_size_limit = 67108864;");class le extends C.Model{}le.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:X,tableName:"ProjectComponents",timestamps:!1});class q extends C.Model{static async getProjectByIdOrSlug(s){return q.findOne({where:{[C.Op.or]:[{id:s},{slug:s}]}})}}q.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(e){this.setDataValue("relatedBlocklets",JSON.stringify(e||{}))}}},{sequelize:X,paranoid:!0});q.hasMany(le,{foreignKey:"projectId",as:"components"});const $t=async(e,{componentId:s})=>{const t=`@tailwind components;
|
|
2
2
|
@tailwind utilities;
|
|
3
3
|
`,n=`.CustomComponent_${s}`;return(await vt.default([xt.default({content:[{raw:e,extension:"tsx"}]}),At.default({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),a=>{a.walkRules(l=>{l.selectors=l.selectors.map(r=>r.replace(/\.(.+)/g,`${n}.$1,${n} .$1`))})}]).process(t)).css},Bt=async(e,{componentId:s})=>{const t=await $t(e,{componentId:s});return`export const __PagesKit_CSS__ = ${JSON.stringify(t)};
|
|
4
4
|
|
|
@@ -29,7 +29,7 @@ var ${e} = ${t?"async":""} function () {
|
|
|
29
29
|
|
|
30
30
|
return exports;
|
|
31
31
|
};
|
|
32
|
-
`},K=new Te.LRUCache({max:100}),qe=60*60,he=60;function $e(e){I.info("clear preload components cache",{cacheKey:e}),K.delete(e)}function Be(e){for(const s of K.keys())s.includes(e)&&(I.info("clear preload components cache",{cacheKey:s}),$e(s))}function Ve({mode:e,instanceId:s,componentId:t,locale:n}){return["getPreloadComponents",e,s,t,n].join("-")}async function Ht({mode:e,req:s,state:t,locale:n,instances:o,module:a}){const{supportedLocales:l,config:{defaultLocale:r}}=t;if(!r)return null;const i=(await Promise.all(o.map(async h=>{try{const S=Ve({mode:e,instanceId:h.id,componentId:h.componentId,locale:n});if(e!=="draft"&&h.useCache&&K.has(S))return I.info(`get preload component from cache: ${S}`),K.get(S);const P=Y({state:t,componentId:h.componentId});if(!P)return null;const _=await Ge({req:s,state:t,componentId:P.id,locale:n,defaultLocale:r,properties:h.properties});if(!_)return null;const N={instanceId:h.id,preload:_};if(e!=="draft"&&h.useCache){let L=qe;h.cacheDuration&&(L=h.cacheDuration),I.info(`set preload component to cache(${L}s): ${S}`),K.set(S,N,{ttl:L*1e3})}return N}catch(S){return I.error("get preload component error",{instanceId:h.id,componentId:h.componentId},{error:S}),null}}))).filter(h=>!!h),c=Object.values(i.reduce((h,S)=>({...h,...S.preload.components}),{}));async function u(){const h=await Promise.all(c.map(async S=>{const P=ne.componentUMDName({componentId:S.component.id}),_=a===te.PreloadComponentScriptModule.ESM?{module:a,script:await ke(S.script,{componentId:S.component.id,module:a,tailwind:e!=="draft"})}:{module:a,script:await ke(S.script,{componentId:S.component.id,module:a,moduleName:P,tailwind:e!=="draft"}),moduleName:P};return[S.component.id,{component:S.component,script:_}]}));return Object.fromEntries(h)}const p=await u();return{config:{defaultLocale:r,supportedLocales:l},components:p,instances:i.map(h=>({id:h.instanceId,componentId:h.preload.component.id,locales:{[h.preload.locale]:{props:h.preload.props}}}))}}async function Ge({req:e,state:s,componentId:t,locale:n,defaultLocale:o,properties:a}){const{supportedLocales:l}=s,r=Y({state:s,componentId:t});if(!r)return null;const i=l.some(u=>u.locale===n)?n:o;if(!i)return null;const c=await He({req:e,state:s,componentId:t,locale:i,defaultLocale:o,properties:a});return c?{component:r,...c}:null}const Jt=20;async function He({req:e,depth:s=0,state:t,componentId:n,locale:o,defaultLocale:a,properties:l}){if(s>Jt)throw new RangeError("max component depth exceeded");const r=Kt({state:t,componentId:n,properties:l,locale:o});if(!r)return null;const{props:i}=r,c={locale:o||a,components:{[r.component.id]:{component:r.component,script:r.script}},props:{...i}};try{const u=await Yt({...r,req:e});u!=null&&u.props&&Object.assign(c.props,u.props)}catch(u){I.error("preload data at server side error",{componentId:n,name:r.component.name},{error:u})}return await Promise.all(Object.entries(i).map(async([u,p])=>{if((p==null?void 0:p.type)===ne.RenderNestedComponent){const g=await He({req:e,depth:s+1,state:t,componentId:p.componentId,locale:o,defaultLocale:a,properties:p.properties});g&&(Object.assign(c.components,g.components),Object.assign(c.props,{[u]:{type:ne.RenderNestedComponent,componentId:p.componentId,props:g.props}}))}})),c}function Kt({state:e,componentId:s,locale:t,properties:n}){const o=Y({state:e,componentId:s});if(!o)return null;const a=ne.mergeComponent({componentId:s,getComponent:l=>Y({state:e,componentId:l}),locale:t,defaultLocale:e.config.defaultLocale,properties:n});return a?{component:o,script:a.script,props:{locale:t,...a.properties}}:null}function Y({state:e,componentId:s}){var t,n,o;return((t=e.components[s])==null?void 0:t.data)??((o=(n=e.resources.components)==null?void 0:n[s])==null?void 0:o.component)}function zt({state:e,name:s}){var n,o;const t=s.toLowerCase();return((n=Object.values(e.components).find(a=>{var l;return((l=a.data.name)==null?void 0:l.toLowerCase())===t}))==null?void 0:n.data)??((o=e.resources.components&&Object.values(e.resources.components).find(a=>{var l;return((l=a.component.name)==null?void 0:l.toLowerCase())===t}))==null?void 0:o.component)}async function Yt({component:e,script:s,props:t,req:n}){const o=await Fe(s,"getServerSideProps");if(!o)return null;
|
|
32
|
+
`},K=new Te.LRUCache({max:100}),qe=60*60,he=60;function $e(e){I.info("clear preload components cache",{cacheKey:e}),K.delete(e)}function Be(e){for(const s of K.keys())s.includes(e)&&(I.info("clear preload components cache",{cacheKey:s}),$e(s))}function Ve({mode:e,instanceId:s,componentId:t,locale:n}){return["getPreloadComponents",e,s,t,n].join("-")}async function Ht({mode:e,req:s,state:t,locale:n,instances:o,module:a}){const{supportedLocales:l,config:{defaultLocale:r}}=t;if(!r)return null;const i=(await Promise.all(o.map(async h=>{try{const S=Ve({mode:e,instanceId:h.id,componentId:h.componentId,locale:n});if(e!=="draft"&&h.useCache&&K.has(S))return I.info(`get preload component from cache: ${S}`),K.get(S);const P=Y({state:t,componentId:h.componentId});if(!P)return null;const _=await Ge({req:s,state:t,componentId:P.id,locale:n,defaultLocale:r,properties:h.properties});if(!_)return null;const N={instanceId:h.id,preload:_};if(e!=="draft"&&h.useCache){let L=qe;h.cacheDuration&&(L=h.cacheDuration),I.info(`set preload component to cache(${L}s): ${S}`),K.set(S,N,{ttl:L*1e3})}return N}catch(S){return I.error("get preload component error",{instanceId:h.id,componentId:h.componentId},{error:S}),null}}))).filter(h=>!!h),c=Object.values(i.reduce((h,S)=>({...h,...S.preload.components}),{}));async function u(){const h=await Promise.all(c.map(async S=>{const P=ne.componentUMDName({componentId:S.component.id}),_=a===te.PreloadComponentScriptModule.ESM?{module:a,script:await ke(S.script,{componentId:S.component.id,module:a,tailwind:e!=="draft"})}:{module:a,script:await ke(S.script,{componentId:S.component.id,module:a,moduleName:P,tailwind:e!=="draft"}),moduleName:P};return[S.component.id,{component:S.component,script:_}]}));return Object.fromEntries(h)}const p=await u();return{config:{defaultLocale:r,supportedLocales:l},components:p,instances:i.map(h=>({id:h.instanceId,componentId:h.preload.component.id,locales:{[h.preload.locale]:{props:h.preload.props}}}))}}async function Ge({req:e,state:s,componentId:t,locale:n,defaultLocale:o,properties:a}){const{supportedLocales:l}=s,r=Y({state:s,componentId:t});if(!r)return null;const i=l.some(u=>u.locale===n)?n:o;if(!i)return null;const c=await He({req:e,state:s,componentId:t,locale:i,defaultLocale:o,properties:a});return c?{component:r,...c}:null}const Jt=20;async function He({req:e,depth:s=0,state:t,componentId:n,locale:o,defaultLocale:a,properties:l}){if(s>Jt)throw new RangeError("max component depth exceeded");const r=Kt({state:t,componentId:n,properties:l,locale:o});if(!r)return null;const{props:i}=r,c={locale:o||a,components:{[r.component.id]:{component:r.component,script:r.script}},props:{...i}};try{const u=await Yt({...r,req:e});u!=null&&u.props&&Object.assign(c.props,u.props)}catch(u){I.error("preload data at server side error",{componentId:n,name:r.component.name},{error:u})}return await Promise.all(Object.entries(i).map(async([u,p])=>{if((p==null?void 0:p.type)===ne.RenderNestedComponent){const g=await He({req:e,depth:s+1,state:t,componentId:p.componentId,locale:o,defaultLocale:a,properties:p.properties});g&&(Object.assign(c.components,g.components),Object.assign(c.props,{[u]:{type:ne.RenderNestedComponent,componentId:p.componentId,props:g.props}}))}})),c}function Kt({state:e,componentId:s,locale:t,properties:n}){const o=Y({state:e,componentId:s});if(!o)return null;const a=ne.mergeComponent({componentId:s,getComponent:l=>Y({state:e,componentId:l}),locale:t,defaultLocale:e.config.defaultLocale,properties:n});return a?{component:o,script:a.script,props:{locale:t,...a.properties}}:null}function Y({state:e,componentId:s}){var t,n,o;return((t=e.components[s])==null?void 0:t.data)??((o=(n=e.resources.components)==null?void 0:n[s])==null?void 0:o.component)}function zt({state:e,name:s}){var n,o;const t=s.toLowerCase();return((n=Object.values(e.components).find(a=>{var l;return((l=a.data.name)==null?void 0:l.toLowerCase())===t}))==null?void 0:n.data)??((o=e.resources.components&&Object.values(e.resources.components).find(a=>{var l;return((l=a.component.name)==null?void 0:l.toLowerCase())===t}))==null?void 0:o.component)}async function Yt({component:e,script:s,props:t,req:n}){const o=await Fe(s,"getServerSideProps");if(!o)return null;const a=new Promise((r,i)=>{setTimeout(()=>{i(new Error("getServerSideProps timeout in promise race"))},he*1e3)});return await Promise.race([a,$.Sandbox.callFunction({code:`${o}
|
|
33
33
|
|
|
34
34
|
export async function getServerSidePropsWrapper(props) {
|
|
35
35
|
const { location, fetch } = props;
|
|
@@ -48,10 +48,10 @@ export async function getServerSidePropsWrapper(props) {
|
|
|
48
48
|
}
|
|
49
49
|
}`,filename:`${e.name||e.id}.js`,moduleLoader:r=>{if(r==="@blocklet/pages-kit/builtin/utils")return`const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
|
|
50
50
|
export { joinURL, withQuery, getQuery, getComponentMountPoint }
|
|
51
|
-
`;if(r==="@blocklet/pages-kit/builtin/dayjs")return $.BuiltinModules.dayjs},global:{console:{log:(...r)=>{I.info(...r)},warn:(...r)=>{I.warn(...r)},error:(...r)=>{I.error(...r)}},getComponentMountPoint:ot.getComponentMountPoint,joinURL:v.joinURL,withQuery:v.withQuery,getQuery:v.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:v.joinURL(v.withHttps(n.hostname),n.originalUrl)},fetch:(r,{...i}={})=>{const c=typeof r=="string"&&r.startsWith("/")?v.joinURL(w.default.env.appUrl,r):r;if(typeof c=="string"&&v.parseURL(c).host===v.parseURL(w.default.env.appUrl).host){const u=n.get("cookie");if(u){const p=new Me.Headers(i.headers);p.set("cookie",u),i.headers=p}}return
|
|
51
|
+
`;if(r==="@blocklet/pages-kit/builtin/dayjs")return $.BuiltinModules.dayjs},global:{console:{log:(...r)=>{I.info(...r)},warn:(...r)=>{I.warn(...r)},error:(...r)=>{I.error(...r)}},getComponentMountPoint:ot.getComponentMountPoint,joinURL:v.joinURL,withQuery:v.withQuery,getQuery:v.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:v.joinURL(v.withHttps(n.hostname),n.originalUrl)},fetch:(r,{...i}={})=>{const c=typeof r=="string"&&r.startsWith("/")?v.joinURL(w.default.env.appUrl,r):r;if(typeof c=="string"&&v.parseURL(c).host===v.parseURL(w.default.env.appUrl).host){const u=n.get("cookie");if(u){const p=new Me.Headers(i.headers);p.set("cookie",u),i.headers=p}}return Ct.default(c,{...i,timeout:he*1e3}).then(u=>({ok:u.ok,status:u.status,statusText:u.statusText,headers:Object.fromEntries(u.headers.entries()),json:()=>u.json()}))},props:t}]})])}const Je=$.memoize(async(e,s,t)=>{const n=await Fe(e,s);if(n)try{return await $.Sandbox.callFunction({code:`
|
|
52
52
|
${n}
|
|
53
53
|
|
|
54
54
|
export function get${s}SchemaWrapper() {
|
|
55
55
|
return ${s};
|
|
56
56
|
}
|
|
57
|
-
`,filename:`${t}.js`,functionName:`get${s}SchemaWrapper`})}catch(o){return I.error(`获取 ${s} 失败`,{componentId:t,error:o}),null}return null},{keyGenerator:(e,s,t)=>{const n=ie.createHash("md5").update(e).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",n,s,t])},lruOptions:{max:100,ttl:1e3*60*60}}),Wt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",ye="page",Se="trigger-reload-project-resource",Oe=Wt,Qt="z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV",{uploadToMediaKit:Xt}=require("@blocklet/uploader-server"),we=yt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),Ce=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,z=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Re=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Zt=1e4,es=3e4,ee=0,de=1,ts=0,ss=1,Ee=w.default,H=m.join(oe.default.env.BLOCKLET_DATA_DIR,"site-state"),ns=["production","draft"],os=["production"];function Ke(e){return(e==null?void 0:e.replace(/\//g,"|"))||""}function rs(){var t;const e=Ee.env.languages.map(n=>({locale:n.code,name:n.name})),s=(t=e[0])==null?void 0:t.locale;return{pageIds:[],pages:{},components:{},supportedLocales:e,config:{defaultLocale:s},resources:{}}}const F=class F extends B.Doc{constructor(s){super(),this.options=s,this.states={},this.conns=new Map,this.awarenessChangeHandler=({added:t,updated:n,removed:o},a)=>{const l=t.concat(n,o);if(a!==null){const c=this.conns.get(a);c&&(t.forEach(u=>{c.add(u)}),o.forEach(u=>{c.delete(u)}))}const r=A.createEncoder();A.writeVarUint(r,de),A.writeVarUint8Array(r,G.encodeAwarenessUpdate(this.awareness,l));const i=A.toUint8Array(r);this.conns.forEach((c,u)=>this.send(u,i))},this.updateHandler=t=>{const n=A.createEncoder();A.writeVarUint(n,ee),ue.writeUpdate(n,t);const o=A.toUint8Array(n);this.conns.forEach((a,l)=>this.send(l,o))},this.ensureDataStructure=()=>{var l;const{supportedLocales:t,pages:n,pageIds:o,config:a}=this.syncedStore;{const r=new Set(Object.keys(n));let i=0;for(;i<o.length;){const c=o[i];r.has(c)?(r.delete(c),i++):o.splice(i,1)}}t.splice(0,t.length),t.push(...Ee.env.languages.map(r=>({locale:r.code,name:r.name}))),a.defaultLocale=(l=t[0])==null?void 0:l.locale;{let r=0;const i=new Set;for(;r<t.length;){const{locale:c}=t[r];i.has(c)?t.splice(r,1):(r++,i.add(c))}}},this.send=(t,n)=>{t.readyState!==ts&&t.readyState!==ss&&this.closeConn(t);try{t.send(n,o=>{o&&this.closeConn(t)})}catch{this.closeConn(t)}},this.closeConn=t=>{if(t.removeAllListeners(),this.conns.has(t)){const n=this.conns.get(t);this.conns.delete(t),n&&G.removeAwarenessStates(this.awareness,Array.from(n),null)}t.close()},this.autoSave=R.debounce(()=>{E.mkdirSync(m.dirname(this.draftYjsFilePath),{recursive:!0}),E.writeFileSync(this.draftYjsFilePath,B.encodeStateAsUpdate(this))},Zt),this.save=({flush:t=!1}={})=>{this.autoSave(),t&&this.autoSave.flush()},this.publish=async({mode:t,pages:n})=>{const o=await this.getState("draft"),a=await this.getState("production");await be(o,a,{pages:n,pageMergeMode:"replace",deletePages:!0,publishMode:t}),a.config.publishedAt=new Date().getTime();for(const l of n||Object.keys(this.syncedStore.pages))this.syncedStore.pages[l]&&(this.syncedStore.pages[l].publishedAt=new Date().toISOString());await this.setState(t,a)},this.mergeState=async(t,n)=>{var r,i,c;const o=JSON.parse(JSON.stringify(n));(r=t.config).fontFamily??(r.fontFamily={});const a=(i=o.config)==null?void 0:i.fontFamily,l=(c=t.config)==null?void 0:c.fontFamily;t.config.fontFamily.title=(a==null?void 0:a.title)||(l==null?void 0:l.title),t.config.fontFamily.description=(a==null?void 0:a.description)||(l==null?void 0:l.description),await new Promise((u,p)=>{this.transact(async()=>{try{const g=await be(t,n);u(g)}catch(g){p(g)}})})},this.addConnection=t=>{if(this.conns.has(t))return;t.binaryType="arraybuffer",this.conns.set(t,new Set),t.on("message",a=>this.messageListener(t,new Uint8Array(a)));let n=!0;const o=setInterval(()=>{if(!n)this.conns.has(t)&&this.closeConn(t),clearInterval(o);else if(this.conns.has(t)){n=!1;try{t.ping()}catch{this.closeConn(t),clearInterval(o)}}},es);t.on("close",()=>{this.closeConn(t),clearInterval(o)}),t.on("pong",()=>{n=!0});{const a=A.createEncoder();A.writeVarUint(a,ee),ue.writeSyncStep1(a,this),this.send(t,A.toUint8Array(a));const l=this.awareness.getStates();if(l.size>0){const r=A.createEncoder();A.writeVarUint(r,de),A.writeVarUint8Array(r,G.encodeAwarenessUpdate(this.awareness,Array.from(l.keys()))),this.send(t,A.toUint8Array(r))}}},this.messageListener=(t,n)=>{try{const o=A.createEncoder(),a=pe.createDecoder(n),l=pe.readVarUint(a);switch(l){case ee:A.writeVarUint(o,ee),ue.readSyncMessage(a,o,this,null),A.length(o)>1&&(this.ensureDataStructure(),this.send(t,A.toUint8Array(o)));break;case de:{G.applyAwarenessUpdate(this.awareness,pe.readVarUint8Array(a),t);break}default:I.warn(`Unsupported messageType ${l}`)}}catch(o){I.error(o)}this.save()},E.existsSync(this.draftYjsFilePath)&&B.applyUpdate(this,E.readFileSync(this.draftYjsFilePath)),this.syncedStore=mt.reactive(Z.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(s){if(!s)throw new Error("Should provide project context");try{const t=m.join(H,s),n=m.join(H,`@del-${s}`);E.renameSync(t,n)}catch(t){I.error("Failed to safe delete project state dir:",t)}}static get projectIds(){return ge.globSync("*/",{cwd:H,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(s=>F.shared(s))}static shared(s){if(!s)throw new Error("Should provide project context");let t=this.sharedInstances.get(s);return t||(t=new F({path:m.join(H,s)}),this.sharedInstances.set(s,t),t)}destroy(){this.conns.forEach((s,t)=>this.closeConn(t)),this.awareness.destroy(),super.destroy()}initObserver(){const s=n=>{n.observeDeep(o=>{o.some(a=>a.changes.keys.has("updatedAt")||a.changes.keys.has("publishedAt"))||n.set("updatedAt",new Date().toISOString())})};this.syncedStore.pages&&Object.keys(this.syncedStore.pages).forEach(n=>{const o=Z.getYjsValue(this.syncedStore.pages[n]);o&&o instanceof B.Map&&s(o)});const t=Z.getYjsValue(this.syncedStore.pages);t&&t instanceof B.Map&&t.observe(n=>{n.changes.keys.forEach((o,a)=>{if(o.action==="add"){const l=Z.getYjsValue(this.syncedStore.pages[a]);l&&l instanceof B.Map&&s(l)}})})}get draftYjsFilePath(){return m.join(this.options.path,"draft.yjs")}async getState(s){var t,n,o,a;if(s==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[s]&&(this.states[s]=await je(this.getPublishDir(s),{includeResources:!0})??rs(),!((n=(t=this.states[s])==null?void 0:t.config)!=null&&n.defaultLocale))){(o=this.states[s]).config??(o.config={});const l=Ee.env.languages.map(r=>({locale:r.code,name:r.name}));this.states[s].config.defaultLocale=(a=l[0])==null?void 0:a.locale}return{...this.states[s],resources:await _e().then(async l=>{var u,p,g,h;const{pages:r,components:i}=R.pick(l,"pages","components");let c=i;if((p=(u=this.states[s])==null?void 0:u.resources)!=null&&p.components)c={...(h=(g=this.states[s])==null?void 0:g.resources)==null?void 0:h.components};else{const S=m.basename(this.options.path),P=await q.findByPk(S);if(P!=null&&P.useAllResources)c=i;else{const N=(await le.findAll({where:{projectId:S}})).map(y=>y.componentId);c=Object.fromEntries(Object.entries(i||{}).filter(([y])=>N.includes(y)))}}return{pages:r,components:c}}).catch(()=>({}))}}async setState(s,t){const n=await We(t,{exportAssets:!1,includeResources:!0}),o=this.getPublishDir(s);E.mkdirSync(m.dirname(o),{recursive:!0}),E.rmSync(o,{force:!0,recursive:!0}),E.renameSync(n,o),this.states[s]=t}getPublishDir(s){return m.join(this.options.path,s)}static async pageUrlMap(s){const{projectIds:t}=this,n={};for(const o of t){const a=await q.findByPk(o);if(!a)continue;const l=await F.shared(o).getState(s),r=R.union(w.default.env.languages.map(i=>i.code),l.supportedLocales.map(i=>i.locale));for(const i of l.pageIds){const c=l.pages[i];if(!c||s==="production"&&!c.isPublic)continue;const u=c.slug,p=a.slug||o,g={projectId:o,projectSlug:p,pageSlug:u,pageId:i,defaultLocale:r==null?void 0:r[0],locales:r,publishedAt:l.config.publishedAt,isPublic:c.isPublic,isTemplate:c.isTemplate};p&&(n[v.joinURL("/",p,u)]={...g,shouldRedirect:!0,mainPage:!0}),n[v.joinURL("/",o,u)]={...g,shouldRedirect:!0,mainPage:!0};for(const h of r){const S={...g,locale:h};n[v.joinURL("/",h,o,u)]=S,p&&(n[v.joinURL("/",h,p,u)]=S)}}}return n}};F.INSTANCE_TTL=30*60*1e3,F.sharedInstances=new Te.LRUCache({max:100,ttl:F.INSTANCE_TTL,dispose:s=>{s.destroy()}});let W=F;function ze(){return E.mkdtempSync(m.join(w.default.env.dataDir,"tmp-"))}function re(e,s,t=[]){return Array.isArray(e)?e.flatMap((n,o)=>re(n,s,[...t,o])):typeof e=="object"?e===null?[]:Object.entries(e).flatMap(([n,o])=>re(o,s,[...t,n])):s(e)?[t]:[]}function M(e){return e.filter(s=>s!=null)}async function as(e,s,t){if(!e||!E.existsSync(e)||!E.lstatSync(e).isFile())return null;let n=t[e];return n||(n=(async()=>(await Xt({filePath:e,fileName:s})).data.filename)(),t[e]=n),n}const is=async(e,s)=>{const t=m.basename(e),n=await ce.call({name:Oe,path:v.joinURL("/uploads",t),responseType:"stream",method:"GET"});if(n.status>=200&&n.status<400){const o=E.createWriteStream(s);await wt.pipeline(n.data,o)}else throw new Error(`download asset failed ${n.status}`)},cs=async(e,s)=>{await Promise.all(e.map(async t=>{try{await is(t,m.join(s,m.basename(t)))}catch(n){I.error(`Failed to export assets: ${t}, ${n}`)}}))};function Ye(e){return Ce.test(e)?[e]:z.test(e)?(Re.lastIndex=0,Array.from(e.matchAll(Re)).map(t=>t[1]).filter(t=>!!t)):[]}async function fe(e,s,t){const{getFilename:n,exportAssets:o}=t,a=m.join(s,n(e));if(E.mkdirSync(m.dirname(a),{recursive:!0}),E.writeFileSync(a,J.stringify(e)),o){const r=re(e,i=>typeof i=="string"&&(Ce.test(i)||z.test(i))).map(i=>{const c=R.get(e,i);return Ye(c)}).flat().filter(Boolean);await cs(r,m.dirname(a))}}const Ne=new Te.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function Le(e,s,t){var r;const n=re(e,i=>typeof i=="string"&&(Ce.test(i)||z.test(i))),o=Dt.default(2),a=n.map(i=>o(async()=>{try{const c=R.get(e,i),u=Ye(c);for(const p of u){const g=m.basename(p),h=t.getFilePath(p,i),S=h?`${h}:${g}`:g,P=Ne.get(S);if(P){z.test(c)||R.set(e,i,P);return}const _=await as(h,g,s);_&&(z.test(c)||R.set(e,i,_),Ne.set(S,_))}}catch(c){I.error(`Failed to process upload for path ${i.join(".")}:`,c.message||c.reason)}})),l=await Promise.allSettled(a);(r=t.onFinish)==null||r.call(t,l)}async function We(e,{exportAssets:s,pageIds:t="all",componentIds:n="all",rawConfig:o,includeResources:a=!1}={}){var N,L,y,O,T,C;const l=t==="all"?e.pageIds:t,r=ls({state:e,pageIds:l,componentIds:n==="all"?Object.keys(e.components):n}),i=(f,d)=>{var b;return{id:f.id,name:f.name,isTemplateSection:f.isTemplateSection??!1,component:f.component,config:f.config,visibility:f.visibility,properties:((b=f.locales)==null?void 0:b[d])??{}}},c=(f,d)=>{var b;return{id:f.id,createdAt:f.createdAt,updatedAt:f.updatedAt,publishedAt:f.publishedAt,isPublic:f.isPublic??!0,isTemplate:f.isTemplate??!1,meta:((b=f.locales)==null?void 0:b[d])??{},sections:M(f.sectionIds.map(k=>{const U=f.sections[k];return U&&i(U,d)}))}},u=M(e.supportedLocales.map(f=>f.locale).flatMap(f=>l.map(d=>{const b=e.pages[d];return b&&{locale:f,slug:b.slug,page:c(b,f)}}))),p=ze(),g=m.join(p,"pages");E.mkdirSync(g,{recursive:!0});const h=m.join(p,"components");E.mkdirSync(h,{recursive:!0});for(const{locale:f,slug:d,page:b}of u)await fe(b,g,{getFilename:()=>`${Ke(d)||"index"}.${f}.yml`,exportAssets:s});for(const f of r){const d=(N=e.components[f])==null?void 0:N.data;d&&await fe(d,h,{getFilename:b=>`${b.name||"unnamed"}.${b.id}.yml`,exportAssets:s})}const S=m.join(p,".blocklet/pages/pages.config.yml");E.mkdirSync(m.dirname(S),{recursive:!0});const P={pages:M(l.map(f=>{const d=e.pages[f];return d&&{id:f,slug:d.slug}})),components:M(r.map(f=>{var b;const d=(b=e.components[f])==null?void 0:b.data;return d&&{id:f,name:d.name}})),...a?{resources:{components:M(Object.keys(((L=e.resources)==null?void 0:L.components)||{}).map(f=>{var d,b,k,U;return{id:f,name:(U=(k=(b=(d=e.resources)==null?void 0:d.components)==null?void 0:b[f])==null?void 0:k.component)==null?void 0:U.name}}))}}:{},supportedLocales:e.supportedLocales,config:e.config};E.writeFileSync(S,J.stringify(P));const _=m.join(p,"config.source.json");if(o&&E.writeFileSync(_,JSON.stringify(o)),a){const f=m.join(p,"resources"),d=m.join(f,"components");E.mkdirSync(d,{recursive:!0});for(const b of Object.keys(((y=e==null?void 0:e.resources)==null?void 0:y.components)??{})){const k=(C=(T=(O=e.resources)==null?void 0:O.components)==null?void 0:T[b])==null?void 0:C.component;k&&await fe(k,d,{getFilename:U=>`${U.name||"unnamed"}.${U.id}.yml`,exportAssets:s})}}return p}async function je(e,{importAssets:s,includeResources:t}={}){var a,l,r;if(!E.existsSync(e))return null;let n,o=!1;try{E.lstatSync(e).isDirectory()?n=e:/\.(tgz|gz|tar)$/.test(e)&&(o=!0,n=ze(),await Et.x({file:e,C:n}));const i=ge.globSync("**/.blocklet/pages/pages.config.yml",{cwd:n,absolute:!0}).at(0),c=i&&m.join(m.dirname(i),"../../pages"),u=i&&m.join(m.dirname(i),"../../components"),p=i&&m.join(m.dirname(i),"../../chunks");if(!i)return null;const g=J.parse(E.readFileSync(i).toString()),h=(y,O,T)=>{let C=m.join(y,`${O}${T?`.${T}`:""}.yml`);return(!E.existsSync(C)||!E.lstatSync(C).isFile())&&(C=m.join(y,O,`index${T?`.${T}`:""}.yml`),!E.existsSync(C)||!E.lstatSync(C))?null:J.parse(E.readFileSync(C).toString())},S=(y,O)=>{try{const T=ge.globSync(`*.${O}.yml`,{cwd:y,absolute:!0})[0];return T?J.parse(E.readFileSync(T).toString()):null}catch(T){I.error("parse component error",T)}return null},P=M(g.pages.map(({slug:y})=>{var f;const O=M(g.supportedLocales.map(({locale:d})=>{const b=c?h(c,Ke(y),d):void 0;if(b)return{locale:d,page:b};const k=c?h(c,y,d):void 0;return k&&{locale:d,page:k}})),T=(f=O[0])==null?void 0:f.page;if(!T)return null;const C=T.sections.map(d=>{const b=d.id||we();return{id:b,component:d.component,config:d.config,name:d.name,isTemplateSection:d.isTemplateSection??!1,visibility:d.visibility,locales:Object.fromEntries(M(O.map(({locale:k,page:U})=>{const ve=U.sections.find(tt=>tt.id===b);return ve&&[k,ve.properties]})))}});return{id:T.id||we(),createdAt:T.createdAt,updatedAt:T.updatedAt,publishedAt:T.publishedAt,isPublic:T.isPublic??!0,isTemplate:T.isTemplate??!1,slug:y,sections:Object.fromEntries(C.map(d=>[d.id,d])),sectionIds:C.map(d=>d.id),locales:Object.fromEntries(O.map(({locale:d,page:b})=>[d,b.meta]))}})),_=u?M(((a=g.components)==null?void 0:a.map(({id:y})=>S(u,y)))??[]):[];if(s){const y=(...O)=>{I.info(`[${o?m.basename(e):m.basename(m.join(e,"../../../../"))}] importAssets:`,...O)};try{y("wait image-bin api ready"),await Rt.default({resources:[`${ce.getComponentWebEndpoint(Lt)}/api/sdk/uploads`],validateStatus:C=>C>=200&&C<=500}),y("image-bin api is ready");const O={},T={};y("start to upload assets"),await Promise.allSettled([Le(_,O,{getFilePath:C=>u&&m.join(u,C),onFinish:C=>{y(`upload ${C.length} component assets`)}}),Le(P,T,{getFilePath:(C,f)=>{const d=R.get(P,f.slice(0,1));return c&&m.join(c,m.dirname(d.slug),C)},onFinish:C=>{y(`upload ${C.length} page assets`)}})]),y("upload assets done"),xe.default.gc&&xe.default.gc()}catch(O){y("Error during asset import:",O)}}const N={};if(t){const y=i&&m.join(m.dirname(i),"../../resources/components"),O=M(((r=(l=g.resources)==null?void 0:l.components)==null?void 0:r.map(({id:T})=>S(y,T)))??[]);O.length>0&&(N.components=Object.fromEntries(O.map((T,C)=>[T.id,{index:C,component:T}])))}const L={};if(p&&E.existsSync(p)){const y=E.readdirSync(p);for(const O of y)L[O]=m.join(p,O)}return{supportedLocales:g.supportedLocales,pageIds:P.map(y=>y.id),components:Object.fromEntries(_.map((y,O)=>[y.id,{index:O,data:y}])),pages:Object.fromEntries(P.map(y=>[y.id,y])),config:g.config||{},resources:N,chunks:L}}finally{o&&n&&E.rmSync(n,{force:!0,recursive:!0})}}async function be(e,s,{pages:t,pageMergeMode:n="byUpdateTime",deletePages:o=!1,publishMode:a=void 0}={}){try{a&&Be(a)}catch(u){I.error("clear preload page cache error",{error:u})}const{pageIds:l,pages:r,supportedLocales:i}=e;for(const u of t??l){const p=r[u];if(!p){const g=s.pageIds.indexOf(u);g!==-1&&o&&(s.pageIds.splice(g,1),delete s.pages[u]);continue}if(s.pageIds.includes(p.id)){if(n==="replace")s.pages[p.id]=p;else if(n==="byUpdateTime"){const g=s.pages[p.id];(!g||p.updatedAt&&p.updatedAt>g.updatedAt)&&(s.pages[p.id]=p)}}else s.pageIds.push(p.id),s.pages[p.id]=p}if(o&&!t)for(const u of s.pageIds)e.pageIds.includes(u)||delete s.pages[u],s.pageIds=[...s.pageIds].filter(p=>e.pageIds.includes(p));if(s.supportedLocales.splice(0,s.supportedLocales.length),s.supportedLocales.push(...R.cloneDeep(i)),o)for(const u of Object.keys(s.components))delete s.components[u];let c=JSON.parse(JSON.stringify(e.components));c=Object.fromEntries(await Promise.all(Object.entries(c).map(async([u,p])=>{const g=await Qe(p==null?void 0:p.data);return[u,{...p,data:g}]}))),Object.assign(s.components,c),Object.assign(s.config,JSON.parse(JSON.stringify(e.config))),s.resources.components=JSON.parse(JSON.stringify(e.resources.components||{}))}const Qe=$.memoize(async e=>{var s;if(!R.isEmpty(e==null?void 0:e.properties))return e;if(((s=e==null?void 0:e.renderer)==null?void 0:s.type)==="react-component"){const{script:t}=(e==null?void 0:e.renderer)||{};if(t)try{const n=await Je(t,"PROPERTIES_SCHEMA",e.id);n&&n.length>0&&e&&(e.properties={},n.forEach((o,a)=>{e!=null&&e.properties&&(e.properties[o.id]={index:a,data:o})}))}catch(n){I.error("checkPropertiesFromCode error",{componentId:e.id,name:e.name},{error:n})}}return e},{keyGenerator:e=>{var l;const s=(e==null?void 0:e.id)||"",t=(e==null?void 0:e.name)||"",n=((l=e==null?void 0:e.renderer)==null?void 0:l.type)||"",o=(e==null?void 0:e.properties)||{},a=ie.createHash("md5").update(JSON.stringify(o)).digest("hex");return JSON.stringify(["checkPropertiesFromCode",s,t,n,a])},lruOptions:{max:100,ttl:1e3*60*60}});function ls({state:e,pageIds:s=[],componentIds:t=[]}){var l;const n=(r,i=new Set)=>(Array.isArray(r)&&r.forEach(c=>n(c,i)),r&&typeof r=="object"&&(typeof r.componentId=="string"&&i.add(r.componentId),Object.values(r).forEach(c=>n(c,i))),i),o=new Set(t);for(const r of s){const i=e.pages[r];n(i,o)}const a=[...o];for(;a.length;){const r=a.shift();o.has(r)||o.add(r);const i=(l=e.components[r])==null?void 0:l.data;if(i)for(const c of n(i))o.has(c)||a.push(c)}return[...o]}let ae,V,Ie,Pe,Ae;function Xe(){return ae=(async()=>{const e=ce.getResources({types:[{did:Oe,type:ye},{did:Qt,type:ye}]});V=(await Promise.all(e.map(async t=>{const n=t.path?await je(t.path,{importAssets:!1}):void 0;return n?{blockletId:t.did,state:n,blockletTitle:t.title}:void 0}))).filter(t=>!!t),Ie=V.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.pages).map(o=>o?[o==null?void 0:o.id,{page:o,blockletId:n.blockletId}]:[]))),{});const s=V.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.components).map(o=>[o.data.id,{blockletId:n.blockletId,component:o.data}]))),{});Pe=Object.fromEntries(await Promise.all(Object.entries(s).map(async([t,n])=>{const o=await Qe(n.component);return[t,{...n,component:o}]}))),Ae=V.reduce((t,n)=>Object.assign(t,n.state.chunks),{})})(),ae}function Ze(e){const s=R.debounce(async()=>{await Xe().catch(t=>{I.error("load resource states error",{error:t})}),await(e==null?void 0:e({states:V,pages:Ie,components:Pe,chunks:Ae}))},3e3,{leading:!1,trailing:!0});return s(),w.default.events.on(w.default.Events.componentAdded,s),w.default.events.on(w.default.Events.componentRemoved,s),w.default.events.on(w.default.Events.componentStarted,s),w.default.events.on(w.default.Events.componentStopped,s),w.default.events.on(w.default.Events.componentUpdated,s),w.default.events.on(Se,s),()=>{w.default.events.off(w.default.Events.componentAdded,s),w.default.events.off(w.default.Events.componentRemoved,s),w.default.events.off(w.default.Events.componentStarted,s),w.default.events.off(w.default.Events.componentStopped,s),w.default.events.off(w.default.Events.componentUpdated,s),w.default.events.off(Se,s)}}const et=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),se=globalThis;var Ue;(Ue=se[et])==null||Ue.call(se);se[et]=Ze(async({pages:e,components:s})=>{const{projectIds:t}=W;await Promise.all(t.map(async n=>{const o=W.shared(n);o.syncedStore.resources.pages=e;const a=await q.findByPk(n);if(a!=null&&a.useAllResources)o.syncedStore.resources.components=s;else{const r=(await le.findAll({where:{projectId:n}})).map(c=>c.componentId),i=Object.fromEntries(Object.entries(s||{}).filter(([c])=>r.includes(c)));o.syncedStore.resources.components=i}I.info(`update [${n}] resource states:`,{pages:Object.keys(o.syncedStore.resources.pages||{}).length,components:Object.keys(o.syncedStore.resources.components||{}).length})}))});async function us(){I.info("trigger reload all project resource"),w.default.events.emit(Se)}async function _e({ensureLoaded:e=!0}={}){return e&&(ae??(ae=Xe()),await ae),{states:V,pages:Ie,components:Pe,chunks:Ae}}exports.COMPONENT_DID=Oe;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=qe;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=he;exports.PUBLISH_MODES=os;exports.Project=q;exports.RESOURCE_TYPE=ye;exports.SITE_STATE_PATH=H;exports.STATE_MODES=ns;exports.SiteState=W;exports.clearPreloadComponentsCache=$e;exports.clearPreloadComponentsCacheByMode=Be;exports.fromPackage=je;exports.getComponentFromState=Y;exports.getComponentFromStateByName=zt;exports.getExportSchemaValueFromCode=Je;exports.getMultiTenantAllProjectAccessPassports=Ft;exports.getPreloadComponent=Ge;exports.getPreloadComponents=Ht;exports.getPreloadComponentsCacheKey=Ve;exports.getResourceStates=_e;exports.initPackResourceStates=Ze;exports.isMultiTenant=Mt;exports.logger=I;exports.mergeState=be;exports.nextId=we;exports.toPackage=We;exports.triggerReloadAllProjectResource=us;
|
|
57
|
+
`,filename:`${t}.js`,functionName:`get${s}SchemaWrapper`})}catch(o){return I.error(`获取 ${s} 失败`,{componentId:t,error:o}),null}return null},{keyGenerator:(e,s,t)=>{const n=ie.createHash("md5").update(e).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",n,s,t])},lruOptions:{max:100,ttl:1e3*60*60}}),Wt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",ye="page",Se="trigger-reload-project-resource",Oe=Wt,Qt="z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV",{uploadToMediaKit:Xt}=require("@blocklet/uploader-server"),we=yt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),je=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,z=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Re=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Zt=1e4,es=3e4,ee=0,de=1,ts=0,ss=1,Ee=w.default,H=m.join(oe.default.env.BLOCKLET_DATA_DIR,"site-state"),ns=["production","draft"],os=["production"];function Ke(e){return(e==null?void 0:e.replace(/\//g,"|"))||""}function rs(){var t;const e=Ee.env.languages.map(n=>({locale:n.code,name:n.name})),s=(t=e[0])==null?void 0:t.locale;return{pageIds:[],pages:{},components:{},supportedLocales:e,config:{defaultLocale:s},resources:{}}}const F=class F extends B.Doc{constructor(s){super(),this.options=s,this.states={},this.conns=new Map,this.awarenessChangeHandler=({added:t,updated:n,removed:o},a)=>{const l=t.concat(n,o);if(a!==null){const c=this.conns.get(a);c&&(t.forEach(u=>{c.add(u)}),o.forEach(u=>{c.delete(u)}))}const r=A.createEncoder();A.writeVarUint(r,de),A.writeVarUint8Array(r,G.encodeAwarenessUpdate(this.awareness,l));const i=A.toUint8Array(r);this.conns.forEach((c,u)=>this.send(u,i))},this.updateHandler=t=>{const n=A.createEncoder();A.writeVarUint(n,ee),ue.writeUpdate(n,t);const o=A.toUint8Array(n);this.conns.forEach((a,l)=>this.send(l,o))},this.ensureDataStructure=()=>{var l;const{supportedLocales:t,pages:n,pageIds:o,config:a}=this.syncedStore;{const r=new Set(Object.keys(n));let i=0;for(;i<o.length;){const c=o[i];r.has(c)?(r.delete(c),i++):o.splice(i,1)}}t.splice(0,t.length),t.push(...Ee.env.languages.map(r=>({locale:r.code,name:r.name}))),a.defaultLocale=(l=t[0])==null?void 0:l.locale;{let r=0;const i=new Set;for(;r<t.length;){const{locale:c}=t[r];i.has(c)?t.splice(r,1):(r++,i.add(c))}}},this.send=(t,n)=>{t.readyState!==ts&&t.readyState!==ss&&this.closeConn(t);try{t.send(n,o=>{o&&this.closeConn(t)})}catch{this.closeConn(t)}},this.closeConn=t=>{if(t.removeAllListeners(),this.conns.has(t)){const n=this.conns.get(t);this.conns.delete(t),n&&G.removeAwarenessStates(this.awareness,Array.from(n),null)}t.close()},this.autoSave=R.debounce(()=>{E.mkdirSync(m.dirname(this.draftYjsFilePath),{recursive:!0}),E.writeFileSync(this.draftYjsFilePath,B.encodeStateAsUpdate(this))},Zt),this.save=({flush:t=!1}={})=>{this.autoSave(),t&&this.autoSave.flush()},this.publish=async({mode:t,pages:n})=>{const o=await this.getState("draft"),a=await this.getState("production");await be(o,a,{pages:n,pageMergeMode:"replace",deletePages:!0,publishMode:t}),a.config.publishedAt=new Date().getTime();for(const l of n||Object.keys(this.syncedStore.pages))this.syncedStore.pages[l]&&(this.syncedStore.pages[l].publishedAt=new Date().toISOString());await this.setState(t,a)},this.mergeState=async(t,n)=>{var r,i,c;const o=JSON.parse(JSON.stringify(n));(r=t.config).fontFamily??(r.fontFamily={});const a=(i=o.config)==null?void 0:i.fontFamily,l=(c=t.config)==null?void 0:c.fontFamily;t.config.fontFamily.title=(a==null?void 0:a.title)||(l==null?void 0:l.title),t.config.fontFamily.description=(a==null?void 0:a.description)||(l==null?void 0:l.description),await new Promise((u,p)=>{this.transact(async()=>{try{const g=await be(t,n);u(g)}catch(g){p(g)}})})},this.addConnection=t=>{if(this.conns.has(t))return;t.binaryType="arraybuffer",this.conns.set(t,new Set),t.on("message",a=>this.messageListener(t,new Uint8Array(a)));let n=!0;const o=setInterval(()=>{if(!n)this.conns.has(t)&&this.closeConn(t),clearInterval(o);else if(this.conns.has(t)){n=!1;try{t.ping()}catch{this.closeConn(t),clearInterval(o)}}},es);t.on("close",()=>{this.closeConn(t),clearInterval(o)}),t.on("pong",()=>{n=!0});{const a=A.createEncoder();A.writeVarUint(a,ee),ue.writeSyncStep1(a,this),this.send(t,A.toUint8Array(a));const l=this.awareness.getStates();if(l.size>0){const r=A.createEncoder();A.writeVarUint(r,de),A.writeVarUint8Array(r,G.encodeAwarenessUpdate(this.awareness,Array.from(l.keys()))),this.send(t,A.toUint8Array(r))}}},this.messageListener=(t,n)=>{try{const o=A.createEncoder(),a=pe.createDecoder(n),l=pe.readVarUint(a);switch(l){case ee:A.writeVarUint(o,ee),ue.readSyncMessage(a,o,this,null),A.length(o)>1&&(this.ensureDataStructure(),this.send(t,A.toUint8Array(o)));break;case de:{G.applyAwarenessUpdate(this.awareness,pe.readVarUint8Array(a),t);break}default:I.warn(`Unsupported messageType ${l}`)}}catch(o){I.error(o)}this.save()},E.existsSync(this.draftYjsFilePath)&&B.applyUpdate(this,E.readFileSync(this.draftYjsFilePath)),this.syncedStore=mt.reactive(Z.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(s){if(!s)throw new Error("Should provide project context");try{const t=m.join(H,s),n=m.join(H,`@del-${s}`);E.renameSync(t,n)}catch(t){I.error("Failed to safe delete project state dir:",t)}}static get projectIds(){return ge.globSync("*/",{cwd:H,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(s=>F.shared(s))}static shared(s){if(!s)throw new Error("Should provide project context");let t=this.sharedInstances.get(s);return t||(t=new F({path:m.join(H,s)}),this.sharedInstances.set(s,t),t)}destroy(){this.conns.forEach((s,t)=>this.closeConn(t)),this.awareness.destroy(),super.destroy()}initObserver(){const s=n=>{n.observeDeep(o=>{o.some(a=>a.changes.keys.has("updatedAt")||a.changes.keys.has("publishedAt"))||n.set("updatedAt",new Date().toISOString())})};this.syncedStore.pages&&Object.keys(this.syncedStore.pages).forEach(n=>{const o=Z.getYjsValue(this.syncedStore.pages[n]);o&&o instanceof B.Map&&s(o)});const t=Z.getYjsValue(this.syncedStore.pages);t&&t instanceof B.Map&&t.observe(n=>{n.changes.keys.forEach((o,a)=>{if(o.action==="add"){const l=Z.getYjsValue(this.syncedStore.pages[a]);l&&l instanceof B.Map&&s(l)}})})}get draftYjsFilePath(){return m.join(this.options.path,"draft.yjs")}async getState(s){var t,n,o,a;if(s==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[s]&&(this.states[s]=await Ce(this.getPublishDir(s),{includeResources:!0})??rs(),!((n=(t=this.states[s])==null?void 0:t.config)!=null&&n.defaultLocale))){(o=this.states[s]).config??(o.config={});const l=Ee.env.languages.map(r=>({locale:r.code,name:r.name}));this.states[s].config.defaultLocale=(a=l[0])==null?void 0:a.locale}return{...this.states[s],resources:await _e().then(async l=>{var u,p,g,h;const{pages:r,components:i}=R.pick(l,"pages","components");let c=i;if((p=(u=this.states[s])==null?void 0:u.resources)!=null&&p.components)c={...(h=(g=this.states[s])==null?void 0:g.resources)==null?void 0:h.components};else{const S=m.basename(this.options.path),P=await q.findByPk(S);if(P!=null&&P.useAllResources)c=i;else{const N=(await le.findAll({where:{projectId:S}})).map(y=>y.componentId);c=Object.fromEntries(Object.entries(i||{}).filter(([y])=>N.includes(y)))}}return{pages:r,components:c}}).catch(()=>({}))}}async setState(s,t){const n=await We(t,{exportAssets:!1,includeResources:!0}),o=this.getPublishDir(s);E.mkdirSync(m.dirname(o),{recursive:!0}),E.rmSync(o,{force:!0,recursive:!0}),E.renameSync(n,o),this.states[s]=t}getPublishDir(s){return m.join(this.options.path,s)}static async pageUrlMap(s){const{projectIds:t}=this,n={};for(const o of t){const a=await q.findByPk(o);if(!a)continue;const l=await F.shared(o).getState(s),r=R.union(w.default.env.languages.map(i=>i.code),l.supportedLocales.map(i=>i.locale));for(const i of l.pageIds){const c=l.pages[i];if(!c||s==="production"&&!c.isPublic)continue;const u=c.slug,p=a.slug||o,g={projectId:o,projectSlug:p,pageSlug:u,pageId:i,defaultLocale:r==null?void 0:r[0],locales:r,publishedAt:l.config.publishedAt,isPublic:c.isPublic,isTemplate:c.isTemplate};p&&(n[v.joinURL("/",p,u)]={...g,shouldRedirect:!0,mainPage:!0}),n[v.joinURL("/",o,u)]={...g,shouldRedirect:!0,mainPage:!0};for(const h of r){const S={...g,locale:h};n[v.joinURL("/",h,o,u)]=S,p&&(n[v.joinURL("/",h,p,u)]=S)}}}return n}};F.INSTANCE_TTL=30*60*1e3,F.sharedInstances=new Te.LRUCache({max:100,ttl:F.INSTANCE_TTL,dispose:s=>{s.destroy()}});let W=F;function ze(){return E.mkdtempSync(m.join(w.default.env.dataDir,"tmp-"))}function re(e,s,t=[]){return Array.isArray(e)?e.flatMap((n,o)=>re(n,s,[...t,o])):typeof e=="object"?e===null?[]:Object.entries(e).flatMap(([n,o])=>re(o,s,[...t,n])):s(e)?[t]:[]}function M(e){return e.filter(s=>s!=null)}async function as(e,s,t){if(!e||!E.existsSync(e)||!E.lstatSync(e).isFile())return null;let n=t[e];return n||(n=(async()=>(await Xt({filePath:e,fileName:s})).data.filename)(),t[e]=n),n}const is=async(e,s)=>{const t=m.basename(e),n=await ce.call({name:Oe,path:v.joinURL("/uploads",t),responseType:"stream",method:"GET"});if(n.status>=200&&n.status<400){const o=E.createWriteStream(s);await wt.pipeline(n.data,o)}else throw new Error(`download asset failed ${n.status}`)},cs=async(e,s)=>{await Promise.all(e.map(async t=>{try{await is(t,m.join(s,m.basename(t)))}catch(n){I.error(`Failed to export assets: ${t}, ${n}`)}}))};function Ye(e){return je.test(e)?[e]:z.test(e)?(Re.lastIndex=0,Array.from(e.matchAll(Re)).map(t=>t[1]).filter(t=>!!t)):[]}async function fe(e,s,t){const{getFilename:n,exportAssets:o}=t,a=m.join(s,n(e));if(E.mkdirSync(m.dirname(a),{recursive:!0}),E.writeFileSync(a,J.stringify(e)),o){const r=re(e,i=>typeof i=="string"&&(je.test(i)||z.test(i))).map(i=>{const c=R.get(e,i);return Ye(c)}).flat().filter(Boolean);await cs(r,m.dirname(a))}}const Ne=new Te.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function Le(e,s,t){var r;const n=re(e,i=>typeof i=="string"&&(je.test(i)||z.test(i))),o=Dt.default(2),a=n.map(i=>o(async()=>{try{const c=R.get(e,i),u=Ye(c);for(const p of u){const g=m.basename(p),h=t.getFilePath(p,i),S=h?`${h}:${g}`:g,P=Ne.get(S);if(P){z.test(c)||R.set(e,i,P);return}const _=await as(h,g,s);_&&(z.test(c)||R.set(e,i,_),Ne.set(S,_))}}catch(c){I.error(`Failed to process upload for path ${i.join(".")}:`,c.message||c.reason)}})),l=await Promise.allSettled(a);(r=t.onFinish)==null||r.call(t,l)}async function We(e,{exportAssets:s,pageIds:t="all",componentIds:n="all",rawConfig:o,includeResources:a=!1}={}){var N,L,y,O,T,j;const l=t==="all"?e.pageIds:t,r=ls({state:e,pageIds:l,componentIds:n==="all"?Object.keys(e.components):n}),i=(f,d)=>{var b;return{id:f.id,name:f.name,isTemplateSection:f.isTemplateSection??!1,component:f.component,config:f.config,visibility:f.visibility,properties:((b=f.locales)==null?void 0:b[d])??{}}},c=(f,d)=>{var b;return{id:f.id,createdAt:f.createdAt,updatedAt:f.updatedAt,publishedAt:f.publishedAt,isPublic:f.isPublic??!0,isTemplate:f.isTemplate??!1,meta:((b=f.locales)==null?void 0:b[d])??{},sections:M(f.sectionIds.map(k=>{const U=f.sections[k];return U&&i(U,d)}))}},u=M(e.supportedLocales.map(f=>f.locale).flatMap(f=>l.map(d=>{const b=e.pages[d];return b&&{locale:f,slug:b.slug,page:c(b,f)}}))),p=ze(),g=m.join(p,"pages");E.mkdirSync(g,{recursive:!0});const h=m.join(p,"components");E.mkdirSync(h,{recursive:!0});for(const{locale:f,slug:d,page:b}of u)await fe(b,g,{getFilename:()=>`${Ke(d)||"index"}.${f}.yml`,exportAssets:s});for(const f of r){const d=(N=e.components[f])==null?void 0:N.data;d&&await fe(d,h,{getFilename:b=>`${b.name||"unnamed"}.${b.id}.yml`,exportAssets:s})}const S=m.join(p,".blocklet/pages/pages.config.yml");E.mkdirSync(m.dirname(S),{recursive:!0});const P={pages:M(l.map(f=>{const d=e.pages[f];return d&&{id:f,slug:d.slug}})),components:M(r.map(f=>{var b;const d=(b=e.components[f])==null?void 0:b.data;return d&&{id:f,name:d.name}})),...a?{resources:{components:M(Object.keys(((L=e.resources)==null?void 0:L.components)||{}).map(f=>{var d,b,k,U;return{id:f,name:(U=(k=(b=(d=e.resources)==null?void 0:d.components)==null?void 0:b[f])==null?void 0:k.component)==null?void 0:U.name}}))}}:{},supportedLocales:e.supportedLocales,config:e.config};E.writeFileSync(S,J.stringify(P));const _=m.join(p,"config.source.json");if(o&&E.writeFileSync(_,JSON.stringify(o)),a){const f=m.join(p,"resources"),d=m.join(f,"components");E.mkdirSync(d,{recursive:!0});for(const b of Object.keys(((y=e==null?void 0:e.resources)==null?void 0:y.components)??{})){const k=(j=(T=(O=e.resources)==null?void 0:O.components)==null?void 0:T[b])==null?void 0:j.component;k&&await fe(k,d,{getFilename:U=>`${U.name||"unnamed"}.${U.id}.yml`,exportAssets:s})}}return p}async function Ce(e,{importAssets:s,includeResources:t}={}){var a,l,r;if(!E.existsSync(e))return null;let n,o=!1;try{E.lstatSync(e).isDirectory()?n=e:/\.(tgz|gz|tar)$/.test(e)&&(o=!0,n=ze(),await Et.x({file:e,C:n}));const i=ge.globSync("**/.blocklet/pages/pages.config.yml",{cwd:n,absolute:!0}).at(0),c=i&&m.join(m.dirname(i),"../../pages"),u=i&&m.join(m.dirname(i),"../../components"),p=i&&m.join(m.dirname(i),"../../chunks");if(!i)return null;const g=J.parse(E.readFileSync(i).toString()),h=(y,O,T)=>{let j=m.join(y,`${O}${T?`.${T}`:""}.yml`);return(!E.existsSync(j)||!E.lstatSync(j).isFile())&&(j=m.join(y,O,`index${T?`.${T}`:""}.yml`),!E.existsSync(j)||!E.lstatSync(j))?null:J.parse(E.readFileSync(j).toString())},S=(y,O)=>{try{const T=ge.globSync(`*.${O}.yml`,{cwd:y,absolute:!0})[0];return T?J.parse(E.readFileSync(T).toString()):null}catch(T){I.error("parse component error",T)}return null},P=M(g.pages.map(({slug:y})=>{var f;const O=M(g.supportedLocales.map(({locale:d})=>{const b=c?h(c,Ke(y),d):void 0;if(b)return{locale:d,page:b};const k=c?h(c,y,d):void 0;return k&&{locale:d,page:k}})),T=(f=O[0])==null?void 0:f.page;if(!T)return null;const j=T.sections.map(d=>{const b=d.id||we();return{id:b,component:d.component,config:d.config,name:d.name,isTemplateSection:d.isTemplateSection??!1,visibility:d.visibility,locales:Object.fromEntries(M(O.map(({locale:k,page:U})=>{const ve=U.sections.find(tt=>tt.id===b);return ve&&[k,ve.properties]})))}});return{id:T.id||we(),createdAt:T.createdAt,updatedAt:T.updatedAt,publishedAt:T.publishedAt,isPublic:T.isPublic??!0,isTemplate:T.isTemplate??!1,slug:y,sections:Object.fromEntries(j.map(d=>[d.id,d])),sectionIds:j.map(d=>d.id),locales:Object.fromEntries(O.map(({locale:d,page:b})=>[d,b.meta]))}})),_=u?M(((a=g.components)==null?void 0:a.map(({id:y})=>S(u,y)))??[]):[];if(s){const y=(...O)=>{I.info(`[${o?m.basename(e):m.basename(m.join(e,"../../../../"))}] importAssets:`,...O)};try{y("wait image-bin api ready"),await Rt.default({resources:[`${ce.getComponentWebEndpoint(Lt)}/api/sdk/uploads`],validateStatus:j=>j>=200&&j<=500}),y("image-bin api is ready");const O={},T={};y("start to upload assets"),await Promise.allSettled([Le(_,O,{getFilePath:j=>u&&m.join(u,j),onFinish:j=>{y(`upload ${j.length} component assets`)}}),Le(P,T,{getFilePath:(j,f)=>{const d=R.get(P,f.slice(0,1));return c&&m.join(c,m.dirname(d.slug),j)},onFinish:j=>{y(`upload ${j.length} page assets`)}})]),y("upload assets done"),xe.default.gc&&xe.default.gc()}catch(O){y("Error during asset import:",O)}}const N={};if(t){const y=i&&m.join(m.dirname(i),"../../resources/components"),O=M(((r=(l=g.resources)==null?void 0:l.components)==null?void 0:r.map(({id:T})=>S(y,T)))??[]);O.length>0&&(N.components=Object.fromEntries(O.map((T,j)=>[T.id,{index:j,component:T}])))}const L={};if(p&&E.existsSync(p)){const y=E.readdirSync(p);for(const O of y)L[O]=m.join(p,O)}return{supportedLocales:g.supportedLocales,pageIds:P.map(y=>y.id),components:Object.fromEntries(_.map((y,O)=>[y.id,{index:O,data:y}])),pages:Object.fromEntries(P.map(y=>[y.id,y])),config:g.config||{},resources:N,chunks:L}}finally{o&&n&&E.rmSync(n,{force:!0,recursive:!0})}}async function be(e,s,{pages:t,pageMergeMode:n="byUpdateTime",deletePages:o=!1,publishMode:a=void 0}={}){try{a&&Be(a)}catch(u){I.error("clear preload page cache error",{error:u})}const{pageIds:l,pages:r,supportedLocales:i}=e;for(const u of t??l){const p=r[u];if(!p){const g=s.pageIds.indexOf(u);g!==-1&&o&&(s.pageIds.splice(g,1),delete s.pages[u]);continue}if(s.pageIds.includes(p.id)){if(n==="replace")s.pages[p.id]=p;else if(n==="byUpdateTime"){const g=s.pages[p.id];(!g||p.updatedAt&&p.updatedAt>g.updatedAt)&&(s.pages[p.id]=p)}}else s.pageIds.push(p.id),s.pages[p.id]=p}if(o&&!t)for(const u of s.pageIds)e.pageIds.includes(u)||delete s.pages[u],s.pageIds=[...s.pageIds].filter(p=>e.pageIds.includes(p));if(s.supportedLocales.splice(0,s.supportedLocales.length),s.supportedLocales.push(...R.cloneDeep(i)),o)for(const u of Object.keys(s.components))delete s.components[u];let c=JSON.parse(JSON.stringify(e.components));c=Object.fromEntries(await Promise.all(Object.entries(c).map(async([u,p])=>{const g=await Qe(p==null?void 0:p.data);return[u,{...p,data:g}]}))),Object.assign(s.components,c),Object.assign(s.config,JSON.parse(JSON.stringify(e.config))),s.resources.components=JSON.parse(JSON.stringify(e.resources.components||{}))}const Qe=$.memoize(async e=>{var s;if(!R.isEmpty(e==null?void 0:e.properties))return e;if(((s=e==null?void 0:e.renderer)==null?void 0:s.type)==="react-component"){const{script:t}=(e==null?void 0:e.renderer)||{};if(t)try{const n=await Je(t,"PROPERTIES_SCHEMA",e.id);n&&n.length>0&&e&&(e.properties={},n.forEach((o,a)=>{e!=null&&e.properties&&(e.properties[o.id]={index:a,data:o})}))}catch(n){I.error("checkPropertiesFromCode error",{componentId:e.id,name:e.name},{error:n})}}return e},{keyGenerator:e=>{var l;const s=(e==null?void 0:e.id)||"",t=(e==null?void 0:e.name)||"",n=((l=e==null?void 0:e.renderer)==null?void 0:l.type)||"",o=(e==null?void 0:e.properties)||{},a=ie.createHash("md5").update(JSON.stringify(o)).digest("hex");return JSON.stringify(["checkPropertiesFromCode",s,t,n,a])},lruOptions:{max:100,ttl:1e3*60*60}});function ls({state:e,pageIds:s=[],componentIds:t=[]}){var l;const n=(r,i=new Set)=>(Array.isArray(r)&&r.forEach(c=>n(c,i)),r&&typeof r=="object"&&(typeof r.componentId=="string"&&i.add(r.componentId),Object.values(r).forEach(c=>n(c,i))),i),o=new Set(t);for(const r of s){const i=e.pages[r];n(i,o)}const a=[...o];for(;a.length;){const r=a.shift();o.has(r)||o.add(r);const i=(l=e.components[r])==null?void 0:l.data;if(i)for(const c of n(i))o.has(c)||a.push(c)}return[...o]}let ae,V,Ie,Pe,Ae;function Xe(){return ae=(async()=>{const e=ce.getResources({types:[{did:Oe,type:ye},{did:Qt,type:ye}]});V=(await Promise.all(e.map(async t=>{const n=t.path?await Ce(t.path,{importAssets:!1}):void 0;return n?{blockletId:t.did,state:n,blockletTitle:t.title}:void 0}))).filter(t=>!!t),Ie=V.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.pages).map(o=>o?[o==null?void 0:o.id,{page:o,blockletId:n.blockletId}]:[]))),{});const s=V.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.components).map(o=>[o.data.id,{blockletId:n.blockletId,component:o.data}]))),{});Pe=Object.fromEntries(await Promise.all(Object.entries(s).map(async([t,n])=>{const o=await Qe(n.component);return[t,{...n,component:o}]}))),Ae=V.reduce((t,n)=>Object.assign(t,n.state.chunks),{})})(),ae}function Ze(e){const s=R.debounce(async()=>{await Xe().catch(t=>{I.error("load resource states error",{error:t})}),await(e==null?void 0:e({states:V,pages:Ie,components:Pe,chunks:Ae}))},3e3,{leading:!1,trailing:!0});return s(),w.default.events.on(w.default.Events.componentAdded,s),w.default.events.on(w.default.Events.componentRemoved,s),w.default.events.on(w.default.Events.componentStarted,s),w.default.events.on(w.default.Events.componentStopped,s),w.default.events.on(w.default.Events.componentUpdated,s),w.default.events.on(Se,s),()=>{w.default.events.off(w.default.Events.componentAdded,s),w.default.events.off(w.default.Events.componentRemoved,s),w.default.events.off(w.default.Events.componentStarted,s),w.default.events.off(w.default.Events.componentStopped,s),w.default.events.off(w.default.Events.componentUpdated,s),w.default.events.off(Se,s)}}const et=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),se=globalThis;var Ue;(Ue=se[et])==null||Ue.call(se);se[et]=Ze(async({pages:e,components:s})=>{const{projectIds:t}=W;await Promise.all(t.map(async n=>{const o=W.shared(n);o.syncedStore.resources.pages=e;const a=await q.findByPk(n);if(a!=null&&a.useAllResources)o.syncedStore.resources.components=s;else{const r=(await le.findAll({where:{projectId:n}})).map(c=>c.componentId),i=Object.fromEntries(Object.entries(s||{}).filter(([c])=>r.includes(c)));o.syncedStore.resources.components=i}I.info(`update [${n}] resource states:`,{pages:Object.keys(o.syncedStore.resources.pages||{}).length,components:Object.keys(o.syncedStore.resources.components||{}).length})}))});async function us(){I.info("trigger reload all project resource"),w.default.events.emit(Se)}async function _e({ensureLoaded:e=!0}={}){return e&&(ae??(ae=Xe()),await ae),{states:V,pages:Ie,components:Pe,chunks:Ae}}exports.COMPONENT_DID=Oe;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=qe;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=he;exports.PUBLISH_MODES=os;exports.Project=q;exports.RESOURCE_TYPE=ye;exports.SITE_STATE_PATH=H;exports.STATE_MODES=ns;exports.SiteState=W;exports.clearPreloadComponentsCache=$e;exports.clearPreloadComponentsCacheByMode=Be;exports.fromPackage=Ce;exports.getComponentFromState=Y;exports.getComponentFromStateByName=zt;exports.getExportSchemaValueFromCode=Je;exports.getMultiTenantAllProjectAccessPassports=Ft;exports.getPreloadComponent=Ge;exports.getPreloadComponents=Ht;exports.getPreloadComponentsCacheKey=Ve;exports.getResourceStates=_e;exports.initPackResourceStates=Ze;exports.isMultiTenant=Mt;exports.logger=I;exports.mergeState=be;exports.nextId=we;exports.toPackage=We;exports.triggerReloadAllProjectResource=us;
|
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-DNRKik3e.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,10 +1,15 @@
|
|
|
1
|
-
"use strict";const
|
|
2
|
-
${
|
|
3
|
-
${
|
|
4
|
-
${
|
|
1
|
+
"use strict";const N=require("vite-plugin-node-polyfills/shims/process"),_=require("./_chunks/site-state-DNRKik3e.js"),P=require("@blocklet/crawler/middlewares"),G=require("@blocklet/pages-kit/types"),J=require("@blocklet/pages-kit/utils/preload"),W=require("@blocklet/sdk/lib/component"),R=require("@blocklet/sdk/lib/config"),K=require("express"),M=require("fs"),Q=require("mustache"),x=require("path"),S=require("ufo"),T=o=>o&&o.__esModule?o:{default:o},U=T(N),p=T(R),z=T(Q),V=["/assets/"],q=()=>[!0,"true"].includes(p.default.env.preferences.allowCrawler);function D(){q()?P.initCronCrawlBlocklet({time:"30 30 */12 * * *",options:{}}):P.cancelCronCrawlBlocklet()}D();p.default.events.on(p.default.Events.envUpdate,D);function X({app:o,viteDevServer:g,state:c}){let w;if(g){const n=M.readFileSync(x.resolve(U.default.cwd(),"./index.html"),"utf-8");o.use(async(C,v,k)=>{const b=C.originalUrl;w=await g.transformIndexHtml(b,n),k()})}else w=M.readFileSync(x.resolve(U.default.env.BLOCKLET_APP_DIR,"dist/index.html"),"utf-8");const y=K.Router();y.use(P.initSEOMiddleware({autoReturnHtml:!1,allowCrawler:q})),y.get("/:path(*)?",async(n,C,v)=>{var $,L,j;if(V.some(r=>n.path.startsWith(r))){v();return}const k=performance.now(),b=()=>Math.round(performance.now()-k),O="production";let e,u,s=w;if(n.path.startsWith("/pages")){const r=n.params.lang,i=n.cookies.nf_lang,d=new Set([...p.default.env.languages.map(f=>f.code)]);let m=(r&&d.has(r)?r:void 0)||(d.has(i)?i:void 0)||[...d][0];if((!m||!(($=c.supportedLocales)!=null&&$.find(f=>f.locale===m)))&&(m=((j=(L=c.supportedLocales)==null?void 0:L[0])==null?void 0:j.locale)||""),m){const f=[];Object.values(c.pages).forEach(l=>{const E=Object.values((l==null?void 0:l.sections)??{}).filter(a=>{var h;return a.component==="custom-component"&&((h=a.config)==null?void 0:h.componentId)}).map(a=>{var h,I;return{id:a.id,componentId:a.config.componentId,useCache:a.config.useCache,cacheDuration:a.config.cacheDuration,properties:(I=(h=a.locales)==null?void 0:h[m])==null?void 0:I.properties}});f.push(...E)});const H=new Promise((l,E)=>{setTimeout(()=>{E(new Error("getPreloadComponents timeout in promise race, skip it"))},90*1e3)});try{await Promise.race([H,_.getPreloadComponents({mode:O,req:n,state:c,locale:m,instances:f,module:G.PreloadComponentScriptModule.UMD_FN}).then(l=>{l&&(u=J.injectPreloadComponents(l))})])}catch(l){_.logger.warn("getPreloadComponents timeout in promise race, skip inject html elements"),_.logger.warn(l)}}}try{const r=(e==null?void 0:e.title)||p.default.env.appName,i=(e==null?void 0:e.description)||p.default.env.appDescription,d=S.withQuery(S.joinURL(p.default.env.appUrl,"/.well-known/service/blocklet/og.png"),{title:r,description:i});s=z.default.render(w,{ogTitle:r,ogDescription:i,ogImage:Y(e==null?void 0:e.image)||d,pagesPublishedAt:(c==null?void 0:c.config.publishedAt)||new Date().getTime()})}catch{}const t=c==null?void 0:c.config.fontFamily,B=n.query.mode==="draft"||n.url.includes("preview");s=s.replace('<script id="injected-head-elements"><\/script>',`
|
|
2
|
+
${e!=null&&e.backgroundColor?`<meta name="theme-color" content="${e.backgroundColor}" /><style>html,body,#app {background-color: ${e.backgroundColor} !important;}</style>`:""}
|
|
3
|
+
${t!=null&&t.title?`<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${t.title}&display=swap">`:""}
|
|
4
|
+
${t!=null&&t.description&&(t==null?void 0:t.description)!==(t==null?void 0:t.title)?`<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${t.description}&display=swap">`:""}
|
|
5
|
+
|
|
6
|
+
<script type="application/json" id="__PAGE_STATE__">
|
|
7
|
+
${JSON.stringify(c).replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026")}
|
|
8
|
+
<\/script>
|
|
9
|
+
|
|
5
10
|
<script>
|
|
6
11
|
|
|
7
|
-
window.__PAGE_STATE__ =
|
|
12
|
+
window.__PAGE_STATE__ = JSON.parse(document.getElementById('__PAGE_STATE__').textContent)
|
|
8
13
|
|
|
9
14
|
document.querySelectorAll('link[rel="preload"][as="style"]').forEach(function (link) {
|
|
10
15
|
const l = document.createElement('link');
|
|
@@ -14,10 +19,10 @@
|
|
|
14
19
|
});
|
|
15
20
|
<\/script>
|
|
16
21
|
|
|
17
|
-
${
|
|
22
|
+
${B?`<script src="https://cdn.tailwindcss.com"><\/script>
|
|
18
23
|
<script>
|
|
19
24
|
window.tailwind.config = {
|
|
20
25
|
darkMode: "class",
|
|
21
26
|
};
|
|
22
27
|
<\/script>`:""}
|
|
23
|
-
`);const
|
|
28
|
+
`);const A=R.getBlockletJs();if(A&&(s=s.replace('<script src="__blocklet__.js"><\/script>',`<script>${A}<\/script>`)),u!=null&&u.html&&(s=s.replace('<script id="injected-html-elements"><\/script>',u.html)),n.cachedHtml){const r=/<body>([\s\S]*?)<\/body>/,i=r.exec(n.cachedHtml),d=i?i[1]:"";s=s.replace(r,`<body>${d}</body>`)}C.send(s),_.logger.info(`[html] render: ${n.path}, ${b()}ms`),s=null,e=null,u=null}),o.use(y)}function Y(o){const g=W.getComponentMountPoint("image-bin");return g&&o&&!/^(https?:\/\/|\/)/.test(o)?p.default.env.appUrl+S.joinURL(g,"uploads",o):o}module.exports=X;
|
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-DNRKik3e.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"}});require("vite-plugin-node-polyfills/shims/process");require("vite-plugin-node-polyfills/shims/global");const e=require("./_chunks/site-state-
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});require("vite-plugin-node-polyfills/shims/process");require("vite-plugin-node-polyfills/shims/global");const e=require("./_chunks/site-state-DNRKik3e.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;
|
|
@@ -2,12 +2,12 @@ import ee from "vite-plugin-node-polyfills/shims/process";
|
|
|
2
2
|
import Oe from "vite-plugin-node-polyfills/shims/global";
|
|
3
3
|
import { getComponentMountPoint as ot } from "@blocklet/pages-kit/builtin/utils";
|
|
4
4
|
import { PreloadComponentScriptModule as Q } from "@blocklet/pages-kit/types";
|
|
5
|
-
import { componentUMDName as nt, RenderNestedComponent as
|
|
5
|
+
import { componentUMDName as nt, RenderNestedComponent as ve, mergeComponent as rt } from "@blocklet/pages-kit/utils/property";
|
|
6
6
|
import { memoize as ae, Sandbox as $e, BuiltinModules as at } from "@blocklet/quickjs";
|
|
7
7
|
import w from "@blocklet/sdk/lib/config";
|
|
8
8
|
import { LRUCache as he } from "lru-cache";
|
|
9
9
|
import it, { Headers as ct } from "node-fetch";
|
|
10
|
-
import { joinURL as U,
|
|
10
|
+
import { joinURL as U, getQuery as lt, withQuery as pt, parseURL as Ae, withHttps as ut } from "ufo";
|
|
11
11
|
import { createHash as ie } from "crypto";
|
|
12
12
|
import dt from "@blocklet/logger";
|
|
13
13
|
import mt from "vite-plugin-node-polyfills/shims/buffer";
|
|
@@ -16,16 +16,16 @@ import { createBuiltinModuleTransformer as gt, isRelativeModule as Te } from "@b
|
|
|
16
16
|
import { call as Be, getResources as ht, getComponentWebEndpoint as yt } from "@blocklet/sdk/lib/component";
|
|
17
17
|
import wt from "autoprefixer";
|
|
18
18
|
import * as St from "esbuild";
|
|
19
|
-
import { readFileSync as J, existsSync as B, lstatSync as X, readdirSync as Et, rmSync as Ve, mkdtempSync as bt, mkdirSync as M, writeFileSync as te, renameSync as
|
|
19
|
+
import { readFileSync as J, existsSync as B, lstatSync as X, readdirSync as Et, rmSync as Ve, mkdtempSync as bt, mkdirSync as M, writeFileSync as te, renameSync as Pe, createWriteStream as It } from "fs";
|
|
20
20
|
import Ot from "postcss";
|
|
21
|
-
import
|
|
21
|
+
import vt from "tailwindcss";
|
|
22
22
|
import x from "typescript";
|
|
23
|
-
import { reactive as
|
|
23
|
+
import { reactive as At } from "@reactivedata/reactive";
|
|
24
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
|
-
import * as
|
|
28
|
-
import { get as ye, isEmpty as
|
|
27
|
+
import * as P from "lib0/encoding";
|
|
28
|
+
import { get as ye, isEmpty as Pt, set as Ce, debounce as Ge, pick as Ct, union as xt, cloneDeep as jt } from "lodash";
|
|
29
29
|
import { customAlphabet as kt } from "nanoid";
|
|
30
30
|
import Nt from "p-limit";
|
|
31
31
|
import Dt, { join as O, dirname as L, basename as G } from "path";
|
|
@@ -45,7 +45,7 @@ w.env.INIT_TEMPLATE_PATH;
|
|
|
45
45
|
const Wt = ee.env.DATABASE_URL || Dt.join(w.env.dataDir, "db/pages-kit.db"), je = w, no = () => w.env.tenantMode === "multiple", ro = () => {
|
|
46
46
|
var t;
|
|
47
47
|
return (Gt(je.env.preferences.multiTenantAllProjectAccessPassports) ? [] : (t = je.env.preferences.multiTenantAllProjectAccessPassports) == null ? void 0 : t.split(",")) || [];
|
|
48
|
-
},
|
|
48
|
+
}, v = dt("pages-kit"), zt = T.sqlite.DATE.parse;
|
|
49
49
|
T.sqlite.DATE.parse = (t, s) => typeof t == "number" ? new Date(t) : zt(t, s);
|
|
50
50
|
const z = new Jt({
|
|
51
51
|
dialect: "sqlite",
|
|
@@ -143,7 +143,7 @@ const Yt = async (t, { componentId: s }) => {
|
|
|
143
143
|
@tailwind utilities;
|
|
144
144
|
`, o = `.CustomComponent_${s}`;
|
|
145
145
|
return (await Ot([
|
|
146
|
-
|
|
146
|
+
vt({ content: [{ raw: t, extension: "tsx" }] }),
|
|
147
147
|
wt({
|
|
148
148
|
overrideBrowserslist: ["> 1%", "last 2 versions"],
|
|
149
149
|
stats: {}
|
|
@@ -294,11 +294,11 @@ var ${t} = ${e ? "async" : ""} function () {
|
|
|
294
294
|
max: 100
|
|
295
295
|
}), Zt = 60 * 60, Ne = 60;
|
|
296
296
|
function es(t) {
|
|
297
|
-
|
|
297
|
+
v.info("clear preload components cache", { cacheKey: t }), K.delete(t);
|
|
298
298
|
}
|
|
299
299
|
function ts(t) {
|
|
300
300
|
for (const s of K.keys())
|
|
301
|
-
s.includes(t) && (
|
|
301
|
+
s.includes(t) && (v.info("clear preload components cache", { cacheKey: s }), es(s));
|
|
302
302
|
}
|
|
303
303
|
function ss({
|
|
304
304
|
mode: t,
|
|
@@ -331,28 +331,28 @@ async function ao({
|
|
|
331
331
|
locale: o
|
|
332
332
|
});
|
|
333
333
|
if (t !== "draft" && g.useCache && K.has(y))
|
|
334
|
-
return
|
|
335
|
-
const
|
|
336
|
-
if (!
|
|
337
|
-
const
|
|
334
|
+
return v.info(`get preload component from cache: ${y}`), K.get(y);
|
|
335
|
+
const A = se({ state: e, componentId: g.componentId });
|
|
336
|
+
if (!A) return null;
|
|
337
|
+
const C = await os({
|
|
338
338
|
req: s,
|
|
339
339
|
state: e,
|
|
340
|
-
componentId:
|
|
340
|
+
componentId: A.id,
|
|
341
341
|
locale: o,
|
|
342
342
|
defaultLocale: r,
|
|
343
343
|
properties: g.properties
|
|
344
344
|
});
|
|
345
|
-
if (!
|
|
346
|
-
const k = { instanceId: g.id, preload:
|
|
345
|
+
if (!C) return null;
|
|
346
|
+
const k = { instanceId: g.id, preload: C };
|
|
347
347
|
if (t !== "draft" && g.useCache) {
|
|
348
348
|
let N = Zt;
|
|
349
|
-
g.cacheDuration && (N = g.cacheDuration),
|
|
349
|
+
g.cacheDuration && (N = g.cacheDuration), v.info(`set preload component to cache(${N}s): ${y}`), K.set(y, k, {
|
|
350
350
|
ttl: N * 1e3
|
|
351
351
|
});
|
|
352
352
|
}
|
|
353
353
|
return k;
|
|
354
354
|
} catch (y) {
|
|
355
|
-
return
|
|
355
|
+
return v.error("get preload component error", { instanceId: g.id, componentId: g.componentId }, { error: y }), null;
|
|
356
356
|
}
|
|
357
357
|
})
|
|
358
358
|
)).filter((g) => !!g), c = Object.values(
|
|
@@ -361,7 +361,7 @@ async function ao({
|
|
|
361
361
|
async function p() {
|
|
362
362
|
const g = await Promise.all(
|
|
363
363
|
c.map(async (y) => {
|
|
364
|
-
const
|
|
364
|
+
const A = nt({ componentId: y.component.id }), C = a === Q.ESM ? {
|
|
365
365
|
module: a,
|
|
366
366
|
script: await ke(y.script, {
|
|
367
367
|
componentId: y.component.id,
|
|
@@ -373,12 +373,12 @@ async function ao({
|
|
|
373
373
|
script: await ke(y.script, {
|
|
374
374
|
componentId: y.component.id,
|
|
375
375
|
module: a,
|
|
376
|
-
moduleName:
|
|
376
|
+
moduleName: A,
|
|
377
377
|
tailwind: t !== "draft"
|
|
378
378
|
}),
|
|
379
|
-
moduleName:
|
|
379
|
+
moduleName: A
|
|
380
380
|
};
|
|
381
|
-
return [y.component.id, { component: y.component, script:
|
|
381
|
+
return [y.component.id, { component: y.component, script: C }];
|
|
382
382
|
})
|
|
383
383
|
);
|
|
384
384
|
return Object.fromEntries(g);
|
|
@@ -434,11 +434,11 @@ async function Ke({
|
|
|
434
434
|
const p = await as({ ...r, req: t });
|
|
435
435
|
p != null && p.props && Object.assign(c.props, p.props);
|
|
436
436
|
} catch (p) {
|
|
437
|
-
|
|
437
|
+
v.error("preload data at server side error", { componentId: o, name: r.component.name }, { error: p });
|
|
438
438
|
}
|
|
439
439
|
return await Promise.all(
|
|
440
440
|
Object.entries(i).map(async ([p, u]) => {
|
|
441
|
-
if ((u == null ? void 0 : u.type) ===
|
|
441
|
+
if ((u == null ? void 0 : u.type) === ve) {
|
|
442
442
|
const f = await Ke({
|
|
443
443
|
req: t,
|
|
444
444
|
depth: s + 1,
|
|
@@ -450,7 +450,7 @@ async function Ke({
|
|
|
450
450
|
});
|
|
451
451
|
f && (Object.assign(c.components, f.components), Object.assign(c.props, {
|
|
452
452
|
[p]: {
|
|
453
|
-
type:
|
|
453
|
+
type: ve,
|
|
454
454
|
componentId: u.componentId,
|
|
455
455
|
props: f.props
|
|
456
456
|
}
|
|
@@ -499,17 +499,15 @@ async function as({
|
|
|
499
499
|
}) {
|
|
500
500
|
const n = await He(s, "getServerSideProps");
|
|
501
501
|
if (!n) return null;
|
|
502
|
-
|
|
503
|
-
const l = new Promise((r, i) => {
|
|
502
|
+
const a = new Promise((r, i) => {
|
|
504
503
|
setTimeout(() => {
|
|
505
|
-
i(new Error("getServerSideProps timeout in promise race"))
|
|
504
|
+
i(new Error("getServerSideProps timeout in promise race"));
|
|
506
505
|
}, Ne * 1e3);
|
|
507
506
|
});
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
code: `${n}
|
|
507
|
+
return await Promise.race([
|
|
508
|
+
a,
|
|
509
|
+
$e.callFunction({
|
|
510
|
+
code: `${n}
|
|
513
511
|
|
|
514
512
|
export async function getServerSidePropsWrapper(props) {
|
|
515
513
|
const { location, fetch } = props;
|
|
@@ -527,68 +525,65 @@ export async function getServerSidePropsWrapper(props) {
|
|
|
527
525
|
if (originalFetch) globalThis.fetch = originalFetch;
|
|
528
526
|
}
|
|
529
527
|
}`,
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
528
|
+
filename: `${t.name || t.id}.js`,
|
|
529
|
+
moduleLoader: (r) => {
|
|
530
|
+
if (r === "@blocklet/pages-kit/builtin/utils")
|
|
531
|
+
return `const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
|
|
534
532
|
export { joinURL, withQuery, getQuery, getComponentMountPoint }
|
|
535
533
|
`;
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
},
|
|
549
|
-
error: (...r) => {
|
|
550
|
-
A.error(...r);
|
|
551
|
-
}
|
|
534
|
+
if (r === "@blocklet/pages-kit/builtin/dayjs")
|
|
535
|
+
return at.dayjs;
|
|
536
|
+
},
|
|
537
|
+
global: {
|
|
538
|
+
console: {
|
|
539
|
+
// NOTE: do not return logger.xxx result, it will cause memory leak
|
|
540
|
+
// eslint-disable-next-line prettier/prettier
|
|
541
|
+
log: (...r) => {
|
|
542
|
+
v.info(...r);
|
|
543
|
+
},
|
|
544
|
+
warn: (...r) => {
|
|
545
|
+
v.warn(...r);
|
|
552
546
|
},
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
getQuery: pt
|
|
547
|
+
error: (...r) => {
|
|
548
|
+
v.error(...r);
|
|
549
|
+
}
|
|
557
550
|
},
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
551
|
+
getComponentMountPoint: ot,
|
|
552
|
+
joinURL: U,
|
|
553
|
+
withQuery: pt,
|
|
554
|
+
getQuery: lt
|
|
555
|
+
},
|
|
556
|
+
functionName: "getServerSidePropsWrapper",
|
|
557
|
+
args: [
|
|
558
|
+
{
|
|
559
|
+
// NOTE: IMPORTANT! place location and fetch (has side effect) at the args not global
|
|
560
|
+
// because the global is shared between all runtime and just init once
|
|
561
|
+
location: { href: U(ut(o.hostname), o.originalUrl) },
|
|
562
|
+
fetch: (r, { ...i } = {}) => {
|
|
563
|
+
const c = typeof r == "string" && r.startsWith("/") ? U(w.env.appUrl, r) : r;
|
|
564
|
+
if (typeof c == "string" && Ae(c).host === Ae(w.env.appUrl).host) {
|
|
565
|
+
const p = o.get("cookie");
|
|
566
|
+
if (p) {
|
|
567
|
+
const u = new ct(i.headers);
|
|
568
|
+
u.set("cookie", p), i.headers = u;
|
|
572
569
|
}
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
a = null;
|
|
591
|
-
}
|
|
570
|
+
}
|
|
571
|
+
return it(c, {
|
|
572
|
+
...i,
|
|
573
|
+
timeout: Ne * 1e3
|
|
574
|
+
}).then((p) => ({
|
|
575
|
+
ok: p.ok,
|
|
576
|
+
status: p.status,
|
|
577
|
+
statusText: p.statusText,
|
|
578
|
+
headers: Object.fromEntries(p.headers.entries()),
|
|
579
|
+
json: () => p.json()
|
|
580
|
+
}));
|
|
581
|
+
},
|
|
582
|
+
props: e
|
|
583
|
+
}
|
|
584
|
+
]
|
|
585
|
+
})
|
|
586
|
+
]);
|
|
592
587
|
}
|
|
593
588
|
const is = ae(
|
|
594
589
|
async (t, s, e) => {
|
|
@@ -607,7 +602,7 @@ const is = ae(
|
|
|
607
602
|
functionName: `get${s}SchemaWrapper`
|
|
608
603
|
});
|
|
609
604
|
} catch (n) {
|
|
610
|
-
return
|
|
605
|
+
return v.error(`获取 ${s} 失败`, { componentId: e, error: n }), null;
|
|
611
606
|
}
|
|
612
607
|
return null;
|
|
613
608
|
},
|
|
@@ -649,14 +644,14 @@ const _ = class _ extends $.Doc {
|
|
|
649
644
|
c.delete(p);
|
|
650
645
|
}));
|
|
651
646
|
}
|
|
652
|
-
const r =
|
|
653
|
-
|
|
654
|
-
const i =
|
|
647
|
+
const r = P.createEncoder();
|
|
648
|
+
P.writeVarUint(r, ue), P.writeVarUint8Array(r, xe(this.awareness, l));
|
|
649
|
+
const i = P.toUint8Array(r);
|
|
655
650
|
this.conns.forEach((c, p) => this.send(p, i));
|
|
656
651
|
}, this.updateHandler = (e) => {
|
|
657
|
-
const o =
|
|
658
|
-
|
|
659
|
-
const n =
|
|
652
|
+
const o = P.createEncoder();
|
|
653
|
+
P.writeVarUint(o, Y), $t(o, e);
|
|
654
|
+
const n = P.toUint8Array(o);
|
|
660
655
|
this.conns.forEach((a, l) => this.send(l, n));
|
|
661
656
|
}, this.ensureDataStructure = () => {
|
|
662
657
|
var l;
|
|
@@ -741,33 +736,33 @@ const _ = class _ extends $.Doc {
|
|
|
741
736
|
o = !0;
|
|
742
737
|
});
|
|
743
738
|
{
|
|
744
|
-
const a =
|
|
745
|
-
|
|
739
|
+
const a = P.createEncoder();
|
|
740
|
+
P.writeVarUint(a, Y), Bt(a, this), this.send(e, P.toUint8Array(a));
|
|
746
741
|
const l = this.awareness.getStates();
|
|
747
742
|
if (l.size > 0) {
|
|
748
|
-
const r =
|
|
749
|
-
|
|
743
|
+
const r = P.createEncoder();
|
|
744
|
+
P.writeVarUint(r, ue), P.writeVarUint8Array(r, xe(this.awareness, Array.from(l.keys()))), this.send(e, P.toUint8Array(r));
|
|
750
745
|
}
|
|
751
746
|
}
|
|
752
747
|
}, this.messageListener = (e, o) => {
|
|
753
748
|
try {
|
|
754
|
-
const n =
|
|
749
|
+
const n = P.createEncoder(), a = pe.createDecoder(o), l = pe.readVarUint(a);
|
|
755
750
|
switch (l) {
|
|
756
751
|
case Y:
|
|
757
|
-
|
|
752
|
+
P.writeVarUint(n, Y), Vt(a, n, this, null), P.length(n) > 1 && (this.ensureDataStructure(), this.send(e, P.toUint8Array(n)));
|
|
758
753
|
break;
|
|
759
754
|
case ue: {
|
|
760
755
|
Mt(this.awareness, pe.readVarUint8Array(a), e);
|
|
761
756
|
break;
|
|
762
757
|
}
|
|
763
758
|
default:
|
|
764
|
-
|
|
759
|
+
v.warn(`Unsupported messageType ${l}`);
|
|
765
760
|
}
|
|
766
761
|
} catch (n) {
|
|
767
|
-
|
|
762
|
+
v.error(n);
|
|
768
763
|
}
|
|
769
764
|
this.save();
|
|
770
|
-
}, B(this.draftYjsFilePath) && $.applyUpdate(this, J(this.draftYjsFilePath)), this.syncedStore =
|
|
765
|
+
}, B(this.draftYjsFilePath) && $.applyUpdate(this, J(this.draftYjsFilePath)), this.syncedStore = At(
|
|
771
766
|
Tt(
|
|
772
767
|
{ pages: {}, pageIds: [], components: {}, supportedLocales: [], config: {}, resources: {} },
|
|
773
768
|
this
|
|
@@ -780,9 +775,9 @@ const _ = class _ extends $.Doc {
|
|
|
780
775
|
throw new Error("Should provide project context");
|
|
781
776
|
try {
|
|
782
777
|
const e = O(q, s), o = O(q, `@del-${s}`);
|
|
783
|
-
|
|
778
|
+
Pe(e, o);
|
|
784
779
|
} catch (e) {
|
|
785
|
-
|
|
780
|
+
v.error("Failed to safe delete project state dir:", e);
|
|
786
781
|
}
|
|
787
782
|
}
|
|
788
783
|
static get projectIds() {
|
|
@@ -842,15 +837,15 @@ const _ = class _ extends $.Doc {
|
|
|
842
837
|
...this.states[s],
|
|
843
838
|
resources: await tt().then(async (l) => {
|
|
844
839
|
var p, u, f, g;
|
|
845
|
-
const { pages: r, components: i } =
|
|
840
|
+
const { pages: r, components: i } = Ct(l, "pages", "components");
|
|
846
841
|
let c = i;
|
|
847
842
|
if ((u = (p = this.states[s]) == null ? void 0 : p.resources) != null && u.components)
|
|
848
843
|
c = {
|
|
849
844
|
...(g = (f = this.states[s]) == null ? void 0 : f.resources) == null ? void 0 : g.components
|
|
850
845
|
};
|
|
851
846
|
else {
|
|
852
|
-
const y = G(this.options.path),
|
|
853
|
-
if (
|
|
847
|
+
const y = G(this.options.path), A = await F.findByPk(y);
|
|
848
|
+
if (A != null && A.useAllResources)
|
|
854
849
|
c = i;
|
|
855
850
|
else {
|
|
856
851
|
const k = (await ce.findAll({ where: { projectId: y } })).map((h) => h.componentId);
|
|
@@ -865,7 +860,7 @@ const _ = class _ extends $.Doc {
|
|
|
865
860
|
}
|
|
866
861
|
async setState(s, e) {
|
|
867
862
|
const o = await Ss(e, { exportAssets: !1, includeResources: !0 }), n = this.getPublishDir(s);
|
|
868
|
-
M(L(n), { recursive: !0 }), Ve(n, { force: !0, recursive: !0 }),
|
|
863
|
+
M(L(n), { recursive: !0 }), Ve(n, { force: !0, recursive: !0 }), Pe(o, n), this.states[s] = e;
|
|
869
864
|
}
|
|
870
865
|
getPublishDir(s) {
|
|
871
866
|
return O(this.options.path, s);
|
|
@@ -958,7 +953,7 @@ const ys = async (t, s) => {
|
|
|
958
953
|
try {
|
|
959
954
|
await ys(e, O(s, G(e)));
|
|
960
955
|
} catch (o) {
|
|
961
|
-
|
|
956
|
+
v.error(`Failed to export assets: ${e}, ${o}`);
|
|
962
957
|
}
|
|
963
958
|
})
|
|
964
959
|
);
|
|
@@ -993,16 +988,16 @@ async function _e(t, s, e) {
|
|
|
993
988
|
try {
|
|
994
989
|
const c = ye(t, i), p = qe(c);
|
|
995
990
|
for (const u of p) {
|
|
996
|
-
const f = G(u), g = e.getFilePath(u, i), y = g ? `${g}:${f}` : f,
|
|
997
|
-
if (
|
|
998
|
-
W.test(c) ||
|
|
991
|
+
const f = G(u), g = e.getFilePath(u, i), y = g ? `${g}:${f}` : f, A = Ue.get(y);
|
|
992
|
+
if (A) {
|
|
993
|
+
W.test(c) || Ce(t, i, A);
|
|
999
994
|
return;
|
|
1000
995
|
}
|
|
1001
|
-
const
|
|
1002
|
-
|
|
996
|
+
const C = await hs(g, f, s);
|
|
997
|
+
C && (W.test(c) || Ce(t, i, C), Ue.set(y, C));
|
|
1003
998
|
}
|
|
1004
999
|
} catch (c) {
|
|
1005
|
-
|
|
1000
|
+
v.error(`Failed to process upload for path ${i.join(".")}:`, c.message || c.reason);
|
|
1006
1001
|
}
|
|
1007
1002
|
})
|
|
1008
1003
|
), l = await Promise.allSettled(a);
|
|
@@ -1077,7 +1072,7 @@ async function Ss(t, {
|
|
|
1077
1072
|
}
|
|
1078
1073
|
const y = O(u, ".blocklet/pages/pages.config.yml");
|
|
1079
1074
|
M(L(y), { recursive: !0 });
|
|
1080
|
-
const
|
|
1075
|
+
const A = {
|
|
1081
1076
|
pages: R(
|
|
1082
1077
|
l.map((m) => {
|
|
1083
1078
|
const d = t.pages[m];
|
|
@@ -1110,9 +1105,9 @@ async function Ss(t, {
|
|
|
1110
1105
|
supportedLocales: t.supportedLocales,
|
|
1111
1106
|
config: t.config
|
|
1112
1107
|
};
|
|
1113
|
-
te(y, H.stringify(
|
|
1114
|
-
const
|
|
1115
|
-
if (n && te(
|
|
1108
|
+
te(y, H.stringify(A));
|
|
1109
|
+
const C = O(u, "config.source.json");
|
|
1110
|
+
if (n && te(C, JSON.stringify(n)), a) {
|
|
1116
1111
|
const m = O(u, "resources"), d = O(m, "components");
|
|
1117
1112
|
M(d, { recursive: !0 });
|
|
1118
1113
|
for (const S of Object.keys(((h = t == null ? void 0 : t.resources) == null ? void 0 : h.components) ?? {})) {
|
|
@@ -1143,10 +1138,10 @@ async function Qe(t, { importAssets: s, includeResources: e } = {}) {
|
|
|
1143
1138
|
const E = me(`*.${b}.yml`, { cwd: h, absolute: !0 })[0];
|
|
1144
1139
|
return E ? H.parse(J(E).toString()) : null;
|
|
1145
1140
|
} catch (E) {
|
|
1146
|
-
|
|
1141
|
+
v.error("parse component error", E);
|
|
1147
1142
|
}
|
|
1148
1143
|
return null;
|
|
1149
|
-
},
|
|
1144
|
+
}, A = R(
|
|
1150
1145
|
f.pages.map(({ slug: h }) => {
|
|
1151
1146
|
var m;
|
|
1152
1147
|
const b = R(
|
|
@@ -1192,10 +1187,10 @@ async function Qe(t, { importAssets: s, includeResources: e } = {}) {
|
|
|
1192
1187
|
locales: Object.fromEntries(b.map(({ locale: d, page: S }) => [d, S.meta]))
|
|
1193
1188
|
};
|
|
1194
1189
|
})
|
|
1195
|
-
),
|
|
1190
|
+
), C = p ? R(((a = f.components) == null ? void 0 : a.map(({ id: h }) => y(p, h))) ?? []) : [];
|
|
1196
1191
|
if (s) {
|
|
1197
1192
|
const h = (...b) => {
|
|
1198
|
-
|
|
1193
|
+
v.info(`[${n ? G(t) : G(O(t, "../../../../"))}] importAssets:`, ...b);
|
|
1199
1194
|
};
|
|
1200
1195
|
try {
|
|
1201
1196
|
h("wait image-bin api ready"), await Ut({
|
|
@@ -1204,15 +1199,15 @@ async function Qe(t, { importAssets: s, includeResources: e } = {}) {
|
|
|
1204
1199
|
}), h("image-bin api is ready");
|
|
1205
1200
|
const b = {}, E = {};
|
|
1206
1201
|
h("start to upload assets"), await Promise.allSettled([
|
|
1207
|
-
_e(
|
|
1202
|
+
_e(C, b, {
|
|
1208
1203
|
getFilePath: (I) => p && O(p, I),
|
|
1209
1204
|
onFinish: (I) => {
|
|
1210
1205
|
h(`upload ${I.length} component assets`);
|
|
1211
1206
|
}
|
|
1212
1207
|
}),
|
|
1213
|
-
_e(
|
|
1208
|
+
_e(A, E, {
|
|
1214
1209
|
getFilePath: (I, m) => {
|
|
1215
|
-
const d = ye(
|
|
1210
|
+
const d = ye(A, m.slice(0, 1));
|
|
1216
1211
|
return c && O(c, L(d.slug), I);
|
|
1217
1212
|
},
|
|
1218
1213
|
onFinish: (I) => {
|
|
@@ -1241,9 +1236,9 @@ async function Qe(t, { importAssets: s, includeResources: e } = {}) {
|
|
|
1241
1236
|
}
|
|
1242
1237
|
return {
|
|
1243
1238
|
supportedLocales: f.supportedLocales,
|
|
1244
|
-
pageIds:
|
|
1245
|
-
components: Object.fromEntries(
|
|
1246
|
-
pages: Object.fromEntries(
|
|
1239
|
+
pageIds: A.map((h) => h.id),
|
|
1240
|
+
components: Object.fromEntries(C.map((h, b) => [h.id, { index: b, data: h }])),
|
|
1241
|
+
pages: Object.fromEntries(A.map((h) => [h.id, h])),
|
|
1247
1242
|
config: f.config || {},
|
|
1248
1243
|
resources: k,
|
|
1249
1244
|
chunks: N
|
|
@@ -1261,7 +1256,7 @@ async function Me(t, s, {
|
|
|
1261
1256
|
try {
|
|
1262
1257
|
a && ts(a);
|
|
1263
1258
|
} catch (p) {
|
|
1264
|
-
|
|
1259
|
+
v.error("clear preload page cache error", { error: p });
|
|
1265
1260
|
}
|
|
1266
1261
|
const { pageIds: l, pages: r, supportedLocales: i } = t;
|
|
1267
1262
|
for (const p of e ?? l) {
|
|
@@ -1306,7 +1301,7 @@ async function Me(t, s, {
|
|
|
1306
1301
|
const Xe = ae(
|
|
1307
1302
|
async (t) => {
|
|
1308
1303
|
var s;
|
|
1309
|
-
if (!
|
|
1304
|
+
if (!Pt(t == null ? void 0 : t.properties))
|
|
1310
1305
|
return t;
|
|
1311
1306
|
if (((s = t == null ? void 0 : t.renderer) == null ? void 0 : s.type) === "react-component") {
|
|
1312
1307
|
const { script: e } = (t == null ? void 0 : t.renderer) || {};
|
|
@@ -1320,7 +1315,7 @@ const Xe = ae(
|
|
|
1320
1315
|
});
|
|
1321
1316
|
}));
|
|
1322
1317
|
} catch (o) {
|
|
1323
|
-
|
|
1318
|
+
v.error("checkPropertiesFromCode error", { componentId: t.id, name: t.name }, { error: o });
|
|
1324
1319
|
}
|
|
1325
1320
|
}
|
|
1326
1321
|
return t;
|
|
@@ -1411,7 +1406,7 @@ function bs(t) {
|
|
|
1411
1406
|
const s = Ge(
|
|
1412
1407
|
async () => {
|
|
1413
1408
|
await Ze().catch((e) => {
|
|
1414
|
-
|
|
1409
|
+
v.error("load resource states error", { error: e });
|
|
1415
1410
|
}), await (t == null ? void 0 : t({
|
|
1416
1411
|
states: V,
|
|
1417
1412
|
pages: Se,
|
|
@@ -1444,7 +1439,7 @@ Z[et] = bs(async ({ pages: t, components: s }) => {
|
|
|
1444
1439
|
);
|
|
1445
1440
|
n.syncedStore.resources.components = i;
|
|
1446
1441
|
}
|
|
1447
|
-
|
|
1442
|
+
v.info(`update [${o}] resource states:`, {
|
|
1448
1443
|
pages: Object.keys(n.syncedStore.resources.pages || {}).length,
|
|
1449
1444
|
components: Object.keys(n.syncedStore.resources.components || {}).length
|
|
1450
1445
|
});
|
|
@@ -1452,7 +1447,7 @@ Z[et] = bs(async ({ pages: t, components: s }) => {
|
|
|
1452
1447
|
);
|
|
1453
1448
|
});
|
|
1454
1449
|
async function po() {
|
|
1455
|
-
|
|
1450
|
+
v.info("trigger reload all project resource"), w.events.emit(fe);
|
|
1456
1451
|
}
|
|
1457
1452
|
async function tt({
|
|
1458
1453
|
ensureLoaded: t = !0
|
|
@@ -1476,7 +1471,7 @@ export {
|
|
|
1476
1471
|
no as i,
|
|
1477
1472
|
se as j,
|
|
1478
1473
|
io as k,
|
|
1479
|
-
|
|
1474
|
+
v as l,
|
|
1480
1475
|
is as m,
|
|
1481
1476
|
Le as n,
|
|
1482
1477
|
q as o,
|
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-B0nM69Rk.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,123 +1,128 @@
|
|
|
1
1
|
import I from "vite-plugin-node-polyfills/shims/process";
|
|
2
|
-
import { b as
|
|
3
|
-
import { initCronCrawlBlocklet as
|
|
4
|
-
import { PreloadComponentScriptModule as
|
|
5
|
-
import { injectPreloadComponents as
|
|
6
|
-
import { getComponentMountPoint as
|
|
7
|
-
import
|
|
8
|
-
import
|
|
9
|
-
import {
|
|
10
|
-
import
|
|
11
|
-
import
|
|
12
|
-
import {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
O() ? N({
|
|
2
|
+
import { b as D, l as E } from "./_chunks/site-state-B0nM69Rk.js";
|
|
3
|
+
import { initCronCrawlBlocklet as H, cancelCronCrawlBlocklet as N, initSEOMiddleware as G } from "@blocklet/crawler/middlewares";
|
|
4
|
+
import { PreloadComponentScriptModule as J } from "@blocklet/pages-kit/types";
|
|
5
|
+
import { injectPreloadComponents as W } from "@blocklet/pages-kit/utils/preload";
|
|
6
|
+
import { getComponentMountPoint as K } from "@blocklet/sdk/lib/component";
|
|
7
|
+
import p, { getBlockletJs as Q } from "@blocklet/sdk/lib/config";
|
|
8
|
+
import { Router as z } from "express";
|
|
9
|
+
import { readFileSync as L } from "fs";
|
|
10
|
+
import V from "mustache";
|
|
11
|
+
import { resolve as j } from "path";
|
|
12
|
+
import { withQuery as X, joinURL as x } from "ufo";
|
|
13
|
+
const Y = ["/assets/"], M = () => [!0, "true"].includes(p.env.preferences.allowCrawler);
|
|
14
|
+
function U() {
|
|
15
|
+
M() ? H({
|
|
17
16
|
time: "30 30 */12 * * *",
|
|
18
17
|
options: {}
|
|
19
|
-
}) :
|
|
18
|
+
}) : N();
|
|
20
19
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
function
|
|
24
|
-
app:
|
|
25
|
-
viteDevServer:
|
|
20
|
+
U();
|
|
21
|
+
p.events.on(p.Events.envUpdate, U);
|
|
22
|
+
function me({
|
|
23
|
+
app: s,
|
|
24
|
+
viteDevServer: g,
|
|
26
25
|
// projectId,
|
|
27
26
|
state: n
|
|
28
27
|
}) {
|
|
29
|
-
let
|
|
30
|
-
if (
|
|
31
|
-
const t =
|
|
32
|
-
|
|
33
|
-
const
|
|
34
|
-
|
|
28
|
+
let w;
|
|
29
|
+
if (g) {
|
|
30
|
+
const t = L(j(I.cwd(), "./index.html"), "utf-8");
|
|
31
|
+
s.use(async (C, P, y) => {
|
|
32
|
+
const k = C.originalUrl;
|
|
33
|
+
w = await g.transformIndexHtml(k, t), y();
|
|
35
34
|
});
|
|
36
35
|
} else
|
|
37
|
-
|
|
38
|
-
const
|
|
39
|
-
|
|
36
|
+
w = L(j(I.env.BLOCKLET_APP_DIR, "dist/index.html"), "utf-8");
|
|
37
|
+
const _ = z();
|
|
38
|
+
_.use(
|
|
40
39
|
G({
|
|
41
40
|
autoReturnHtml: !1,
|
|
42
|
-
allowCrawler:
|
|
41
|
+
allowCrawler: M
|
|
43
42
|
})
|
|
44
|
-
),
|
|
45
|
-
var
|
|
46
|
-
if (
|
|
47
|
-
|
|
43
|
+
), _.get("/:path(*)?", async (t, C, P) => {
|
|
44
|
+
var S, v, A;
|
|
45
|
+
if (Y.some((c) => t.path.startsWith(c))) {
|
|
46
|
+
P();
|
|
48
47
|
return;
|
|
49
48
|
}
|
|
50
|
-
const y = performance.now(),
|
|
51
|
-
let e,
|
|
49
|
+
const y = performance.now(), k = () => Math.round(performance.now() - y), O = "production";
|
|
50
|
+
let e, d, r = w;
|
|
52
51
|
if (t.path.startsWith("/pages")) {
|
|
53
|
-
const
|
|
54
|
-
let
|
|
55
|
-
if ((!
|
|
56
|
-
const
|
|
52
|
+
const c = t.params.lang, i = t.cookies.nf_lang, m = /* @__PURE__ */ new Set([...p.env.languages.map((f) => f.code)]);
|
|
53
|
+
let u = (c && m.has(c) ? c : void 0) || (m.has(i) ? i : void 0) || [...m][0];
|
|
54
|
+
if ((!u || !((S = n.supportedLocales) != null && S.find((f) => f.locale === u))) && (u = ((A = (v = n.supportedLocales) == null ? void 0 : v[0]) == null ? void 0 : A.locale) || ""), u) {
|
|
55
|
+
const f = [];
|
|
57
56
|
Object.values(n.pages).forEach((l) => {
|
|
58
|
-
const
|
|
59
|
-
(
|
|
60
|
-
var
|
|
61
|
-
return
|
|
57
|
+
const b = Object.values((l == null ? void 0 : l.sections) ?? {}).filter(
|
|
58
|
+
(a) => {
|
|
59
|
+
var h;
|
|
60
|
+
return a.component === "custom-component" && ((h = a.config) == null ? void 0 : h.componentId);
|
|
62
61
|
}
|
|
63
|
-
).map((
|
|
64
|
-
var
|
|
62
|
+
).map((a) => {
|
|
63
|
+
var h, $;
|
|
65
64
|
return {
|
|
66
|
-
id:
|
|
67
|
-
componentId:
|
|
68
|
-
useCache:
|
|
69
|
-
cacheDuration:
|
|
70
|
-
properties: (
|
|
65
|
+
id: a.id,
|
|
66
|
+
componentId: a.config.componentId,
|
|
67
|
+
useCache: a.config.useCache,
|
|
68
|
+
cacheDuration: a.config.cacheDuration,
|
|
69
|
+
properties: ($ = (h = a.locales) == null ? void 0 : h[u]) == null ? void 0 : $.properties
|
|
71
70
|
};
|
|
72
71
|
});
|
|
73
|
-
|
|
72
|
+
f.push(...b);
|
|
74
73
|
});
|
|
75
|
-
const
|
|
74
|
+
const B = new Promise((l, b) => {
|
|
76
75
|
setTimeout(() => {
|
|
77
|
-
|
|
76
|
+
b(new Error("getPreloadComponents timeout in promise race, skip it"));
|
|
78
77
|
}, 90 * 1e3);
|
|
79
78
|
});
|
|
80
79
|
try {
|
|
81
80
|
await Promise.race([
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
mode:
|
|
81
|
+
B,
|
|
82
|
+
D({
|
|
83
|
+
mode: O,
|
|
85
84
|
req: t,
|
|
86
85
|
state: n,
|
|
87
|
-
locale:
|
|
88
|
-
instances:
|
|
89
|
-
module:
|
|
86
|
+
locale: u,
|
|
87
|
+
instances: f,
|
|
88
|
+
module: J.UMD_FN
|
|
90
89
|
}).then((l) => {
|
|
91
|
-
l && (
|
|
90
|
+
l && (d = W(l));
|
|
92
91
|
})
|
|
93
92
|
]);
|
|
94
93
|
} catch (l) {
|
|
95
|
-
|
|
94
|
+
E.warn("getPreloadComponents timeout in promise race, skip inject html elements"), E.warn(l);
|
|
96
95
|
}
|
|
97
96
|
}
|
|
98
97
|
}
|
|
99
98
|
try {
|
|
100
|
-
const
|
|
101
|
-
title:
|
|
102
|
-
description:
|
|
99
|
+
const c = (e == null ? void 0 : e.title) || p.env.appName, i = (e == null ? void 0 : e.description) || p.env.appDescription, m = X(x(p.env.appUrl, "/.well-known/service/blocklet/og.png"), {
|
|
100
|
+
title: c,
|
|
101
|
+
description: i
|
|
103
102
|
});
|
|
104
|
-
|
|
105
|
-
ogTitle:
|
|
106
|
-
ogDescription:
|
|
107
|
-
ogImage:
|
|
103
|
+
r = V.render(w, {
|
|
104
|
+
ogTitle: c,
|
|
105
|
+
ogDescription: i,
|
|
106
|
+
ogImage: Z(e == null ? void 0 : e.image) || m,
|
|
108
107
|
pagesPublishedAt: (n == null ? void 0 : n.config.publishedAt) || (/* @__PURE__ */ new Date()).getTime()
|
|
109
108
|
});
|
|
110
109
|
} catch {
|
|
111
110
|
}
|
|
112
|
-
const o = n == null ? void 0 : n.config.fontFamily,
|
|
113
|
-
|
|
114
|
-
|
|
111
|
+
const o = n == null ? void 0 : n.config.fontFamily, R = t.query.mode === "draft" || t.url.includes("preview");
|
|
112
|
+
r = r.replace(
|
|
113
|
+
'<script id="injected-head-elements"><\/script>',
|
|
114
|
+
`
|
|
115
115
|
${e != null && e.backgroundColor ? `<meta name="theme-color" content="${e.backgroundColor}" /><style>html,body,#app {background-color: ${e.backgroundColor} !important;}</style>` : ""}
|
|
116
116
|
${o != null && o.title ? `<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${o.title}&display=swap">` : ""}
|
|
117
117
|
${o != null && o.description && (o == null ? void 0 : o.description) !== (o == null ? void 0 : o.title) ? `<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${o.description}&display=swap">` : ""}
|
|
118
|
+
|
|
119
|
+
<script type="application/json" id="__PAGE_STATE__">
|
|
120
|
+
${JSON.stringify(n).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026")}
|
|
121
|
+
<\/script>
|
|
122
|
+
|
|
118
123
|
<script>
|
|
119
124
|
|
|
120
|
-
window.__PAGE_STATE__ =
|
|
125
|
+
window.__PAGE_STATE__ = JSON.parse(document.getElementById('__PAGE_STATE__').textContent)
|
|
121
126
|
|
|
122
127
|
document.querySelectorAll('link[rel="preload"][as="style"]').forEach(function (link) {
|
|
123
128
|
const l = document.createElement('link');
|
|
@@ -127,25 +132,26 @@ function ue({
|
|
|
127
132
|
});
|
|
128
133
|
<\/script>
|
|
129
134
|
|
|
130
|
-
${
|
|
135
|
+
${R ? `<script src="https://cdn.tailwindcss.com"><\/script>
|
|
131
136
|
<script>
|
|
132
137
|
window.tailwind.config = {
|
|
133
138
|
darkMode: "class",
|
|
134
139
|
};
|
|
135
140
|
<\/script>` : ""}
|
|
136
|
-
`
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
c(
|
|
141
|
+
`
|
|
142
|
+
);
|
|
143
|
+
const T = Q();
|
|
144
|
+
if (T && (r = r.replace('<script src="__blocklet__.js"><\/script>', `<script>${T}<\/script>`)), d != null && d.html && (r = r.replace('<script id="injected-html-elements"><\/script>', d.html)), t.cachedHtml) {
|
|
145
|
+
const c = /<body>([\s\S]*?)<\/body>/, i = c.exec(t.cachedHtml), m = i ? i[1] : "";
|
|
146
|
+
r = r.replace(c, `<body>${m}</body>`);
|
|
141
147
|
}
|
|
142
|
-
|
|
143
|
-
}),
|
|
148
|
+
C.send(r), E.info(`[html] render: ${t.path}, ${k()}ms`), r = null, e = null, d = null;
|
|
149
|
+
}), s.use(_);
|
|
144
150
|
}
|
|
145
|
-
function
|
|
146
|
-
const
|
|
147
|
-
return
|
|
151
|
+
function Z(s) {
|
|
152
|
+
const g = K("image-bin");
|
|
153
|
+
return g && s && !/^(https?:\/\/|\/)/.test(s) ? p.env.appUrl + x(g, "uploads", s) : s;
|
|
148
154
|
}
|
|
149
155
|
export {
|
|
150
|
-
|
|
156
|
+
me as default
|
|
151
157
|
};
|
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-B0nM69Rk.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,6 +1,6 @@
|
|
|
1
1
|
import "vite-plugin-node-polyfills/shims/process";
|
|
2
2
|
import "vite-plugin-node-polyfills/shims/global";
|
|
3
|
-
import { q as H, o as M, p as O, S as j, r as q, a as v, u as B, s as L, n as U, t as b, v as h } from "./_chunks/site-state-
|
|
3
|
+
import { q as H, o as M, p as O, S as j, r as q, a as v, u as B, s as L, n as U, t as b, v as h } from "./_chunks/site-state-B0nM69Rk.js";
|
|
4
4
|
import "@blocklet/quickjs";
|
|
5
5
|
import "@blocklet/sdk/lib/component";
|
|
6
6
|
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.26",
|
|
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
|
|
206
|
-
"@blocklet/pages-kit": "^0.4.
|
|
205
|
+
"@blocklet/pages-kit": "^0.4.26",
|
|
206
|
+
"@blocklet/pages-kit-block-studio": "^0.4.26"
|
|
207
207
|
},
|
|
208
208
|
"devDependencies": {
|
|
209
209
|
"@trivago/prettier-plugin-sort-imports": "^5.2.1",
|