@blocklet/pages-kit-inner-components 0.5.29 → 0.5.30

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.
@@ -7,7 +7,7 @@ import "lru-cache";
7
7
  import "node-fetch";
8
8
  import "ufo";
9
9
  import "crypto";
10
- import { c as _, G as E, d as i, e as d, j as l, k as N, m as O, h as P, g as c, f as g } from "./chunks/site-state-BB9-Tm4i.js";
10
+ import { c as _, G as E, d as i, e as d, j as l, k as N, m as O, h as P, g as c, f as g } from "./chunks/site-state-DJ3JcBMm.js";
11
11
  export {
12
12
  _ as CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS,
13
13
  E as GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS,
@@ -5,7 +5,7 @@ import R from "@blocklet/sdk/lib/wallet";
5
5
  import J from "@blocklet/sdk/lib/wallet-authenticator";
6
6
  import z from "@blocklet/sdk/lib/wallet-handler";
7
7
  import G, { resolve as x } from "path";
8
- import { l as T, g as Y } from "./chunks/site-state-BB9-Tm4i.js";
8
+ import { l as T, g as Y } from "./chunks/site-state-DJ3JcBMm.js";
9
9
  import { createSnapshotMiddleware as Q } from "@arcblock/crawler-middleware";
10
10
  import { PreloadComponentScriptModule as V } from "@blocklet/pages-kit/types";
11
11
  import { isMuiColorKey as X } from "@blocklet/pages-kit/utils/common";
@@ -1,4 +1,4 @@
1
- import { P as S, i as b, a as M, l as x, C as J, R as X, S as N, t as W, b as G } from "./chunks/site-state-BB9-Tm4i.js";
1
+ import { P as S, i as b, a as M, l as x, C as J, R as X, S as N, t as W, b as G } from "./chunks/site-state-DJ3JcBMm.js";
2
2
  import { AsyncLocalStorage as K } from "async_hooks";
3
3
  import { Router as Y } from "express";
4
4
  import d from "fs";
@@ -9,16 +9,16 @@ import C, { join as z } from "path";
9
9
  import D from "@blocklet/sdk/lib/middlewares/auth";
10
10
  import { getResourceExportDir as H } from "@blocklet/sdk/lib/component";
11
11
  new K();
12
- const Q = async (e, t, o) => {
12
+ const Q = async (o, t, e) => {
13
13
  var n, s, r, i;
14
14
  try {
15
- const { projectId: a } = e.params;
15
+ const { projectId: a } = o.params;
16
16
  if (!a)
17
- return o();
17
+ return e();
18
18
  const m = await S.findByPk(a);
19
19
  if (!m)
20
20
  return t == null ? void 0 : t.status(404).json({ error: "Project not found" });
21
- const y = (n = e.user) == null ? void 0 : n.did, w = ((s = e.user) == null ? void 0 : s.role) || "UNKNOWN_ROLE";
21
+ const y = (n = o.user) == null ? void 0 : n.did, w = ((s = o.user) == null ? void 0 : s.role) || "UNKNOWN_ROLE";
22
22
  if (!y)
23
23
  return t == null ? void 0 : t.status(401).json({ error: "Authentication required" });
24
24
  if (b()) {
@@ -27,75 +27,75 @@ const Q = async (e, t, o) => {
27
27
  return t == null ? void 0 : t.status(403).json({ error: "No permission to access this project in multi-tenant mode" });
28
28
  } else if (!["owner", "admin", "pagesEditor"].includes(w))
29
29
  return t == null ? void 0 : t.status(403).json({ error: "No permission to access this project in single-tenant mode" });
30
- e.project = m, e.projectId = a, o();
30
+ o.project = m, o.projectId = a, e();
31
31
  } catch (a) {
32
32
  x.error("Project middleware error:", a), t == null || t.status(500).json({ error: "Internal server error" });
33
33
  }
34
34
  };
35
- function T(e, t) {
36
- return new Promise((o, n) => {
37
- const s = d.createReadStream(e), r = d.createWriteStream(t);
38
- s.on("error", n), r.on("error", n), r.on("finish", o), s.pipe(r);
35
+ function B(o, t) {
36
+ return new Promise((e, n) => {
37
+ const s = d.createReadStream(o), r = d.createWriteStream(t);
38
+ s.on("error", n), r.on("error", n), r.on("finish", e), s.pipe(r);
39
39
  });
40
40
  }
41
- async function B(e, t) {
41
+ async function T(o, t) {
42
42
  await d.promises.mkdir(t, { recursive: !0 });
43
- const o = await d.promises.readdir(e, { withFileTypes: !0 });
44
- for (const n of o) {
45
- const s = C.join(e, n.name), r = C.join(t, n.name);
46
- n.isDirectory() ? await B(s, r) : await T(s, r);
43
+ const e = await d.promises.readdir(o, { withFileTypes: !0 });
44
+ for (const n of e) {
45
+ const s = C.join(o, n.name), r = C.join(t, n.name);
46
+ n.isDirectory() ? await T(s, r) : await B(s, r);
47
47
  }
48
48
  }
49
- async function V(e, t) {
50
- (await d.promises.stat(e)).isDirectory() ? await B(e, t) : await T(e, t);
49
+ async function V(o, t) {
50
+ (await d.promises.stat(o)).isDirectory() ? await T(o, t) : await B(o, t);
51
51
  }
52
- const h = (e, t, o) => b() ? D()(e, t, o) : D({ roles: ["owner", "admin", "pagesEditor"] })(e, t, o), Z = (e, t) => {
53
- const o = H({ projectId: e, releaseId: t });
54
- return z(o, J, X);
55
- }, O = Y(), L = "@page", U = "@component", I = ":", E = "ALL", F = "@project", k = ({ pageId: e, projectId: t }) => [L, t, e].join(I), q = (e) => {
56
- const [t, o, n] = e.split(I);
57
- if (t === L) return { pageId: n, projectId: o };
58
- }, v = ({ componentId: e, projectId: t }) => [U, t, e].join(I), tt = (e) => {
59
- const [t, o, n] = e.split(I);
60
- if (t === U) return { componentId: n, projectId: o };
61
- }, et = (e) => [F, e].join(I), ot = (e) => {
62
- const [t, o] = e.split(I);
63
- if (t === F) return o;
64
- }, rt = (e) => {
52
+ const h = (o, t, e) => b() ? D()(o, t, e) : D({ roles: ["owner", "admin", "pagesEditor"] })(o, t, e), Z = (o, t) => {
53
+ const e = H({ projectId: o, releaseId: t });
54
+ return z(e, J, X);
55
+ }, O = Y(), L = "@page", U = "@component", I = ":", E = "ALL", F = "@project", k = ({ pageId: o, projectId: t }) => [L, t, o].join(I), q = (o) => {
56
+ const [t, e, n] = o.split(I);
57
+ if (t === L) return { pageId: n, projectId: e };
58
+ }, v = ({ componentId: o, projectId: t }) => [U, t, o].join(I), tt = (o) => {
59
+ const [t, e, n] = o.split(I);
60
+ if (t === U) return { componentId: n, projectId: e };
61
+ }, ot = (o) => [F, o].join(I), et = (o) => {
62
+ const [t, e] = o.split(I);
63
+ if (t === F) return e;
64
+ }, rt = (o) => {
65
65
  try {
66
- return JSON.parse(e);
66
+ return JSON.parse(o);
67
67
  } catch {
68
68
  }
69
69
  return {};
70
70
  };
71
- async function A(e) {
72
- const t = await N.shared(e).getState("production"), o = await S.findByPk(e), n = t.pageIds.map((r) => {
71
+ async function A(o) {
72
+ const t = await N.getStateByProjectId(o, "production"), e = await S.findByPk(o), n = t.pageIds.map((r) => {
73
73
  const i = t.pages[r];
74
74
  if (i)
75
- return { id: k({ pageId: r, projectId: e }), name: i.slug };
75
+ return { id: k({ pageId: r, projectId: o }), name: i.slug };
76
76
  }).filter(Boolean), s = $(Object.values(t.components), (r) => r.index).map(({ data: r }) => ({
77
- id: v({ componentId: r.id, projectId: e }),
77
+ id: v({ componentId: r.id, projectId: o }),
78
78
  name: r.name || r.id
79
79
  }));
80
80
  return {
81
- id: et(e),
82
- name: (o == null ? void 0 : o.name) || "Unnamed Project",
81
+ id: ot(o),
82
+ name: (e == null ? void 0 : e.name) || "Unnamed Project",
83
83
  children: [
84
- { id: k({ pageId: E, projectId: e }), name: "Pages", children: n },
84
+ { id: k({ pageId: E, projectId: o }), name: "Pages", children: n },
85
85
  {
86
- id: v({ componentId: E, projectId: e }),
86
+ id: v({ componentId: E, projectId: o }),
87
87
  name: "Components",
88
88
  children: s
89
89
  }
90
90
  ]
91
91
  };
92
92
  }
93
- O.get("/resources", h, async (e, t) => {
94
- const { projectId: o } = rt(e.query.resourcesParams);
95
- if (o) {
96
- e.params = { ...e.params, projectId: o }, await Q(e, t, () => {
93
+ O.get("/resources", h, async (o, t) => {
94
+ const { projectId: e } = rt(o.query.resourcesParams);
95
+ if (e) {
96
+ o.params = { ...o.params, projectId: e }, await Q(o, t, () => {
97
97
  });
98
- const r = await A(o);
98
+ const r = await A(e);
99
99
  t.json({ resources: [r] });
100
100
  return;
101
101
  }
@@ -113,10 +113,10 @@ const nt = g.object({
113
113
  resources: g.array().items(g.string()).required(),
114
114
  locale: g.string().allow("")
115
115
  });
116
- O.post("/resources", h, async (e, t) => {
117
- const { resources: o, projectId: n, releaseId: s } = await nt.validateAsync(e.body), r = "production", i = [], a = [];
118
- for (const c of o) {
119
- if (ot(c))
116
+ O.post("/resources", h, async (o, t) => {
117
+ const { resources: e, projectId: n, releaseId: s } = await nt.validateAsync(o.body), r = "production", i = [], a = [];
118
+ for (const c of e) {
119
+ if (et(c))
120
120
  continue;
121
121
  const { pageId: l, projectId: f } = q(c) || {};
122
122
  if (l)
@@ -135,7 +135,7 @@ O.post("/resources", h, async (e, t) => {
135
135
  const m = _(i, "projectId"), y = _(a, "projectId"), w = /* @__PURE__ */ new Set([...Object.keys(m), ...Object.keys(y)]), P = Z(n, s);
136
136
  d.rmSync(P, { recursive: !0, force: !0 }), d.mkdirSync(P, { recursive: !0 });
137
137
  for (const c of w) {
138
- const l = await N.shared(c).getState(r), f = m[c], u = y[c], p = f == null ? void 0 : f.map((j) => j.pageId), R = u == null ? void 0 : u.map((j) => j.componentId);
138
+ const l = await N.getStateByProjectId(c, r), f = m[c], u = y[c], p = f == null ? void 0 : f.map((j) => j.pageId), R = u == null ? void 0 : u.map((j) => j.componentId);
139
139
  if (p != null && p.length || R != null && R.length) {
140
140
  const j = await W(l, {
141
141
  exportAssets: !0,
@@ -151,8 +151,8 @@ O.post("/resources", h, async (e, t) => {
151
151
  }
152
152
  t.json({});
153
153
  });
154
- O.get("/all-resources", h, async (e, t) => {
155
- const { states: o } = await G(), n = o == null ? void 0 : o.map((s) => {
154
+ O.get("/all-resources", h, async (o, t) => {
155
+ const { states: e } = await G(), n = e == null ? void 0 : e.map((s) => {
156
156
  const r = {
157
157
  blockletId: s.blockletId,
158
158
  blockletTitle: s.blockletTitle,
@@ -1,4 +1,4 @@
1
- import { q as j, o as q, p as v, S as B, r as L, s as U, u as h, b as y, w as z, v as C, n as F, t as G, x as J } from "./chunks/site-state-BB9-Tm4i.js";
1
+ import { q as j, o as q, p as v, S as B, r as L, s as U, u as h, b as y, w as z, v as C, n as F, t as G, x as J } from "./chunks/site-state-DJ3JcBMm.js";
2
2
  import "@blocklet/pages-kit/utils/property";
3
3
  import "@blocklet/pages-kit/utils/route";
4
4
  import "@blocklet/sdk/lib/component";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blocklet/pages-kit-inner-components",
3
- "version": "0.5.29",
3
+ "version": "0.5.30",
4
4
  "description": "Pages Kit inner components library",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -204,8 +204,8 @@
204
204
  "yaml": "^2.5.0",
205
205
  "yjs": "^13.6.18",
206
206
  "zustand": "^4.5.5",
207
- "@blocklet/pages-kit": "^0.5.29",
208
- "@blocklet/pages-kit-block-studio": "^0.5.29"
207
+ "@blocklet/pages-kit": "^0.5.30",
208
+ "@blocklet/pages-kit-block-studio": "^0.5.30"
209
209
  },
210
210
  "devDependencies": {
211
211
  "@trivago/prettier-plugin-sort-imports": "^5.2.1",
@@ -1,57 +0,0 @@
1
- "use strict";var Pt=Object.defineProperty;var _t=(e,s,t)=>s in e?Pt(e,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[s]=t;var x=(e,s,t)=>_t(e,typeof s!="symbol"?s+"":s,t);const jt=require("@blocklet/pages-kit/builtin/utils"),ye=require("@blocklet/pages-kit/types"),re=require("@blocklet/pages-kit/utils/property"),ie=require("@blocklet/quickjs"),Dt=require("@blocklet/sdk/lib/config"),qe=require("lru-cache"),at=require("node-fetch"),M=require("ufo"),W=require("crypto"),vt=require("@blocklet/logger"),S=require("fs"),w=require("path"),xt=require("lodash/isNil"),kt=require("@blocklet/pages-kit/utils/builtin"),ot=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),$e=require("@blocklet/sdk/lib/component"),Nt=require("autoprefixer"),Rt=require("esbuild"),Lt=require("postcss"),Mt=require("tailwindcss"),Ut=require("typescript"),Q=require("@syncedstore/core"),Ft=require("yjs"),qt=require("@blocklet/pages-kit/utils/data-source"),be=require("@blocklet/pages-kit/utils/route"),$t=require("lodash"),Bt=require("@reactivedata/reactive"),ke=require("glob"),Ht=require("lib0/decoding"),Gt=require("lib0/encoding"),Vt=require("lodash/cloneDeep"),Jt=require("lodash/debounce"),zt=require("lodash/get"),Kt=require("lodash/isEmpty"),Yt=require("lodash/pick"),Wt=require("lodash/set"),Qt=require("lodash/union"),Xt=require("nanoid"),Zt=require("p-limit"),es=require("stream/promises"),ts=require("tar"),ss=require("wait-on"),se=require("y-protocols/awareness"),je=require("y-protocols/sync"),ns=require("yaml"),j=require("sequelize");require("sqlite3");require("@blocklet/pages-kit/types/state");const N=e=>e&&e.__esModule?e:{default:e};function de(e){if(e&&e.__esModule)return e;const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const t in e)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(s,t,n.get?n:{enumerable:!0,get:()=>e[t]})}}return s.default=e,Object.freeze(s)}const I=N(Dt),as=N(at),os=N(vt),rt=N(w),rs=N(xt),is=N(Nt),cs=de(Rt),ls=N(Lt),ds=N(Mt),L=N(Ut),B=de(Ft),De=de(Ht),k=de(Gt),us=N(Vt),it=N(Jt),Be=N(zt),ps=N(Kt),fs=N(Yt),Qe=N(Wt),ms=N(Qt),gs=N(Zt),hs=N(ss),X=de(ns);I.default.env.mode;I.default.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY;I.default.env.OPENAI_BASE_URL||process.env.OPENAI_BASE_URL;I.default.env.TRANSLATE_ADDITIONAL_PROMPT||process.env.TRANSLATE_ADDITIONAL_PROMPT;I.default.env.PAGE_CONTENT_ADDITIONAL_PROMPT||process.env.PAGE_CONTENT_ADDITIONAL_PROMPT;const ys="image-bin";I.default.env.INIT_TEMPLATE_PATH;const Ss=process.env.DATABASE_URL||rt.default.join(I.default.env.dataDir,"db/pages-kit.db"),Xe=I.default,ws=()=>I.default.env.tenantMode==="multiple",bs=()=>{var e;return(rs.default(Xe.env.preferences.multiTenantAllProjectAccessPassports)?[]:(e=Xe.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:e.split(","))||[]},Es=rt.default.join(I.default.env.dataDir,"fs-memoize-cache"),Is=I.default.env.FS_MEMOIZE_CACHE_VERSION||"v1.0.0",O=os.default("pages-kit"),Os=j.DataTypes.sqlite.DATE.parse;j.DataTypes.sqlite.DATE.parse=(e,s)=>typeof e=="number"?new Date(e):Os(e,s);const ue=new j.Sequelize({dialect:"sqlite",storage:Ss,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});ue.query("pragma journal_mode = WAL;");ue.query("pragma synchronous = normal;");ue.query("pragma journal_size_limit = 67108864;");class Te extends j.Model{}Te.init({id:{type:j.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:j.DataTypes.UUIDV4},projectId:{type:j.DataTypes.UUID,allowNull:!1},componentId:{type:j.DataTypes.STRING,allowNull:!1}},{sequelize:ue,tableName:"ProjectComponents",timestamps:!1});class J extends j.Model{static async getProjectByIdOrSlug(s){return J.findOne({where:{[j.Op.or]:[{id:s},{slug:s}]}})}}J.init({id:{type:j.DataTypes.UUID,defaultValue:j.DataTypes.UUIDV4,primaryKey:!0},name:{type:j.DataTypes.STRING,allowNull:!1},description:j.DataTypes.TEXT,createdAt:j.DataTypes.DATE,updatedAt:j.DataTypes.DATE,createdBy:{type:j.DataTypes.STRING,allowNull:!1},updatedBy:{type:j.DataTypes.STRING,allowNull:!1},slug:j.DataTypes.STRING,icon:j.DataTypes.STRING,pinnedAt:j.DataTypes.DATE,useAllResources:j.DataTypes.BOOLEAN,npmSecret:j.DataTypes.STRING,relatedBlocklets:{type:j.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(e){this.setDataValue("relatedBlocklets",JSON.stringify(e||{}))}}},{sequelize:ue,paranoid:!0});J.hasMany(Te,{foreignKey:"projectId",as:"components"});const As=Es,Ts=Is,Ne=7*24*60*60*1e3,Cs=24*60*60*1e3,ct=async(e="")=>{const s=w.join(As,e);try{if(!(await S.promises.stat(s)).isDirectory())throw new Error(`${s} is not a directory`)}catch{await S.promises.mkdir(s,{recursive:!0})}return s},Ps=(e,s)=>{const t=W.createHash("md5").update(s).digest("hex");return w.join(e,`${Ts}-${t}.json`)},_s=async(e="")=>{const s=await ct(e),t=Date.now();try{const n=await S.promises.readdir(s);await Promise.all(n.filter(a=>a.endsWith(".json")).map(async a=>{const o=w.join(s,a);try{const d=await S.promises.readFile(o,"utf-8"),i=JSON.parse(d);i.createdAt&&t-i.createdAt>Ne&&await S.promises.unlink(o)}catch{try{const i=await S.promises.stat(o);t-i.mtimeMs>Ne&&await S.promises.unlink(o)}catch{}}}))}catch(n){console.error(`Failed to cleanup cache in ${s}:`,n)}},js=(()=>{const e=new Set;return setInterval(async()=>{await Promise.all(Array.from(e).map(n=>_s(n)))},Cs).unref(),n=>{e.add(n)}})();function He(e,s){return s.subdir&&js(s.subdir),ie.memoize(async(...n)=>{const a=await ct(s.subdir||""),o=s.keyGenerator?s.keyGenerator(...n):JSON.stringify(n),d=Ps(a,o);try{const i=await S.promises.readFile(d,"utf-8"),{value:p,createdAt:r}=JSON.parse(i);if(r&&Date.now()-r>Ne)throw await S.promises.unlink(d).catch(()=>{}),new Error("Cache expired");return p}catch{const p=await e(...n),r=JSON.stringify({value:p,createdAt:Date.now()});return S.promises.writeFile(d,r,"utf-8").catch(u=>{console.error("Failed to write fs cache:",u)}),p}},{keyGenerator:s.keyGenerator,lruOptions:s.lruOptions})}const Ds=async(e,{componentId:s})=>{const t=`@tailwind components;
2
- @tailwind utilities;
3
- `,n=`.CustomComponent_${s}`;return(await ls.default([ds.default({content:[{raw:e,extension:"tsx"}]}),is.default({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),o=>{o.walkRules(d=>{d.selectors=d.selectors.map(i=>i.replace(/\.(.+)/g,`${n}.$1,${n} .$1`))})}]).process(t)).css},vs=async(e,{componentId:s})=>{const t=await Ds(e,{componentId:s});return`export const __PagesKit_CSS__ = ${JSON.stringify(t)};
4
-
5
- ${e}
6
- `},Ze=He(async(e,s)=>{let t=L.default.transpileModule(e,{compilerOptions:{jsx:L.default.JsxEmit.React,target:L.default.ScriptTarget.ES2016,module:L.default.ModuleKind.ESNext},transformers:{before:[ot.createBuiltinModuleTransformer(L.default)]}}).outputText;if(s.tailwind&&(t=await vs(t,{componentId:s.componentId})),s.module===ye.PreloadComponentScriptModule.ESM)return t;const n=L.default.transpileModule(t,{compilerOptions:{jsx:L.default.JsxEmit.React,target:L.default.ScriptTarget.ES2016,module:L.default.ModuleKind.CommonJS,moduleResolution:L.default.ModuleResolutionKind.Node16}}).outputText;return s.module===ye.PreloadComponentScriptModule.CJS?n:ks(s.moduleName,n)},{keyGenerator:(e,s)=>{const t=W.createHash("md5").update(e).digest("hex"),n={...s,componentId:s.componentId,module:s.module,...s.module!==ye.PreloadComponentScriptModule.ESM?{moduleName:s.moduleName}:{},tailwind:s.tailwind};return JSON.stringify(["transpileModule",t,n])},lruOptions:{max:100,ttl:1e3*60*60},subdir:"transpileModule"}),xs=async(e,s)=>{var d,i;const n=(i=(d=(await cs.build({entryPoints:["index.tsx"],external:Object.keys(kt.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(p){let r=null;p.onResolve({filter:/.*/},u=>u.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:u.path==="./component"?{path:"component.tsx",namespace:"vfs"}:null),p.onLoad({filter:/.*/,namespace:"vfs"},async u=>{var g;if(u.path==="index.tsx")return{contents:`export { ${s} } from './component'`,loader:"tsx"};if(u.path==="component.tsx")return{contents:e,loader:"tsx"};if(ot.isRelativeModule(u.path)){const y=u.path.split("/").pop();if(r||(r=await Ce({ensureLoaded:!1})),(g=r==null?void 0:r.chunks)!=null&&g[y])try{const c=S.readFileSync(r.chunks[y],"utf-8");return O.info("get chunk from local file system",y),{contents:c,loader:"tsx"}}catch{}}return null})}}]})).outputFiles)==null?void 0:d[0])==null?void 0:i.contents;if(!n)throw new Error("Failed to build server code");const a=Buffer.from(n).toString();return L.default.transpileModule(a,{compilerOptions:{module:L.default.ModuleKind.ESNext,target:L.default.ScriptTarget.ES2020}}).outputText},lt=He(async(e,s)=>{const t=await xs(e,s);return new RegExp(`export\\s+\\{\\s+${s}\\s+\\}`,"m").test(t)?t:void 0},{keyGenerator:(e,s)=>{const t=W.createHash("md5").update(e).digest("hex");return JSON.stringify(["extractExportValueSchema",t,s])},lruOptions:{max:100,ttl:1e3*60*60},subdir:"extractExportValueSchema"}),ks=(e,s)=>`// GENERATED FILE. DO NOT EDIT.
7
- var ${e} = async function () {
8
-
9
- const exports = {};
10
- let moduleExports = null;
11
-
12
- // add commonjs module compatibility layer
13
- const module = { exports: moduleExports };
14
-
15
- // execute component code
16
- ${s}
17
-
18
- // handle possible module.exports
19
- if (module.exports && module.exports !== moduleExports) {
20
- // if module.exports is used, use it first
21
- return typeof module.exports === 'object' ? module.exports : { default: module.exports };
22
- }
23
-
24
- // ensure a default export
25
- if (!('default' in exports) && Object.keys(exports).length === 0) {
26
- // module has no exports, return null to indicate invalid
27
- return null;
28
- }
29
-
30
- return exports;
31
- };
32
- `,ae=new qe.LRUCache({max:100}),dt=60*60,Re=60;function ut(e){O.info("clear preload components cache",{cacheKey:e}),ae.delete(e)}function pt(e){for(const s of ae.keys())s.includes(e)&&(O.info("clear preload components cache",{cacheKey:s}),ut(s))}function ft({mode:e,instanceId:s,componentId:t,locale:n}){return["getPreloadComponents",e,s,t,n].join("-")}async function Ns({mode:e,req:s,state:t,locale:n,instances:a,module:o}){const{supportedLocales:d,config:{defaultLocale:i}}=t;if(!i)return null;const p=(await Promise.all(a.map(async c=>{try{const l=ft({mode:e,instanceId:c.id,componentId:c.componentId,locale:n});if(e!=="draft"&&c.useCache&&ae.has(l))return O.info(`get preload component from cache: ${l}`),ae.get(l);const f=ce({state:t,componentId:c.componentId});if(!f)return null;const E=await mt({req:s,state:t,componentId:f.id,locale:n,defaultLocale:i,properties:c.properties});if(!E)return null;const v={instanceId:c.id,preload:E};if(e!=="draft"&&c.useCache){let T=dt;c.cacheDuration&&(T=c.cacheDuration),O.info(`set preload component to cache(${T}s): ${l}`),ae.set(l,v,{ttl:T*1e3})}return v}catch(l){return O.error("get preload component error",{instanceId:c.id,componentId:c.componentId},{error:l}),null}}))).filter(c=>!!c),r=Object.values(p.reduce((c,l)=>({...c,...l.preload.components}),{}));async function u(){const c=await Promise.all(r.map(async l=>{const f=re.componentUMDName({componentId:l.component.id}),E=o===ye.PreloadComponentScriptModule.ESM?{module:o,script:await Ze(l.script,{componentId:l.component.id,module:o,tailwind:e!=="draft"})}:{module:o,script:await Ze(l.script,{componentId:l.component.id,module:o,moduleName:f,tailwind:e!=="draft"}),moduleName:f};return[l.component.id,{component:l.component,script:E}]}));return Object.fromEntries(c)}const g=await u();return{config:{defaultLocale:i,supportedLocales:d},components:g,instances:p.map(c=>({id:c.instanceId,componentId:c.preload.component.id,locales:{[c.preload.locale]:{props:c.preload.props}}}))}}async function mt({req:e,state:s,componentId:t,locale:n,defaultLocale:a,properties:o}){const{supportedLocales:d}=s,i=ce({state:s,componentId:t});if(!i)return null;const p=d.some(u=>u.locale===n)?n:a;if(!p)return null;const r=await gt({req:e,state:s,componentId:t,locale:p,defaultLocale:a,properties:o});return r?{component:i,...r}:null}const Rs=20;async function gt({req:e,depth:s=0,state:t,componentId:n,locale:a,defaultLocale:o,properties:d}){if(s>Rs)throw new RangeError("max component depth exceeded");const i=Ls({state:t,componentId:n,properties:d,locale:a});if(!i)return null;const{props:p}=i,r={locale:a||o,components:{[i.component.id]:{component:i.component,script:i.script}},props:{...p}};try{const u=await Us({...i,req:e});u!=null&&u.props&&Object.assign(r.props,u.props)}catch(u){O.error("preload data at server side error",{componentId:n,name:i.component.name},{error:u})}return await Promise.all(Object.entries(p).map(async([u,g])=>{if((g==null?void 0:g.type)===re.RenderNestedComponent){const y=await gt({req:e,depth:s+1,state:t,componentId:g.componentId,locale:a,defaultLocale:o,properties:g.properties});y&&(Object.assign(r.components,y.components),Object.assign(r.props,{[u]:{type:re.RenderNestedComponent,componentId:g.componentId,props:y.props}}))}})),r}function Ls({state:e,componentId:s,locale:t,properties:n}){const a=ce({state:e,componentId:s});if(!a)return null;const o=re.mergeComponent({componentId:s,getComponent:d=>ce({state:e,componentId:d}),locale:t,defaultLocale:e.config.defaultLocale,properties:n});return o?{component:a,script:o.script,props:{locale:t,...o.props}}:null}function ce({state:e,componentId:s}){var t,n,a;return((t=e.components[s])==null?void 0:t.data)??((a=(n=e.resources.components)==null?void 0:n[s])==null?void 0:a.component)}function Ms({state:e,name:s}){var n,a;const t=s.toLowerCase();return((n=Object.values(e.components).find(o=>{var d;return((d=o.data.name)==null?void 0:d.toLowerCase())===t}))==null?void 0:n.data)??((a=e.resources.components&&Object.values(e.resources.components).find(o=>{var d;return((d=o.component.name)==null?void 0:d.toLowerCase())===t}))==null?void 0:a.component)}async function Us({component:e,script:s,props:t,req:n}){if(!(s!=null&&s.includes("getServerSideProps")))return null;const a=await lt(s,"getServerSideProps");if(!a)return null;const o=new Promise(i=>{setTimeout(()=>{i({})},Re*1e3)});return await Promise.race([o,ie.Sandbox.callFunction({code:`${a}
33
-
34
- export async function getServerSidePropsWrapper(props) {
35
- const { location, fetch, props: componentProps } = props;
36
- // 使用局部变量而不是全局变量
37
- const originalLocation = typeof window !== 'undefined' ? window.location : undefined;
38
- const originalFetch = globalThis.fetch;
39
-
40
- try {
41
- globalThis.location = location;
42
- globalThis.fetch = fetch;
43
- return await getServerSideProps(componentProps);
44
- } finally {
45
- // 清理全局状态
46
- if (originalLocation) globalThis.location = originalLocation;
47
- if (originalFetch) globalThis.fetch = originalFetch;
48
- }
49
- }`,filename:`${e.name||e.id}.js`,moduleLoader:i=>{if(i==="@blocklet/pages-kit/builtin/utils")return`const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
50
- export { joinURL, withQuery, getQuery, getComponentMountPoint }
51
- `;if(i==="@blocklet/pages-kit/builtin/dayjs")return ie.BuiltinModules.dayjs},global:{console:{log:(...i)=>{O.info(...i)},warn:(...i)=>{O.warn(...i)},error:(...i)=>{O.error(...i)}},getComponentMountPoint:jt.getComponentMountPoint,joinURL:M.joinURL,withQuery:M.withQuery,getQuery:M.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:M.joinURL(M.withHttps(n.hostname),n.originalUrl)},fetch:(i,{...p}={})=>{const r=typeof i=="string"&&i.startsWith("/")?M.joinURL(I.default.env.appUrl,i):i;if(typeof r=="string"&&M.parseURL(r).host===M.parseURL(I.default.env.appUrl).host){const u=n.get("cookie");if(u){const g=new at.Headers(p.headers);g.set("cookie",u),p.headers=g}}return as.default(r,{...p,timeout:Re*1e3}).then(u=>({ok:u.ok,status:u.status,statusText:u.statusText,headers:Object.fromEntries(u.headers.entries()),json:()=>u.json()}))},props:t}]})])}const ht=ie.memoize(async(e,s,t)=>{if(!(e!=null&&e.includes(s)))return null;const n=await lt(e,s);if(n)try{return await ie.Sandbox.callFunction({code:`
52
- ${n}
53
-
54
- export function get${s}SchemaWrapper() {
55
- return ${s};
56
- }
57
- `,filename:`${t}.js`,functionName:`get${s}SchemaWrapper`})}catch(a){return O.error(`获取 ${s} 失败`,{componentId:t,error:a}),null}return null},{keyGenerator:(e,s,t)=>{const n=W.createHash("md5").update(e).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",n,s,t])},lruOptions:{max:100,ttl:1e3*60*60}}),Fs="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",Le="page",Me="trigger-reload-project-resource",Ge=Fs,qs="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM";function Ee(e){e.observeDeep(s=>{s.some(t=>t.changes.keys.has("updatedAt")||t.changes.keys.has("publishedAt"))||e.set("updatedAt",new Date().toISOString())})}function yt(){return S.mkdtempSync(w.join(I.default.env.dataDir,"tmp-"))}function Ie(e,s,t=[]){return Array.isArray(e)?e.flatMap((n,a)=>Ie(n,s,[...t,a])):typeof e=="object"?e===null?[]:Object.entries(e).flatMap(([n,a])=>Ie(a,s,[...t,n])):s(e)?[t]:[]}function U(e){return e.filter(s=>s!=null)}function $s(e){e.pages&&Object.keys(e.pages).forEach(t=>{const n=Q.getYjsValue(e.pages[t]);n&&n instanceof B.Map&&Ee(n)});const s=Q.getYjsValue(e.pages);s&&s instanceof B.Map&&s.observe(t=>{t.changes.keys.forEach((n,a)=>{if(n.action==="add"){const o=Q.getYjsValue(e.pages[a]);o&&o instanceof B.Map&&Ee(o)}})})}function Bs(e){e.routes&&Object.keys(e.routes).forEach(t=>{var a;const n=Q.getYjsValue((a=e.routes)==null?void 0:a[t]);n&&n instanceof B.Map&&Ee(n)});const s=Q.getYjsValue(e.routes);s&&s instanceof B.Map&&s.observe(t=>{t.changes.keys.forEach((n,a)=>{var o;if(n.action==="add"){const d=Q.getYjsValue((o=e.routes)==null?void 0:o[a]);d&&d instanceof B.Map&&Ee(d)}})})}function Hs(e,s){var t;for(const n of s||Object.keys(e.routes||{})){let a=n,o=[];if(n.includes("-")){const[d,...i]=n.split("-");a=d,o=i||[]}if(((t=e.routes)==null?void 0:t[a])!==void 0){e.routes[a].publishedAt=new Date().toISOString();const d=e.routes[a];if(!d||!d.params||d.params.length===0)continue;if(n.includes("-")&&o.length>0){const i=be.getRouteMetaDataByOptionIds(o,d);i&&(i.publishedAt=new Date().toISOString())}if(!s){const i=be.generateParamCombinations({basePath:d.path,params:d.params,routeId:d.id,paramsOptions:d.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const p of i)p.routeMetaData??(p.routeMetaData={}),p.routeMetaData.publishedAt=new Date().toISOString()}}}}function ve({page:e,route:s,state:t,routeId:n,routePathInfo:a}){var d,i,p,r,u,g,y,c,l;O.info(`Executing datasource data assembly, routeId: ${n}, routePathInfo: ${JSON.stringify(a)}`);const o={...$t.cloneDeep(e),id:n,slug:(a==null?void 0:a.path)??s.path,createdAt:s.createdAt,updatedAt:((d=a==null?void 0:a.routeMetaData)==null?void 0:d.updatedAt)??s.updatedAt,publishedAt:((i=a==null?void 0:a.routeMetaData)==null?void 0:i.publishedAt)??s.publishedAt,isPublic:(((p=a==null?void 0:a.routeMetaData)==null?void 0:p.isPublic)??s.isPublic)&&s.isPublic};for(const f of t.supportedLocales){if(s.dataSource){let E=s.id;a&&(E=a.paramOptionIds.join("-"));const v=((g=(u=(r=s.dataSource.pathDataMappings)==null?void 0:r[E])==null?void 0:u.dataCache)==null?void 0:g[f.locale])??((l=(c=(y=s.dataSource.pathDataMappings)==null?void 0:y[E])==null?void 0:c.dataCache)==null?void 0:l[t.config.defaultLocale||"en"]);if(!v)continue;qt.setPageDataSource(o,t,f.locale,v)}a&&a.routeMetaData&&(a.routeMetaData.publishedAt=new Date().toISOString())}return o}const{uploadToMediaKit:Gs}=require("@blocklet/uploader-server"),Se=Xt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),Ve=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,oe=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,et=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Vs=1e4,Js=3e4,ge=0,xe=1,zs=0,Ks=1,Ue=I.default,ne=w.join(process.env.BLOCKLET_DATA_DIR,"site-state"),Ys=["production","draft"],Ws=["production"];function Oe(e){return(e==null?void 0:e.replace(/\//g,"|"))||""}function Qs(){var t;const e=Ue.env.languages.map(n=>({locale:n.code,name:n.name})),s=(t=e[0])==null?void 0:t.locale;return{pageIds:[],pages:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{},components:{},supportedLocales:e,config:{defaultLocale:s},resources:{}}}const V=class V extends B.Doc{constructor(t){super();x(this,"states",{});x(this,"syncedStore");x(this,"conns",new Map);x(this,"awareness");x(this,"awarenessChangeHandler",({added:t,updated:n,removed:a},o)=>{const d=t.concat(n,a);if(o!==null){const r=this.conns.get(o);r&&(t.forEach(u=>{r.add(u)}),a.forEach(u=>{r.delete(u)}))}const i=k.createEncoder();k.writeVarUint(i,xe),k.writeVarUint8Array(i,se.encodeAwarenessUpdate(this.awareness,d));const p=k.toUint8Array(i);this.conns.forEach((r,u)=>this.send(u,p))});x(this,"updateHandler",t=>{const n=k.createEncoder();k.writeVarUint(n,ge),je.writeUpdate(n,t);const a=k.toUint8Array(n);this.conns.forEach((o,d)=>this.send(d,a))});x(this,"ensureDataStructure",()=>{var p;const{supportedLocales:t,pages:n,pageIds:a,config:o,routes:d,routeIds:i}=this.syncedStore;{const r=new Set(Object.keys(n));let u=0;for(;u<a.length;){const g=a[u];r.has(g)?(r.delete(g),u++):a.splice(u,1)}}{const r=new Set(Object.keys(d));let u=0;for(;u<i.length;){const g=i[u];r.has(g)?(r.delete(g),u++):i.splice(u,1)}}t.splice(0,t.length),t.push(...Ue.env.languages.map(r=>({locale:r.code,name:r.name}))),o.defaultLocale=(p=t[0])==null?void 0:p.locale;{let r=0;const u=new Set;for(;r<t.length;){const{locale:g}=t[r];u.has(g)?t.splice(r,1):(r++,u.add(g))}}});x(this,"send",(t,n)=>{t.readyState!==zs&&t.readyState!==Ks&&this.closeConn(t);try{t.send(n,a=>{a&&this.closeConn(t)})}catch{this.closeConn(t)}});x(this,"closeConn",t=>{if(t.removeAllListeners(),this.conns.has(t)){const n=this.conns.get(t);this.conns.delete(t),n&&se.removeAwarenessStates(this.awareness,Array.from(n),null)}t.close()});x(this,"autoSave",it.default(()=>{S.mkdirSync(w.dirname(this.draftYjsFilePath),{recursive:!0}),S.writeFileSync(this.draftYjsFilePath,B.encodeStateAsUpdate(this))},Vs));x(this,"save",({flush:t=!1}={})=>{this.autoSave(),t&&this.autoSave.flush()});x(this,"publish",async({mode:t,routes:n})=>{const a=await this.getState("draft"),o=await this.getState("production");await Fe(a,o,{routes:n,mergeMode:"replace",deleteRoutes:!0,publishMode:t}),o.config.publishedAt=new Date().getTime(),Hs(this.syncedStore,n),await this.setState(t,o)});x(this,"mergeState",async(t,n)=>{var i,p,r;const a=JSON.parse(JSON.stringify(n));(i=t.config).fontFamily??(i.fontFamily={});const o=(p=a.config)==null?void 0:p.fontFamily,d=(r=t.config)==null?void 0:r.fontFamily;t.config.fontFamily.title=(o==null?void 0:o.title)||(d==null?void 0:d.title),t.config.fontFamily.description=(o==null?void 0:o.description)||(d==null?void 0:d.description),await new Promise((u,g)=>{this.transact(async()=>{try{const y=await Fe(t,n);u(y)}catch(y){g(y)}})})});x(this,"addConnection",t=>{if(this.conns.has(t))return;t.binaryType="arraybuffer",this.conns.set(t,new Set),t.on("message",o=>this.messageListener(t,new Uint8Array(o)));let n=!0;const a=setInterval(()=>{if(!n)this.conns.has(t)&&this.closeConn(t),clearInterval(a);else if(this.conns.has(t)){n=!1;try{t.ping()}catch{this.closeConn(t),clearInterval(a)}}},Js);t.on("close",()=>{this.closeConn(t),clearInterval(a)}),t.on("pong",()=>{n=!0});{const o=k.createEncoder();k.writeVarUint(o,ge),je.writeSyncStep1(o,this),this.send(t,k.toUint8Array(o));const d=this.awareness.getStates();if(d.size>0){const i=k.createEncoder();k.writeVarUint(i,xe),k.writeVarUint8Array(i,se.encodeAwarenessUpdate(this.awareness,Array.from(d.keys()))),this.send(t,k.toUint8Array(i))}}});x(this,"messageListener",(t,n)=>{try{const a=k.createEncoder(),o=De.createDecoder(n),d=De.readVarUint(o);switch(d){case ge:k.writeVarUint(a,ge),je.readSyncMessage(o,a,this,null),k.length(a)>1&&(this.ensureDataStructure(),this.send(t,k.toUint8Array(a)));break;case xe:{se.applyAwarenessUpdate(this.awareness,De.readVarUint8Array(o),t);break}default:O.warn(`Unsupported messageType ${d}`)}}catch(a){O.error(a)}this.save()});this.options=t,S.existsSync(this.draftYjsFilePath)&&B.applyUpdate(this,S.readFileSync(this.draftYjsFilePath)),this.syncedStore=Bt.reactive(Q.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new se.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(t){if(!t)throw new Error("Should provide project context");try{const n=w.join(ne,t),a=w.join(ne,`@del-${t}`);S.renameSync(n,a)}catch(n){O.error("Failed to safe delete project state dir:",n)}}static get projectIds(){return ke.globSync("*/",{cwd:ne,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(t=>V.shared(t))}static shared(t){if(!t)throw new Error("Should provide project context");let n=this.sharedInstances.get(t);return n||(n=new V({path:w.join(ne,t)}),this.sharedInstances.set(t,n),n)}destroy(){this.conns.forEach((t,n)=>this.closeConn(n)),this.awareness.destroy(),super.destroy()}initObserver(){$s(this.syncedStore),Bs(this.syncedStore)}get draftYjsFilePath(){return w.join(this.options.path,"draft.yjs")}async getState(t){var n,a,o,d;if(t==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[t]&&(this.states[t]=await Je(this.getPublishDir(t),{includeResources:!0})??Qs(),!((a=(n=this.states[t])==null?void 0:n.config)!=null&&a.defaultLocale))){(o=this.states[t]).config??(o.config={});const i=Ue.env.languages.map(p=>({locale:p.code,name:p.name}));this.states[t].config.defaultLocale=(d=i[0])==null?void 0:d.locale}return{...this.states[t],resources:await Ce().then(async i=>{var c,l,f,E;const{pages:p,components:r}=fs.default(i,"pages","components");let u=r;const g=w.basename(this.options.path),y=await J.findByPk(g);if(y!=null&&y.useAllResources)u=r;else{const T=(await Te.findAll({where:{projectId:g}})).map(F=>F.componentId);u=Object.fromEntries(Object.entries(r||{}).filter(([F])=>T.includes(F)))}return Object.keys(((l=(c=this.states[t])==null?void 0:c.resources)==null?void 0:l.components)||{}).length>0&&(u={...u,...(E=(f=this.states[t])==null?void 0:f.resources)==null?void 0:E.components}),{pages:p,components:u}}).catch(()=>({}))}}async setState(t,n){const a=await Et(n,{exportAssets:!1,includeResources:!0}),o=this.getPublishDir(t);S.mkdirSync(w.dirname(o),{recursive:!0}),S.rmSync(o,{force:!0,recursive:!0}),S.renameSync(a,o),this.states[t]=n}getPublishDir(t){return w.join(this.options.path,t)}static async pageUrlMap(t){var o,d;const{projectIds:n}=this,a={};for(const i of n){const p=await J.findByPk(i);if(!p)continue;const r=await V.shared(i).getState(t),u=p.slug||i,g=ms.default(I.default.env.languages.map(c=>c.code),r.supportedLocales.map(c=>c.locale)),y=(c,l)=>{u&&(a[M.joinURL("/",u,c)]={...l,shouldRedirect:!0,mainPage:!0}),a[M.joinURL("/",i,c)]={...l,shouldRedirect:!0,mainPage:!0};for(const f of g){const E={...l,locale:f};a[M.joinURL("/",f,i,c)]=E,u&&(a[M.joinURL("/",f,u,c)]=E)}};if(t==="draft")for(const c of r.routeIds||[]){const l=(o=r==null?void 0:r.routes)==null?void 0:o[c];if(!l)continue;if(l.params&&l.params.length>0){const v=be.generateParamCombinations({basePath:l.path,params:l.params,routeId:l.id,paramsOptions:l.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const T of v){const R=T.path,F={projectId:i,projectSlug:u,pageSlug:R,pageId:l.displayTemplateId||"",routeId:c,defaultLocale:g==null?void 0:g[0],locales:g,publishedAt:r.config.publishedAt,isPublic:l.isPublic&&((d=T==null?void 0:T.routeMetaData)==null?void 0:d.isPublic)};y(R,F)}}const f=l.path,E={projectId:i,projectSlug:u,pageSlug:f,pageId:l.displayTemplateId||"",routeId:c,defaultLocale:g==null?void 0:g[0],locales:g,publishedAt:r.config.publishedAt,isPublic:l.isPublic};y(f,E)}for(const c of r.pageIds){const l=r.pages[c];if(!l||t==="production"&&!l.isPublic)continue;const f=l.slug,E=p.slug||i,v={projectId:i,projectSlug:E,pageSlug:f,pageId:c,defaultLocale:g==null?void 0:g[0],locales:g,publishedAt:r.config.publishedAt,isPublic:l.isPublic,templateConfig:l.templateConfig};y(f,v)}}return a}getDocumentSize(){return B.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const t=[];for(const[n,a]of this.sharedInstances.entries()){const o=a.getDocumentSize();t.push({projectId:n,sizeInBytes:o,sizeInMB:`${(o/(1024*1024)).toFixed(2)} MB`,activeConnections:a.conns.size})}return t}};x(V,"INSTANCE_TTL",30*60*1e3),x(V,"sharedInstances",new qe.LRUCache({max:100,ttl:V.INSTANCE_TTL,dispose:t=>{t.destroy()}}));let le=V;async function Xs(e,s,t){if(!e||!S.existsSync(e)||!S.lstatSync(e).isFile())return null;let n=t[e];return n||(n=(async()=>{var a;try{const o=(a=await Gs({filePath:e,fileName:s}))==null?void 0:a.data;return o==null?void 0:o.filename}catch(o){return O.error(`Failed to upload asset ${e}:`,o),null}})(),t[e]=n),n}const St=async(e,s)=>{const t=w.basename(e),n=await $e.call({name:Ge,path:M.joinURL("/uploads",t),responseType:"stream",method:"GET"});if(n.status>=200&&n.status<400){const a=S.createWriteStream(s);await es.pipeline(n.data,a)}else throw new Error(`download asset failed ${n.status}`)},wt=async(e,s)=>{await Promise.all(e.map(async t=>{try{await St(t,w.join(s,w.basename(t)))}catch(n){O.error(`Failed to export assets: ${t}, ${n}`)}}))};function bt(e){return Ve.test(e)?[e]:oe.test(e)?(et.lastIndex=0,Array.from(e.matchAll(et)).map(t=>t[1]).filter(t=>!!t)):[]}async function he(e,s,t){const{getFilename:n,exportAssets:a}=t,o=w.join(s,n(e));if(S.mkdirSync(w.dirname(o),{recursive:!0}),S.writeFileSync(o,X.stringify(e)),a){const i=Ie(e,p=>typeof p=="string"&&(Ve.test(p)||oe.test(p))).map(p=>{const r=Be.default(e,p);return bt(r)}).flat().filter(Boolean);await wt(i,w.dirname(o))}}const tt=new qe.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function st(e,s,t){var i;const n=Ie(e,p=>typeof p=="string"&&(Ve.test(p)||oe.test(p))),a=gs.default(2),o=n.map(p=>a(async()=>{try{const r=Be.default(e,p),u=bt(r);for(const g of u){const y=w.basename(g),c=t.getFilePath(g,p),l=c?`${c}:${y}`:y,f=tt.get(l);if(f){oe.test(r)||Qe.default(e,p,f);return}const E=await Xs(c,y,s);E&&(oe.test(r)||Qe.default(e,p,E),tt.set(l,E))}}catch(r){O.error(`Failed to process upload for path ${p.join(".")}:`,r.message||r.reason)}})),d=await Promise.allSettled(o);(i=t.onFinish)==null||i.call(t,d)}async function Et(e,{exportAssets:s,pageIds:t="all",componentIds:n="all",rawConfig:a,includeResources:o=!1,routeIds:d="all"}={}){var ee,b,m,A,P,z,_,q,K,fe,te,me;const i=t==="all"?e.pageIds:t,p=re.getComponentDependencies({state:e,pageIds:i,componentIds:n==="all"?Object.keys(e.components):n}),r=d==="all"?e.routeIds:d,u=(h,C)=>{var D;return{id:h.id,name:h.name,isTemplateSection:h.isTemplateSection??!1,templateDescription:h.templateDescription,llmConfig:h.llmConfig,component:h.component,config:h.config,visibility:h.visibility,properties:((D=h.locales)==null?void 0:D[C])??{}}},g=(h,C)=>{var D;return{id:h.id,createdAt:h.createdAt,updatedAt:h.updatedAt,publishedAt:h.publishedAt,isPublic:h.isPublic??!0,templateConfig:h.templateConfig,meta:((D=h.locales)==null?void 0:D[C])??{},sections:U(h.sectionIds.map(G=>{const H=h.sections[G];return H&&u(H,C)}))}},y=h=>({id:h.id,createdAt:h.createdAt,updatedAt:h.updatedAt,publishedAt:h.publishedAt,path:h.path,handler:h.handler,isPublic:h.isPublic??!0,params:h.params??[],enabledGenerate:h.enabledGenerate??!1,displayTemplateId:h.displayTemplateId,dataSource:h.dataSource}),c=U(r.map(h=>{const C=e.routes[h];return C&&y(C)})),l=U(e.supportedLocales.map(h=>h.locale).flatMap(h=>i.map(C=>{const D=e.pages[C];return D&&{locale:h,slug:D.slug,page:g(D,h)}}))),f=yt(),E=w.join(f,"pages");S.mkdirSync(E,{recursive:!0});const v=w.join(f,"components");S.mkdirSync(v,{recursive:!0});const T=w.join(f,"routes");S.mkdirSync(T,{recursive:!0});for(const{locale:h,slug:C,page:D}of l)await he(D,E,{getFilename:()=>`${Oe(C)||"index"}.${h}.yml`,exportAssets:s});for(const h of c)await he(h,T,{getFilename:()=>`${Oe(h.path)||"index"}.yml`,exportAssets:s});for(const h of p){const C=(ee=e.components[h])==null?void 0:ee.data;C&&await he(C,v,{getFilename:D=>`${D.name||"unnamed"}.${D.id}.yml`,exportAssets:s})}const R=w.join(f,".blocklet/pages/pages.config.yml");S.mkdirSync(w.dirname(R),{recursive:!0});const F={pages:U(i.map(h=>{const C=e.pages[h];return C&&{id:h,slug:C.slug}})),routes:U(r.map(h=>{const C=e.routes[h];return C&&{id:h,path:C.path}})),components:U(p.map(h=>{var D;const C=(D=e.components[h])==null?void 0:D.data;return C&&{id:h,name:C.name}})),...o?{resources:{components:U(Object.keys(((b=e.resources)==null?void 0:b.components)||{}).filter(h=>p.includes(h)).map(h=>{var C,D,G,H;return{id:h,name:(H=(G=(D=(C=e.resources)==null?void 0:C.components)==null?void 0:D[h])==null?void 0:G.component)==null?void 0:H.name}}))}}:{},supportedLocales:e.supportedLocales,config:e.config};S.writeFileSync(R,X.stringify(F));const pe=w.join(f,"config.source.json");if(a&&S.writeFileSync(pe,JSON.stringify(a)),o){const h=w.join(f,"resources"),C=w.join(h,"components");S.mkdirSync(C,{recursive:!0});for(const H of Object.keys(((m=e==null?void 0:e.resources)==null?void 0:m.components)??{}).filter($=>p.includes($))){const $=(z=(P=(A=e.resources)==null?void 0:A.components)==null?void 0:P[H])==null?void 0:z.component;$&&await he($,C,{getFilename:Y=>`${Y.name||"unnamed"}.${Y.id}.yml`,exportAssets:s})}const D=w.join(f,"chunks");S.mkdirSync(D,{recursive:!0});const{chunks:G}=await Ce();for(const H of Object.keys(((_=e==null?void 0:e.resources)==null?void 0:_.components)??{}).filter($=>p.includes($))){const $=(fe=(K=(q=e.resources)==null?void 0:q.components)==null?void 0:K[H])==null?void 0:fe.component;if($&&((te=$.renderer)==null?void 0:te.type)==="react-component"){const Y=((me=$.renderer)==null?void 0:me.chunks)??[];if((Y==null?void 0:Y.length)>0)for(const Pe of Y){const We=w.join(D,Pe),_e=G==null?void 0:G[Pe];try{_e&&S.existsSync(_e)&&!S.existsSync(We)&&S.copyFileSync(_e,We)}catch(Ct){O.error(`copy chunk ${Pe} error`,Ct.message)}}}}}return f}async function Je(e,{importAssets:s,includeResources:t}={}){var o,d,i,p;if(!S.existsSync(e))return null;let n,a=!1;try{S.lstatSync(e).isDirectory()?n=e:/\.(tgz|gz|tar)$/.test(e)&&(a=!0,n=yt(),await ts.x({file:e,C:n}));const r=ke.globSync("**/.blocklet/pages/pages.config.yml",{cwd:n,absolute:!0}).at(0),u=r&&w.join(w.dirname(r),"../../pages"),g=r&&w.join(w.dirname(r),"../../components"),y=r&&w.join(w.dirname(r),"../../chunks"),c=r&&w.join(w.dirname(r),"../../routes");if(!r)return null;const l=X.parse(S.readFileSync(r).toString()),f=(b,m,A)=>{let P=w.join(b,`${m}${A?`.${A}`:""}.yml`);return(!S.existsSync(P)||!S.lstatSync(P).isFile())&&(P=w.join(b,m,`index${A?`.${A}`:""}.yml`),!S.existsSync(P)||!S.lstatSync(P))?null:X.parse(S.readFileSync(P).toString())},E=(b,m)=>{try{const A=ke.globSync(`*.${m}.yml`,{cwd:b,absolute:!0})[0];return A?X.parse(S.readFileSync(A).toString()):null}catch(A){O.error("parse component error",A)}return null},v=(b,m)=>{let A=w.join(b,`${m}.yml`);return(!S.existsSync(A)||!S.lstatSync(A).isFile())&&(A=w.join(b,m,"index.yml"),!S.existsSync(A)||!S.lstatSync(A))?null:X.parse(S.readFileSync(A).toString())},T=U(l.pages.map(({slug:b})=>{var z;const m=U(l.supportedLocales.map(({locale:_})=>{const q=u?f(u,Oe(b),_):void 0;if(q)return{locale:_,page:q};const K=u?f(u,b,_):void 0;return K&&{locale:_,page:K}})),A=(z=m[0])==null?void 0:z.page;if(!A)return null;const P=A.sections.map(_=>{const q=_.id||Se();return{id:q,component:_.component,config:_.config,name:_.name,isTemplateSection:_.isTemplateSection??!1,templateDescription:_.templateDescription,llmConfig:_.llmConfig,visibility:_.visibility,locales:Object.fromEntries(U(m.map(({locale:K,page:fe})=>{const te=fe.sections.find(me=>me.id===q);return te&&[K,te.properties]})))}});return{id:A.id||Se(),createdAt:A.createdAt,updatedAt:A.updatedAt,publishedAt:A.publishedAt,isPublic:A.isPublic??!0,templateConfig:A.templateConfig,slug:b,sections:Object.fromEntries(P.map(_=>[_.id,_])),sectionIds:P.map(_=>_.id),locales:Object.fromEntries(m.map(({locale:_,page:q})=>[_,q.meta]))}})),R=U(((o=l==null?void 0:l.routes)==null?void 0:o.map(({path:b})=>{const m=c?v(c,Oe(b)):void 0;return{...m,id:(m==null?void 0:m.id)||Se(),createdAt:(m==null?void 0:m.createdAt)??new Date().toISOString(),updatedAt:(m==null?void 0:m.updatedAt)??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:(m==null?void 0:m.path)??`/${m==null?void 0:m.id}`,params:m==null?void 0:m.params,handler:(m==null?void 0:m.handler)??"Pages Kit",isPublic:(m==null?void 0:m.isPublic)??!0,enabledGenerate:(m==null?void 0:m.enabledGenerate)??!1,displayTemplateId:(m==null?void 0:m.displayTemplateId)??void 0,dataSource:(m==null?void 0:m.dataSource)??{}}}))??[]),F=g?U(((d=l.components)==null?void 0:d.map(({id:b})=>E(g,b)))??[]):[];if(s){const b=(...m)=>{O.info(`[${a?w.basename(e):w.basename(w.join(e,"../../../../"))}] importAssets:`,...m)};try{b("wait image-bin api ready"),await hs.default({resources:[`${$e.getComponentWebEndpoint(ys)}/api/sdk/uploads`],validateStatus:P=>P>=200&&P<=500}),b("image-bin api is ready");const m={},A={};b("start to upload assets"),await Promise.allSettled([st(F,m,{getFilePath:P=>g&&w.join(g,P),onFinish:P=>{b(`upload ${P.length} component assets`)}}),st(T,A,{getFilePath:(P,z)=>{const _=Be.default(T,z.slice(0,1));return u&&w.join(u,w.dirname(_.slug),P)},onFinish:P=>{b(`upload ${P.length} page assets`)}})]),b("upload assets done"),global.gc&&global.gc()}catch(m){b("Error during asset import:",m)}}const pe={};if(t){const b=r&&w.join(w.dirname(r),"../../resources/components"),m=U(((p=(i=l.resources)==null?void 0:i.components)==null?void 0:p.map(({id:A})=>E(b,A)))??[]);m.length>0&&(pe.components=Object.fromEntries(m.map((A,P)=>[A.id,{index:P,component:A}])))}const ee={};if(y&&S.existsSync(y)){const b=S.readdirSync(y);for(const m of b)ee[m]=w.join(y,m)}return{supportedLocales:l.supportedLocales,pageIds:T.map(b=>b.id),components:Object.fromEntries(F.map((b,m)=>[b.id,{index:m,data:b}])),pages:Object.fromEntries(T.map(b=>[b.id,b])),config:l.config||{},resources:pe,chunks:ee,routeIds:R.map(b=>b.id),routes:Object.fromEntries(R.map(b=>[b.id,b])),dataSourceIds:[],dataSources:{}}}finally{a&&n&&S.rmSync(n,{force:!0,recursive:!0})}}async function Fe(e,s,{routes:t,mergeMode:n="byUpdateTime",deleteRoutes:a=!1,publishMode:o=void 0}={}){try{o&&pt(o)}catch(y){O.error("clear preload page cache error",{error:y})}const{pages:d,pageIds:i,routeIds:p,routes:r,supportedLocales:u}=e;if(o==="production"){let y=t??[],c=null;for(const l of p??[]){const f=r==null?void 0:r[l];if(f!=null&&f.params&&(f==null?void 0:f.params.length)>0&&(f!=null&&f.paramsOptions)&&(f==null?void 0:f.paramsOptions.length)>0){const E=be.generateParamCombinations({basePath:f.path,params:f.params,routeId:f.id,paramsOptions:f.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),v=Object.fromEntries(E.map(T=>[`${l}-${T.paramOptionIds.join("-")}`,T]));c={...c||{},...v},t||(y=[...y,...E.map(T=>`${l}-${T.paramOptionIds.join("-")}`)])}else t||y.push(l)}O.info("routeIds to be published: ",y);for(const l of y){let f=l;if(f.includes("-")){const[T]=f.split("-");f=T}const E=r==null?void 0:r[f];if(!E){const T=s.pageIds.indexOf(f);T!==-1&&a&&(s.pageIds.splice(T,1),delete s.pages[f]);for(const R of s.pageIds)R.includes(`${f}-`)&&(s.pageIds.splice(s.pageIds.indexOf(R),1),delete s.pages[R]);O.info("delete main route page",f);continue}if(l.includes("-")&&!(c!=null&&c[l])){const T=s.pageIds.indexOf(l);T!==-1&&a&&(s.pageIds.splice(T,1),delete s.pages[l]),O.info("delete page",l);continue}if(!E.displayTemplateId){O.info("no display template",l);continue}const v=d[E.displayTemplateId];if(!v){O.info("no template page",l);continue}if(s.pageIds.includes(l)){if(O.info("has need update page",l),n==="replace")s.pages[l]=ve({page:v,route:E,state:e,routeId:l,routePathInfo:c==null?void 0:c[l]}),O.info("replace page",l);else if(n==="byUpdateTime"){const T=s.pages[E.id];(!T||E.updatedAt&&E.updatedAt>T.updatedAt)&&(s.pages[l]=ve({page:v,route:E,state:e,routeId:l,routePathInfo:c==null?void 0:c[l]}),O.info("replace page by update time",l))}}else s.pageIds.push(l),s.pages[l]=ve({page:v,route:E,state:e,routeId:l,routePathInfo:c==null?void 0:c[l]}),O.info("add page",l)}if(a&&!t)for(const l of s.pageIds)y!=null&&y.includes(l)||(delete s.pages[l],O.info("delete page",l)),s.pageIds=[...s.pageIds].filter(f=>y==null?void 0:y.includes(f))}else{for(const y of i){const c=d[y];if(c)if(s.pageIds.includes(c.id)){if(n==="replace")s.pages[c.id]=c;else if(n==="byUpdateTime"){const l=s.pages[c.id];(!l||c.updatedAt&&c.updatedAt>l.updatedAt)&&(s.pages[c.id]=c)}}else s.pageIds.push(c.id),s.pages[c.id]=c}for(const y of p){const c=r[y];if(c)if(s.routeIds.includes(c.id)){if(n==="replace")s.routes[c.id]=c;else if(n==="byUpdateTime"){const l=s.routes[c.id];(!l||c.updatedAt&&c.updatedAt>l.updatedAt)&&(s.routes[c.id]=c)}}else s.routeIds.push(c.id),s.routes[c.id]=c}}if(s.supportedLocales.splice(0,s.supportedLocales.length),s.supportedLocales.push(...us.default(u)),a)for(const y of Object.keys(s.components))delete s.components[y];let g=JSON.parse(JSON.stringify(e.components));g=Object.fromEntries(await Promise.all(Object.entries(g).map(async([y,c])=>{const l=await It(c==null?void 0:c.data);return[y,{...c,data:l}]}))),Object.assign(s.components,g),Object.assign(s.config,JSON.parse(JSON.stringify(e.config))),s.resources.components=JSON.parse(JSON.stringify(e.resources.components||{}))}const It=He(async e=>{var s;if(!ps.default(e==null?void 0:e.properties))return e;if(((s=e==null?void 0:e.renderer)==null?void 0:s.type)==="react-component"){const{script:t}=(e==null?void 0:e.renderer)||{};if(t&&t.includes("PROPERTIES_SCHEMA"))try{const n=await ht(t,"PROPERTIES_SCHEMA",e.id);n&&n.length>0&&e&&(e.properties={},n.forEach((a,o)=>{e!=null&&e.properties&&(e.properties[a.id]={index:o,data:a})}))}catch(n){O.error("checkPropertiesFromCode error",{componentId:e.id,name:e.name},{error:n})}}return e},{keyGenerator:e=>{var r,u,g,y;const s=(e==null?void 0:e.id)||"",t=(e==null?void 0:e.name)||"",n=((r=e==null?void 0:e.renderer)==null?void 0:r.type)||"",a=(e==null?void 0:e.properties)||{},o=(e==null?void 0:e.updatedAt)||"",d=W.createHash("md5").update(JSON.stringify(a)).digest("hex");let i="",p="";return((u=e==null?void 0:e.renderer)==null?void 0:u.type)==="react-component"&&(i=W.createHash("md5").update(((g=e==null?void 0:e.renderer)==null?void 0:g.script)||"").digest("hex"),p=W.createHash("md5").update(((y=e==null?void 0:e.renderer)==null?void 0:y.editComponent)||"").digest("hex")),JSON.stringify(["checkPropertiesFromCode",s,t,n,d,o,i,p])},lruOptions:{max:100,ttl:1e3*60*60},subdir:"checkPropertiesFromCode"});let Ae,Z,ze,Ke,Ye;function Ot(){return Ae=(async()=>{const e=$e.getResources({types:[{did:Ge,type:Le},{did:qs,type:Le}]});Z=(await Promise.all(e.map(async t=>{const n=t.path?await Je(t.path,{importAssets:!1}):void 0;return n?{blockletId:t.did,state:n,blockletTitle:t.title}:void 0}))).filter(t=>!!t),ze=Z.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.pages).map(a=>a?[a==null?void 0:a.id,{page:a,blockletId:n.blockletId}]:[]))),{});const s=Z.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.components).map(a=>[a.data.id,{blockletId:n.blockletId,component:a.data}]))),{});Ke=Object.fromEntries(await Promise.all(Object.entries(s).map(async([t,n])=>{const a=await It(n.component);return[t,{...n,component:a}]}))),Ye=Z.reduce((t,n)=>Object.assign(t,n.state.chunks),{})})(),Ae}function At(e){const s=it.default(async()=>{await Ot().catch(t=>{O.error("load resource states error",{error:t})}),await(e==null?void 0:e({states:Z,pages:ze,components:Ke,chunks:Ye}))},3e3,{leading:!1,trailing:!0});return s(),I.default.events.on(I.default.Events.componentAdded,s),I.default.events.on(I.default.Events.componentRemoved,s),I.default.events.on(I.default.Events.componentStarted,s),I.default.events.on(I.default.Events.componentStopped,s),I.default.events.on(I.default.Events.componentUpdated,s),I.default.events.on(Me,s),()=>{I.default.events.off(I.default.Events.componentAdded,s),I.default.events.off(I.default.Events.componentRemoved,s),I.default.events.off(I.default.Events.componentStarted,s),I.default.events.off(I.default.Events.componentStopped,s),I.default.events.off(I.default.Events.componentUpdated,s),I.default.events.off(Me,s)}}const Tt=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),we=globalThis;var nt;(nt=we[Tt])==null||nt.call(we);we[Tt]=At(async({pages:e,components:s})=>{const{projectIds:t}=le;O.info(`start update resource states projects(${t.length})`,t),await Promise.race([new Promise(n=>{setTimeout(()=>{n({})},30*1e3)}),Promise.all(t.map(async n=>{const a=le.shared(n);a.syncedStore.resources.pages=e;const o=await J.findByPk(n);if(o!=null&&o.useAllResources)a.syncedStore.resources.components=s;else{const i=(await Te.findAll({where:{projectId:n}})).map(r=>r.componentId),p=Object.fromEntries(Object.entries(s||{}).filter(([r])=>i.includes(r)));a.syncedStore.resources.components=p}O.info(`update [${n}] resource states:`,{pages:Object.keys(a.syncedStore.resources.pages||{}).length,components:Object.keys(a.syncedStore.resources.components||{}).length})}))]).catch(n=>{O.error("update resource states failed:",n)})});async function Zs(){O.info("trigger reload all project resource"),I.default.events.emit(Me)}async function Ce({ensureLoaded:e=!0}={}){return e&&(Ae??(Ae=Ot()),await Ae),{states:Z,pages:ze,components:Ke,chunks:Ye}}exports.COMPONENT_DID=Ge;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=dt;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=Re;exports.PUBLISH_MODES=Ws;exports.Project=J;exports.RESOURCE_TYPE=Le;exports.SITE_STATE_PATH=ne;exports.STATE_MODES=Ys;exports.SiteState=le;exports.clearPreloadComponentsCache=ut;exports.clearPreloadComponentsCacheByMode=pt;exports.downloadAsset=St;exports.downloadAssets=wt;exports.fromPackage=Je;exports.getComponentFromState=ce;exports.getComponentFromStateByName=Ms;exports.getExportSchemaValueFromCode=ht;exports.getMultiTenantAllProjectAccessPassports=bs;exports.getPreloadComponent=mt;exports.getPreloadComponents=Ns;exports.getPreloadComponentsCacheKey=ft;exports.getResourceStates=Ce;exports.initPackResourceStates=At;exports.isMultiTenant=ws;exports.logger=O;exports.mergeState=Fe;exports.nextId=Se;exports.toPackage=Et;exports.triggerReloadAllProjectResource=Zs;