@blocklet/pages-kit-inner-components 0.6.2 → 0.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/chunks/{site-state-DDXqWF74.js → site-state-BG2d2tBl.js} +7 -7
- package/lib/cjs/project-html.js +1 -1
- package/lib/cjs/resources.js +1 -1
- package/lib/es/chunks/{site-state-Bh8guIeX.js → site-state-BoVWlYLn.js} +4 -0
- package/lib/es/project-html.js +1 -1
- package/lib/es/resources.js +1 -1
- package/package.json +3 -3
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";var pt=Object.create;var ke=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,mt=Object.prototype.hasOwnProperty;var ht=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dt(e))!mt.call(t,o)&&o!==n&&ke(t,o,{get:()=>e[o],enumerable:!(s=ut(e,o))||s.enumerable});return t};var q=(t,e,n)=>(n=t!=null?pt(ft(t)):{},ht(e||!t||!t.__esModule?ke(n,"default",{value:t,enumerable:!0}):n,t));const gt=require("@blocklet/pages-kit/builtin/utils"),
|
|
1
|
+
"use strict";var pt=Object.create;var ke=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,mt=Object.prototype.hasOwnProperty;var ht=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dt(e))!mt.call(t,o)&&o!==n&&ke(t,o,{get:()=>e[o],enumerable:!(s=ut(e,o))||s.enumerable});return t};var q=(t,e,n)=>(n=t!=null?pt(ft(t)):{},ht(e||!t||!t.__esModule?ke(n,"default",{value:t,enumerable:!0}):n,t));const gt=require("@blocklet/pages-kit/builtin/utils"),be=require("@blocklet/pages-kit/types"),W=require("@blocklet/pages-kit/utils/property"),ee=require("@blocklet/quickjs"),Ie=require("@blocklet/pages-kit/utils/builtin"),yt=require("@blocklet/sdk/lib/config"),le=require("lru-cache"),Be=require("node-fetch"),R=require("ufo"),St=require("lodash/isEmpty"),wt=require("crypto"),w=require("fs"),h=require("path"),bt=require("lodash/isNil"),It=require("@blocklet/logger"),Ve=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),Ce=require("@blocklet/sdk/lib/component"),F=require("@syncedstore/core"),Et=require("yjs"),Pt=require("@blocklet/pages-kit/utils/data-source"),te=require("@blocklet/pages-kit/utils/route"),Ct=require("lodash"),Re=require("@blocklet/pages-kit/utils/common"),At=require("@blocklet/pages-kit/utils/page-model"),Ot=require("@reactivedata/reactive"),ne=require("glob"),Tt=require("lib0/decoding"),jt=require("lib0/encoding"),vt=require("lodash/cloneDeep"),Dt=require("lodash/debounce"),kt=require("lodash/get"),Rt=require("lodash/set"),xt=require("lodash/union"),_t=require("p-limit"),v=require("sequelize"),Mt=require("stream/promises"),Lt=require("tar"),$t=require("wait-on"),z=require("y-protocols/awareness"),ge=require("y-protocols/sync"),Nt=require("yaml");require("sqlite3");require("@blocklet/pages-kit/types/state");const _=t=>t&&t.__esModule?t:{default:t};function pe(t){if(t&&t.__esModule)return t;const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,s.get?s:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const P=_(yt),Ut=_(Be),Ae=_(St),Ge=_(h),Ft=_(bt),qt=_(It),$=pe(Et),ye=pe(Tt),k=pe(jt),Bt=_(vt),Je=_(Dt),Oe=_(kt),xe=_(Rt),Vt=_(xt),Gt=_(_t),Jt=_($t),B=pe(Nt);P.default.env.mode;P.default.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY;P.default.env.OPENAI_BASE_URL||process.env.OPENAI_BASE_URL;P.default.env.TRANSLATE_ADDITIONAL_PROMPT||process.env.TRANSLATE_ADDITIONAL_PROMPT;P.default.env.PAGE_CONTENT_ADDITIONAL_PROMPT||process.env.PAGE_CONTENT_ADDITIONAL_PROMPT;const zt="image-bin";P.default.env.INIT_TEMPLATE_PATH;const ze=process.env.DATABASE_URL||Ge.default.join(P.default.env.dataDir,"db/pages-kit.db"),_e=P.default,Kt=()=>P.default.env.tenantMode==="multiple",Ht=()=>(Ft.default(_e.env.preferences.multiTenantAllProjectAccessPassports)?[]:_e.env.preferences.multiTenantAllProjectAccessPassports?.split(","))||[],Yt=Ge.default.join(P.default.env.dataDir,"fs-memoize-cache"),Wt=P.default.env.FS_MEMOIZE_CACHE_VERSION||"v1.0.0",f=qt.default("pages-kit"),Qt=v.DataTypes.sqlite.DATE.parse;v.DataTypes.sqlite.DATE.parse=(t,e)=>typeof t=="number"?new Date(t):Qt(t,e);const N=new v.Sequelize({dialect:"sqlite",storage:ze,benchmark:process.env.ENABLE_SEQUELIZE_BENCHMARK==="true",retry:{match:[/SQLITE_BUSY/],name:"query",max:10},logging:process.env.ENABLE_SEQUELIZE_LOGGING==="true"?console.log:!1});N.query("pragma journal_mode = WAL;");N.query("pragma synchronous = normal;");N.query("pragma journal_size_limit = 33554432;");N.query("pragma cache_size = -2000;");N.query("pragma mmap_size = 33554432;");process.on("SIGINT",async()=>{await N.close(),process.exit(0)});process.on("SIGTERM",async()=>{await N.close(),process.exit(0)});async function Xt(t,e){try{if(t.getDialect()!=="sqlite")return;const[n]=await t.query("SELECT 1");if(!n||n.length===0)return;await t.query("PRAGMA shrink_memory;")}catch(n){if(n.name==="SequelizeConnectionError"||n?.message&&/closed!/.test(n.message))return;console.error("Failed to cleanup SQLite memory",e,n)}}setInterval(async()=>{f.info("Start cleanupSqliteMemory"),await Xt(N,ze),f.info("End cleanupSqliteMemory")},60*1e3*10);class Te extends v.Model{}Te.init({id:{type:v.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:v.DataTypes.UUIDV4},projectId:{type:v.DataTypes.UUID,allowNull:!1},componentId:{type:v.DataTypes.STRING,allowNull:!1}},{sequelize:N,tableName:"ProjectComponents",timestamps:!1});class M extends v.Model{static async getProjectByIdOrSlug(e){return M.findOne({where:{[v.Op.or]:[{id:e},{slug:e}]}})}}M.init({id:{type:v.DataTypes.UUID,defaultValue:v.DataTypes.UUIDV4,primaryKey:!0},name:{type:v.DataTypes.STRING,allowNull:!1},description:v.DataTypes.TEXT,createdAt:v.DataTypes.DATE,updatedAt:v.DataTypes.DATE,createdBy:{type:v.DataTypes.STRING,allowNull:!1},updatedBy:{type:v.DataTypes.STRING,allowNull:!1},slug:v.DataTypes.STRING,icon:v.DataTypes.STRING,pinnedAt:v.DataTypes.DATE,useAllResources:v.DataTypes.BOOLEAN,npmSecret:v.DataTypes.STRING,relatedBlocklets:{type:v.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){const t=this.getDataValue("relatedBlocklets");if(typeof t=="object")return t??{};try{return t?JSON.parse(t):{}}catch(e){return f.error("Failed to parse relatedBlocklets",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("relatedBlocklets",t?JSON.stringify(t):"{}")}catch(e){f.error("Failed to set relatedBlocklets",{error:e,value:t}),this.setDataValue("relatedBlocklets","{}")}}},productionState:{type:v.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){const t=this.getDataValue("productionState");if(typeof t=="object")return t??{};try{return t?JSON.parse(t):{}}catch(e){return f.error("Failed to parse productionState",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("productionState",t?JSON.stringify(t):"{}")}catch(e){f.error("Failed to set productionState",{error:e,value:t}),this.setDataValue("productionState","{}")}}}},{sequelize:N,paranoid:!0});M.hasMany(Te,{foreignKey:"projectId",as:"components"});const Zt=Yt,en=Wt,se=30*24*60*60*1e3,tn=24*60*60*1e3,Ke=async(t="")=>{const e=h.join(Zt,t);try{if(!(await w.promises.stat(e)).isDirectory())throw new Error(`${e} is not a directory`)}catch{await w.promises.mkdir(e,{recursive:!0})}return e},Me=(t,...e)=>t.keyGenerator?t.keyGenerator(...e):JSON.stringify([t.subdir||"",...e]),nn=(t,e)=>{const n=wt.createHash("md5").update(e).digest("hex");return h.join(t,`${en}-${n}.json`)},sn=async(t="")=>{const e=await Ke(t),n=Date.now();try{const s=await w.promises.readdir(e);await Promise.all(s.filter(o=>o.endsWith(".json")).map(async o=>{const r=h.join(e,o);try{const c=await w.promises.readFile(r,"utf-8"),a=JSON.parse(c);a.createdAt&&n-a.createdAt>se&&await w.promises.unlink(r)}catch{try{const a=await w.promises.stat(r);n-a.mtimeMs>se&&await w.promises.unlink(r)}catch{}}}))}catch(s){console.error(`Failed to cleanup cache in ${e}:`,s)}},on=(()=>{const t=new Set;return setInterval(async()=>{await Promise.all(Array.from(t).map(s=>sn(s)))},tn).unref(),s=>{t.add(s)}})();function ue(t,e){return e.subdir&&on(e.subdir),ee.memoize(async(...s)=>{const o=await Ke(e.subdir||""),r=Me(e,...s),c=nn(o,r);try{const a=await w.promises.readFile(c,"utf-8"),{value:p,createdAt:d}=JSON.parse(a);if(d&&Date.now()-d>se)throw await w.promises.unlink(c).catch(()=>{}),new Error("Cache expired");return p}catch{const p=await t(...s),d=JSON.stringify({value:p,createdAt:Date.now()});return w.promises.writeFile(c,d,"utf-8").catch(E=>{console.error("Failed to write fs cache:",E)}),p}},{keyGenerator:(...s)=>Me(e,...s),lruOptions:e.lruOptions||{max:100,ttl:se}})}const He=async()=>await import("typescript"),rn=async()=>await import("esbuild"),an=async()=>(await import("postcss")).default,cn=async()=>(await import("tailwindcss")).default,ln=async()=>(await import("autoprefixer")).default,pn=async(t,{componentId:e})=>{const n=`@tailwind components;
|
|
2
2
|
@tailwind utilities;
|
|
3
|
-
`,s=`.CustomComponent_${e}`,o=await
|
|
3
|
+
`,s=`.CustomComponent_${e}`,o=await an(),r=await cn(),c=await ln();return(await o([r({content:[{raw:t,extension:"tsx"}]}),c({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),p=>{p.walkRules(d=>{d.selectors=d.selectors.map(E=>E.replace(/\.(.+)/g,`${s}.$1,${s} .$1`))})}]).process(n)).css},un=async(t,{componentId:e})=>{const n=await pn(t,{componentId:e});return`export const __PagesKit_CSS__ = ${JSON.stringify(n)};
|
|
4
4
|
|
|
5
5
|
${t}
|
|
6
|
-
`},Le=ue(async(t,e)=>{const n=await He();let s=n.transpileModule(t,{compilerOptions:{jsx:n.JsxEmit.React,target:n.ScriptTarget.ES2016,module:n.ModuleKind.ESNext},transformers:{before:[Ve.createBuiltinModuleTransformer(n)]}}).outputText;if(e.tailwind&&(s=await un(s,{componentId:e.componentId})),e.module===
|
|
6
|
+
`},Le=ue(async(t,e)=>{const n=await He();let s=n.transpileModule(t,{compilerOptions:{jsx:n.JsxEmit.React,target:n.ScriptTarget.ES2016,module:n.ModuleKind.ESNext},transformers:{before:[Ve.createBuiltinModuleTransformer(n)]}}).outputText;if(e.tailwind&&(s=await un(s,{componentId:e.componentId})),e.module===be.PreloadComponentScriptModule.ESM)return s;const o=n.transpileModule(s,{compilerOptions:{jsx:n.JsxEmit.React,target:n.ScriptTarget.ES2016,module:n.ModuleKind.CommonJS,moduleResolution:n.ModuleResolutionKind.Node16}}).outputText;return e.module===be.PreloadComponentScriptModule.CJS?o:mn(e.moduleName,o)},{subdir:"transpileModule"}),dn=async(t,e)=>{const{build:n}=await rn(),o=(await n({entryPoints:["index.tsx"],external:Object.keys(Ie.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(p){let d=null;p.onResolve({filter:/.*/},E=>E.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:E.path==="./component"?{path:"component.tsx",namespace:"vfs"}:null),p.onLoad({filter:/.*/,namespace:"vfs"},async E=>{if(E.path==="index.tsx")return{contents:`export { ${e} } from './component'`,loader:"tsx"};if(E.path==="component.tsx")return{contents:t,loader:"tsx"};if(Ve.isRelativeModule(E.path)){const g=E.path.split("/").pop();if(d||(d=await ct({ensureLoaded:!1})),d?.chunks?.[g])try{const b=w.readFileSync(d.chunks[g],"utf-8");return f.info("get chunk from local file system",g),{contents:b,loader:"tsx"}}catch{}}return null})}}]})).outputFiles?.[0]?.contents;if(!o)throw new Error("Failed to build server code");const r=Buffer.from(o).toString(),c=await He();return c.transpileModule(r,{compilerOptions:{module:c.ModuleKind.ESNext,target:c.ScriptTarget.ES2020}}).outputText},fn=(t,e)=>new RegExp(`export\\s+\\{[^}]*(?:\\w+\\s+as\\s+${e}\\b|\\b${e}\\b)[^}]*\\}`,"m").test(t)?t:void 0,Ye=ue(async(t,e)=>{const n=await dn(t,e);return fn(n,e)},{subdir:"extractExportValueSchema"}),mn=(t,e)=>`// GENERATED FILE. DO NOT EDIT.
|
|
7
7
|
var ${t} = async function () {
|
|
8
8
|
|
|
9
9
|
const exports = {};
|
|
@@ -29,7 +29,7 @@ var ${t} = async function () {
|
|
|
29
29
|
|
|
30
30
|
return exports;
|
|
31
31
|
};
|
|
32
|
-
`,We=async()=>{const{Sandbox:t}=await import("@blocklet/quickjs");return t};function hn(t){return t?.type==="react-component"}const K=new le.LRUCache({max:100,ttl:1e3*60*60*24}),gn=60*60,$e=10;function yn(t){f.info("clear preload components cache",{cacheKey:t}),K.delete(t)}function Sn(t){for(const e of K.keys())e.includes(t)&&(f.info("clear preload components cache",{cacheKey:e}),yn(e))}function wn({mode:t,instanceId:e,componentId:n,locale:s}){return["getPreloadComponents",t,e,n,s].join("-")}async function
|
|
32
|
+
`,We=async()=>{const{Sandbox:t}=await import("@blocklet/quickjs");return t};function hn(t){return t?.type==="react-component"}const K=new le.LRUCache({max:100,ttl:1e3*60*60*24}),gn=60*60,$e=10;function yn(t){f.info("clear preload components cache",{cacheKey:t}),K.delete(t)}function Sn(t){for(const e of K.keys())e.includes(t)&&(f.info("clear preload components cache",{cacheKey:e}),yn(e))}function wn({mode:t,instanceId:e,componentId:n,locale:s}){return["getPreloadComponents",t,e,n,s].join("-")}async function bn({mode:t,req:e,state:n,locale:s,instances:o,module:r}){const{supportedLocales:c,config:{defaultLocale:a}}=n;if(!a)return null;const p=(await Promise.all(o.map(async l=>{try{const i=wn({mode:t,instanceId:l.id,componentId:l.componentId,locale:s});if(t!=="draft"&&l.useCache&&K.has(i))return f.info(`get preload component from cache: ${i}`),K.get(i);const S=oe({state:n,componentId:l.componentId});if(!S)return null;const A=await In({req:e,state:n,componentId:S.id,locale:s,defaultLocale:a,properties:l.properties});if(!A)return null;const y={instanceId:l.id,preload:A};if(t!=="draft"&&l.useCache){let m=gn;l.cacheDuration&&(m=l.cacheDuration),f.info(`set preload component to cache(${m}s): ${i}`),K.set(i,y,{ttl:m*1e3})}return y}catch(i){return f.error("get preload component error",{instanceId:l.id,componentId:l.componentId},{error:i}),null}}))).filter(l=>!!l),d=Object.values(p.reduce((l,i)=>({...l,...i.preload.components}),{}));async function E(){const l=await Promise.all(d.map(async i=>{const S=W.componentUMDName({componentId:i.component.id}),A=r===be.PreloadComponentScriptModule.ESM?{module:r,script:await Le(i.script,{componentId:i.component.id,module:r,tailwind:t!=="draft"})}:{module:r,script:await Le(i.script,{componentId:i.component.id,module:r,moduleName:S,tailwind:t!=="draft"}),moduleName:S};return[i.component.id,{component:i.component,script:A}]}));return Object.fromEntries(l)}const g=await E();return{config:{defaultLocale:a,supportedLocales:c},components:g,instances:p.map(l=>({id:l.instanceId,componentId:l.preload.component.id,locales:{[l.preload.locale]:{props:l.preload.props}}}))}}async function In({req:t,state:e,componentId:n,locale:s,defaultLocale:o,properties:r}){const{supportedLocales:c}=e,a=oe({state:e,componentId:n});if(!a)return null;const p=c.some(E=>E.locale===s)?s:o;if(!p)return null;const d=await Qe({req:t,state:e,componentId:n,locale:p,defaultLocale:o,properties:r});return d?{component:a,...d}:null}const En=20;async function Qe({req:t,depth:e=0,state:n,componentId:s,locale:o,defaultLocale:r,properties:c}){if(e>En)throw new RangeError("max component depth exceeded");const a=Pn({state:n,componentId:s,properties:c,locale:o});if(!a)return null;const{props:p,component:d}=a,E={locale:o||r,components:{[a.component.id]:{component:a.component,script:a.script}},props:{...p}};try{const g=hn(d.renderer)?d.renderer.getServerSideProps:void 0,b=await Cn({...a,req:t,serverSideProps:g});b?.props&&Object.assign(E.props,b.props)}catch(g){f.error("preload data at server side error",{componentId:s,name:a.component.name},{error:g})}return await Promise.all(Object.entries(p).map(async([g,b])=>{if(b?.type===W.RenderNestedComponent){const l=await Qe({req:t,depth:e+1,state:n,componentId:b.componentId,locale:o,defaultLocale:r,properties:b.properties});l&&(Object.assign(E.components,l.components),Object.assign(E.props,{[g]:{type:W.RenderNestedComponent,componentId:b.componentId,props:l.props}}))}})),E}function Pn({state:t,componentId:e,locale:n,properties:s}){const o=oe({state:t,componentId:e});if(!o)return null;const r=W.mergeComponent({componentId:e,getComponent:c=>oe({state:t,componentId:c}),locale:n,defaultLocale:t.config.defaultLocale,properties:s});return r?{component:o,script:r.script,props:{locale:n,...r.props}}:null}function oe({state:t,componentId:e}){return t.components[e]?.data??t.resources.components?.[e]?.component}async function Cn({component:t,script:e,props:n,req:s,serverSideProps:o}){if(!o&&!e?.includes("getServerSideProps"))return null;const r=o??await Ye(e,"getServerSideProps");if(!r)return null;const a=(r.match(/export\s*{\s*(\w+)\s+as\s+getServerSideProps\s*}/)||r.match(/export\s*{\s*getServerSideProps\s*}/))?.[1]||"getServerSideProps",p=new Promise(g=>{setTimeout(()=>{g({})},$e*1e3)}),d=await We();return await Promise.race([p,d.callFunction({code:`${r}
|
|
33
33
|
|
|
34
34
|
export async function getServerSidePropsWrapper(props) {
|
|
35
35
|
const { location, fetch, props: componentProps } = props;
|
|
@@ -40,7 +40,7 @@ export async function getServerSidePropsWrapper(props) {
|
|
|
40
40
|
try {
|
|
41
41
|
globalThis.location = location;
|
|
42
42
|
globalThis.fetch = fetch;
|
|
43
|
-
return await ${
|
|
43
|
+
return await ${a}(componentProps);
|
|
44
44
|
} finally {
|
|
45
45
|
// 清理全局状态
|
|
46
46
|
if (originalLocation) globalThis.location = originalLocation;
|
|
@@ -48,10 +48,10 @@ export async function getServerSidePropsWrapper(props) {
|
|
|
48
48
|
}
|
|
49
49
|
}`,filename:`${t.name||t.id}.js`,moduleLoader:g=>{if(g==="@blocklet/pages-kit/builtin/utils")return` const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
|
|
50
50
|
export { joinURL, withQuery, getQuery, getComponentMountPoint }
|
|
51
|
-
`;if(g==="@blocklet/pages-kit/builtin/dayjs")return ee.BuiltinModules.dayjs;if(g in ee.BuiltinModules)return ee.BuiltinModules[g];if(g in
|
|
51
|
+
`;if(g==="@blocklet/pages-kit/builtin/dayjs")return ee.BuiltinModules.dayjs;if(g in ee.BuiltinModules)return ee.BuiltinModules[g];if(g in Ie.BuiltinModules){const b=Ie.BuiltinModules[g];return Ae.default(b)?void 0:b}},global:{console:{log:(...g)=>{f.info(...g)},warn:(...g)=>{f.warn(...g)},error:(...g)=>{f.error(...g)}},getComponentMountPoint:gt.getComponentMountPoint,joinURL:R.joinURL,withQuery:R.withQuery,getQuery:R.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:R.joinURL(R.withHttps(s.hostname),s.originalUrl)},fetch:(g,{...b}={})=>{const l=typeof g=="string"&&g.startsWith("/")?R.joinURL(P.default.env.appUrl,g):g;if(typeof l=="string"&&R.parseURL(l).host===R.parseURL(P.default.env.appUrl).host){const i=s.get("cookie");if(i){const S=new Be.Headers(b.headers);S.set("cookie",i),b.headers=S}}return Ut.default(l,{...b,timeout:$e*1e3}).then(i=>({ok:i.ok,status:i.status,statusText:i.statusText,headers:Object.fromEntries(i.headers.entries()),json:()=>i.json()}))},props:n}]})])}const An=ue(async(t,e,n,s)=>{if(!t?.includes(e)&&!s)return null;const o=s??await Ye(t,e);if(o)try{return await(await We()).callFunction({code:`
|
|
52
52
|
${o}
|
|
53
53
|
|
|
54
54
|
export function get${e}SchemaWrapper() {
|
|
55
55
|
return ${e};
|
|
56
56
|
}
|
|
57
|
-
`,filename:`${n}.js`,functionName:`get${e}SchemaWrapper`})}catch(a){return f.error(`获取 ${e} 失败`,{componentId:n,error:a}),null}return null},{subdir:"getExportSchemaValueFromCode"}),On="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",Ee="page",Ne="trigger-reload-project-resource",je=On,Tn="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM";function ae(t){t.observeDeep(e=>{e.some(n=>n.changes.keys.has("updatedAt")||n.changes.keys.has("publishedAt"))||t.set("updatedAt",new Date().toISOString())})}function Xe(){return w.mkdtempSync(h.join(P.default.env.dataDir,"tmp-"))}function re(t,e,n=[]){return Array.isArray(t)?t.flatMap((s,o)=>re(s,e,[...n,o])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([s,o])=>re(o,e,[...n,s])):e(t)?[n]:[]}function x(t){return t.filter(e=>e!=null)}function jn(t){t.pages&&Object.keys(t.pages).forEach(n=>{const s=F.getYjsValue(t.pages[n]);s&&s instanceof $.Map&&ae(s)});const e=F.getYjsValue(t.pages);e&&e instanceof $.Map&&e.observe(n=>{n.changes.keys.forEach((s,o)=>{if(s.action==="add"){const a=F.getYjsValue(t.pages[o]);a&&a instanceof $.Map&&ae(a)}})})}function vn(t){t.routes&&Object.keys(t.routes).forEach(n=>{const s=F.getYjsValue(t.routes?.[n]);s&&s instanceof $.Map&&ae(s)});const e=F.getYjsValue(t.routes);e&&e instanceof $.Map&&e.observe(n=>{n.changes.keys.forEach((s,o)=>{if(s.action==="add"){const a=F.getYjsValue(t.routes?.[o]);a&&a instanceof $.Map&&ae(a)}})})}function Dn(t,e){for(const n of e||Object.keys(t.routes||{})){let s=n,o=[];if(n.includes("-")){const[a,...c]=n.split("-");s=a,o=c||[]}if(t.routes?.[s]!==void 0){t.routes[s].publishedAt=new Date().toISOString();const a=t.routes[s];if(!a||!a.params||a.params.length===0)continue;if(n.includes("-")&&o.length>0){const c=te.getRouteMetaDataByOptionIds(o,a);c&&(c.publishedAt=new Date().toISOString())}if(!e){const c=te.generateParamCombinations({basePath:a.path,params:a.params,routeId:a.id,paramsOptions:a.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const r of c)r.routeMetaData??={},r.routeMetaData.publishedAt=new Date().toISOString()}}}}function Se({page:t,route:e,state:n,routeId:s,routePathInfo:o}){f.info(`Executing datasource data assembly, routeId: ${s}, routePathInfo: ${JSON.stringify(o)}`);const a={...Ct.cloneDeep(t),id:s,slug:o?.path??e.path,createdAt:e.createdAt,updatedAt:o?.routeMetaData?.updatedAt??e.updatedAt,publishedAt:o?.routeMetaData?.publishedAt??e.publishedAt,isPublic:(o?.routeMetaData?.isPublic??e.isPublic)&&e.isPublic};for(const c of n.supportedLocales){if(e.dataSource){let r=e.id;o&&(r=o.paramOptionIds.join("-"));const p=e.dataSource.pathDataMappings?.[r]?.dataCache?.[c.locale]??e.dataSource.pathDataMappings?.[r]?.dataCache?.[n.config.defaultLocale||"en"];if(!p)continue;Pt.setPageDataSource(a,n,c.locale,p)}o&&o.routeMetaData&&(o.routeMetaData.publishedAt=new Date().toISOString())}return a}const V=new le.LRUCache({max:100,ttl:10*60*1e3});function kn(t,e=[]){let n=0;const s=Array.from(V.keys()),o=[];for(const a of t){o.push(`page-html:prod:${a}:lang-path=none`);for(const c of e)o.push(`page-html:prod:/${c}${a}:lang-path=${c}`)}for(const a of s){const c=a.split(":lang-path=")[0]||"";for(const r of o){const d=(r.split(":lang-path=")[0]||"").replace(/\/:[^/]+/g,"");if(c.startsWith(d)){V.delete(a),n++,f.info(`[Cache CLEAR] key: ${a}`);break}}}return f.info(`[Cache CLEAR] cleared ${n} entries for patterns:`,o),n}function Rn({projectId:t,projectSlug:e,supportedLocales:n=[]}){let s=0;const o=Array.from(V.keys()),a=[];a.push(`page-html:prod:/${t}`),e&&e!==t&&a.push(`page-html:prod:/${e}`);for(const c of n)a.push(`page-html:prod:/${c}/${t}`),e&&e!==t&&(e!=="/"?a.push(`page-html:prod:/${c}/${e}`):a.push(`page-html:prod:/${c}`));for(const c of o)for(const r of a)if(c.startsWith(r)){V.delete(c),s++,f.info(`[Cache CLEAR PROJECT] key: ${c}`);break}return f.info(`[Cache CLEAR PROJECT] cleared ${s} entries for project ${t}${e?` (slug: ${e})`:""}`),s}function xn(){const t=V.size;return V.clear(),f.info(`[Cache CLEAR ALL] cleared ${t} entries`),t}P.default.events.on(P.default.Events.envUpdate,xn);const{uploadToMediaKit:_n}=require("@blocklet/uploader-server"),ve=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,H=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Ue=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Mn=1e4,Ln=3e4,Q=0,we=1,$n=0,Nn=1,Ze=P.default,X=h.join(process.env.BLOCKLET_DATA_DIR,"site-state");function ie(t){return t?.replace(/\//g,"|")||""}function Un(){const t=Ze.env.languages.map(n=>({locale:n.code,name:n.name})),e=t[0]?.locale;return{pageIds:[],pages:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{},components:{},supportedLocales:t,config:{defaultLocale:e},resources:{}}}class j extends $.Doc{constructor(e){super(),this.options=e,w.existsSync(this.draftYjsFilePath)&&$.applyUpdate(this,w.readFileSync(this.draftYjsFilePath)),this.syncedStore=Ot.reactive(F.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new z.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static RELEASE_DELAY=5*60*1e3;static PERIODIC_CHECK_INTERVAL=2*60*60*1e3;static sharedInstances={};static pageUrlMapCache=new le.LRUCache({max:100,ttl:1e3*60*60*24});static periodicCheckTimer;static safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const n=h.join(X,e),s=h.join(X,`@del-${e}`);w.renameSync(n,s)}catch(n){f.error("Failed to safe delete project state dir:",n)}}static async getProjectIds(){return(await M.findAll({attributes:["id"],raw:!0})).map(e=>e.id)}static get projectIds(){return ne.globSync("*/",{cwd:X,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*","undefined"]})}static get allShared(){return this.projectIds.map(e=>j.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let n=j.sharedInstances[e];return n||(n=new j({path:h.join(X,e)}),j.sharedInstances[e]=n,it({projectId:e,pages:de,components:fe}),n)}static async getProductionState(e){return(await M.findByPk(e,{attributes:["productionState"]}))?.productionState??Un()}destroy(){this.cancelRelease(),this.save({flush:!0}),this.conns.forEach((n,s)=>this.closeConn(s)),this.awareness.destroy();const e=h.basename(this.options.path);delete j.sharedInstances[e],super.destroy()}initObserver(){jn(this.syncedStore),vn(this.syncedStore)}get draftYjsFilePath(){return h.join(this.options.path,"draft.yjs")}static async getStateByProjectId(e,n){if(n==="draft"){const s=j.shared(e);return JSON.parse(JSON.stringify(s.syncedStore))}return j.getProductionState(e)}async getState(e){if(e==="draft")return JSON.parse(JSON.stringify(this.syncedStore));const n=h.basename(this.options.path);return j.getProductionState(n)}async setState(e,n){const s=await tt(n,{exportAssets:!1,includeResources:!0}),o=this.getPublishDir(e);if(w.mkdirSync(h.dirname(o),{recursive:!0}),w.rmSync(o,{force:!0,recursive:!0}),w.renameSync(s,o),e==="production"){const a=h.basename(this.options.path);j.pageUrlMapCache.delete(a),await M.update({productionState:n},{where:{id:a}})}}getPublishDir(e){return h.join(this.options.path,e)}syncedStore;conns=new Map;awareness;releaseTimer;awarenessChangeHandler=({added:e,updated:n,removed:s},o)=>{const a=e.concat(n,s);if(o!==null){const p=this.conns.get(o);p&&(e.forEach(d=>{p.add(d)}),s.forEach(d=>{p.delete(d)}))}const c=k.createEncoder();k.writeVarUint(c,we),k.writeVarUint8Array(c,z.encodeAwarenessUpdate(this.awareness,a));const r=k.toUint8Array(c);this.conns.forEach((p,d)=>this.send(d,r))};updateHandler=e=>{const n=k.createEncoder();k.writeVarUint(n,Q),ge.writeUpdate(n,e);const s=k.toUint8Array(n);this.conns.forEach((o,a)=>this.send(a,s))};ensureDataStructure=()=>{const{supportedLocales:e,pages:n,pageIds:s,config:o,routes:a,routeIds:c}=this.syncedStore;{const r=new Set(Object.keys(n));let p=0;for(;p<s.length;){const d=s[p];r.has(d)?(r.delete(d),p++):s.splice(p,1)}}{const r=new Set(Object.keys(a));let p=0;for(;p<c.length;){const d=c[p];r.has(d)?(r.delete(d),p++):c.splice(p,1)}}e.splice(0,e.length),e.push(...Ze.env.languages.map(r=>({locale:r.code,name:r.name}))),o.defaultLocale=e[0]?.locale;{let r=0;const p=new Set;for(;r<e.length;){const{locale:d}=e[r];p.has(d)?e.splice(r,1):(r++,p.add(d))}}};send=(e,n)=>{e.readyState!==$n&&e.readyState!==Nn&&this.closeConn(e);try{e.send(n,s=>{s&&this.closeConn(e)})}catch{this.closeConn(e)}};closeConn=e=>{if(e.removeAllListeners(),this.conns.has(e)){const n=this.conns.get(e);this.conns.delete(e),n&&z.removeAwarenessStates(this.awareness,Array.from(n),null)}e.close(),this.checkAndScheduleRelease()};checkAndScheduleRelease(){this.conns.size===0&&this.scheduleRelease()}scheduleRelease(){this.cancelRelease();const e=h.basename(this.options.path);this.releaseTimer=setTimeout(()=>{f.info(`[SiteState] releasing instance due to no active connections: ${e}`),this.conns.size===0&&(this.releaseTimer=void 0,this.destroy())},j.RELEASE_DELAY),f.info(`[SiteState] scheduled release for project ${e} in ${j.RELEASE_DELAY/1e3}s`)}cancelRelease(){if(this.releaseTimer){clearTimeout(this.releaseTimer),this.releaseTimer=void 0;const e=h.basename(this.options.path);f.info(`[SiteState] cancelled scheduled release for project ${e}`)}}autoSave=Je.default(()=>{w.mkdirSync(h.dirname(this.draftYjsFilePath),{recursive:!0}),w.writeFileSync(this.draftYjsFilePath,$.encodeStateAsUpdate(this))},Mn);save=({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()};publish=async({mode:e,routes:n})=>{const s=await this.getState("draft"),o=await this.getState("production");await qe(s,o,{routes:n,mergeMode:"replace",deleteRoutes:!0,publishMode:e}),o.config.publishedAt=new Date().getTime(),Dn(this.syncedStore,n),await this.setState(e,o),await this.clearPageCacheForRoutes(n,o)};mergeState=async(e,n)=>{const s=JSON.parse(JSON.stringify(n));e.config.fontFamily??={};const o=s.config?.fontFamily,a=e.config?.fontFamily;e.config.fontFamily.title=o?.title||a?.title,e.config.fontFamily.description=o?.description||a?.description,await new Promise((c,r)=>{this.transact(async()=>{try{const p=await qe(e,n);c(p)}catch(p){r(p)}})})};clearPageCacheForRoutes=async(e,n)=>{const s=h.basename(this.options.path),a=(await M.findByPk(s))?.slug||s;if(f.info(`[SiteState] clearing page cache for project ${s}, routes:`,e||[]),!e||e.length===0){Rn({projectId:s,projectSlug:a,supportedLocales:n.supportedLocales.map(d=>d.locale)});return}const c=n.supportedLocales.map(d=>d.locale),r=[],p=e.filter(d=>n.pages[d]);for(const d of p){const g=n.pages[d].slug;a&&a!==s&&(a==="/"?r.push(g):r.push(`/${a}${g}`)),r.push(`/${s}${g}`)}if(f.info(`[SiteState] clearing page cache for project ${s}, pathPatterns:`,r),r.length>0){const d=kn(r,c);f.info(`[SiteState] cleared ${d} page cache entries for project ${s}, routes:`,e)}};addConnection=e=>{if(this.conns.has(e))return;this.cancelRelease(),e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",o=>this.messageListener(e,new Uint8Array(o)));let n=!0;const s=setInterval(()=>{if(!n)this.conns.has(e)&&this.closeConn(e),clearInterval(s);else if(this.conns.has(e)){n=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(s)}}},Ln);e.on("close",()=>{this.closeConn(e),clearInterval(s)}),e.on("pong",()=>{n=!0});{const o=k.createEncoder();k.writeVarUint(o,Q),ge.writeSyncStep1(o,this),this.send(e,k.toUint8Array(o));const a=this.awareness.getStates();if(a.size>0){const c=k.createEncoder();k.writeVarUint(c,we),k.writeVarUint8Array(c,z.encodeAwarenessUpdate(this.awareness,Array.from(a.keys()))),this.send(e,k.toUint8Array(c))}}};messageListener=(e,n)=>{try{const s=k.createEncoder(),o=ye.createDecoder(n),a=ye.readVarUint(o);switch(a){case Q:k.writeVarUint(s,Q),ge.readSyncMessage(o,s,this,null),k.length(s)>1&&(this.ensureDataStructure(),this.send(e,k.toUint8Array(s)));break;case we:{z.applyAwarenessUpdate(this.awareness,ye.readVarUint8Array(o),e);break}default:f.warn(`Unsupported messageType ${a}`)}}catch(s){f.error(s)}this.save()};static async pageUrlMap(e,n){let s=[];n?s=[n]:s=await this.getProjectIds();let o={};if(e==="production"&&s?.length){const a=new Map(s.map(c=>[c,!0]));for(const c of s){const r=j.pageUrlMapCache.get(c);r&&(o={...o,...r},a.delete(c))}s=Array.from(a.keys())}if(s?.length){const a=await M.findAll({where:{id:{[v.Op.in]:s}}});await Promise.all(a.map(async c=>{const r=c.id,p=c.slug||r,d={},E=e==="production"&&c?.productionState?c.productionState:await j.getStateByProjectId(c.id,e),g=Vt.default(P.default.env.languages.map(l=>l.code),E.supportedLocales.map(l=>l.locale)),I=(l,i)=>{p&&(d[R.joinURL("/",p,l)]={...i,shouldRedirect:!0,mainPage:!0}),d[R.joinURL("/",r,l)]={...i,shouldRedirect:!0,mainPage:!0};for(const S of g){const A={...i,locale:S};d[R.joinURL("/",S,r,l)]=A,p&&(d[R.joinURL("/",S,p,l)]=A)}};if(e==="draft")for(const l of E.routeIds||[]){const i=E?.routes?.[l];if(!i)continue;if(i.params&&i.params.length>0){const y=te.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const m of y){const b=m.path,O={projectId:r,projectSlug:p,pageSlug:b,pageId:i.displayTemplateId||"",routeId:l,defaultLocale:g?.[0],locales:g,publishedAt:E.config.publishedAt,isPublic:i.isPublic&&m?.routeMetaData?.isPublic};I(b,O)}}const S=i.path,A={projectId:r,projectSlug:p,pageSlug:S,pageId:i.displayTemplateId||"",routeId:l,defaultLocale:g?.[0],locales:g,publishedAt:E.config.publishedAt,isPublic:i.isPublic};I(S,A)}for(const l of E.pageIds){const i=E.pages[l];if(!i||e==="production"&&!i.isPublic)continue;const S=i.slug,A=c.slug||r,y={projectId:r,projectSlug:A,pageSlug:S,pageId:l,defaultLocale:g?.[0],locales:g,publishedAt:E.config.publishedAt,isPublic:i.isPublic,templateConfig:i.templateConfig};I(S,y)}e==="production"&&j.pageUrlMapCache.set(r,d),o={...o,...d}}))}return o}getDocumentSize(){return $.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const e=[];for(const[n,s]of Object.entries(j.sharedInstances)){const o=s.getDocumentSize();e.push({projectId:n,sizeInBytes:o,sizeInMB:`${(o/(1024*1024)).toFixed(2)} MB`,activeConnections:s.conns.size})}return e}static startPeriodicCheck(){this.periodicCheckTimer||(this.periodicCheckTimer=setInterval(()=>{this.performPeriodicCheck()},this.PERIODIC_CHECK_INTERVAL),f.info(`[SiteState] periodic check started, interval: ${this.PERIODIC_CHECK_INTERVAL/(60*60*1e3)} hours`))}static stopPeriodicCheck(){this.periodicCheckTimer&&(clearInterval(this.periodicCheckTimer),this.periodicCheckTimer=void 0,f.info("[SiteState] periodic check stopped"))}static performPeriodicCheck(){const e=Object.keys(j.sharedInstances).length,n=[],s=[];for(const[o,a]of Object.entries(j.sharedInstances))a.conns.size===0?n.push({projectId:o,instance:a}):s.push({projectId:o,connections:a.conns.size});if(f.info(`[SiteState] periodic check summary: total instances: ${e}, with connections: ${s.length}, without connections: ${n.length}`),n.length>0){f.info(`[SiteState] releasing ${n.length} instances without connections:`,n.map(a=>a.projectId));let o=0;for(const{projectId:a,instance:c}of n)try{f.info(`[SiteState] releasing instance due to periodic check: ${a}`),c.destroy(),o++}catch(r){f.error(`[SiteState] failed to release instance ${a} during periodic check:`,r)}f.info(`[SiteState] periodic check completed: ${o}/${n.length} instances released successfully`)}else e>0?f.debug("[SiteState] periodic check: all instances have active connections"):f.debug("[SiteState] periodic check: no instances exist")}}async function Fn(t,e,n){if(!t||!w.existsSync(t)||!w.lstatSync(t).isFile())return null;let s=n[t];return s||(s=(async()=>{try{return(await _n({filePath:t,fileName:e}))?.data?.filename}catch(o){return f.error(`Failed to upload asset ${t}:`,o),null}})(),n[t]=s),s}const qn=async(t,e)=>{const n=h.basename(t),s=await Ce.call({name:je,path:R.joinURL("/uploads",n),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const o=w.createWriteStream(e);await Mt.pipeline(s.data,o)}else throw new Error(`download asset failed ${s.status}`)},Bn=async(t,e)=>{await Promise.all(t.map(async n=>{try{await qn(n,h.join(e,h.basename(n)))}catch(s){f.error(`Failed to export assets: ${n}, ${s}`)}}))};function et(t){return ve.test(t)?[t]:H.test(t)?(Ue.lastIndex=0,Array.from(t.matchAll(Ue)).map(n=>n[1]).filter(n=>!!n)):[]}async function Z(t,e,n){const{getFilename:s,exportAssets:o}=n,a=h.join(e,s(t));if(w.mkdirSync(h.dirname(a),{recursive:!0}),w.writeFileSync(a,B.stringify(t)),o){const r=re(t,p=>typeof p=="string"&&(ve.test(p)||H.test(p))).map(p=>{const d=Oe.default(t,p);return et(d)}).flat().filter(Boolean);await Bn(r,h.dirname(a))}}const Pe=new le.LRUCache({max:100,ttl:1*60*1e3});async function Fe(t,e,n){const s=re(t,r=>typeof r=="string"&&(ve.test(r)||H.test(r))),o=Gt.default(2),a=s.map(r=>o(async()=>{try{const p=Oe.default(t,r),d=et(p);for(const E of d){const g=h.basename(E),I=n.getFilePath(E,r),l=I?`${I}:${g}`:g,i=Pe.get(l);if(i){H.test(p)||xe.default(t,r,i);return}const S=await Fn(I,g,e);S&&(H.test(p)||xe.default(t,r,S),Pe.set(l,S))}}catch(p){f.error(`Failed to process upload for path ${r.join(".")}:`,p.message||p.reason)}})),c=await Promise.allSettled(a);n.onFinish?.(c)}async function tt(t,{exportAssets:e,pageIds:n="all",componentIds:s="all",rawConfig:o,includeResources:a=!1,routeIds:c="all"}={}){const r=n==="all"?t.pageIds:n,p=W.getComponentDependencies({state:t,pageIds:r,componentIds:s==="all"?Object.keys(t.components):s}),d=c==="all"?t.routeIds:c,E=u=>({id:u.id,name:u.name,isTemplateSection:u.isTemplateSection??!1,templateDescription:u.templateDescription,llmConfig:u.llmConfig,component:u.component,config:u.config,visibility:u.visibility,sections:u?.sectionIds?x(u?.sectionIds?.map(C=>{const D=u.sections?.[C];return D&&E(D)})):void 0}),g=(u,C)=>({id:u.id,createdAt:u.createdAt,updatedAt:u.updatedAt,publishedAt:u.publishedAt,isPublic:u.isPublic??!0,templateConfig:u.templateConfig,meta:u.locales?.[C]??{},sections:x(u.sectionIds.map(D=>{const U=u.sections[D];return U&&E(U)})),dataSource:Object.fromEntries(Object.entries(u.dataSource||{}).map(([D,U])=>[D,U?.[C]??{}]))}),I=u=>({id:u.id,createdAt:u.createdAt,updatedAt:u.updatedAt,publishedAt:u.publishedAt,path:u.path,handler:u.handler,isPublic:u.isPublic??!0,params:u.params??[],enabledGenerate:u.enabledGenerate??!1,displayTemplateId:u.displayTemplateId,dataSource:u.dataSource}),l=x(d.map(u=>{const C=t.routes[u];return C&&I(C)})),i=x(t.supportedLocales.map(u=>u.locale).flatMap(u=>r.map(C=>{const D=t.pages[C];return D&&{locale:u,slug:D.slug,page:g(D,u)}}))),S=Xe(),A=h.join(S,"pages");w.mkdirSync(A,{recursive:!0});const y=h.join(S,"components");w.mkdirSync(y,{recursive:!0});const m=h.join(S,"routes");w.mkdirSync(m,{recursive:!0});for(const{locale:u,slug:C,page:D}of i)await Z(D,A,{getFilename:()=>`${ie(C)||"index"}.${u}.yml`,exportAssets:e});for(const u of l)await Z(u,m,{getFilename:()=>`${ie(u.path)||"index"}.yml`,exportAssets:e});for(const u of p){const C=t.components[u]?.data;C&&await Z(C,y,{getFilename:D=>`${D.name||"unnamed"}.${D.id}.yml`,exportAssets:e})}const b=h.join(S,".blocklet/pages/pages.config.yml");w.mkdirSync(h.dirname(b),{recursive:!0});const O={pages:x(r.map(u=>{const C=t.pages[u];return C&&{id:u,slug:C.slug}})),routes:x(d.map(u=>{const C=t.routes[u];return C&&{id:u,path:C.path}})),components:x(p.map(u=>{const C=t.components[u]?.data;return C&&{id:u,name:C.name}})),...a?{resources:{components:x(Object.keys(t.resources?.components||{}).filter(u=>p.includes(u)).map(u=>({id:u,name:t.resources?.components?.[u]?.component?.name})))}}:{},supportedLocales:t.supportedLocales,config:t.config};w.writeFileSync(b,B.stringify(O));const T=h.join(S,"config.source.json");if(o&&w.writeFileSync(T,JSON.stringify(o)),a){const u=h.join(S,"resources"),C=h.join(u,"components");w.mkdirSync(C,{recursive:!0});for(const G of Object.keys(t?.resources?.components??{}).filter(L=>p.includes(L))){const L=t.resources?.components?.[G]?.component;L&&await Z(L,C,{getFilename:J=>`${J.name||"unnamed"}.${J.id}.yml`,exportAssets:e})}const D=h.join(S,"chunks");w.mkdirSync(D,{recursive:!0});const U=Gn();for(const G of Object.keys(t?.resources?.components??{}).filter(L=>p.includes(L))){const L=t.resources?.components?.[G]?.component;if(L&&L.renderer?.type==="react-component"){const J=L.renderer?.chunks??[];if(J?.length>0)for(const me of J){const De=h.join(D,me),he=U?.[me];try{he&&w.existsSync(he)&&!w.existsSync(De)&&w.copyFileSync(he,De)}catch(lt){f.error(`copy chunk ${me} error`,lt.message)}}}}}return S}async function Vn(t,{importAssets:e,includeResources:n}={}){if(!w.existsSync(t))return null;let s,o=!1;try{w.lstatSync(t).isDirectory()?s=t:/\.(tgz|gz|tar)$/.test(t)&&(o=!0,s=Xe(),await Lt.x({file:t,C:s}));const a=ne.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}).at(0),c=a&&h.join(h.dirname(a),"../../pages"),r=a&&h.join(h.dirname(a),"../../components"),p=a&&h.join(h.dirname(a),"../../routes");if(!a)return null;const d=B.parse(w.readFileSync(a).toString()),E=(y,m,b)=>{let O=h.join(y,`${m}${b?`.${b}`:""}.yml`);return(!w.existsSync(O)||!w.lstatSync(O).isFile())&&(O=h.join(y,m,`index${b?`.${b}`:""}.yml`),!w.existsSync(O)||!w.lstatSync(O))?null:B.parse(w.readFileSync(O).toString())},g=(y,m)=>{try{const b=ne.globSync(`*.${m}.yml`,{cwd:y,absolute:!0})[0];return b?B.parse(w.readFileSync(b).toString()):null}catch(b){f.error("parse component error",b)}return null},I=(y,m)=>{let b=h.join(y,`${m}.yml`);return(!w.existsSync(b)||!w.lstatSync(b).isFile())&&(b=h.join(y,m,"index.yml"),!w.existsSync(b)||!w.lstatSync(b))?null:B.parse(w.readFileSync(b).toString())},l=x(d.pages.map(({slug:y})=>{const m=x(d.supportedLocales.map(({locale:T})=>{const u=c?E(c,ie(y),T):void 0;if(u)return{locale:T,page:u};const C=c?E(c,y,T):void 0;return C&&{locale:T,page:C}})),b=m[0]?.page;if(!b)return null;const O=b.sections.map(At.unzipSection);return{id:b.id||Re.nextId(),createdAt:b.createdAt,updatedAt:b.updatedAt,publishedAt:b.publishedAt,isPublic:b.isPublic??!0,templateConfig:b.templateConfig,slug:y,sections:Object.fromEntries(O.map(T=>[T.id,T])),sectionIds:O.map(T=>T.id),locales:Object.fromEntries(m.map(({locale:T,page:u})=>[T,u.meta])),dataSource:b.dataSource?Object.fromEntries([...new Set(m.flatMap(({page:T})=>Object.keys(T.dataSource??{})))].map(T=>[T,Object.fromEntries(m.map(({locale:u,page:C})=>{const D=C.dataSource?.[T];return[u,D||{}]}))])):Object.fromEntries([...new Set(m.flatMap(({page:T})=>T.sections.map(u=>u.id)))].map(T=>[T,Object.fromEntries(m.map(({locale:u,page:C})=>{const D=C.dataSource?.[T];if(D)return[u,D];const U=C.sections.find(G=>G.id===T);return[u,U?.properties||{}]}))]))}})),i=x(d?.routes?.map(({path:y})=>{const m=p?I(p,ie(y)):void 0;return{...m,id:m?.id||Re.nextId(),createdAt:m?.createdAt??new Date().toISOString(),updatedAt:m?.updatedAt??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:m?.path??`/${m?.id}`,params:m?.params,handler:m?.handler??"Pages Kit",isPublic:m?.isPublic??!0,enabledGenerate:m?.enabledGenerate??!1,displayTemplateId:m?.displayTemplateId??void 0,dataSource:m?.dataSource??{}}})??[]),S=r?x(d.components?.map(({id:y})=>g(r,y))??[]):[];if(e){const y=(...m)=>{f.info(`[${o?h.basename(t):h.basename(h.join(t,"../../../../"))}] importAssets:`,...m)};try{y("wait image-bin api ready"),await Jt.default({resources:[`${Ce.getComponentWebEndpoint(zt)}/api/sdk/uploads`],validateStatus:O=>O>=200&&O<=500}),y("image-bin api is ready");const m={},b={};y("start to upload assets"),await Promise.allSettled([Fe(S,m,{getFilePath:O=>r&&h.join(r,O),onFinish:O=>{y(`upload ${O.length} component assets`)}}),Fe(l,b,{getFilePath:(O,T)=>{const u=Oe.default(l,T.slice(0,1));return c&&h.join(c,h.dirname(u.slug),O)},onFinish:O=>{y(`upload ${O.length} page assets`)}})]),y("upload assets done"),Pe.clear(),global.gc&&global.gc()}catch(m){y("Error during asset import:",m)}}const A={};if(n){const y=a&&h.join(h.dirname(a),"../../resources/components"),m=x(d.resources?.components?.map(({id:b})=>g(y,b))??[]);m.length>0&&(A.components=Object.fromEntries(m.map((b,O)=>[b.id,{index:O,component:b}])))}return{supportedLocales:d.supportedLocales,pageIds:l.map(y=>y.id),components:Object.fromEntries(S.map((y,m)=>[y.id,{index:m,data:y}])),pages:Object.fromEntries(l.map(y=>[y.id,y])),config:d.config||{},resources:A,routeIds:i.map(y=>y.id),routes:Object.fromEntries(i.map(y=>[y.id,y])),dataSourceIds:[],dataSources:{}}}finally{o&&s&&w.rmSync(s,{force:!0,recursive:!0})}}async function qe(t,e,{routes:n,mergeMode:s="byUpdateTime",deleteRoutes:o=!1,publishMode:a=void 0}={}){try{a&&Sn(a)}catch(I){f.error("clear preload page cache error",{error:I})}const{pages:c,pageIds:r,routeIds:p,routes:d,supportedLocales:E}=t;if(a==="production"){let I=n??[],l=null;for(const i of p??[]){const S=d?.[i];if(S?.params&&S?.params.length>0&&S?.paramsOptions&&S?.paramsOptions.length>0){const A=te.generateParamCombinations({basePath:S.path,params:S.params,routeId:S.id,paramsOptions:S.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),y=Object.fromEntries(A.map(m=>[`${i}-${m.paramOptionIds.join("-")}`,m]));l={...l||{},...y},n||(I=[...I,...A.map(m=>`${i}-${m.paramOptionIds.join("-")}`)])}else n||I.push(i)}f.info("routeIds to be published: ",I);for(const i of I){let S=i;if(S.includes("-")){const[m]=S.split("-");S=m}const A=d?.[S];if(!A){const m=e.pageIds.indexOf(S);m!==-1&&o&&(e.pageIds.splice(m,1),delete e.pages[S]);for(const b of e.pageIds)b.includes(`${S}-`)&&(e.pageIds.splice(e.pageIds.indexOf(b),1),delete e.pages[b]);f.info("delete main route page",S);continue}if(i.includes("-")&&!l?.[i]){const m=e.pageIds.indexOf(i);m!==-1&&o&&(e.pageIds.splice(m,1),delete e.pages[i]),f.info("delete page",i);continue}if(!A.displayTemplateId){f.info("no display template",i);continue}const y=c[A.displayTemplateId];if(!y){f.info("no template page",i);continue}if(e.pageIds.includes(i)){if(f.info("has need update page",i),s==="replace")e.pages[i]=Se({page:y,route:A,state:t,routeId:i,routePathInfo:l?.[i]}),f.info("replace page",i);else if(s==="byUpdateTime"){const m=e.pages[A.id];(!m||A.updatedAt&&A.updatedAt>m.updatedAt)&&(e.pages[i]=Se({page:y,route:A,state:t,routeId:i,routePathInfo:l?.[i]}),f.info("replace page by update time",i))}}else e.pageIds.push(i),e.pages[i]=Se({page:y,route:A,state:t,routeId:i,routePathInfo:l?.[i]}),f.info("add page",i)}if(o&&!n)for(const i of e.pageIds)I?.includes(i)||(delete e.pages[i],f.info("delete page",i)),e.pageIds=[...e.pageIds].filter(S=>I?.includes(S))}else{for(const I of r){const l=c[I];if(l)if(e.pageIds.includes(l.id)){if(s==="replace")e.pages[l.id]=l;else if(s==="byUpdateTime"){const i=e.pages[l.id];(!i||l.updatedAt&&l.updatedAt>i.updatedAt)&&(e.pages[l.id]=l)}}else e.pageIds.push(l.id),e.pages[l.id]=l}for(const I of p){const l=d[I];if(l)if(e.routeIds.includes(l.id)){if(s==="replace")e.routes[l.id]=l;else if(s==="byUpdateTime"){const i=e.routes[l.id];(!i||l.updatedAt&&l.updatedAt>i.updatedAt)&&(e.routes[l.id]=l)}}else e.routeIds.push(l.id),e.routes[l.id]=l}}if(e.supportedLocales.splice(0,e.supportedLocales.length),e.supportedLocales.push(...Bt.default(E)),o)for(const I of Object.keys(e.components))delete e.components[I];let g=JSON.parse(JSON.stringify(t.components));g=Object.fromEntries(await Promise.all(Object.entries(g).map(async([I,l])=>{const i=await nt(l?.data);return[I,{...l,data:i}]}))),Object.assign(e.components,g),Object.assign(e.config,JSON.parse(JSON.stringify(t.config))),Ae.default(t.resources.components)||(e.resources.components=JSON.parse(JSON.stringify(t.resources.components||{})))}const nt=ue(async t=>{if(!Ae.default(t?.properties))return t;if(t?.renderer?.type==="react-component"){const{script:e,PROPERTIES_SCHEMA:n}=t?.renderer||{};if(n||e&&e.includes("PROPERTIES_SCHEMA"))try{const s=await An(e??"","PROPERTIES_SCHEMA",t.id,n);s&&s.length>0&&t&&(t.properties={},s.forEach((o,a)=>{t?.properties&&(t.properties[o.id]={index:a,data:o})}))}catch(s){f.error("getPropertiesFromCode error",{componentId:t.id,name:t.name},{error:s})}}return t},{subdir:"getPropertiesFromCode"});let ce,Y,de,fe;const st=()=>Ce.getResources({types:[{did:je,type:Ee},{did:Tn,type:Ee}]}),Gn=()=>{const t=st(),e={};return t.forEach(n=>{const s=ne.globSync("**/.blocklet/pages/pages.config.yml",{cwd:n.path,absolute:!0}).at(0),o=s&&h.join(h.dirname(s),"../../chunks");if(o&&w.existsSync(o)){const a=w.readdirSync(o);for(const c of a)e[c]=h.join(o,c)}}),e};function ot(){return ce=(async()=>{const t=st();Y=(await Promise.all(t.map(async n=>{const s=n.path?await Vn(n.path,{importAssets:!1}):void 0;return s?{blockletId:n.did,state:s,blockletTitle:n.title}:void 0}))).filter(n=>!!n),de=Y.reduce((n,s)=>Object.assign(n,Object.fromEntries(Object.values(s.state.pages).map(o=>o?[o?.id,{page:o,blockletId:s.blockletId}]:[]))),{});const e=Y.reduce((n,s)=>Object.assign(n,Object.fromEntries(Object.values(s.state.components).map(o=>[o.data.id,{blockletId:s.blockletId,component:o.data}]))),{});fe=Object.fromEntries(await Promise.all(Object.entries(e).map(async([n,s])=>{const o=await nt(s.component);return[n,{...s,component:o}]})))})(),ce}function Jn(t){const e=Je.default(async()=>{await ot().catch(n=>{f.error("load resource states error",{error:n})}),await t?.({states:Y,pages:de,components:fe})},3e3,{leading:!1,trailing:!0});return e(),P.default.events.on(P.default.Events.componentAdded,e),P.default.events.on(P.default.Events.componentRemoved,e),P.default.events.on(P.default.Events.componentStarted,e),P.default.events.on(P.default.Events.componentStopped,e),P.default.events.on(P.default.Events.componentUpdated,e),P.default.events.on(Ne,e),()=>{P.default.events.off(P.default.Events.componentAdded,e),P.default.events.off(P.default.Events.componentRemoved,e),P.default.events.off(P.default.Events.componentStarted,e),P.default.events.off(P.default.Events.componentStopped,e),P.default.events.off(P.default.Events.componentUpdated,e),P.default.events.off(Ne,e)}}const at=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),rt=globalThis;rt[at]?.();rt[at]=Jn(async({pages:t,components:e})=>{const n=await j.getProjectIds();f.info(`start update resource states projects(${n.length})`,n),await Promise.race([new Promise(s=>{setTimeout(()=>{s({})},30*1e3)}),Promise.all(n.map(async s=>{it({projectId:s,pages:t,components:e})}))]).catch(s=>{f.error("update resource states failed:",s)})});j.startPeriodicCheck();process.on("beforeExit",()=>{j.stopPeriodicCheck()});process.on("SIGINT",()=>{j.stopPeriodicCheck(),process.exit(0)});process.on("SIGTERM",()=>{j.stopPeriodicCheck(),process.exit(0)});async function it({projectId:t,pages:e,components:n}){const s=j.sharedInstances[t];if(!s){f.info(`projectId: ${t} not found in sharedInstances`);return}if(s.syncedStore.resources.pages=e,(await M.findByPk(t))?.useAllResources)s.syncedStore.resources.components=n;else{const c=(await Te.findAll({where:{projectId:t}})).map(p=>p.componentId),r=Object.fromEntries(Object.entries(n||{}).filter(([p])=>c.includes(p)));s.syncedStore.resources.components=r}f.info(`update [${t}] resource states:`,{pages:Object.keys(s.syncedStore.resources.pages||{}).length,components:Object.keys(s.syncedStore.resources.components||{}).length})}async function ct({ensureLoaded:t=!0}={}){return t&&(ce??=ot(),await ce),{states:Y,pages:de,components:fe}}P.default.events.on(P.default.Events.envUpdate,()=>{j.pageUrlMapCache.clear(),f.info("clear all page url map cache")});exports.COMPONENT_DID=je;exports.Project=M;exports.RESOURCE_TYPE=Ee;exports.SiteState=j;exports.getMultiTenantAllProjectAccessPassports=Ht;exports.getPreloadComponents=In;exports.getResourceStates=ct;exports.isMultiTenant=Kt;exports.logger=f;exports.toPackage=tt;
|
|
57
|
+
`,filename:`${n}.js`,functionName:`get${e}SchemaWrapper`})}catch(r){return f.error(`获取 ${e} 失败`,{componentId:n,error:r}),null}return null},{subdir:"getExportSchemaValueFromCode"}),On="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",Ee="page",Ne="trigger-reload-project-resource",je=On,Tn="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM";function re(t){t.observeDeep(e=>{e.some(n=>n.changes.keys.has("updatedAt")||n.changes.keys.has("publishedAt"))||t.set("updatedAt",new Date().toISOString())})}function Xe(){return w.mkdtempSync(h.join(P.default.env.dataDir,"tmp-"))}function ae(t,e,n=[]){return Array.isArray(t)?t.flatMap((s,o)=>ae(s,e,[...n,o])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([s,o])=>ae(o,e,[...n,s])):e(t)?[n]:[]}function x(t){return t.filter(e=>e!=null)}function jn(t){t.pages&&Object.keys(t.pages).forEach(n=>{const s=F.getYjsValue(t.pages[n]);s&&s instanceof $.Map&&re(s)});const e=F.getYjsValue(t.pages);e&&e instanceof $.Map&&e.observe(n=>{n.changes.keys.forEach((s,o)=>{if(s.action==="add"){const r=F.getYjsValue(t.pages[o]);r&&r instanceof $.Map&&re(r)}})})}function vn(t){t.routes&&Object.keys(t.routes).forEach(n=>{const s=F.getYjsValue(t.routes?.[n]);s&&s instanceof $.Map&&re(s)});const e=F.getYjsValue(t.routes);e&&e instanceof $.Map&&e.observe(n=>{n.changes.keys.forEach((s,o)=>{if(s.action==="add"){const r=F.getYjsValue(t.routes?.[o]);r&&r instanceof $.Map&&re(r)}})})}function Dn(t,e){for(const n of e||Object.keys(t.routes||{})){let s=n,o=[];if(n.includes("-")){const[r,...c]=n.split("-");s=r,o=c||[]}if(t.routes?.[s]!==void 0){t.routes[s].publishedAt=new Date().toISOString();const r=t.routes[s];if(!r||!r.params||r.params.length===0)continue;if(n.includes("-")&&o.length>0){const c=te.getRouteMetaDataByOptionIds(o,r);c&&(c.publishedAt=new Date().toISOString())}if(!e){const c=te.generateParamCombinations({basePath:r.path,params:r.params,routeId:r.id,paramsOptions:r.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const a of c)a.routeMetaData??={},a.routeMetaData.publishedAt=new Date().toISOString()}}}}function Se({page:t,route:e,state:n,routeId:s,routePathInfo:o}){f.info(`Executing datasource data assembly, routeId: ${s}, routePathInfo: ${JSON.stringify(o)}`);const r={...Ct.cloneDeep(t),id:s,slug:o?.path??e.path,createdAt:e.createdAt,updatedAt:o?.routeMetaData?.updatedAt??e.updatedAt,publishedAt:o?.routeMetaData?.publishedAt??e.publishedAt,isPublic:(o?.routeMetaData?.isPublic??e.isPublic)&&e.isPublic};for(const c of n.supportedLocales){if(e.dataSource){let a=e.id;o&&(a=o.paramOptionIds.join("-"));const p=e.dataSource.pathDataMappings?.[a]?.dataCache?.[c.locale]??e.dataSource.pathDataMappings?.[a]?.dataCache?.[n.config.defaultLocale||"en"];if(!p)continue;Pt.setPageDataSource(r,n,c.locale,p)}o&&o.routeMetaData&&(o.routeMetaData.publishedAt=new Date().toISOString())}return r}const V=new le.LRUCache({max:100,ttl:10*60*1e3});function kn(t,e=[]){let n=0;const s=Array.from(V.keys()),o=[];for(const r of t){o.push(`page-html:prod:${r}:lang-path=none`);for(const c of e)o.push(`page-html:prod:/${c}${r}:lang-path=${c}`)}for(const r of s){const c=r.split(":lang-path=")[0]||"";for(const a of o){const d=(a.split(":lang-path=")[0]||"").replace(/\/:[^/]+/g,"");if(c.startsWith(d)){V.delete(r),n++,f.info(`[Cache CLEAR] key: ${r}`);break}}}return f.info(`[Cache CLEAR] cleared ${n} entries for patterns:`,o),n}function Rn({projectId:t,projectSlug:e,supportedLocales:n=[]}){let s=0;const o=Array.from(V.keys()),r=[];r.push(`page-html:prod:/${t}`),e&&e!==t&&r.push(`page-html:prod:/${e}`);for(const c of n)r.push(`page-html:prod:/${c}/${t}`),e&&e!==t&&(e!=="/"?r.push(`page-html:prod:/${c}/${e}`):r.push(`page-html:prod:/${c}`));for(const c of o)for(const a of r)if(c.startsWith(a)){V.delete(c),s++,f.info(`[Cache CLEAR PROJECT] key: ${c}`);break}return f.info(`[Cache CLEAR PROJECT] cleared ${s} entries for project ${t}${e?` (slug: ${e})`:""}`),s}function xn(){const t=V.size;return V.clear(),f.info(`[Cache CLEAR ALL] cleared ${t} entries`),t}P.default.events.on(P.default.Events.envUpdate,xn);const{uploadToMediaKit:_n}=require("@blocklet/uploader-server"),ve=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,H=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Ue=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Mn=1e4,Ln=3e4,Q=0,we=1,$n=0,Nn=1,Ze=P.default,X=h.join(process.env.BLOCKLET_DATA_DIR,"site-state");function ie(t){return t?.replace(/\//g,"|")||""}function Un(){const t=Ze.env.languages.map(n=>({locale:n.code,name:n.name})),e=t[0]?.locale;return{pageIds:[],pages:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{},components:{},supportedLocales:t,config:{defaultLocale:e},resources:{}}}class j extends $.Doc{constructor(e){super(),this.options=e,w.existsSync(this.draftYjsFilePath)&&$.applyUpdate(this,w.readFileSync(this.draftYjsFilePath)),this.syncedStore=Ot.reactive(F.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new z.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static RELEASE_DELAY=5*60*1e3;static PERIODIC_CHECK_INTERVAL=2*60*60*1e3;static sharedInstances={};static pageUrlMapCache=new le.LRUCache({max:100,ttl:1e3*60*60*24});static periodicCheckTimer;static safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const n=h.join(X,e),s=h.join(X,`@del-${e}`);w.renameSync(n,s)}catch(n){f.error("Failed to safe delete project state dir:",n)}}static async getProjectIds(){return(await M.findAll({attributes:["id"],raw:!0})).map(e=>e.id)}static get projectIds(){return ne.globSync("*/",{cwd:X,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*","undefined"]})}static get allShared(){return this.projectIds.map(e=>j.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let n=j.sharedInstances[e];return n||(n=new j({path:h.join(X,e)}),j.sharedInstances[e]=n,it({projectId:e,pages:de,components:fe}),n)}static async getProductionState(e){return(await M.findByPk(e,{attributes:["productionState"]}))?.productionState??Un()}destroy(){this.cancelRelease(),this.save({flush:!0}),this.conns.forEach((n,s)=>this.closeConn(s)),this.awareness.destroy();const e=h.basename(this.options.path);delete j.sharedInstances[e],super.destroy()}initObserver(){jn(this.syncedStore),vn(this.syncedStore)}get draftYjsFilePath(){return h.join(this.options.path,"draft.yjs")}static async getStateByProjectId(e,n){if(n==="draft"){const s=j.shared(e);return JSON.parse(JSON.stringify(s.syncedStore))}return j.getProductionState(e)}async getState(e){if(e==="draft")return JSON.parse(JSON.stringify(this.syncedStore));const n=h.basename(this.options.path);return j.getProductionState(n)}async setState(e,n){const s=await tt(n,{exportAssets:!1,includeResources:!0}),o=this.getPublishDir(e);if(w.mkdirSync(h.dirname(o),{recursive:!0}),w.rmSync(o,{force:!0,recursive:!0}),w.renameSync(s,o),e==="production"){const r=h.basename(this.options.path);j.pageUrlMapCache.delete(r),await M.update({productionState:n},{where:{id:r}})}}getPublishDir(e){return h.join(this.options.path,e)}syncedStore;conns=new Map;awareness;releaseTimer;awarenessChangeHandler=({added:e,updated:n,removed:s},o)=>{const r=e.concat(n,s);if(o!==null){const p=this.conns.get(o);p&&(e.forEach(d=>{p.add(d)}),s.forEach(d=>{p.delete(d)}))}const c=k.createEncoder();k.writeVarUint(c,we),k.writeVarUint8Array(c,z.encodeAwarenessUpdate(this.awareness,r));const a=k.toUint8Array(c);this.conns.forEach((p,d)=>this.send(d,a))};updateHandler=e=>{const n=k.createEncoder();k.writeVarUint(n,Q),ge.writeUpdate(n,e);const s=k.toUint8Array(n);this.conns.forEach((o,r)=>this.send(r,s))};ensureDataStructure=()=>{const{supportedLocales:e,pages:n,pageIds:s,config:o,routes:r,routeIds:c}=this.syncedStore;{const a=new Set(Object.keys(n));let p=0;for(;p<s.length;){const d=s[p];a.has(d)?(a.delete(d),p++):s.splice(p,1)}}{const a=new Set(Object.keys(r));let p=0;for(;p<c.length;){const d=c[p];a.has(d)?(a.delete(d),p++):c.splice(p,1)}}e.splice(0,e.length),e.push(...Ze.env.languages.map(a=>({locale:a.code,name:a.name}))),o.defaultLocale=e[0]?.locale;{let a=0;const p=new Set;for(;a<e.length;){const{locale:d}=e[a];p.has(d)?e.splice(a,1):(a++,p.add(d))}}};send=(e,n)=>{e.readyState!==$n&&e.readyState!==Nn&&this.closeConn(e);try{e.send(n,s=>{s&&this.closeConn(e)})}catch{this.closeConn(e)}};closeConn=e=>{if(e.removeAllListeners(),this.conns.has(e)){const n=this.conns.get(e);this.conns.delete(e),n&&z.removeAwarenessStates(this.awareness,Array.from(n),null)}e.close(),this.checkAndScheduleRelease()};checkAndScheduleRelease(){this.conns.size===0&&this.scheduleRelease()}scheduleRelease(){this.cancelRelease();const e=h.basename(this.options.path);this.releaseTimer=setTimeout(()=>{f.info(`[SiteState] releasing instance due to no active connections: ${e}`),this.conns.size===0&&(this.releaseTimer=void 0,this.destroy())},j.RELEASE_DELAY),f.info(`[SiteState] scheduled release for project ${e} in ${j.RELEASE_DELAY/1e3}s`)}cancelRelease(){if(this.releaseTimer){clearTimeout(this.releaseTimer),this.releaseTimer=void 0;const e=h.basename(this.options.path);f.info(`[SiteState] cancelled scheduled release for project ${e}`)}}autoSave=Je.default(()=>{w.mkdirSync(h.dirname(this.draftYjsFilePath),{recursive:!0}),w.writeFileSync(this.draftYjsFilePath,$.encodeStateAsUpdate(this))},Mn);save=({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()};publish=async({mode:e,routes:n})=>{const s=await this.getState("draft"),o=await this.getState("production");await qe(s,o,{routes:n,mergeMode:"replace",deleteRoutes:!0,publishMode:e}),o.config.publishedAt=new Date().getTime(),Dn(this.syncedStore,n),await this.setState(e,o),await this.clearPageCacheForRoutes(n,o)};mergeState=async(e,n)=>{const s=JSON.parse(JSON.stringify(n));e.config.fontFamily??={};const o=s.config?.fontFamily,r=e.config?.fontFamily;e.config.fontFamily.title=o?.title||r?.title,e.config.fontFamily.description=o?.description||r?.description,await new Promise((c,a)=>{this.transact(async()=>{try{const p=await qe(e,n);c(p)}catch(p){a(p)}})})};clearPageCacheForRoutes=async(e,n)=>{const s=h.basename(this.options.path),r=(await M.findByPk(s))?.slug||s;if(f.info(`[SiteState] clearing page cache for project ${s}, routes:`,e||[]),!e||e.length===0){Rn({projectId:s,projectSlug:r,supportedLocales:n.supportedLocales.map(d=>d.locale)});return}const c=n.supportedLocales.map(d=>d.locale),a=[],p=e.filter(d=>n.pages[d]);for(const d of p){const g=n.pages[d].slug;r&&r!==s&&(r==="/"?a.push(g):a.push(`/${r}${g}`)),a.push(`/${s}${g}`)}if(f.info(`[SiteState] clearing page cache for project ${s}, pathPatterns:`,a),a.length>0){const d=kn(a,c);f.info(`[SiteState] cleared ${d} page cache entries for project ${s}, routes:`,e)}};addConnection=e=>{if(this.conns.has(e))return;this.cancelRelease(),e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",o=>this.messageListener(e,new Uint8Array(o)));let n=!0;const s=setInterval(()=>{if(!n)this.conns.has(e)&&this.closeConn(e),clearInterval(s);else if(this.conns.has(e)){n=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(s)}}},Ln);e.on("close",()=>{this.closeConn(e),clearInterval(s)}),e.on("pong",()=>{n=!0});{const o=k.createEncoder();k.writeVarUint(o,Q),ge.writeSyncStep1(o,this),this.send(e,k.toUint8Array(o));const r=this.awareness.getStates();if(r.size>0){const c=k.createEncoder();k.writeVarUint(c,we),k.writeVarUint8Array(c,z.encodeAwarenessUpdate(this.awareness,Array.from(r.keys()))),this.send(e,k.toUint8Array(c))}}};messageListener=(e,n)=>{try{const s=k.createEncoder(),o=ye.createDecoder(n),r=ye.readVarUint(o);switch(r){case Q:k.writeVarUint(s,Q),ge.readSyncMessage(o,s,this,null),k.length(s)>1&&(this.ensureDataStructure(),this.send(e,k.toUint8Array(s)));break;case we:{z.applyAwarenessUpdate(this.awareness,ye.readVarUint8Array(o),e);break}default:f.warn(`Unsupported messageType ${r}`)}}catch(s){f.error(s)}this.save()};static async pageUrlMap(e,n){let s=[];n?s=[n]:s=await this.getProjectIds();let o={};if(e==="production"&&s?.length){const r=new Map(s.map(c=>[c,!0]));for(const c of s){const a=j.pageUrlMapCache.get(c);a&&(o={...o,...a},r.delete(c))}s=Array.from(r.keys())}if(s?.length){const r=await M.findAll({where:{id:{[v.Op.in]:s}}});await Promise.all(r.map(async c=>{const a=c.id,p=c.slug||a,d={},E=e==="production"&&c?.productionState?c.productionState:await j.getStateByProjectId(c.id,e),g=Vt.default(P.default.env.languages.map(l=>l.code),E.supportedLocales.map(l=>l.locale)),b=(l,i)=>{p&&(d[R.joinURL("/",p,l)]={...i,shouldRedirect:!0,mainPage:!0}),d[R.joinURL("/",a,l)]={...i,shouldRedirect:!0,mainPage:!0};for(const S of g){const A={...i,locale:S};d[R.joinURL("/",S,a,l)]=A,p&&(d[R.joinURL("/",S,p,l)]=A)}};if(e==="draft")for(const l of E.routeIds||[]){const i=E?.routes?.[l];if(!i)continue;if(i.params&&i.params.length>0){const y=te.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const m of y){const I=m.path,O={projectId:a,projectSlug:p,pageSlug:I,pageId:i.displayTemplateId||"",routeId:l,defaultLocale:g?.[0],locales:g,publishedAt:E.config.publishedAt,isPublic:i.isPublic&&m?.routeMetaData?.isPublic};b(I,O)}}const S=i.path,A={projectId:a,projectSlug:p,pageSlug:S,pageId:i.displayTemplateId||"",routeId:l,defaultLocale:g?.[0],locales:g,publishedAt:E.config.publishedAt,isPublic:i.isPublic};b(S,A)}for(const l of E.pageIds){const i=E.pages[l];if(!i||e==="production"&&!i.isPublic)continue;const S=i.slug,A=c.slug||a,y={projectId:a,projectSlug:A,pageSlug:S,pageId:l,defaultLocale:g?.[0],locales:g,publishedAt:E.config.publishedAt,isPublic:i.isPublic,templateConfig:i.templateConfig};b(S,y)}e==="production"&&j.pageUrlMapCache.set(a,d),o={...o,...d}}))}return o}getDocumentSize(){return $.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const e=[];for(const[n,s]of Object.entries(j.sharedInstances)){const o=s.getDocumentSize();e.push({projectId:n,sizeInBytes:o,sizeInMB:`${(o/(1024*1024)).toFixed(2)} MB`,activeConnections:s.conns.size})}return e}static startPeriodicCheck(){this.periodicCheckTimer||(this.periodicCheckTimer=setInterval(()=>{this.performPeriodicCheck()},this.PERIODIC_CHECK_INTERVAL),f.info(`[SiteState] periodic check started, interval: ${this.PERIODIC_CHECK_INTERVAL/(60*60*1e3)} hours`))}static stopPeriodicCheck(){this.periodicCheckTimer&&(clearInterval(this.periodicCheckTimer),this.periodicCheckTimer=void 0,f.info("[SiteState] periodic check stopped"))}static performPeriodicCheck(){const e=Object.keys(j.sharedInstances).length,n=[],s=[];for(const[o,r]of Object.entries(j.sharedInstances))r.conns.size===0?n.push({projectId:o,instance:r}):s.push({projectId:o,connections:r.conns.size});if(f.info(`[SiteState] periodic check summary: total instances: ${e}, with connections: ${s.length}, without connections: ${n.length}`),n.length>0){f.info(`[SiteState] releasing ${n.length} instances without connections:`,n.map(r=>r.projectId));let o=0;for(const{projectId:r,instance:c}of n)try{f.info(`[SiteState] releasing instance due to periodic check: ${r}`),c.destroy(),o++}catch(a){f.error(`[SiteState] failed to release instance ${r} during periodic check:`,a)}f.info(`[SiteState] periodic check completed: ${o}/${n.length} instances released successfully`)}else e>0?f.debug("[SiteState] periodic check: all instances have active connections"):f.debug("[SiteState] periodic check: no instances exist")}}async function Fn(t,e,n){if(!t||!w.existsSync(t)||!w.lstatSync(t).isFile())return null;let s=n[t];return s||(s=(async()=>{try{return(await _n({filePath:t,fileName:e}))?.data?.filename}catch(o){return f.error(`Failed to upload asset ${t}:`,o),null}})(),n[t]=s),s}const qn=async(t,e)=>{const n=h.basename(t),s=await Ce.call({name:je,path:R.joinURL("/uploads",n),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const o=w.createWriteStream(e);await Mt.pipeline(s.data,o)}else throw new Error(`download asset failed ${s.status}`)},Bn=async(t,e)=>{await Promise.all(t.map(async n=>{try{await qn(n,h.join(e,h.basename(n)))}catch(s){f.error(`Failed to export assets: ${n}, ${s}`)}}))};function et(t){return ve.test(t)?[t]:H.test(t)?(Ue.lastIndex=0,Array.from(t.matchAll(Ue)).map(n=>n[1]).filter(n=>!!n)):[]}async function Z(t,e,n){const{getFilename:s,exportAssets:o}=n,r=h.join(e,s(t));if(w.mkdirSync(h.dirname(r),{recursive:!0}),w.writeFileSync(r,B.stringify(t)),o){const a=ae(t,p=>typeof p=="string"&&(ve.test(p)||H.test(p))).map(p=>{const d=Oe.default(t,p);return et(d)}).flat().filter(Boolean);await Bn(a,h.dirname(r))}}const Pe=new le.LRUCache({max:100,ttl:1*60*1e3});async function Fe(t,e,n){const s=ae(t,a=>typeof a=="string"&&(ve.test(a)||H.test(a))),o=Gt.default(2),r=s.map(a=>o(async()=>{try{const p=Oe.default(t,a),d=et(p);for(const E of d){const g=h.basename(E),b=n.getFilePath(E,a),l=b?`${b}:${g}`:g,i=Pe.get(l);if(i){H.test(p)||xe.default(t,a,i);return}const S=await Fn(b,g,e);S&&(H.test(p)||xe.default(t,a,S),Pe.set(l,S))}}catch(p){f.error(`Failed to process upload for path ${a.join(".")}:`,p.message||p.reason)}})),c=await Promise.allSettled(r);n.onFinish?.(c)}async function tt(t,{exportAssets:e,pageIds:n="all",componentIds:s="all",rawConfig:o,includeResources:r=!1,routeIds:c="all"}={}){const a=n==="all"?t.pageIds:n,p=W.getComponentDependencies({state:t,pageIds:a,componentIds:s==="all"?Object.keys(t.components):s}),d=c==="all"?t.routeIds:c,E=u=>({id:u.id,name:u.name,isTemplateSection:u.isTemplateSection??!1,templateDescription:u.templateDescription,llmConfig:u.llmConfig,component:u.component,config:u.config,visibility:u.visibility,sections:u?.sectionIds?x(u?.sectionIds?.map(C=>{const D=u.sections?.[C];return D&&E(D)})):void 0}),g=(u,C)=>({id:u.id,createdAt:u.createdAt,updatedAt:u.updatedAt,publishedAt:u.publishedAt,isPublic:u.isPublic??!0,templateConfig:u.templateConfig,meta:u.locales?.[C]??{},sections:x(u.sectionIds.map(D=>{const U=u.sections[D];return U&&E(U)})),dataSource:Object.fromEntries(Object.entries(u.dataSource||{}).map(([D,U])=>[D,U?.[C]??{}]))}),b=u=>({id:u.id,createdAt:u.createdAt,updatedAt:u.updatedAt,publishedAt:u.publishedAt,path:u.path,handler:u.handler,isPublic:u.isPublic??!0,params:u.params??[],enabledGenerate:u.enabledGenerate??!1,displayTemplateId:u.displayTemplateId,dataSource:u.dataSource}),l=x(d.map(u=>{const C=t.routes[u];return C&&b(C)})),i=x(t.supportedLocales.map(u=>u.locale).flatMap(u=>a.map(C=>{const D=t.pages[C];return D&&{locale:u,slug:D.slug,page:g(D,u)}}))),S=Xe(),A=h.join(S,"pages");w.mkdirSync(A,{recursive:!0});const y=h.join(S,"components");w.mkdirSync(y,{recursive:!0});const m=h.join(S,"routes");w.mkdirSync(m,{recursive:!0});for(const{locale:u,slug:C,page:D}of i)await Z(D,A,{getFilename:()=>`${ie(C)||"index"}.${u}.yml`,exportAssets:e});for(const u of l)await Z(u,m,{getFilename:()=>`${ie(u.path)||"index"}.yml`,exportAssets:e});for(const u of p){const C=t.components[u]?.data;C&&await Z(C,y,{getFilename:D=>`${D.name||"unnamed"}.${D.id}.yml`,exportAssets:e})}const I=h.join(S,".blocklet/pages/pages.config.yml");w.mkdirSync(h.dirname(I),{recursive:!0});const O={pages:x(a.map(u=>{const C=t.pages[u];return C&&{id:u,slug:C.slug}})),routes:x(d.map(u=>{const C=t.routes[u];return C&&{id:u,path:C.path}})),components:x(p.map(u=>{const C=t.components[u]?.data;return C&&{id:u,name:C.name}})),...r?{resources:{components:x(Object.keys(t.resources?.components||{}).filter(u=>p.includes(u)).map(u=>({id:u,name:t.resources?.components?.[u]?.component?.name})))}}:{},supportedLocales:t.supportedLocales,config:t.config};w.writeFileSync(I,B.stringify(O));const T=h.join(S,"config.source.json");if(o&&w.writeFileSync(T,JSON.stringify(o)),r){const u=h.join(S,"resources"),C=h.join(u,"components");w.mkdirSync(C,{recursive:!0});for(const G of Object.keys(t?.resources?.components??{}).filter(L=>p.includes(L))){const L=t.resources?.components?.[G]?.component;L&&await Z(L,C,{getFilename:J=>`${J.name||"unnamed"}.${J.id}.yml`,exportAssets:e})}const D=h.join(S,"chunks");w.mkdirSync(D,{recursive:!0});const U=Gn();for(const G of Object.keys(t?.resources?.components??{}).filter(L=>p.includes(L))){const L=t.resources?.components?.[G]?.component;if(L&&L.renderer?.type==="react-component"){const J=L.renderer?.chunks??[];if(J?.length>0)for(const me of J){const De=h.join(D,me),he=U?.[me];try{he&&w.existsSync(he)&&!w.existsSync(De)&&w.copyFileSync(he,De)}catch(lt){f.error(`copy chunk ${me} error`,lt.message)}}}}}return S}async function Vn(t,{importAssets:e,includeResources:n}={}){if(!w.existsSync(t))return null;let s,o=!1;try{w.lstatSync(t).isDirectory()?s=t:/\.(tgz|gz|tar)$/.test(t)&&(o=!0,s=Xe(),await Lt.x({file:t,C:s}));const r=ne.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}).at(0),c=r&&h.join(h.dirname(r),"../../pages"),a=r&&h.join(h.dirname(r),"../../components"),p=r&&h.join(h.dirname(r),"../../routes");if(!r)return null;const d=B.parse(w.readFileSync(r).toString()),E=(y,m,I)=>{let O=h.join(y,`${m}${I?`.${I}`:""}.yml`);return(!w.existsSync(O)||!w.lstatSync(O).isFile())&&(O=h.join(y,m,`index${I?`.${I}`:""}.yml`),!w.existsSync(O)||!w.lstatSync(O))?null:B.parse(w.readFileSync(O).toString())},g=(y,m)=>{try{const I=ne.globSync(`*.${m}.yml`,{cwd:y,absolute:!0})[0];return I?B.parse(w.readFileSync(I).toString()):null}catch(I){f.error("parse component error",I)}return null},b=(y,m)=>{let I=h.join(y,`${m}.yml`);return(!w.existsSync(I)||!w.lstatSync(I).isFile())&&(I=h.join(y,m,"index.yml"),!w.existsSync(I)||!w.lstatSync(I))?null:B.parse(w.readFileSync(I).toString())},l=x(d.pages.map(({slug:y})=>{const m=x(d.supportedLocales.map(({locale:T})=>{const u=c?E(c,ie(y),T):void 0;if(u)return{locale:T,page:u};const C=c?E(c,y,T):void 0;return C&&{locale:T,page:C}})),I=m[0]?.page;if(!I)return null;const O=I.sections.map(At.unzipSection);return{id:I.id||Re.nextId(),createdAt:I.createdAt,updatedAt:I.updatedAt,publishedAt:I.publishedAt,isPublic:I.isPublic??!0,templateConfig:I.templateConfig,slug:y,sections:Object.fromEntries(O.map(T=>[T.id,T])),sectionIds:O.map(T=>T.id),locales:Object.fromEntries(m.map(({locale:T,page:u})=>[T,u.meta])),dataSource:I.dataSource?Object.fromEntries([...new Set(m.flatMap(({page:T})=>Object.keys(T.dataSource??{})))].map(T=>[T,Object.fromEntries(m.map(({locale:u,page:C})=>{const D=C.dataSource?.[T];return[u,D||{}]}))])):Object.fromEntries([...new Set(m.flatMap(({page:T})=>T.sections.map(u=>u.id)))].map(T=>[T,Object.fromEntries(m.map(({locale:u,page:C})=>{const D=C.dataSource?.[T];if(D)return[u,D];const U=C.sections.find(G=>G.id===T);return[u,U?.properties||{}]}))]))}})),i=x(d?.routes?.map(({path:y})=>{const m=p?b(p,ie(y)):void 0;return{...m,id:m?.id||Re.nextId(),createdAt:m?.createdAt??new Date().toISOString(),updatedAt:m?.updatedAt??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:m?.path??`/${m?.id}`,params:m?.params,handler:m?.handler??"Pages Kit",isPublic:m?.isPublic??!0,enabledGenerate:m?.enabledGenerate??!1,displayTemplateId:m?.displayTemplateId??void 0,dataSource:m?.dataSource??{}}})??[]),S=a?x(d.components?.map(({id:y})=>g(a,y))??[]):[];if(e){const y=(...m)=>{f.info(`[${o?h.basename(t):h.basename(h.join(t,"../../../../"))}] importAssets:`,...m)};try{y("wait image-bin api ready"),await Jt.default({resources:[`${Ce.getComponentWebEndpoint(zt)}/api/sdk/uploads`],validateStatus:O=>O>=200&&O<=500}),y("image-bin api is ready");const m={},I={};y("start to upload assets"),await Promise.allSettled([Fe(S,m,{getFilePath:O=>a&&h.join(a,O),onFinish:O=>{y(`upload ${O.length} component assets`)}}),Fe(l,I,{getFilePath:(O,T)=>{const u=Oe.default(l,T.slice(0,1));return c&&h.join(c,h.dirname(u.slug),O)},onFinish:O=>{y(`upload ${O.length} page assets`)}})]),y("upload assets done"),Pe.clear(),global.gc&&global.gc()}catch(m){y("Error during asset import:",m)}}const A={};if(n){const y=r&&h.join(h.dirname(r),"../../resources/components"),m=x(d.resources?.components?.map(({id:I})=>g(y,I))??[]);m.length>0&&(A.components=Object.fromEntries(m.map((I,O)=>[I.id,{index:O,component:I}])))}return{supportedLocales:d.supportedLocales,pageIds:l.map(y=>y.id),components:Object.fromEntries(S.map((y,m)=>[y.id,{index:m,data:y}])),pages:Object.fromEntries(l.map(y=>[y.id,y])),config:d.config||{},resources:A,routeIds:i.map(y=>y.id),routes:Object.fromEntries(i.map(y=>[y.id,y])),dataSourceIds:[],dataSources:{}}}finally{o&&s&&w.rmSync(s,{force:!0,recursive:!0})}}async function qe(t,e,{routes:n,mergeMode:s="byUpdateTime",deleteRoutes:o=!1,publishMode:r=void 0}={}){try{r&&Sn(r)}catch(b){f.error("clear preload page cache error",{error:b})}const{pages:c,pageIds:a,routeIds:p,routes:d,supportedLocales:E}=t;if(r==="production"){let b=n??[],l=null;for(const i of p??[]){const S=d?.[i];if(S?.params&&S?.params.length>0&&S?.paramsOptions&&S?.paramsOptions.length>0){const A=te.generateParamCombinations({basePath:S.path,params:S.params,routeId:S.id,paramsOptions:S.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),y=Object.fromEntries(A.map(m=>[`${i}-${m.paramOptionIds.join("-")}`,m]));l={...l||{},...y},n||(b=[...b,...A.map(m=>`${i}-${m.paramOptionIds.join("-")}`)])}else n||b.push(i)}f.info("routeIds to be published: ",b);for(const i of b){let S=i;if(S.includes("-")){const[m]=S.split("-");S=m}const A=d?.[S];if(!A){const m=e.pageIds.indexOf(S);m!==-1&&o&&(e.pageIds.splice(m,1),delete e.pages[S]);for(const I of e.pageIds)I.includes(`${S}-`)&&(e.pageIds.splice(e.pageIds.indexOf(I),1),delete e.pages[I]);f.info("delete main route page",S);continue}if(i.includes("-")&&!l?.[i]){const m=e.pageIds.indexOf(i);m!==-1&&o&&(e.pageIds.splice(m,1),delete e.pages[i]),f.info("delete page",i);continue}if(!A.displayTemplateId){f.info("no display template",i);continue}const y=c[A.displayTemplateId];if(!y){f.info("no template page",i);continue}if(e.pageIds.includes(i)){if(f.info("has need update page",i),s==="replace")e.pages[i]=Se({page:y,route:A,state:t,routeId:i,routePathInfo:l?.[i]}),f.info("replace page",i);else if(s==="byUpdateTime"){const m=e.pages[A.id];(!m||A.updatedAt&&A.updatedAt>m.updatedAt)&&(e.pages[i]=Se({page:y,route:A,state:t,routeId:i,routePathInfo:l?.[i]}),f.info("replace page by update time",i))}}else e.pageIds.push(i),e.pages[i]=Se({page:y,route:A,state:t,routeId:i,routePathInfo:l?.[i]}),f.info("add page",i)}if(o&&!n)for(const i of e.pageIds)b?.includes(i)||(delete e.pages[i],f.info("delete page",i)),e.pageIds=[...e.pageIds].filter(S=>b?.includes(S))}else{for(const b of a){const l=c[b];if(l)if(e.pageIds.includes(l.id)){if(s==="replace")e.pages[l.id]=l;else if(s==="byUpdateTime"){const i=e.pages[l.id];(!i||l.updatedAt&&l.updatedAt>i.updatedAt)&&(e.pages[l.id]=l)}}else e.pageIds.push(l.id),e.pages[l.id]=l}for(const b of p){const l=d[b];if(l)if(e.routeIds.includes(l.id)){if(s==="replace")e.routes[l.id]=l;else if(s==="byUpdateTime"){const i=e.routes[l.id];(!i||l.updatedAt&&l.updatedAt>i.updatedAt)&&(e.routes[l.id]=l)}}else e.routeIds.push(l.id),e.routes[l.id]=l}}if(e.supportedLocales.splice(0,e.supportedLocales.length),e.supportedLocales.push(...Bt.default(E)),o)for(const b of Object.keys(e.components))delete e.components[b];let g=JSON.parse(JSON.stringify(t.components));g=Object.fromEntries(await Promise.all(Object.entries(g).map(async([b,l])=>{const i=await nt(l?.data);return[b,{...l,data:i}]}))),Object.assign(e.components,g),Object.assign(e.config,JSON.parse(JSON.stringify(t.config))),Ae.default(t.resources.components)||(e.resources.components=JSON.parse(JSON.stringify(t.resources.components||{})))}const nt=ue(async t=>{if(!Ae.default(t?.properties))return t;if(t?.renderer?.type==="react-component"){const{script:e,PROPERTIES_SCHEMA:n}=t?.renderer||{};if(n||e&&e.includes("PROPERTIES_SCHEMA"))try{const s=await An(e??"","PROPERTIES_SCHEMA",t.id,n);s&&s.length>0&&t&&(t.properties={},s.forEach((o,r)=>{t?.properties&&(t.properties[o.id]={index:r,data:o})}))}catch(s){f.error("getPropertiesFromCode error",{componentId:t.id,name:t.name},{error:s})}}return t},{subdir:"getPropertiesFromCode"});let ce,Y,de,fe;const st=()=>Ce.getResources({types:[{did:je,type:Ee},{did:Tn,type:Ee}]}),Gn=()=>{const t=st(),e={};return t.forEach(n=>{const s=ne.globSync("**/.blocklet/pages/pages.config.yml",{cwd:n.path,absolute:!0}).at(0),o=s&&h.join(h.dirname(s),"../../chunks");if(o&&w.existsSync(o)){const r=w.readdirSync(o);for(const c of r)e[c]=h.join(o,c)}}),e};function ot(){return ce=(async()=>{const t=st();Y=(await Promise.all(t.map(async n=>{const s=n.path?await Vn(n.path,{importAssets:!1}):void 0;return s?{blockletId:n.did,state:s,blockletTitle:n.title}:void 0}))).filter(n=>!!n),de=Y.reduce((n,s)=>Object.assign(n,Object.fromEntries(Object.values(s.state.pages).map(o=>o?[o?.id,{page:o,blockletId:s.blockletId}]:[]))),{});const e=Y.reduce((n,s)=>Object.assign(n,Object.fromEntries(Object.values(s.state.components).map(o=>[o.data.id,{blockletId:s.blockletId,component:o.data}]))),{});fe=Object.fromEntries(await Promise.all(Object.entries(e).map(async([n,s])=>{const o=await nt(s.component);return[n,{...s,component:o}]})))})(),ce}function Jn(t){const e=Je.default(async()=>{await ot().catch(n=>{f.error("load resource states error",{error:n})}),await t?.({states:Y,pages:de,components:fe})},3e3,{leading:!1,trailing:!0});return e(),P.default.events.on(P.default.Events.componentAdded,e),P.default.events.on(P.default.Events.componentRemoved,e),P.default.events.on(P.default.Events.componentStarted,e),P.default.events.on(P.default.Events.componentStopped,e),P.default.events.on(P.default.Events.componentUpdated,e),P.default.events.on(Ne,e),()=>{P.default.events.off(P.default.Events.componentAdded,e),P.default.events.off(P.default.Events.componentRemoved,e),P.default.events.off(P.default.Events.componentStarted,e),P.default.events.off(P.default.Events.componentStopped,e),P.default.events.off(P.default.Events.componentUpdated,e),P.default.events.off(Ne,e)}}const rt=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),at=globalThis;at[rt]?.();at[rt]=Jn(async({pages:t,components:e})=>{const n=await j.getProjectIds();f.info(`start update resource states projects(${n.length})`,n),await Promise.race([new Promise(s=>{setTimeout(()=>{s({})},30*1e3)}),Promise.all(n.map(async s=>{it({projectId:s,pages:t,components:e})}))]).catch(s=>{f.error("update resource states failed:",s)})});j.startPeriodicCheck();process.on("beforeExit",()=>{j.stopPeriodicCheck()});process.on("SIGINT",()=>{j.stopPeriodicCheck(),process.exit(0)});process.on("SIGTERM",()=>{j.stopPeriodicCheck(),process.exit(0)});async function it({projectId:t,pages:e,components:n}){const s=j.sharedInstances[t];if(!s){f.info(`projectId: ${t} not found in sharedInstances`);return}if(s.syncedStore.resources.pages=e,(await M.findByPk(t))?.useAllResources)s.syncedStore.resources.components=n;else{const c=(await Te.findAll({where:{projectId:t}})).map(p=>p.componentId),a=Object.fromEntries(Object.entries(n||{}).filter(([p])=>c.includes(p)));s.syncedStore.resources.components=a}f.info(`update [${t}] resource states:`,{pages:Object.keys(s.syncedStore.resources.pages||{}).length,components:Object.keys(s.syncedStore.resources.components||{}).length})}async function ct({ensureLoaded:t=!0}={}){return t&&(ce??=ot(),await ce),{states:Y,pages:de,components:fe}}P.default.events.on(P.default.Events.envUpdate,()=>{j.pageUrlMapCache.clear(),f.info("clear all page url map cache")});exports.COMPONENT_DID=je;exports.Project=M;exports.RESOURCE_TYPE=Ee;exports.SiteState=j;exports.getMultiTenantAllProjectAccessPassports=Ht;exports.getPreloadComponents=bn;exports.getResourceStates=ct;exports.isMultiTenant=Kt;exports.logger=f;exports.toPackage=tt;
|
package/lib/cjs/project-html.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var B=Object.create;var $=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,O=Object.prototype.hasOwnProperty;var F=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of U(e))!O.call(t,o)&&o!==n&&$(t,o,{get:()=>e[o],enumerable:!(s=N(e,o))||s.enumerable});return t};var R=(t,e,n)=>(n=t!=null?B(L(t)):{},F(e||!t||!t.__esModule?$(n,"default",{value:t,enumerable:!0}):n,t));const z=require("@arcblock/did-auth-storage-nedb"),x=require("@blocklet/sdk/lib/config"),G=require("@blocklet/sdk/lib/service/auth"),J=require("@blocklet/sdk/lib/wallet"),Y=require("@blocklet/sdk/lib/wallet-authenticator"),Q=require("@blocklet/sdk/lib/wallet-handler"),I=require("path"),b=require("./chunks/site-state-
|
|
1
|
+
"use strict";var B=Object.create;var $=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,O=Object.prototype.hasOwnProperty;var F=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of U(e))!O.call(t,o)&&o!==n&&$(t,o,{get:()=>e[o],enumerable:!(s=N(e,o))||s.enumerable});return t};var R=(t,e,n)=>(n=t!=null?B(L(t)):{},F(e||!t||!t.__esModule?$(n,"default",{value:t,enumerable:!0}):n,t));const z=require("@arcblock/did-auth-storage-nedb"),x=require("@blocklet/sdk/lib/config"),G=require("@blocklet/sdk/lib/service/auth"),J=require("@blocklet/sdk/lib/wallet"),Y=require("@blocklet/sdk/lib/wallet-authenticator"),Q=require("@blocklet/sdk/lib/wallet-handler"),I=require("path"),b=require("./chunks/site-state-BG2d2tBl.js"),V=require("crypto"),X=require("@arcblock/crawler-middleware"),Z=require("@blocklet/pages-kit/types"),ee=require("@blocklet/pages-kit/utils/common"),j=require("@blocklet/pages-kit/utils/preload"),te=require("@blocklet/sdk/lib/component"),ne=require("express"),E=require("fs"),oe=require("lodash/get"),ae=require("mustache"),A=require("ufo"),i=t=>t&&t.__esModule?t:{default:t},se=i(z),r=i(x),re=i(G),ce=i(J),le=i(Y),ie=i(Q),de=i(I),ue=i(oe),pe=i(ae),he=(t={})=>{const e={data:new Map,timers:new Map,set:(n,s,o=t.ttl||36e5)=>{t.max&&e.data.size>=t.max&&e.delete(e.data.keys().next().value),e.timers.has(n)&&clearTimeout(e.timers.get(n)),e.timers.set(n,setTimeout(()=>e.delete(n),o)),e.data.set(n,s)},get:n=>e.data.get(n),has:n=>e.data.has(n),delete:n=>(e.timers.has(n)&&clearTimeout(e.timers.get(n)),e.timers.delete(n),e.data.delete(n)),clear:()=>{e.data.clear();for(const n of e.timers.values())clearTimeout(n);e.timers.clear()}};return e},P=he({max:1,ttl:1e3*30});ce.default();const fe=new le.default;new ie.default({authenticator:fe,tokenStorage:new se.default({dbPath:de.default.join(r.default.env.dataDir,"auth.db")})});const me=new re.default,ge=async()=>{try{const t=P.get("blockletInfo");if(t)return t;const{blocklet:e}=await me.getBlocklet();return P.set("blockletInfo",e),e}catch{return null}},_e=async()=>await import("cheerio"),C={};function ye(t,e){const n=JSON.stringify([t,e]);return V.createHash("md5").update(n).digest("hex")}async function we(t,e){{const s=(await _e()).load(t);return e.forEach(o=>{s(o.selector.cheerio).replaceWith(o.value)}),s.html()}}async function ve(t,e){if(!e||e.length===0)return t;const n=ye(t,e);return C[n]??=we(t,e).finally(()=>{setTimeout(()=>{delete C[n]},2*1e3)}),C[n]}function Se(t){return t.match(/<body[^>]*>(.*?)<\/body>/s)?.[1]||""}const be=["/assets/"];function ke({app:t,viteDevServer:e,state:n}){let s;if(e){const a=E.readFileSync(I.resolve(process.cwd(),"./index.html"),"utf-8");t.use(async(m,v,k)=>{const q=m.originalUrl;s=await e.transformIndexHtml(q,a),k()})}else s=E.readFileSync(I.resolve(process.env.BLOCKLET_APP_DIR,"dist/index.html"),"utf-8");const o=ne.Router();o.use((a,m,v)=>{if(a.headers["x-unique-record"]==="dial_http"){b.logger.info("[html] dial http request, return 200 status code"),m.status(200).send("ok");return}v()}),r.default.env.preferences.snapkitEnabled&&r.default.env.preferences.snapkitEndpoint&&r.default.env.SNAP_KIT_ACCESS_KEY&&o.use(X.createSnapshotMiddleware({endpoint:r.default.env.preferences.snapkitEndpoint,accessKey:r.default.env.SNAP_KIT_ACCESS_KEY,cacheMax:r.default.env.preferences.snapkitCacheSize||100})),o.get("/:path(*)?",async(a,m,v)=>{if(be.some(c=>a.path?.startsWith(c))){v();return}const k=performance.now(),q=()=>Math.round(performance.now()-k),M="production";let g,S,_=s;if(a.path.startsWith("/pages")){const c=a.params.lang,y=a.cookies.nf_lang,w=new Set([...r.default.env.languages.map(f=>f.code)]);let h=(c&&w.has(c)?c:void 0)||(w.has(y)?y:void 0)||[...w][0];if((!h||!n.supportedLocales?.find(f=>f.locale===h))&&(h=n.supportedLocales?.[0]?.locale||""),h){const f=[];Object.values(n.pages).forEach(l=>{const H=Object.values(l?.sections??{}).filter(u=>u.component==="custom-component"&&u.config?.componentId).map(u=>({id:u.id,componentId:u.config.componentId,useCache:u.config.useCache,cacheDuration:u.config.cacheDuration,properties:l?.dataSource?.[u.id]?.[h]}));f.push(...H)});const K=new Promise(l=>{setTimeout(()=>{l({})},30*1e3)});try{await Promise.race([K,b.getPreloadComponents({mode:M,req:a,state:n,locale:h,instances:f,module:Z.PreloadComponentScriptModule.UMD_FN}).then(l=>{l&&(S=j.injectPreloadComponents(l))})])}catch(l){b.logger.warn("getPreloadComponents timeout in promise race, skip inject html elements",l)}}}try{const c=g?.title||r.default.env.appName,y=g?.description||r.default.env.appDescription,w=A.withQuery(A.joinURL(r.default.env.appUrl,"/.well-known/service/blocklet/og.png"),{title:c,description:y});_=pe.default.render(s,{ogTitle:c,ogDescription:y,ogImage:qe(g?.image)||w,pagesPublishedAt:n?.config.publishedAt||new Date().getTime()})}catch{}const p=n?.config.fontFamily,W=a.query.mode==="draft"||a.url.includes("preview")||a.path?.startsWith("/admin");let d=g?.backgroundColor;if(d&&ee.isMuiColorKey(d)){const c=await ge();d=ue.default(c,`settings.theme.light.palette.${d}`,d)}const T=x.getBlockletJs(),D=[{selector:{cheerio:"#injected-head-elements",pattern:/<script[^>]*id=["']injected-head-elements["'][^>]*><\/script>/gis},value:`
|
|
2
2
|
${d?`<meta name="theme-color" content="${d}" /><style>html,body,#app {background-color: ${d};}</style>`:""}
|
|
3
3
|
${p?.title?`<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${p.title}&display=swap">`:""}
|
|
4
4
|
${p?.description&&p?.description!==p?.title?`<link rel="preload" as="style" href="https://fonts.googleapis.com/css?family=${p.description}&display=swap">`:""}
|
package/lib/cjs/resources.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const c=require("./chunks/site-state-
|
|
1
|
+
"use strict";const c=require("./chunks/site-state-BG2d2tBl.js"),L=require("async_hooks"),U=require("express"),F=require("fs"),W=require("joi"),$=require("lodash/groupBy"),z=require("lodash/sortBy"),T=require("path"),G=require("@blocklet/sdk/lib/middlewares/auth"),H=require("@blocklet/sdk/lib/component"),m=e=>e&&e.__esModule?e:{default:e},d=m(F),f=m(W),O=m($),J=m(z),b=m(T),q=m(G);new L.AsyncLocalStorage;const K=async(e,t,r)=>{try{const{projectId:n}=e.params;if(!n)return r();const s=await c.Project.findByPk(n);if(!s)return t?.status(404).json({error:"Project not found"});const o=e.user?.did,a=e.user?.role||"UNKNOWN_ROLE";if(!o)return t?.status(401).json({error:"Authentication required"});if(c.isMultiTenant()){const g=s.createdBy===o,y=c.getMultiTenantAllProjectAccessPassports()?.includes?.(a);if(!g&&!y)return t?.status(403).json({error:"No permission to access this project in multi-tenant mode"})}else if(!["owner","admin","pagesEditor"].includes(a))return t?.status(403).json({error:"No permission to access this project in single-tenant mode"});e.project=s,e.projectId=n,r()}catch(n){c.logger.error("Project middleware error:",n),t?.status(400).json({error:"Internal server error"})}};function x(e,t){return new Promise((r,n)=>{const s=d.default.createReadStream(e),o=d.default.createWriteStream(t);s.on("error",n),o.on("error",n),o.on("finish",r),s.pipe(o)})}async function B(e,t){await d.default.promises.mkdir(t,{recursive:!0});const r=await d.default.promises.readdir(e,{withFileTypes:!0});for(const n of r){const s=b.default.join(e,n.name),o=b.default.join(t,n.name);n.isDirectory()?await B(s,o):await x(s,o)}}async function Y(e,t){(await d.default.promises.stat(e)).isDirectory()?await B(e,t):await x(e,t)}const k=(e,t,r)=>c.isMultiTenant()?q.default()(e,t,r):q.default({roles:["owner","admin","pagesEditor"]})(e,t,r),Q=(e,t)=>{const r=H.getResourceExportDir({projectId:e,releaseId:t});return T.join(r,c.COMPONENT_DID,c.RESOURCE_TYPE)},h=U.Router(),N="@page",R="@component",j=":",P="ALL",C="@project",v=({pageId:e,projectId:t})=>[N,t,e].join(j),V=e=>{const[t,r,n]=e.split(j);if(t===N)return{pageId:n,projectId:r}},A=({componentId:e,projectId:t})=>[R,t,e].join(j),X=e=>{const[t,r,n]=e.split(j);if(t===R)return{componentId:n,projectId:r}},Z=e=>[C,e].join(j),ee=e=>{const[t,r]=e.split(j);if(t===C)return r},te=e=>{try{return JSON.parse(e)}catch{}return{}};async function D(e){const t=await c.SiteState.getStateByProjectId(e,"production"),r=await c.Project.findByPk(e),n=t.pageIds.map(o=>{const a=t.pages[o];if(a)return{id:v({pageId:o,projectId:e}),name:a.slug}}).filter(Boolean),s=J.default(Object.values(t.components),o=>o.index).map(({data:o})=>({id:A({componentId:o.id,projectId:e}),name:o.name||o.id}));return{id:Z(e),name:r?.name||"Unnamed Project",children:[{id:v({pageId:P,projectId:e}),name:"Pages",children:n},{id:A({componentId:P,projectId:e}),name:"Components",children:s}]}}h.get("/resources",k,async(e,t)=>{const{projectId:r}=te(e.query.resourcesParams);if(r){e.params={...e.params,projectId:r},await K(e,t,()=>{});const o=await D(r);t.json({resources:[o]});return}const n=await c.Project.findAll({where:{}}),s=await Promise.all(n.map(o=>D(o.id)));t.json({resources:s})});const re=f.default.object({projectId:f.default.string().required().min(1),releaseId:f.default.string().allow(""),resources:f.default.array().items(f.default.string()).required(),locale:f.default.string().allow("")});h.post("/resources",k,async(e,t)=>{const{resources:r,projectId:n,releaseId:s}=await re.validateAsync(e.body),o="production",a=[],g=[];for(const i of r){if(ee(i))continue;const{pageId:u,projectId:w}=V(i)||{};if(u)u===P||u&&w&&a.push({pageId:u,projectId:w});else{const{componentId:I,projectId:p}=X(i)||{};I===P||I&&p&&g.push({componentId:I,projectId:p})}}const y=O.default(a,"projectId"),E=O.default(g,"projectId"),M=new Set([...Object.keys(y),...Object.keys(E)]),S=Q(n,s);d.default.rmSync(S,{recursive:!0,force:!0}),d.default.mkdirSync(S,{recursive:!0});for(const i of M){const u=await c.SiteState.getStateByProjectId(i,o),w=y[i],I=E[i],p=w?.map(l=>l.pageId),_=I?.map(l=>l.componentId);if(p?.length||_?.length){const l=await c.toPackage(u,{exportAssets:!0,pageIds:p,componentIds:_});await Y(l,S),d.default.rmSync(l,{recursive:!0,force:!0})}c.logger.info(`Exported resources for project ${i}`,{pageIds:p,componentIds:_})}t.json({})});h.get("/all-resources",k,async(e,t)=>{const{states:r}=await c.getResourceStates(),n=r?.map(s=>{const o={blockletId:s.blockletId,blockletTitle:s.blockletTitle,components:{}};if(s.state.components&&(o.components=s.state.components),Object.keys(o.components).length!==0)return o}).filter(Boolean);t.json(n)});var oe=h;module.exports=oe;
|
|
@@ -159,6 +159,8 @@ N.init(
|
|
|
159
159
|
defaultValue: {},
|
|
160
160
|
get() {
|
|
161
161
|
const t = this.getDataValue("relatedBlocklets");
|
|
162
|
+
if (typeof t == "object")
|
|
163
|
+
return t ?? {};
|
|
162
164
|
try {
|
|
163
165
|
return t ? JSON.parse(t) : {};
|
|
164
166
|
} catch (e) {
|
|
@@ -179,6 +181,8 @@ N.init(
|
|
|
179
181
|
defaultValue: {},
|
|
180
182
|
get() {
|
|
181
183
|
const t = this.getDataValue("productionState");
|
|
184
|
+
if (typeof t == "object")
|
|
185
|
+
return t ?? {};
|
|
182
186
|
try {
|
|
183
187
|
return t ? JSON.parse(t) : {};
|
|
184
188
|
} catch (e) {
|
package/lib/es/project-html.js
CHANGED
|
@@ -5,7 +5,7 @@ import B from "@blocklet/sdk/lib/wallet";
|
|
|
5
5
|
import N from "@blocklet/sdk/lib/wallet-authenticator";
|
|
6
6
|
import q from "@blocklet/sdk/lib/wallet-handler";
|
|
7
7
|
import O, { resolve as T } from "path";
|
|
8
|
-
import { l as _, b as U } from "./chunks/site-state-
|
|
8
|
+
import { l as _, b as U } from "./chunks/site-state-BoVWlYLn.js";
|
|
9
9
|
import { createHash as L } from "crypto";
|
|
10
10
|
import { createSnapshotMiddleware as z } from "@arcblock/crawler-middleware";
|
|
11
11
|
import { PreloadComponentScriptModule as F } from "@blocklet/pages-kit/types";
|
package/lib/es/resources.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as S, i as B, g as F, l as N, C as W, R as $, S as T, t as z, a as G } from "./chunks/site-state-
|
|
1
|
+
import { P as S, i as B, g as F, l as N, C as W, R as $, S as T, t as z, a as G } from "./chunks/site-state-BoVWlYLn.js";
|
|
2
2
|
import { AsyncLocalStorage as H } from "async_hooks";
|
|
3
3
|
import { Router as J } from "express";
|
|
4
4
|
import i from "fs";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blocklet/pages-kit-inner-components",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.3",
|
|
4
4
|
"description": "Pages Kit inner components library",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -203,8 +203,8 @@
|
|
|
203
203
|
"yaml": "^2.5.0",
|
|
204
204
|
"yjs": "^13.6.18",
|
|
205
205
|
"zustand": "^4.5.5",
|
|
206
|
-
"@blocklet/pages-kit": "^0.6.
|
|
207
|
-
"@blocklet/pages-kit-block-studio": "^0.6.
|
|
206
|
+
"@blocklet/pages-kit": "^0.6.3",
|
|
207
|
+
"@blocklet/pages-kit-block-studio": "^0.6.3"
|
|
208
208
|
},
|
|
209
209
|
"devDependencies": {
|
|
210
210
|
"@trivago/prettier-plugin-sort-imports": "^5.2.1",
|