@blocklet/pages-kit-inner-components 0.7.2 → 0.7.4
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-DApZigAR.js +1 -0
- package/lib/cjs/resources.js +1 -1
- package/lib/cjs/site-state.js +1 -1
- package/lib/es/chunks/site-state-zNlcYOxL.js +1936 -0
- package/lib/es/resources.js +22 -20
- package/lib/es/site-state.js +1 -1
- package/package.json +3 -3
- package/lib/cjs/chunks/site-state-DCRNxkS5.js +0 -1
- package/lib/es/chunks/site-state-21ffGEui.js +0 -1743
package/lib/es/resources.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { i as
|
|
2
|
-
import { P as E, C as L, R as M, S as
|
|
1
|
+
import { i as b, a as T, l as x } from "./chunks/components-CcZk17uO.js";
|
|
2
|
+
import { P as E, C as L, R as M, S as A, t as F, c as J, g as X } from "./chunks/site-state-zNlcYOxL.js";
|
|
3
3
|
import { Router as G } from "express";
|
|
4
4
|
import { rm as C, mkdir as K } from "fs/promises";
|
|
5
5
|
import u from "joi";
|
|
6
6
|
import O from "lodash/groupBy";
|
|
7
7
|
import W from "lodash/sortBy";
|
|
8
|
-
import { authMiddleware as
|
|
8
|
+
import { authMiddleware as S } from "@blocklet/sdk/lib/middlewares/auth";
|
|
9
9
|
import { getResourceExportDir as Y } from "@blocklet/sdk/lib/component";
|
|
10
10
|
import { join as $ } from "path";
|
|
11
11
|
const z = async (e, t, o) => {
|
|
@@ -13,13 +13,15 @@ const z = async (e, t, o) => {
|
|
|
13
13
|
const { projectId: s } = e.params;
|
|
14
14
|
if (!s)
|
|
15
15
|
return o();
|
|
16
|
-
const n = await E.findByPk(s
|
|
16
|
+
const n = await E.findByPk(s, {
|
|
17
|
+
attributes: { exclude: ["productionState", "relatedBlocklets"] }
|
|
18
|
+
});
|
|
17
19
|
if (!n)
|
|
18
20
|
return t?.status(404).json({ error: "Project not found" });
|
|
19
21
|
const r = e.user?.did, c = e.user?.role || "UNKNOWN_ROLE";
|
|
20
22
|
if (!r)
|
|
21
23
|
return t?.status(401).json({ error: "Authentication required" });
|
|
22
|
-
if (
|
|
24
|
+
if (b()) {
|
|
23
25
|
const j = n.createdBy === r, I = T()?.includes?.(c);
|
|
24
26
|
if (!j && !I)
|
|
25
27
|
return t?.status(403).json({ error: "No permission to access this project in multi-tenant mode" });
|
|
@@ -27,20 +29,20 @@ const z = async (e, t, o) => {
|
|
|
27
29
|
return t?.status(403).json({ error: "No permission to access this project in single-tenant mode" });
|
|
28
30
|
e.project = n, e.projectId = s, o();
|
|
29
31
|
} catch (s) {
|
|
30
|
-
|
|
32
|
+
x.error("Project middleware error:", s), t?.status(400).json({ error: "Internal server error" });
|
|
31
33
|
}
|
|
32
|
-
}, y = (e, t, o) =>
|
|
34
|
+
}, y = (e, t, o) => b() ? S()(e, t, o) : S({ roles: ["owner", "admin", "pagesEditor"] })(e, t, o), H = (e, t) => {
|
|
33
35
|
const o = Y({ projectId: e, releaseId: t });
|
|
34
36
|
return $(o, L, M);
|
|
35
|
-
}, w = G(),
|
|
37
|
+
}, w = G(), D = "@page", B = "@component", m = ":", g = "ALL", N = "@project", _ = ({ pageId: e, projectId: t }) => [D, t, e].join(m), Q = (e) => {
|
|
36
38
|
const [t, o, s] = e.split(m);
|
|
37
|
-
if (t ===
|
|
38
|
-
}, k = ({ componentId: e, projectId: t }) => [
|
|
39
|
+
if (t === D) return { pageId: s, projectId: o };
|
|
40
|
+
}, k = ({ componentId: e, projectId: t }) => [B, t, e].join(m), V = (e) => {
|
|
39
41
|
const [t, o, s] = e.split(m);
|
|
40
|
-
if (t ===
|
|
41
|
-
}, Z = (e) => [
|
|
42
|
+
if (t === B) return { componentId: s, projectId: o };
|
|
43
|
+
}, Z = (e) => [N, e].join(m), q = (e) => {
|
|
42
44
|
const [t, o] = e.split(m);
|
|
43
|
-
if (t ===
|
|
45
|
+
if (t === N) return o;
|
|
44
46
|
}, ee = (e) => {
|
|
45
47
|
try {
|
|
46
48
|
return JSON.parse(e);
|
|
@@ -49,10 +51,10 @@ const z = async (e, t, o) => {
|
|
|
49
51
|
return {};
|
|
50
52
|
};
|
|
51
53
|
async function v(e) {
|
|
52
|
-
const t = await
|
|
54
|
+
const t = await A.getStateByProjectId({ projectId: e, mode: "production" }), o = await E.findByPk(e), s = t.pageIds.map((r) => {
|
|
53
55
|
const c = t.pages[r];
|
|
54
56
|
if (c)
|
|
55
|
-
return { id:
|
|
57
|
+
return { id: _({ pageId: r, projectId: e }), name: c.slug };
|
|
56
58
|
}).filter(Boolean), n = W(Object.values(t.components), (r) => r.index).map(({ data: r }) => ({
|
|
57
59
|
id: k({ componentId: r.id, projectId: e }),
|
|
58
60
|
name: r.name || r.id
|
|
@@ -61,7 +63,7 @@ async function v(e) {
|
|
|
61
63
|
id: Z(e),
|
|
62
64
|
name: o?.name || "Unnamed Project",
|
|
63
65
|
children: [
|
|
64
|
-
{ id:
|
|
66
|
+
{ id: _({ pageId: g, projectId: e }), name: "Pages", children: s },
|
|
65
67
|
{
|
|
66
68
|
id: k({ componentId: g, projectId: e }),
|
|
67
69
|
name: "Components",
|
|
@@ -112,10 +114,10 @@ w.post("/resources", y, async (e, t) => {
|
|
|
112
114
|
});
|
|
113
115
|
}
|
|
114
116
|
}
|
|
115
|
-
const I = O(c, "projectId"), h = O(j, "projectId"),
|
|
117
|
+
const I = O(c, "projectId"), h = O(j, "projectId"), U = /* @__PURE__ */ new Set([...Object.keys(I), ...Object.keys(h)]), P = H(s, n);
|
|
116
118
|
await C(P, { recursive: !0, force: !0 }), await K(P, { recursive: !0 });
|
|
117
|
-
for (const i of
|
|
118
|
-
const a = await
|
|
119
|
+
for (const i of U) {
|
|
120
|
+
const a = await A.getStateByProjectId({ projectId: i, mode: r }), f = I[i], l = h[i], d = f?.map((p) => p.pageId), R = l?.map((p) => p.componentId);
|
|
119
121
|
if (d?.length || R?.length) {
|
|
120
122
|
const p = await F(a, {
|
|
121
123
|
exportAssets: !0,
|
|
@@ -124,7 +126,7 @@ w.post("/resources", y, async (e, t) => {
|
|
|
124
126
|
});
|
|
125
127
|
await J(p, P), await C(p, { recursive: !0, force: !0 });
|
|
126
128
|
}
|
|
127
|
-
|
|
129
|
+
x.info(`Exported resources for project ${i}`, {
|
|
128
130
|
pageIds: d,
|
|
129
131
|
componentIds: R
|
|
130
132
|
});
|
package/lib/es/site-state.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./chunks/components-CcZk17uO.js";
|
|
2
|
-
import { d as b, a as h, b as y, S as L, f as U, h as q, i as v, e as z, g as C, j as F, m as G, t as J, k as K, u as N } from "./chunks/site-state-
|
|
2
|
+
import { d as b, a as h, b as y, S as L, f as U, h as q, i as v, e as z, g as C, j as F, m as G, t as J, k as K, u as N } from "./chunks/site-state-zNlcYOxL.js";
|
|
3
3
|
import { nextId as V } from "@blocklet/pages-kit/utils/common";
|
|
4
4
|
import "@blocklet/pages-kit/utils/page-model";
|
|
5
5
|
import "@blocklet/pages-kit/utils/property";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blocklet/pages-kit-inner-components",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.4",
|
|
4
4
|
"description": "Pages Kit inner components library",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -201,8 +201,8 @@
|
|
|
201
201
|
"yaml": "^2.5.0",
|
|
202
202
|
"yjs": "^13.6.18",
|
|
203
203
|
"zustand": "^4.5.5",
|
|
204
|
-
"@blocklet/pages-kit": "^0.7.
|
|
205
|
-
"@blocklet/pages-kit-block-studio": "^0.7.
|
|
204
|
+
"@blocklet/pages-kit": "^0.7.4",
|
|
205
|
+
"@blocklet/pages-kit-block-studio": "^0.7.4"
|
|
206
206
|
},
|
|
207
207
|
"devDependencies": {
|
|
208
208
|
"@trivago/prettier-plugin-sort-imports": "^5.2.1",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const u=require("./components-CnPdZJ2Z.js"),G=require("@syncedstore/core"),rt=require("yjs"),it=require("@blocklet/pages-kit/utils/data-source"),se=require("@blocklet/pages-kit/utils/route"),ct=require("lodash/cloneDeep"),lt=require("@blocklet/sdk/lib/config"),ee=require("fs"),f=require("path"),Me=require("@blocklet/pages-kit/utils/common"),ut=require("@blocklet/pages-kit/utils/page-model"),dt=require("@blocklet/pages-kit/utils/property"),je=require("@blocklet/sdk/lib/component"),pt=require("@reactivedata/reactive"),C=require("fs/promises"),ne=require("glob"),ft=require("lib0/decoding"),gt=require("lib0/encoding"),mt=require("lodash/debounce"),ht=require("lodash/get"),yt=require("lodash/isEmpty"),St=require("lodash/set"),wt=require("lodash/union"),Ce=require("lru-cache"),It=require("p-limit"),A=require("sequelize"),bt=require("stream/promises"),Et=require("tar"),N=require("ufo"),Pt=require("wait-on"),H=require("y-protocols/awareness"),ge=require("y-protocols/sync"),At=require("yaml"),$e=require("./html-dP5_4zu1.js");require("sqlite3");require("@blocklet/pages-kit/types/state");const $=t=>t&&t.__esModule?t:{default:t};function le(t){if(t&&t.__esModule)return t;const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const s=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(e,a,s.get?s:{enumerable:!0,get:()=>t[a]})}}return e.default=t,Object.freeze(e)}const F=le(rt),W=$(ct),E=$(lt),V=$(ee),Ne=$(f),me=le(ft),k=le(gt),Oe=$(mt),De=$(ht),Te=$(yt),Fe=$(St),jt=$(wt),Re=$(It),Ct=$(Pt),K=le(At),Ot=A.DataTypes.sqlite.DATE.parse;A.DataTypes.sqlite.DATE.parse=(t,e)=>typeof t=="number"?new Date(t):Ot(t,e);const B=new A.Sequelize({dialect:"sqlite",storage:u.databaseUrl,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});B.query("PRAGMA journal_mode = WAL;");B.query("PRAGMA synchronous = normal;");B.query("PRAGMA journal_size_limit = 67108864;");B.query("PRAGMA cache_size = 10000;");process.on("SIGINT",async()=>{await B.close(),process.exit(0)});process.on("SIGTERM",async()=>{await B.close(),process.exit(0)});async function Dt(t,e){try{if(t.getDialect()!=="sqlite")return;const[a]=await t.query("SELECT 1");if(!a||a.length===0)return;await t.query("PRAGMA shrink_memory;")}catch(a){if(a.name==="SequelizeConnectionError"||a?.message&&/closed!/.test(a.message))return;console.error("Failed to cleanup SQLite memory",e,a)}}let we=null;we&&clearInterval(we);we=setInterval(async()=>{u.logger.info("Start cleanupSqliteMemory"),await Dt(B,u.databaseUrl),u.logger.info("End cleanupSqliteMemory")},60*1e3*10);const Tt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",Ie="page",be="trigger-reload-project-resource",ve=Tt,Rt="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM",vt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o";class ke extends A.Model{}ke.init({id:{type:A.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:A.DataTypes.UUIDV4},projectId:{type:A.DataTypes.UUID,allowNull:!1},componentId:{type:A.DataTypes.STRING,allowNull:!1}},{sequelize:B,tableName:"ProjectComponents",timestamps:!1});const kt="SLUG_INVALID",J=t=>({error:"slugInvalid",code:kt,field:"slug",message:t}),_t={error:"slugRequired",code:"SLUG_REQUIRED",field:"slug",message:()=>"Project slug is required"},Lt={error:"slugAlreadyExists",code:"SLUG_EXISTS",field:"slug",message:t=>`Project slug "${t}" already exists`},Ut=[/\.\./,/<[^>]*>/,/%[0-9a-f]{2}/i,/[<>'"%;{}()\\]/,/\x00/,/\n|\r|\t|\v|\f/,/[^a-zA-Z0-9-_@/\\:]/],qe=t=>{if(!t)return"";if(t==="/")return"/";const e=N.withoutTrailingSlash(t);return N.withLeadingSlash(e)||"/"},Mt=t=>t.did===vt;class U extends A.Model{static async getProjectByIdOrSlug(e,a){return e?U.findOne({where:{[A.Op.or]:[{id:e},{slug:e}],...a?.createdBy?{createdBy:a.createdBy}:{}}}):null}static async validateProjectSlug({slug:e,projectId:a}){if(e==null)return null;if(e==="")return _t;const s=e==="/"?"/":N.withoutTrailingSlash(N.withLeadingSlash(e)),n=qe(s);if(s!=="/"&&s.endsWith("/"))return J(i=>`Project slug "${i}" cannot end with /`);if(/\/{2,}/.test(s))return J(i=>`Project slug "${i}" cannot contain consecutive /`);if(/\s/.test(s))return J(i=>`Project slug "${i}" cannot contain whitespace`);if(Ut.some(i=>i.test(s)))return J(i=>`Project slug "${i}" contains invalid characters`);if(E.default.components?.filter(i=>i.mountPoint&&!Mt(i)).some(i=>qe(i.mountPoint)===n))return J(i=>`Project slug "${i}" conflicts with existing blocklet`);const l=await U.findOne({where:{slug:s}});return l&&l?.id!==a?Lt:null}}U.init({id:{type:A.DataTypes.UUID,defaultValue:A.DataTypes.UUIDV4,primaryKey:!0},name:{type:A.DataTypes.STRING,allowNull:!1},description:A.DataTypes.TEXT,createdAt:A.DataTypes.DATE,updatedAt:A.DataTypes.DATE,createdBy:{type:A.DataTypes.STRING,allowNull:!1},updatedBy:{type:A.DataTypes.STRING,allowNull:!1},slug:A.DataTypes.STRING,icon:A.DataTypes.STRING,pinnedAt:A.DataTypes.DATE,useAllResources:A.DataTypes.BOOLEAN,npmSecret:A.DataTypes.STRING,relatedBlocklets:{type:A.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 u.logger.error("Failed to parse relatedBlocklets",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("relatedBlocklets",t?JSON.stringify(t):"{}")}catch(e){u.logger.error("Failed to set relatedBlocklets",{error:e,value:t}),this.setDataValue("relatedBlocklets","{}")}}},productionState:{type:A.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 u.logger.error("Failed to parse productionState",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("productionState",t?JSON.stringify(t):"{}")}catch(e){u.logger.error("Failed to set productionState",{error:e,value:t}),this.setDataValue("productionState","{}")}}},meta:{type:A.DataTypes.JSON,allowNull:!0}},{sequelize:B,paranoid:!0,indexes:[{name:"projects_slug_unique",unique:!0,fields:["slug"]},{name:"projects_created_by",fields:["createdBy"]},{name:"projects_pinned_updated_meta_not_null",fields:[{name:"pinnedAt",order:"DESC"},{name:"updatedAt",order:"DESC"}],where:{meta:{[A.Op.ne]:null}}}]});U.hasMany(ke,{foreignKey:"projectId",as:"components"});async function q(t){try{return await V.default.promises.access(t,V.default.constants.F_OK),!0}catch{return!1}}function Ge(t,e){return new Promise((a,s)=>{const n=V.default.createReadStream(t),o=V.default.createWriteStream(e);n.on("error",s),o.on("error",s),o.on("finish",a),n.pipe(o)})}async function Ve(t,e){await V.default.promises.mkdir(e,{recursive:!0});const a=await V.default.promises.readdir(t,{withFileTypes:!0});for(const s of a){const n=Ne.default.join(t,s.name),o=Ne.default.join(e,s.name);s.isDirectory()?await Ve(n,o):await Ge(n,o)}}async function $t(t,e){(await V.default.promises.stat(t)).isDirectory()?await Ve(t,e):await Ge(t,e)}function oe(t){t.observeDeep(e=>{e.some(a=>a.changes.keys.has("updatedAt")||a.changes.keys.has("publishedAt"))||t.set("updatedAt",new Date().toISOString())})}function ze(){return ee.mkdtempSync(f.join(E.default.env.dataDir,"tmp-"))}function re(t,e,a=[]){return Array.isArray(t)?t.flatMap((s,n)=>re(s,e,[...a,n])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([s,n])=>re(n,e,[...a,s])):e(t)?[a]:[]}function L(t){return t.filter(e=>e!=null)}function Nt(t){t.pages&&Object.keys(t.pages).forEach(a=>{const s=G.getYjsValue(t.pages[a]);s&&s instanceof F.Map&&oe(s)});const e=G.getYjsValue(t.pages);e&&e instanceof F.Map&&e.observe(a=>{a.changes.keys.forEach((s,n)=>{if(s.action==="add"){const o=G.getYjsValue(t.pages[n]);o&&o instanceof F.Map&&oe(o)}})})}function Ft(t){t.routes&&Object.keys(t.routes).forEach(a=>{const s=G.getYjsValue(t.routes?.[a]);s&&s instanceof F.Map&&oe(s)});const e=G.getYjsValue(t.routes);e&&e instanceof F.Map&&e.observe(a=>{a.changes.keys.forEach((s,n)=>{if(s.action==="add"){const o=G.getYjsValue(t.routes?.[n]);o&&o instanceof F.Map&&oe(o)}})})}function qt(t,e){for(const a of e||Object.keys(t.routes||{})){let s=a,n=[];if(a.includes("-")){const[o,...l]=a.split("-");s=o,n=l||[]}if(t.routes?.[s]!==void 0){t.routes[s].publishedAt=new Date().toISOString();const o=t.routes[s];if(!o||!o.params||o.params.length===0)continue;if(a.includes("-")&&n.length>0){const l=se.getRouteMetaDataByOptionIds(n,o);l&&(l.publishedAt=new Date().toISOString())}if(!e){const l=se.generateParamCombinations({basePath:o.path,params:o.params,routeId:o.id,paramsOptions:o.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const i of l)i.routeMetaData??={},i.routeMetaData.publishedAt=new Date().toISOString()}}}}function he({page:t,route:e,state:a,routeId:s,routePathInfo:n}){u.logger.info(`Executing datasource data assembly, routeId: ${s}, routePathInfo: ${JSON.stringify(n)}`);const o={...W.default(t),id:s,slug:n?.path??e.path,createdAt:e.createdAt,updatedAt:n?.routeMetaData?.updatedAt??e.updatedAt,publishedAt:n?.routeMetaData?.publishedAt??e.publishedAt,isPublic:(n?.routeMetaData?.isPublic??e.isPublic)&&e.isPublic};for(const l of a.supportedLocales){if(e.dataSource){let i=e.id;n&&(i=n.paramOptionIds.join("-"));const c=e.dataSource.pathDataMappings?.[i]?.dataCache?.[l.locale]??e.dataSource.pathDataMappings?.[i]?.dataCache?.[a.config.defaultLocale||"en"];if(!c)continue;it.setPageDataSource(o,a,l.locale,c)}n&&n.routeMetaData&&(n.routeMetaData.publishedAt=new Date().toISOString())}return o}["true","1","yes","y"].includes(process.env.USE_FS_CACHE_HTML??"");const Bt=60*60*1e3,X=new Ce.LRUCache({max:300,ttl:Bt,ttlResolution:10*1e3,allowStale:!0});function xt(t,e=[]){let a=0;const s=Array.from(X.keys()),n=t.map(o=>N.withoutTrailingSlash(o));for(const o of s)for(const l of n){if($e.matchCacheKey(o,{currentPath:l})){X.delete(o),a++,u.logger.info(`[Cache CLEAR] key: ${o}`);break}for(const i of e)if($e.matchCacheKey(o,{currentPath:`/${i}${l}`})){X.delete(o),a++,u.logger.info(`[Cache CLEAR] key: ${o}`);break}}return u.logger.info(`[Cache CLEAR] cleared ${a} entries for paths:`,n),a}function Gt(){const t=X.size;return X.clear(),u.logger.info(`[Cache CLEAR ALL] cleared ${t} entries`),t}E.default.events.on(E.default.Events.envUpdate,Gt);const{uploadToMediaKit:Vt}=require("@blocklet/uploader-server"),_e=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,Q=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Be=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,zt=1e4,Kt=3e4,te=0,ye=1,Yt=0,Ht=1,Ee=E.default,z=f.join(process.env.BLOCKLET_DATA_DIR,"site-state"),Jt=["production","draft"],Wt=["production"];function ie(t){return t?.replace(/\//g,"|")||""}function Ke(){const t=Ee.env.languages?.map(a=>({locale:a.code,name:a.name}))||[],e=t[0]?.locale||"en";return{pageIds:[],pages:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{},components:{},supportedLocales:t,config:{defaultLocale:e},resources:{}}}class j extends F.Doc{constructor(e){super(),this.options=e,ee.existsSync(this.draftYjsFilePath)&&F.applyUpdate(this,ee.readFileSync(this.draftYjsFilePath)),this.syncedStore=pt.reactive(G.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new H.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 Ce.LRUCache({max:300,ttl:1e3*60*60*24});static periodicCheckTimer;static async safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const a=f.join(z,e),s=f.join(z,`@del-${e}`);await C.rename(a,s)}catch(a){u.logger.error("Failed to safe delete project state dir:",a)}}static async getProjectIds(){return(await U.findAll({attributes:["id"],raw:!0}))?.map(e=>e.id)}static get projectIds(){return ne.globSync("*/",{cwd:z,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 a=j.sharedInstances[e];return a||(a=new j({path:f.join(z,e)}),j.sharedInstances[e]=a,a)}static async getProductionState(e){const a=await U.findByPk(e,{attributes:["productionState"]});if(Te.default(a?.productionState)){const s=f.join(z,e,"production"),n=await Le(s,{includeResources:!0})??Ke();if(!n?.config?.defaultLocale){n.config??={};const o=Ee.env.languages?.map(l=>({locale:l.code,name:l.name}))||[];n.config.defaultLocale=o[0]?.locale}return n}return a?.productionState}destroy(){this.cancelRelease(),this.save({flush:!0}),this.conns.forEach((a,s)=>this.closeConn(s)),this.awareness.destroy();const e=f.basename(this.options.path);delete j.sharedInstances[e],super.destroy()}initObserver(){Nt(this.syncedStore),Ft(this.syncedStore)}get draftYjsFilePath(){return f.join(this.options.path,"draft.yjs")}static async getStateByProjectId({projectId:e,mode:a,clone:s=!0}){if(a==="draft"){const n=j.shared(e);return s?W.default(n.syncedStore):n.syncedStore}return j.getProductionState(e)}async getState(e){if(e==="draft")return W.default(this.syncedStore);const a=f.basename(this.options.path);return j.getProductionState(a)}async setState(e,a){const s=await We(a,{exportAssets:!1,includeResources:!0}),n=this.getPublishDir(e);if(await C.mkdir(f.dirname(n),{recursive:!0}),await C.rm(n,{force:!0,recursive:!0}),await C.rename(s,n),e==="production"){const o=f.basename(this.options.path);j.pageUrlMapCache.delete(o);const l=W.default(a);await U.update({productionState:l},{where:{id:o}})}}getPublishDir(e){return f.join(this.options.path,e)}syncedStore;conns=new Map;awareness;releaseTimer;awarenessChangeHandler=({added:e,updated:a,removed:s},n)=>{const o=e.concat(a,s);if(n!==null){const c=this.conns.get(n);c&&(e.forEach(b=>{c.add(b)}),s.forEach(b=>{c.delete(b)}))}const l=k.createEncoder();k.writeVarUint(l,ye),k.writeVarUint8Array(l,H.encodeAwarenessUpdate(this.awareness,o));const i=k.toUint8Array(l);this.conns.forEach((c,b)=>this.send(b,i))};updateHandler=e=>{const a=k.createEncoder();k.writeVarUint(a,te),ge.writeUpdate(a,e);const s=k.toUint8Array(a);this.conns.forEach((n,o)=>this.send(o,s))};ensureDataStructure=()=>{this.transact(()=>{const{supportedLocales:e,pages:a,pageIds:s,config:n,routes:o,routeIds:l}=this.syncedStore;{const i=new Set(Object.keys(a));let c=0;for(;c<s.length;){const b=s[c];i.has(b)?(i.delete(b),c++):s.splice(c,1)}}{const i=new Set(Object.keys(o));let c=0;for(;c<l.length;){const b=l[c];i.has(b)?(i.delete(b),c++):l.splice(c,1)}}e.splice(0,e.length),e.push(...Ee.env.languages.map(i=>({locale:i.code,name:i.name}))),n.defaultLocale=e[0]?.locale;{let i=0;const c=new Set;for(;i<e.length;){const{locale:b}=e[i];c.has(b)?e.splice(i,1):(i++,c.add(b))}}})};send=(e,a)=>{e.readyState!==Yt&&e.readyState!==Ht&&this.closeConn(e);try{e.send(a,s=>{s&&this.closeConn(e)})}catch{this.closeConn(e)}};closeConn=e=>{if(e.removeAllListeners(),this.conns.has(e)){const a=this.conns.get(e);this.conns.delete(e),a&&H.removeAwarenessStates(this.awareness,Array.from(a),null)}e.close(),this.checkAndScheduleRelease()};checkAndScheduleRelease(){this.conns.size===0&&this.scheduleRelease()}scheduleRelease(){this.cancelRelease();const e=f.basename(this.options.path);this.releaseTimer=setTimeout(()=>{u.logger.info(`[SiteState] releasing instance due to no active connections: ${e}`),this.conns.size===0&&(this.releaseTimer=void 0,this.destroy())},j.RELEASE_DELAY),u.logger.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=f.basename(this.options.path);u.logger.info(`[SiteState] cancelled scheduled release for project ${e}`)}}autoSave=Oe.default(async()=>{await C.mkdir(f.dirname(this.draftYjsFilePath),{recursive:!0}),await C.writeFile(this.draftYjsFilePath,F.encodeStateAsUpdate(this))},zt);save=({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()};publish=async({mode:e,routes:a})=>{const s=f.basename(this.options.path);await nt(s);const n=await this.getState("draft"),o=await this.getState("production");await Ae(n,o,{routes:a,mergeMode:"replace",deleteRoutes:!0,publishMode:e}),o.config.publishedAt=new Date().getTime(),qt(this.syncedStore,a),await this.setState(e,o),await this.clearPageCacheForRoutes(a,o)};mergeState=async(e,a)=>{const s=JSON.parse(JSON.stringify(a));e.config.fontFamily??={};const n=s.config?.fontFamily,o=e.config?.fontFamily;e.config.fontFamily.title=n?.title||o?.title,e.config.fontFamily.description=n?.description||o?.description,await new Promise((l,i)=>{this.transact(async()=>{try{const c=await Ae(e,a);l(c)}catch(c){i(c)}})})};clearPageCacheForRoutes=async(e,a)=>{const s=f.basename(this.options.path),o=(await U.findByPk(s))?.slug||s;let l=e;(!l||l.length===0)&&(l=a.pageIds??[]),u.logger.info(`[SiteState] clearing page cache for project ${s}, routes:`,l||[]);const i=a.supportedLocales.map(O=>O.locale),c=[],b=l.filter(O=>a.pageIds?.includes(O));for(const O of b){const w=a.pages[O].slug;o&&o!==s&&(o==="/"?c.push(w):c.push(`/${o}${w}`)),c.push(`/${s}${w}`)}if(c.length>0)try{const O=xt(c,i);u.logger.info(`[SiteState] cleared ${O} page cache entries for project ${s}, routes:`,l)}catch{}j.pageUrlMapCache.delete(s)};addConnection=e=>{if(this.conns.has(e))return;this.cancelRelease(),e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",n=>this.messageListener(e,new Uint8Array(n)));let a=!0;const s=setInterval(()=>{if(!a)this.conns.has(e)&&this.closeConn(e),clearInterval(s);else if(this.conns.has(e)){a=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(s)}}},Kt);e.on("close",()=>{this.closeConn(e),clearInterval(s)}),e.on("pong",()=>{a=!0});{const n=k.createEncoder();k.writeVarUint(n,te),ge.writeSyncStep1(n,this),this.send(e,k.toUint8Array(n));const o=this.awareness.getStates();if(o.size>0){const l=k.createEncoder();k.writeVarUint(l,ye),k.writeVarUint8Array(l,H.encodeAwarenessUpdate(this.awareness,Array.from(o.keys()))),this.send(e,k.toUint8Array(l))}}};messageListener=(e,a)=>{try{const s=k.createEncoder(),n=me.createDecoder(a),o=me.readVarUint(n);switch(o){case te:k.writeVarUint(s,te),ge.readSyncMessage(n,s,this,null),k.length(s)>1&&(this.ensureDataStructure(),this.send(e,k.toUint8Array(s)));break;case ye:{H.applyAwarenessUpdate(this.awareness,me.readVarUint8Array(n),e);break}default:u.logger.warn(`Unsupported messageType ${o}`)}}catch(s){u.logger.error(s)}this.save()};static async pageUrlMap(e,a){u.logger.info(`[SiteState] get pageUrlMap, mode: ${e}, projectId: ${a}`);let s=[];a?s=[a]:s=await this.getProjectIds();let n={};if(e==="production"&&s?.length){const o=new Map(s?.map(l=>[l,!0])||[]);for(const l of s){const i=j.pageUrlMapCache.get(l);i&&(Object.assign(n,i),o.delete(l))}s=Array.from(o.keys())}if(s?.length){u.logger.info("[SiteState] find project infos from database, projectIds: ",s);const o=30,l=Re.default(5);for(let i=0;i<s.length;i+=o){const c=s.slice(i,i+o);u.logger.info(`[SiteState] processing project batch ${i/o+1}, ids: `,c);const b=await U.findAll({where:{id:{[A.Op.in]:c}},attributes:{exclude:["relatedBlocklets"]}});await Promise.all(b?.map(O=>l(async()=>{const R=O.id,w=O.slug||R,g={},d=e==="production"&&O?.productionState?O.productionState:await j.getStateByProjectId({projectId:O.id,mode:e,clone:!1}),I=jt.default(E.default.env.languages?.map(P=>P.code)||[],d.supportedLocales?.map(P=>P.locale)||[]),D=(P,y)=>{w&&(g[N.joinURL("/",w,P)]={...y,shouldRedirect:!0,mainPage:!0}),g[N.joinURL("/",R,P)]={...y,shouldRedirect:!0,mainPage:!0};for(const v of I){const h={...y,locale:v};g[N.joinURL("/",v,R,P)]=h,w&&(g[N.joinURL("/",v,w,P)]=h)}};if(e==="draft")for(const P of d.routeIds||[]){const y=d?.routes?.[P];if(!y)continue;if(y.params&&y.params.length>0){const S=se.generateParamCombinations({basePath:y.path,params:y.params,routeId:y.id,paramsOptions:y.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const r of S){const p=r.path,m={projectId:R,projectSlug:w,pageSlug:p,pageId:y.displayTemplateId||"",routeId:P,defaultLocale:I?.[0],locales:I,publishedAt:d.config.publishedAt,isPublic:y.isPublic&&r?.routeMetaData?.isPublic};D(p,m)}}const v=y.path,h={projectId:R,projectSlug:w,pageSlug:v,pageId:y.displayTemplateId||"",routeId:P,defaultLocale:I?.[0],locales:I,publishedAt:d.config.publishedAt,isPublic:y.isPublic};D(v,h)}for(const P of d.pageIds||[]){const y=d.pages[P];if(!y||e==="production"&&!y.isPublic)continue;const v=y.slug,h=O.slug||R,S={projectId:R,projectSlug:h,pageSlug:v,pageId:P,defaultLocale:I?.[0],locales:I,publishedAt:d.config.publishedAt,isPublic:y.isPublic,templateConfig:y.templateConfig};D(v,S)}e==="production"&&j.pageUrlMapCache.set(R,g),n={...n,...g}})))}}return u.logger.info("[SiteState] success get pageUrlMap"),n}getDocumentSize(){return F.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const e=[];for(const[a,s]of Object.entries(j.sharedInstances)){const n=s.getDocumentSize();e.push({projectId:a,sizeInBytes:n,sizeInMB:`${(n/(1024*1024)).toFixed(2)} MB`,activeConnections:s.conns.size})}return e}static startPeriodicCheck(){this.periodicCheckTimer||(this.periodicCheckTimer=setInterval(()=>{this.performPeriodicCheck()},this.PERIODIC_CHECK_INTERVAL),u.logger.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,u.logger.info("[SiteState] periodic check stopped"))}static performPeriodicCheck(){const e=Object.keys(j.sharedInstances).length,a=[],s=[];for(const[n,o]of Object.entries(j.sharedInstances))o.conns.size===0?a.push({projectId:n,instance:o}):s.push({projectId:n,connections:o.conns.size});if(u.logger.info(`[SiteState] periodic check summary: total instances: ${e}, with connections: ${s.length}, without connections: ${a.length}`),a.length>0){u.logger.info(`[SiteState] releasing ${a.length} instances without connections:`,a.map(o=>o.projectId));let n=0;for(const{projectId:o,instance:l}of a)try{u.logger.info(`[SiteState] releasing instance due to periodic check: ${o}`),l.destroy(),n++}catch(i){u.logger.error(`[SiteState] failed to release instance ${o} during periodic check:`,i)}u.logger.info(`[SiteState] periodic check completed: ${n}/${a.length} instances released successfully`)}else e>0?u.logger.debug("[SiteState] periodic check: all instances have active connections"):u.logger.debug("[SiteState] periodic check: no instances exist")}}async function Xt(t,e,a){if(!t||!await q(t)||!(await C.lstat(t)).isFile())return null;let n=a[t];return n||(n=(async()=>{try{return(await Vt({filePath:t,fileName:e}))?.data?.filename}catch(o){return u.logger.error(`Failed to upload asset ${t}:`,o),null}})(),a[t]=n),n}const Ye=async(t,e)=>{const a=f.basename(t),s=await je.call({name:ve,path:N.joinURL("/uploads",a),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const n=ee.createWriteStream(e);await bt.pipeline(s.data,n)}else throw new Error(`download asset failed ${s.status}`)},He=async(t,e)=>{await Promise.all(t.map(async a=>{try{await Ye(a,f.join(e,f.basename(a)))}catch(s){u.logger.error(`Failed to export assets: ${a}, ${s}`)}}))};function Je(t){return _e.test(t)?[t]:Q.test(t)?(Be.lastIndex=0,Array.from(t.matchAll(Be)).map(a=>a[1]).filter(a=>!!a)):[]}async function ae(t,e,a){const{getFilename:s,exportAssets:n}=a,o=f.join(e,s(t));if(await C.mkdir(f.dirname(o),{recursive:!0}),await C.writeFile(o,K.stringify(t)),n){const i=re(t,c=>typeof c=="string"&&(_e.test(c)||Q.test(c))).map(c=>{const b=De.default(t,c);return Je(b)}).flat().filter(Boolean);await He(i,f.dirname(o))}}const Pe=new Ce.LRUCache({max:100,ttl:1*60*1e3});async function xe(t,e,a){const s=re(t,i=>typeof i=="string"&&(_e.test(i)||Q.test(i))),n=Re.default(2),o=s.map(i=>n(async()=>{try{const c=De.default(t,i),b=Je(c);for(const O of b){const R=f.basename(O),w=a.getFilePath(O,i),g=w?`${w}:${R}`:R,d=Pe.get(g);if(d){Q.test(c)||Fe.default(t,i,d);return}const I=await Xt(w,R,e);I&&(Q.test(c)||Fe.default(t,i,I),Pe.set(g,I))}}catch(c){u.logger.error(`Failed to process upload for path ${i.join(".")}:`,c.message||c.reason)}})),l=await Promise.allSettled(o);a.onFinish?.(l)}async function We(t,{exportAssets:e,pageIds:a="all",componentIds:s="all",rawConfig:n,includeResources:o=!1,routeIds:l="all"}={}){const i=a==="all"?t.pageIds:a,c=dt.getComponentDependencies({state:t,pageIds:i,componentIds:s==="all"?Object.keys(t.components):s});Object.entries(t.components).forEach(([r,p])=>{p.data?.renderer?.type==="component-template"&&c.push(r)});const b=l==="all"?t.routeIds:l,O=r=>({id:r.id,name:r.name,isTemplateSection:r.isTemplateSection??!1,templateDescription:r.templateDescription,component:r.component,config:r.config,visibility:r.visibility,sections:r?.sectionIds?L(r?.sectionIds?.map(p=>{const m=r.sections?.[p];return m&&O(m)})):void 0}),R=(r,p)=>({id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,publishedAt:r.publishedAt,isPublic:r.isPublic??!0,templateConfig:r.templateConfig,meta:r.locales?.[p]??{},sections:L(r.sectionIds.map(m=>{const T=r.sections[m];return T&&O(T)})),dataSource:Object.fromEntries(Object.entries(r.dataSource||{}).map(([m,T])=>[m,T?.[p]??{}]))}),w=r=>({id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,publishedAt:r.publishedAt,path:r.path,handler:r.handler,isPublic:r.isPublic??!0,params:r.params??[],enabledGenerate:r.enabledGenerate??!1,displayTemplateId:r.displayTemplateId,dataSource:r.dataSource}),g=L(b.map(r=>{const p=t.routes[r];return p&&w(p)})),d=L(t.supportedLocales.map(r=>r.locale).flatMap(r=>i.map(p=>{const m=t.pages[p];return m&&{locale:r,slug:m.slug,page:R(m,r)}}))),I=ze(),D=f.join(I,"pages");await C.mkdir(D,{recursive:!0});const P=f.join(I,"components");await C.mkdir(P,{recursive:!0});const y=f.join(I,"routes");await C.mkdir(y,{recursive:!0});for(const{locale:r,slug:p,page:m}of d)await ae(m,D,{getFilename:()=>`${ie(p)||"index"}.${r}.yml`,exportAssets:e});for(const r of g)await ae(r,y,{getFilename:()=>`${ie(r.path)||"index"}.yml`,exportAssets:e});for(const r of c){const p=t.components[r]?.data;p&&await ae(p,P,{getFilename:m=>`${m.name||"unnamed"}.${m.id}.yml`,exportAssets:e})}const v=f.join(I,".blocklet/pages/pages.config.yml");await C.mkdir(f.dirname(v),{recursive:!0});const h={pages:L(i.map(r=>{const p=t.pages[r];return p&&{id:r,slug:p.slug}})),routes:L(b.map(r=>{const p=t.routes[r];return p&&{id:r,path:p.path}})),components:L(c.map(r=>{const p=t.components[r]?.data;return p&&{id:r,name:p.name}})),...o?{resources:{components:L(Object.keys(t.resources?.components||{}).filter(r=>c.includes(r)).map(r=>({id:r,name:t.resources?.components?.[r]?.component?.name})))}}:{},supportedLocales:t.supportedLocales,config:t.config};await C.writeFile(v,K.stringify(h));const S=f.join(I,"config.source.json");if(n&&await C.writeFile(S,JSON.stringify(n)),o){const r=f.join(I,"resources"),p=f.join(r,"components");await C.mkdir(p,{recursive:!0});for(const M of Object.keys(t?.resources?.components??{}).filter(_=>c.includes(_))){const _=t.resources?.components?.[M]?.component;_&&await ae(_,p,{getFilename:x=>`${x.name||"unnamed"}.${x.id}.yml`,exportAssets:e})}const m=f.join(I,"chunks");await C.mkdir(m,{recursive:!0});const T=await Qt();for(const M of Object.keys(t?.resources?.components??{}).filter(_=>c.includes(_))){const _=t.resources?.components?.[M]?.component;if(_&&_.renderer?.type==="react-component"){const x=_.renderer?.chunks??[];if(x?.length>0)for(const Y of x){const Ue=f.join(m,Y),fe=T?.[Y];try{fe&&await q(fe)&&!await q(Ue)&&await C.copyFile(fe,Ue)}catch(ot){u.logger.error(`copy chunk ${Y} error`,ot.message)}}}}}return I}async function Le(t,{importAssets:e,includeResources:a}={}){if(!await q(t))return null;let s,n=!1;try{(await C.lstat(t)).isDirectory()?s=t:/\.(tgz|gz|tar)$/.test(t)&&(n=!0,s=ze(),await Et.x({file:t,C:s}));const i=(await ne.glob("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}))[0],c=i&&f.join(f.dirname(i),"../../pages"),b=i&&f.join(f.dirname(i),"../../components"),O=i&&f.join(f.dirname(i),"../../routes");if(!i)return null;const R=await C.readFile(i,"utf-8"),w=K.parse(R),g=async(h,S,r)=>{let p=f.join(h,`${S}${r?`.${r}`:""}.yml`);if(!await q(p)&&(p=f.join(h,S,`index${r?`.${r}`:""}.yml`),!await q(p))||!(await C.lstat(p)).isFile())return null;const T=await C.readFile(p,"utf-8");return K.parse(T)},d=async(h,S)=>{try{const p=(await ne.glob(`*.${S}.yml`,{cwd:h,absolute:!0}))[0];if(!p)return null;const m=await C.readFile(p,"utf-8");return K.parse(m)}catch(r){u.logger.error("parse component error",r)}return null},I=async(h,S)=>{let r=f.join(h,`${S}.yml`);if(!await q(r)&&(r=f.join(h,S,"index.yml"),!await q(r))||!(await C.lstat(r)).isFile())return null;const m=await C.readFile(r,"utf-8");return K.parse(m)},D=L(await Promise.all(w.pages.map(async({slug:h})=>{const S=L(await Promise.all(w.supportedLocales.map(async({locale:m})=>{const T=c?await g(c,ie(h),m):void 0;if(T)return{locale:m,page:T};const M=c?await g(c,h,m):void 0;return M&&{locale:m,page:M}}))),r=S[0]?.page;if(!r)return null;const p=r.sections.map(ut.unzipSection);return{id:r.id||Me.nextId(),createdAt:r.createdAt,updatedAt:r.updatedAt,publishedAt:r.publishedAt,isPublic:r.isPublic??!0,templateConfig:r.templateConfig,slug:h,sections:Object.fromEntries(p.map(m=>[m.id,m])),sectionIds:p.map(m=>m.id),locales:Object.fromEntries(S.map(({locale:m,page:T})=>[m,T.meta])),dataSource:r.dataSource?Object.fromEntries([...new Set(S.flatMap(({page:m})=>Object.keys(m.dataSource??{})))].map(m=>[m,Object.fromEntries(S.map(({locale:T,page:M})=>{const _=M.dataSource?.[m];return[T,_||{}]}))])):Object.fromEntries([...new Set(S.flatMap(({page:m})=>m.sections.map(T=>T.id)))].map(m=>[m,Object.fromEntries(S.map(({locale:T,page:M})=>{const _=M.dataSource?.[m];if(_)return[T,_];const x=M.sections.find(Y=>Y.id===m);return[T,x?.properties||{}]}))]))}}))),P=L(await Promise.all((w?.routes||[]).map(async({path:h})=>{const S=O?await I(O,ie(h)):void 0;return{...S,id:S?.id||Me.nextId(),createdAt:S?.createdAt??new Date().toISOString(),updatedAt:S?.updatedAt??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:S?.path??`/${S?.id}`,params:S?.params,handler:S?.handler??"Pages Kit",isPublic:S?.isPublic??!0,enabledGenerate:S?.enabledGenerate??!1,displayTemplateId:S?.displayTemplateId??void 0,dataSource:S?.dataSource??{}}}))),y=b?L(await Promise.all((w.components||[]).map(async({id:h})=>d(b,h)))):[];if(e){const h=(...S)=>{u.logger.info(`[${n?f.basename(t):f.basename(f.join(t,"../../../../"))}] importAssets:`,...S)};try{h("wait image-bin api ready"),await Ct.default({resources:[`${je.getComponentWebEndpoint(u.IMAGE_BIN_NAME)}/api/sdk/uploads`],validateStatus:p=>p>=200&&p<=500}),h("image-bin api is ready");const S={},r={};h("start to upload assets"),await Promise.allSettled([xe(y,S,{getFilePath:p=>b&&f.join(b,p),onFinish:p=>{h(`upload ${p.length} component assets`)}}),xe(D,r,{getFilePath:(p,m)=>{const T=De.default(D,m.slice(0,1));return c&&f.join(c,f.dirname(T.slug),p)},onFinish:p=>{h(`upload ${p.length} page assets`)}})]),h("upload assets done"),Pe.clear(),global.gc&&global.gc()}catch(S){h("Error during asset import:",S)}}const v={};if(a){const h=i&&f.join(f.dirname(i),"../../resources/components"),S=L(await Promise.all((w.resources?.components||[]).map(async({id:r})=>d(h,r))));S.length>0&&(v.components=Object.fromEntries(S.map((r,p)=>[r.id,{index:p,component:r}])))}return{supportedLocales:w.supportedLocales,pageIds:D.map(h=>h.id),components:Object.fromEntries(y.map((h,S)=>[h.id,{index:S,data:h}])),pages:Object.fromEntries(D.map(h=>[h.id,h])),config:w.config||{},resources:v,routeIds:P.map(h=>h.id),routes:Object.fromEntries(P.map(h=>[h.id,h])),dataSourceIds:[],dataSources:{}}}finally{n&&s&&await C.rm(s,{force:!0,recursive:!0})}}async function Ae(t,e,{routes:a,mergeMode:s="byUpdateTime",deleteRoutes:n=!1,publishMode:o=void 0}={}){try{o&&u.clearPreloadComponentsCacheByMode(o)}catch(w){u.logger.error("clear preload page cache error",{error:w})}const{pages:l,pageIds:i,routeIds:c,routes:b,supportedLocales:O}=t;if(o==="production"){let w=a??[],g=null;for(const d of c??[]){const I=b?.[d];if(I?.params&&I?.params.length>0&&I?.paramsOptions&&I?.paramsOptions.length>0){const D=se.generateParamCombinations({basePath:I.path,params:I.params,routeId:I.id,paramsOptions:I.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),P=Object.fromEntries(D.map(y=>[`${d}-${y.paramOptionIds.join("-")}`,y]));g={...g||{},...P},a||(w=[...w,...D.map(y=>`${d}-${y.paramOptionIds.join("-")}`)])}else a||w.push(d)}u.logger.info("routeIds to be published: ",w);for(const d of w){let I=d;if(I.includes("-")){const[y]=I.split("-");I=y}const D=b?.[I];if(!D){const y=e.pageIds.indexOf(I);y!==-1&&n&&(e.pageIds.splice(y,1),delete e.pages[I]);for(const v of e.pageIds)v.includes(`${I}-`)&&(e.pageIds.splice(e.pageIds.indexOf(v),1),delete e.pages[v]);u.logger.info("delete main route page",I);continue}if(d.includes("-")&&!g?.[d]){const y=e.pageIds.indexOf(d);y!==-1&&n&&(e.pageIds.splice(y,1),delete e.pages[d]),u.logger.info("delete page",d);continue}if(!D.displayTemplateId){u.logger.info("no display template",d);continue}const P=l[D.displayTemplateId];if(!P){u.logger.info("no template page",d);continue}if(e.pageIds.includes(d)){if(u.logger.info("has need update page",d),s==="replace")e.pages[d]=he({page:P,route:D,state:t,routeId:d,routePathInfo:g?.[d]}),u.logger.info("replace page",d);else if(s==="byUpdateTime"){const y=e.pages[D.id];(!y||D.updatedAt&&D.updatedAt>y.updatedAt)&&(e.pages[d]=he({page:P,route:D,state:t,routeId:d,routePathInfo:g?.[d]}),u.logger.info("replace page by update time",d))}}else e.pageIds.push(d),e.pages[d]=he({page:P,route:D,state:t,routeId:d,routePathInfo:g?.[d]}),u.logger.info("add page",d)}if(n&&!a)for(const d of e.pageIds)w?.includes(d)||(delete e.pages[d],u.logger.info("delete page",d)),e.pageIds=[...e.pageIds].filter(I=>w?.includes(I))}else{for(const w of i){const g=l[w];if(g)if(e.pageIds.includes(g.id)){if(s==="replace")e.pages[g.id]=g;else if(s==="byUpdateTime"){const d=e.pages[g.id];(!d||g.updatedAt&&g.updatedAt>d.updatedAt)&&(e.pages[g.id]=g)}}else e.pageIds.push(g.id),e.pages[g.id]=g}for(const w of c){const g=b[w];if(g)if(e.routeIds.includes(g.id)){if(s==="replace")e.routes[g.id]=g;else if(s==="byUpdateTime"){const d=e.routes[g.id];(!d||g.updatedAt&&g.updatedAt>d.updatedAt)&&(e.routes[g.id]=g)}}else e.routeIds.push(g.id),e.routes[g.id]=g}}if(e.supportedLocales.splice(0,e.supportedLocales.length),e.supportedLocales.push(...W.default(O)),n)for(const w of Object.keys(e.components))delete e.components[w];let R=JSON.parse(JSON.stringify(t.components));R=Object.fromEntries(await Promise.all(Object.entries(R).map(async([w,g])=>{const d=await Xe(g?.data);return[w,{...g,data:d}]}))),Object.assign(e.components,R),Object.assign(e.config,JSON.parse(JSON.stringify(t.config))),Te.default(t.resources.components)||(e.resources.components=JSON.parse(JSON.stringify(t.resources.components||{})))}const Xe=u.memoizeWithFs(async t=>{if(!Te.default(t?.properties))return t;if(t?.renderer?.type==="react-component"){const{script:e,PROPERTIES_SCHEMA:a}=t?.renderer||{};if(a||e&&e.includes("PROPERTIES_SCHEMA"))try{const s=await u.getExportSchemaValueFromCode(e??"","PROPERTIES_SCHEMA",t.id,a);s&&s.length>0&&t&&(t.properties={},s.forEach((n,o)=>{t?.properties&&(t.properties[n.id]={index:o,data:n})}))}catch(s){u.logger.error("getPropertiesFromCode error",{componentId:t.id,name:t.name},{error:s})}}return t},{subdir:"getPropertiesFromCode"});let ce,Z,ue,de;const Qe=()=>je.getResources({types:[{did:ve,type:Ie},{did:Rt,type:Ie}]}),Qt=async()=>{const t=Qe(),e={};for(const a of t){const n=(await ne.glob("**/.blocklet/pages/pages.config.yml",{cwd:a.path,absolute:!0}))[0],o=n&&f.join(f.dirname(n),"../../chunks");if(o&&await q(o)){const l=await C.readdir(o);for(const i of l)e[i]=f.join(o,i)}}return e};function Ze(){return ce=(async()=>{const t=Qe();Z=(await Promise.all(t.map(async a=>{const s=a.path?await Le(a.path,{importAssets:!1}):void 0;return s?{blockletId:a.did,state:s,blockletTitle:a.title}:void 0}))).filter(a=>!!a),ue=Z.reduce((a,s)=>Object.assign(a,Object.fromEntries(Object.values(s.state.pages).map(n=>n?[n?.id,{page:n,blockletId:s.blockletId}]:[]))),{});const e=Z.reduce((a,s)=>Object.assign(a,Object.fromEntries(Object.values(s.state.components).map(n=>[n.data.id,{blockletId:s.blockletId,component:n.data}]))),{});de=Object.fromEntries(await Promise.all(Object.entries(e).map(async([a,s])=>{const n=await Xe(s.component);return[a,{...s,component:n}]})))})(),ce}function et(t){const e=Oe.default(async()=>{await Ze().catch(a=>{u.logger.error("load resource states error",{error:a})}),await t?.({states:Z,pages:ue,components:de})},3e3,{leading:!1,trailing:!0});return e(),E.default.events.on(E.default.Events.componentAdded,e),E.default.events.on(E.default.Events.componentRemoved,e),E.default.events.on(E.default.Events.componentStarted,e),E.default.events.on(E.default.Events.componentStopped,e),E.default.events.on(E.default.Events.componentUpdated,e),E.default.events.on(be,e),()=>{E.default.events.off(E.default.Events.componentAdded,e),E.default.events.off(E.default.Events.componentRemoved,e),E.default.events.off(E.default.Events.componentStarted,e),E.default.events.off(E.default.Events.componentStopped,e),E.default.events.off(E.default.Events.componentUpdated,e),E.default.events.off(be,e)}}const tt=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),at=Symbol.for("GLOBAL_ENV_UPDATE_LISTENER_KEY"),pe=globalThis;pe[tt]?.();pe[tt]=et(async({pages:t,components:e})=>{const a=await j.getProjectIds();u.logger.info(`start update resource states projects(${a.length})`,a);const s=Re.default(10);await Promise.race([new Promise(n=>{setTimeout(()=>{n({})},30*1e3)}),Promise.all(a.map(n=>s(async()=>{st({projectId:n,pages:t,components:e})})))]).catch(n=>{u.logger.error("update resource states failed:",n)})});pe[at]?.();pe[at]=()=>{const t=()=>{j.pageUrlMapCache.clear(),u.logger.info("[Cache CLEAR ALL] clear all page url map cache by env update")};return E.default.events.on(E.default.Events.envUpdate,t),()=>{E.default.events.off(E.default.Events.envUpdate,t)}};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 st({projectId:t,pages:e,components:a}){const s=j.sharedInstances[t];if(!s){u.logger.info(`projectId: ${t} not found in sharedInstances`);return}if(s.syncedStore.resources.pages=e,(await U.findByPk(t))?.useAllResources)s.syncedStore.resources.components=a;else{const l=(await ke.findAll({where:{projectId:t}})).map(c=>c.componentId),i=Object.fromEntries(Object.entries(a||{}).filter(([c])=>l.includes(c)));s.syncedStore.resources.components=i}u.logger.info(`update [${t}] resource states:`,{pages:Object.keys(s.syncedStore.resources.pages||{}).length,components:Object.keys(s.syncedStore.resources.components||{}).length})}const Se=new Map;async function nt(t){if(!Se.has(t)){const e=Oe.default(async a=>st({projectId:a,pages:ue,components:de}),3e3);Se.set(t,e)}return Se.get(t)(t)}async function Zt(){u.logger.info("trigger reload all project resource"),E.default.events.emit(be)}async function ea({ensureLoaded:t=!0}={}){return t&&(ce??=Ze(),await ce),{states:Z,pages:ue,components:de}}exports.COMPONENT_DID=ve;exports.PUBLISH_MODES=Wt;exports.Project=U;exports.RESOURCE_TYPE=Ie;exports.SITE_STATE_PATH=z;exports.STATE_MODES=Jt;exports.SiteState=j;exports.copyRecursive=$t;exports.downloadAsset=Ye;exports.downloadAssets=He;exports.fromPackage=Le;exports.getDefaultState=Ke;exports.getResourceStates=ea;exports.initPackResourceStates=et;exports.mergeState=Ae;exports.toPackage=We;exports.triggerReloadAllProjectResource=Zt;exports.updateResourceStatesByProjectId=nt;
|