@blocklet/pages-kit-inner-components 0.7.22 → 0.7.24

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.
@@ -14,38 +14,42 @@ import { useLocalStorageState as we } from "ahooks";
14
14
  import { produce as _ } from "immer";
15
15
  import R from "lodash/cloneDeep";
16
16
  import te from "lodash/debounce";
17
- import { createContext as Ce, useState as W, useRef as oe, useMemo as D, useCallback as M, useEffect as V, useContext as he } from "react";
17
+ import { createContext as Ce, useState as W, useRef as oe, useMemo as D, useCallback as L, useEffect as V, useContext as he } from "react";
18
18
  import { useParams as ve, useNavigate as Oe } from "react-router-dom";
19
19
  import { IndexeddbPersistence as be } from "y-indexeddb";
20
20
  import { WebsocketProvider as xe } from "y-websocket";
21
21
  import { UndoManager as Ee } from "yjs";
22
22
  import "@blocklet/pages-kit/types";
23
+ const at = (o) => {
24
+ const n = blocklet?.componentMountPoints.find((I) => I.name === o);
25
+ return n ? n.mountPoint : "/";
26
+ };
23
27
  function Te() {
24
28
  const { pathname: o } = window.location, I = o.match(/\/admin\/(maker|previewer)\/([^/]+)/)?.[2], f = window.__PROJECT_ID__;
25
29
  if (!I && !f)
26
30
  throw new Error("Unable to get projectId from pathname");
27
31
  return I || f;
28
32
  }
29
- function at(o) {
33
+ function dt(o) {
30
34
  return `${o}:pages:version`;
31
35
  }
32
- function dt(o, n) {
36
+ function ut(o, n) {
33
37
  return n === "yaml" ? me(o) ? "" : fe.stringify(o, { indent: 2 }) : n === "json" ? JSON.parse(JSON.stringify(o || {})) : n === "array" ? JSON.parse(JSON.stringify(o || [])) : o;
34
38
  }
35
39
  const Q = window.blocklet?.prefix || "/", ne = pe({
36
40
  timeout: 200 * 1e3
37
- }), ke = window.location.protocol === "https:" ? "wss" : "ws", ut = (o) => F(`${ke}://${window.location.hostname}`, Q, `api/${o}/ws/pages`), Ne = "z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";
41
+ }), ke = window.location.protocol === "https:" ? "wss" : "ws", lt = (o) => F(`${ke}://${window.location.hostname}`, Q, `api/${o}/ws/pages`), Ne = "z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";
38
42
  blocklet?.componentMountPoints.find((o) => o.did === Ne)?.mountPoint || F(Q, "/image-bin");
39
- function lt(o) {
43
+ function pt(o) {
40
44
  return o && !/^(https?:\/\/|\/)/.test(o) ? window.location.origin + F(Q, "uploads", o) : o;
41
45
  }
42
- const Le = window.innerWidth <= 750;
43
- function pt(o, n, I) {
46
+ const Me = window.innerWidth <= 750;
47
+ function mt(o, n, I) {
44
48
  if (!o || /\.gif/.test(o)) return o;
45
- const f = (Le ? n / 1.5 : n) * (I === "quality" ? 1.5 : 1);
46
- return Me(o, { imageFilter: "resize", w: f, f: "webp" });
49
+ const f = (Me ? n / 1.5 : n) * (I === "quality" ? 1.5 : 1);
50
+ return Le(o, { imageFilter: "resize", w: f, f: "webp" });
47
51
  }
48
- function Me(o, n) {
52
+ function Le(o, n) {
49
53
  return !o || !n ? o : le(o, n);
50
54
  }
51
55
  async function je(o) {
@@ -80,7 +84,7 @@ function De(o, n) {
80
84
  };
81
85
  }
82
86
  const _e = 500, ce = Ce(null);
83
- function mt({
87
+ function ft({
84
88
  url: o,
85
89
  name: n,
86
90
  children: I,
@@ -113,7 +117,7 @@ function mt({
113
117
  resyncInterval: 5 * 60 * 1e3
114
118
  }),
115
119
  [o, b, y]
116
- ), U = M(() => {
120
+ ), U = L(() => {
117
121
  C && (C.wsconnected ? (C.disconnect(), setTimeout(() => C.connect(), 100)) : C.connect());
118
122
  }, [C]), e = D(
119
123
  () => new Ee(
@@ -130,7 +134,7 @@ function mt({
130
134
  { doc: y }
131
135
  ),
132
136
  [y]
133
- ), [t, r] = W(null), [c, d] = W(!1), [i, l] = W(void 0), m = M(async () => {
137
+ ), [t, r] = W(null), [c, d] = W(!1), [i, l] = W(void 0), m = L(async () => {
134
138
  if (h) {
135
139
  d(!0);
136
140
  try {
@@ -142,7 +146,7 @@ function mt({
142
146
  d(!1);
143
147
  }
144
148
  }
145
- }, [h]), u = M(
149
+ }, [h]), u = L(
146
150
  async (s, a) => {
147
151
  if (l(void 0), !!h) {
148
152
  a?.optimisticUpdate && t && r((g) => ({
@@ -224,7 +228,7 @@ function mt({
224
228
  ...T,
225
229
  networkStatus: "offline"
226
230
  }));
227
- }, L = te(({ status: T }) => {
231
+ }, M = te(({ status: T }) => {
228
232
  if (T === "connected")
229
233
  x(), a && (clearTimeout(a), a = null);
230
234
  else if (T === "disconnected") {
@@ -253,8 +257,8 @@ function mt({
253
257
  }, G = () => {
254
258
  E();
255
259
  };
256
- return C.on("status", L), window.addEventListener("online", A), window.addEventListener("offline", G), C.wsconnected && x(), () => {
257
- a && clearTimeout(a), C.off("status", L), window.removeEventListener("online", A), window.removeEventListener("offline", G);
260
+ return C.on("status", M), window.addEventListener("online", A), window.addEventListener("offline", G), C.wsconnected && x(), () => {
261
+ a && clearTimeout(a), C.off("status", M), window.removeEventListener("online", A), window.removeEventListener("offline", G);
258
262
  };
259
263
  }, [C, S]), f && !O ? null : /* @__PURE__ */ ue(ce.Provider, { value: p, children: I });
260
264
  }
@@ -262,7 +266,7 @@ const Re = () => {
262
266
  const o = he(ce);
263
267
  if (!o)
264
268
  throw new Error("Context is null");
265
- const n = ye(o.state), { setLocalState: I, localState: f } = o, O = Oe(), w = se(), j = oe({}), h = M(
269
+ const n = ye(o.state), { setLocalState: I, localState: f } = o, O = Oe(), w = se(), j = oe({}), h = L(
266
270
  (e) => {
267
271
  const t = n.components[e]?.data;
268
272
  return !t || t.renderer?.type !== "component-template" ? void 0 : (j.current[e] || (j.current[e] = {
@@ -270,7 +274,7 @@ const Re = () => {
270
274
  }), j.current[e]?.page);
271
275
  },
272
276
  [n.components]
273
- ), k = M(
277
+ ), k = L(
274
278
  (e) => {
275
279
  const t = n.components[e]?.data;
276
280
  if (!t || t.renderer?.type !== "component-template")
@@ -285,7 +289,7 @@ const Re = () => {
285
289
  };
286
290
  },
287
291
  [h, n.components]
288
- ), b = M(
292
+ ), b = L(
289
293
  (e) => {
290
294
  const t = n.pages[e];
291
295
  if (t)
@@ -307,7 +311,7 @@ const Re = () => {
307
311
  };
308
312
  },
309
313
  [k, n.pages]
310
- ), v = M(
314
+ ), v = L(
311
315
  (e) => {
312
316
  const t = b(e);
313
317
  if (!t)
@@ -422,7 +426,7 @@ const Re = () => {
422
426
  renderer: e.renderer
423
427
  };
424
428
  }
425
- }, [f.currentPageId, f.currentComponentId, b, k]), J = M(
429
+ }, [f.currentPageId, f.currentComponentId, b, k]), J = L(
426
430
  () => $?.kind === "component-template" ? $ : void 0,
427
431
  [$]
428
432
  ), y = D(
@@ -498,7 +502,7 @@ const Re = () => {
498
502
  }
499
503
  }),
500
504
  [I, O, w, S]
501
- ), C = M(
505
+ ), C = L(
502
506
  (e, t, r, c, d) => {
503
507
  const i = v(e), { page: l } = i, m = R(t), u = r ? R(r) : void 0, p = z(m);
504
508
  return o.doc.transact(() => {
@@ -515,7 +519,7 @@ const Re = () => {
515
519
  const s = (a, g) => {
516
520
  const P = u[a.id];
517
521
  P && (l.dataSource[g.id] = R(P)), a.component === "layout-block" && a.sectionIds?.length && a.sectionIds.forEach((N, x) => {
518
- const E = a.sections?.[N], L = g.sectionIds?.[x], A = L ? g.sections?.[L] : void 0;
522
+ const E = a.sections?.[N], M = g.sectionIds?.[x], A = M ? g.sections?.[M] : void 0;
519
523
  E && A && s(E, A);
520
524
  });
521
525
  };
@@ -672,8 +676,8 @@ const Re = () => {
672
676
  const a = r.replace("layout-", ""), P = l.getComponentById(a)?.model;
673
677
  if (!P || P.component !== "layout-block")
674
678
  throw new Error(`Layout block ${a} not found`);
675
- if (a === t || ((E, L) => {
676
- const A = l.getComponentById(E), G = l.getComponentById(L);
679
+ if (a === t || ((E, M) => {
680
+ const A = l.getComponentById(E), G = l.getComponentById(M);
677
681
  if (!A || !G || A.model.component !== "layout-block")
678
682
  return !1;
679
683
  let T = G.parent;
@@ -718,8 +722,8 @@ const Re = () => {
718
722
  const N = a?.[P];
719
723
  if (N) {
720
724
  if (N && S.currentPage?.dataSource) {
721
- const L = S.currentPage.dataSource[N];
722
- L && (S.currentPage.dataSource[g] = JSON.parse(JSON.stringify(L)));
725
+ const M = S.currentPage.dataSource[N];
726
+ M && (S.currentPage.dataSource[g] = JSON.parse(JSON.stringify(M)));
723
727
  }
724
728
  const x = u.sections?.[g], E = p?.sections?.[N];
725
729
  x?.component === "layout-block" && x.sectionIds && E?.sectionIds && m(x, E);
@@ -814,7 +818,7 @@ const Re = () => {
814
818
  }, se = () => {
815
819
  const { projectId: o } = ve();
816
820
  return o ?? Te() ?? "";
817
- }, ft = () => window.__PROJECT_SLUG__ ?? "";
821
+ }, gt = () => window.__PROJECT_SLUG__ ?? "";
818
822
  function $e(o) {
819
823
  const { resources: n } = o;
820
824
  if (!n.components)
@@ -839,7 +843,7 @@ function Be(o) {
839
843
  ...Je(o)
840
844
  };
841
845
  }
842
- const gt = () => Be(Re().state);
846
+ const St = () => Be(Re().state);
843
847
  function z(o) {
844
848
  const n = JSON.parse(JSON.stringify(o)), I = B();
845
849
  if (n.component === "layout-block") {
@@ -863,20 +867,21 @@ function z(o) {
863
867
  };
864
868
  }
865
869
  export {
866
- mt as S,
870
+ ft as S,
867
871
  Re as a,
868
- at as b,
872
+ dt as b,
869
873
  Be as c,
870
- ft as d,
871
- pt as e,
872
- lt as f,
873
- ut as g,
874
- gt as h,
874
+ gt as d,
875
+ mt as e,
876
+ pt as f,
877
+ lt as g,
878
+ St as h,
875
879
  ne as i,
876
- De as j,
877
- Te as k,
878
- Je as l,
879
- $e as m,
880
- dt as t,
880
+ at as j,
881
+ De as k,
882
+ Te as l,
883
+ Je as m,
884
+ $e as n,
885
+ ut as t,
881
886
  se as u
882
887
  };
package/lib/es/home.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import "react/jsx-runtime";
2
- import "./chunks/state-qDCrgEMQ.js";
2
+ import "./chunks/state-CMRCtF-D.js";
3
3
  import "@arcblock/ux/lib/Locale/context";
4
4
  import "@arcblock/ux/lib/Result";
5
5
  import "@arcblock/ux/lib/Theme";
@@ -21,8 +21,8 @@ import "react-helmet";
21
21
  import "react-router-dom";
22
22
  import "react-use";
23
23
  import "ufo";
24
- import "./chunks/index-Dci_IgHn.js";
25
- import { a as R, e as S, P as W, d as j, c as k, b as q, T as v, H as z } from "./chunks/home-D3e7ljVw.js";
24
+ import "./chunks/index-BZ1MijZ6.js";
25
+ import { a as R, e as S, P as W, d as j, c as k, b as q, T as v, H as z } from "./chunks/home-BujeKjPf.js";
26
26
  import "./chunks/session-Dx5M-1r2.js";
27
27
  export {
28
28
  R as HomeView,
package/lib/es/locales.js CHANGED
@@ -35,6 +35,7 @@ const t = e({
35
35
  chooseTemplateTip: "Choose a template to start, or select Blank Template to create your own",
36
36
  blankTemplate: "Blank Template",
37
37
  welcomeTemplate: "Welcome Template",
38
+ welcomeByWebSmithTemplate: "Welcome Page by WebSmith",
38
39
  limitReached: "Expand Project Count",
39
40
  limitReachedTip: "You have reached the limit of <b>{limit}</b> projects. Please delete the unused projects and try again.<br/>You can also launch your own Pages Kit to create more projects.",
40
41
  limitReachedConfirm: "Launch My Pages Kit",
@@ -636,6 +637,7 @@ const t = e({
636
637
  chooseTemplateTip: "选择模板快速开始,或开创您的独特项目 - 点击创建您的专属之旅!",
637
638
  blankTemplate: "空白模板",
638
639
  welcomeTemplate: "欢迎模板",
640
+ welcomeByWebSmithTemplate: "使用 WebSmith 创建的欢迎页面",
639
641
  limitReached: "扩展项目数量",
640
642
  limitReachedTip: "你已经达到了项目数量上限 <b>{limit}</b>,请删除未使用的项目并重试。<br/>你也可以部署自己的 Pages Kit 来创建更多项目。",
641
643
  limitReachedConfirm: "部署我的 Pages Kit",
@@ -1,5 +1,5 @@
1
1
  import { i as b, a as T, l as x } from "./chunks/components-D4ywfyMi.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-NvsHZBJX.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-D8_lRJeG.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";
package/lib/es/setting.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { jsx as e, jsxs as x, Fragment as U } from "react/jsx-runtime";
2
2
  import { Box as w, Alert as Ze, Typography as E, TextField as R, Stack as S, FormLabel as ee, TableContainer as er, Paper as J, Table as ze, TableHead as je, TableRow as re, TableCell as te, TableBody as Re, Button as D, IconButton as $, FormControlLabel as le, Switch as ye, InputAdornment as H, alpha as ue, Tooltip as B, buttonClasses as rr, Dialog as ve, DialogTitle as Ve, DialogContent as Ae, DialogActions as De, Checkbox as tr, Autocomplete as Ee, MenuItem as X, Collapse as nr, Divider as or, Popper as ir } from "@mui/material";
3
- import { t as xe, f as ne, a as se, h as Ce } from "./chunks/state-qDCrgEMQ.js";
3
+ import { t as xe, f as ne, a as se, h as Ce } from "./chunks/state-CMRCtF-D.js";
4
4
  import _ from "@arcblock/ux/lib/Empty";
5
5
  import { useLocaleContext as V } from "@arcblock/ux/lib/Locale/context";
6
6
  import { CodeEditor as Pe } from "@blocklet/code-editor";
@@ -1,5 +1,5 @@
1
1
  import "./chunks/components-D4ywfyMi.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-NvsHZBJX.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-D8_lRJeG.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.22",
3
+ "version": "0.7.24",
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.22",
205
- "@blocklet/pages-kit-block-studio": "^0.7.22"
204
+ "@blocklet/pages-kit": "^0.7.24",
205
+ "@blocklet/pages-kit-block-studio": "^0.7.24"
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-aaduHC9E.js"),G=require("@syncedstore/core"),it=require("yjs"),ct=require("@blocklet/pages-kit/utils/data-source"),ne=require("@blocklet/pages-kit/utils/route"),lt=require("lodash/cloneDeep"),h=require("sequelize");require("sqlite3");const ut=require("@blocklet/sdk/lib/config"),_=require("ufo"),Be=require("lodash");require("crypto");const Z=require("fs"),pt=require("p-limit"),p=require("path"),dt=require("worker_threads"),Ue=require("@blocklet/pages-kit/utils/common"),ft=require("@blocklet/pages-kit/utils/page-model"),gt=require("@blocklet/pages-kit/utils/property"),Ee=require("@blocklet/sdk/lib/component"),mt=require("@reactivedata/reactive"),D=require("fs/promises"),re=require("glob"),ht=require("lib0/decoding"),yt=require("lib0/encoding"),St=require("lodash/debounce"),wt=require("lodash/get"),It=require("lodash/isEmpty"),bt=require("lodash/set"),Pt=require("lodash/union"),Ge=require("lru-cache"),jt=require("stream/promises"),Et=require("tar"),At=require("wait-on"),W=require("y-protocols/awareness"),fe=require("y-protocols/sync"),Dt=require("yaml"),$e=require("./html-xfTPTsl5.js");require("@blocklet/pages-kit/types/state");const M=t=>t&&t.__esModule?t:{default:t};function pe(t){if(t&&t.__esModule)return t;const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const 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 q=pe(it),Ae=M(lt),E=M(ut),V=M(Z),De=M(pt),Ne=M(p),ge=pe(ht),v=pe(yt),Te=M(St),Re=M(wt),Oe=M(It),Me=M(bt),Tt=M(Pt),Rt=M(At),H=pe(Dt),Ot=h.DataTypes.sqlite.DATE.parse;h.DataTypes.sqlite.DATE.parse=(t,e)=>typeof t=="number"?new Date(t):Ot(t,e);const F=new h.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});F.query("PRAGMA journal_mode = WAL;");F.query("PRAGMA synchronous = normal;");F.query("PRAGMA journal_size_limit = 67108864;");F.query("PRAGMA cache_size = 10000;");process.on("SIGINT",async()=>{await F.close(),process.exit(0)});process.on("SIGTERM",async()=>{await F.close(),process.exit(0)});async function Ct(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 Se=null;Se&&clearInterval(Se);Se=setInterval(async()=>{u.logger.info("Start cleanupSqliteMemory"),await Ct(F,u.databaseUrl),u.logger.info("End cleanupSqliteMemory")},60*1e3*10);const kt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",we="page",Ie="trigger-reload-project-resource",Ce=kt,vt="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM",Lt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o";class ke extends h.Model{}ke.init({id:{type:h.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:h.DataTypes.UUIDV4},projectId:{type:h.DataTypes.UUID,allowNull:!1},componentId:{type:h.DataTypes.STRING,allowNull:!1}},{sequelize:F,tableName:"ProjectComponents",timestamps:!1});const _t="SLUG_INVALID",Y=t=>({error:"slugInvalid",code:_t,field:"slug",message:t}),Ut={error:"slugRequired",code:"SLUG_REQUIRED",field:"slug",message:()=>"Project slug is required"},$t={error:"slugAlreadyExists",code:"SLUG_EXISTS",field:"slug",message:t=>`Project slug "${t}" already exists`},Nt=[/\.\./,/<[^>]*>/,/%[0-9a-f]{2}/i,/[<>'"%;{}()\\]/,/\x00/,/\n|\r|\t|\v|\f/,/[^a-zA-Z0-9-_@/\\:]/],Fe=t=>{if(!t)return"";if(t==="/")return"/";const e=_.withoutTrailingSlash(t);return _.withLeadingSlash(e)||"/"},Mt=t=>t.did===Lt;class $ extends h.Model{static async getProjectByIdOrSlug(e,a){return e?$.findOne({where:{[h.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 Ut;const s=e==="/"?"/":_.withoutTrailingSlash(_.withLeadingSlash(e)),o=Fe(s);if(s!=="/"&&s.endsWith("/"))return Y(r=>`Project slug "${r}" cannot end with /`);if(/\/{2,}/.test(s))return Y(r=>`Project slug "${r}" cannot contain consecutive /`);if(/\s/.test(s))return Y(r=>`Project slug "${r}" cannot contain whitespace`);if(Nt.some(r=>r.test(s)))return Y(r=>`Project slug "${r}" contains invalid characters`);if(E.default.components?.filter(r=>r.mountPoint&&!Mt(r)).some(r=>Fe(r.mountPoint)===o))return Y(r=>`Project slug "${r}" conflicts with existing blocklet`);const c=await $.findOne({where:{slug:s}});return c&&c?.id!==a?$t:null}}$.init({id:{type:h.DataTypes.UUID,defaultValue:h.DataTypes.UUIDV4,primaryKey:!0},name:{type:h.DataTypes.STRING,allowNull:!1},description:h.DataTypes.TEXT,createdAt:h.DataTypes.DATE,updatedAt:h.DataTypes.DATE,createdBy:{type:h.DataTypes.STRING,allowNull:!1},updatedBy:{type:h.DataTypes.STRING,allowNull:!1},slug:h.DataTypes.STRING,icon:h.DataTypes.STRING,pinnedAt:h.DataTypes.DATE,useAllResources:h.DataTypes.BOOLEAN,npmSecret:h.DataTypes.STRING,relatedBlocklets:{type:h.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:h.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:h.DataTypes.JSON,allowNull:!0}},{sequelize:F,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:{[h.Op.ne]:null}}}]});$.hasMany(ke,{foreignKey:"projectId",as:"components"});async function x(t){try{return await V.default.promises.access(t,V.default.constants.F_OK),!0}catch{return!1}}function Ve(t,e){return new Promise((a,s)=>{const o=V.default.createReadStream(t),n=V.default.createWriteStream(e);o.on("error",s),n.on("error",s),n.on("finish",a),o.pipe(n)})}async function ze(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 o=Ne.default.join(t,s.name),n=Ne.default.join(e,s.name);s.isDirectory()?await ze(o,n):await Ve(o,n)}}async function Ft(t,e){(await V.default.promises.stat(t)).isDirectory()?await ze(t,e):await Ve(t,e)}class ee extends h.Model{}ee.init({id:{type:h.DataTypes.UUID,primaryKey:!0,defaultValue:h.DataTypes.UUIDV4},projectId:{type:h.DataTypes.UUID,allowNull:!1,comment:"Project ID"},urlPath:{type:h.DataTypes.STRING(512),allowNull:!1,unique:!0,comment:"URL path, e.g. /project-slug/page-slug or /en/project-slug/page-slug"},projectSlug:{type:h.DataTypes.STRING,allowNull:!0,comment:"Project slug"},pageSlug:{type:h.DataTypes.STRING,allowNull:!1,comment:"Page slug"},pageId:{type:h.DataTypes.UUID,allowNull:!1,comment:"Page ID"},routeId:{type:h.DataTypes.UUID,allowNull:!0,comment:"Route ID (for draft mode)"},locale:{type:h.DataTypes.STRING(10),allowNull:!0,comment:"Locale code, e.g. en, zh"},defaultLocale:{type:h.DataTypes.STRING(10),allowNull:!0,comment:"Default locale"},shouldRedirect:{type:h.DataTypes.BOOLEAN,defaultValue:!1,comment:"Whether this URL should redirect"},mainPage:{type:h.DataTypes.BOOLEAN,defaultValue:!1,comment:"Whether this is the main page"},isPublic:{type:h.DataTypes.BOOLEAN,allowNull:!1,defaultValue:!0,comment:"Whether the page is public"},publishedAt:{type:h.DataTypes.BIGINT,allowNull:!0,comment:"Published timestamp"},locales:{type:h.DataTypes.JSON,allowNull:!0,comment:"Supported locales array"},createdAt:h.DataTypes.DATE,updatedAt:h.DataTypes.DATE},{sequelize:F,tableName:"PageUrlMappings",timestamps:!0,indexes:[{name:"idx_project_id",fields:["projectId"]},{name:"idx_url_path",unique:!0,fields:["urlPath"]},{name:"idx_page_id",fields:["pageId"]}]});function qt(t){const{projectId:e,projectSlug:a,state:s}=t,o=a||e,n=Be.union(E.default.env.languages?.map(l=>l.code)||[],s.supportedLocales?.map(l=>l.locale)||[]),c={},r=(l,S)=>{o&&(c[_.joinURL("/",o,l)]={...S,shouldRedirect:!0,mainPage:!0}),c[_.joinURL("/",e,l)]={...S,shouldRedirect:!0,mainPage:!0};for(const j of n){const T={...S,locale:j};c[_.joinURL("/",j,e,l)]=T,o&&(c[_.joinURL("/",j,o,l)]=T)}};for(const l of s.pageIds||[]){const S=s.pages?.[l];if(!S||!S.isPublic)continue;const j={projectId:e,projectSlug:o,pageSlug:S.slug,pageId:l,defaultLocale:n?.[0],locales:n,publishedAt:s.config?.publishedAt,isPublic:S.isPublic};r(S.slug,j)}return c}async function xt(t,e,a){const s=t.map(n=>n.urlPath),o=await ee.findAll({where:{urlPath:{[h.Op.in]:s},projectId:{[h.Op.ne]:e}},attributes:["urlPath","projectId","projectSlug","pageSlug"],transaction:a,raw:!0});if(o.length>0){u.logger.warn(`[URL Duplicate Warning] Found ${o.length} URL conflicts for project ${e}:`);for(const n of o){const c=t.find(r=>r.urlPath===n.urlPath);if(c){const r=n.projectSlug?_.joinURL(n.projectSlug,n.pageSlug):n.pageSlug;u.logger.warn(` - URL "${n.urlPath}" conflicts with project ${n.projectId} (${r}). Current project trying to use same URL for page: ${c.pageSlug}`)}}u.logger.warn("[URL Duplicate Warning] These duplicate URLs will be ignored during save. Consider using different project slugs or page slugs to avoid conflicts.")}}async function Bt(t){const{projectId:e,transaction:a}=t;try{await ee.destroy({where:{projectId:e},transaction:a});const s=qt(t),o=Object.entries(s).map(([n,c])=>({projectId:e,urlPath:n,projectSlug:c.projectSlug,pageSlug:c.pageSlug,pageId:c.pageId,routeId:c.routeId,locale:c.locale,defaultLocale:c.defaultLocale,shouldRedirect:c.shouldRedirect,mainPage:c.mainPage,isPublic:c.isPublic,publishedAt:typeof c.publishedAt=="number"?c.publishedAt:void 0,locales:c.locales}));if(o.length>0){await xt(o,e,a);const n=100,c=[];for(let r=0;r<o.length;r+=n){const l=o.slice(r,r+n);c.push(ee.bulkCreate(l,{transaction:a,ignoreDuplicates:!0}))}await Promise.all(c),u.logger.info(`Regenerated ${o.length} URL mappings for project ${e}`)}return o.length}catch(s){throw u.logger.error(`Failed to regenerate URL mappings for project ${e}:`,s),s}}function ie(t){t.observeDeep(e=>{e.some(a=>a.changes.keys.has("updatedAt")||a.changes.keys.has("publishedAt"))||t.set("updatedAt",new Date().toISOString())})}function He(){return Z.mkdtempSync(p.join(E.default.env.dataDir,"tmp-"))}function ce(t,e,a=[]){return Array.isArray(t)?t.flatMap((s,o)=>ce(s,e,[...a,o])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([s,o])=>ce(o,e,[...a,s])):e(t)?[a]:[]}function U(t){return t.filter(e=>e!=null)}function Gt(t){return new Promise((e,a)=>{let s;process.env.NODE_ENV==="development"?s=p.join(__dirname,"yaml-worker.js"):s=p.join(__dirname,"api/dist/utils/yaml-worker.js");const o=new dt.Worker(s);o.postMessage({payload:t}),o.on("message",n=>{n.status==="success"?e(n.result):a(new Error(`YAML stringify failed in worker: ${n.message}`)),o.terminate()}),o.on("error",n=>{a(n)}),o.on("exit",n=>{n!==0&&a(new Error(`Worker stopped with exit code ${n}`))})})}function Vt(t){t.pages&&Object.keys(t.pages).forEach(a=>{const s=G.getYjsValue(t.pages[a]);s&&s instanceof q.Map&&ie(s)});const e=G.getYjsValue(t.pages);e&&e instanceof q.Map&&e.observe(a=>{a.changes.keys.forEach((s,o)=>{if(s.action==="add"){const n=G.getYjsValue(t.pages[o]);n&&n instanceof q.Map&&ie(n)}})})}function zt(t){t.routes&&Object.keys(t.routes).forEach(a=>{const s=G.getYjsValue(t.routes?.[a]);s&&s instanceof q.Map&&ie(s)});const e=G.getYjsValue(t.routes);e&&e instanceof q.Map&&e.observe(a=>{a.changes.keys.forEach((s,o)=>{if(s.action==="add"){const n=G.getYjsValue(t.routes?.[o]);n&&n instanceof q.Map&&ie(n)}})})}function Ht(t,e){for(const a of e||Object.keys(t.routes||{})){let s=a,o=[];if(a.includes("-")){const[n,...c]=a.split("-");s=n,o=c||[]}if(t.routes?.[s]!==void 0){t.routes[s].publishedAt=new Date().toISOString();const n=t.routes[s];if(!n||!n.params||n.params.length===0)continue;if(a.includes("-")&&o.length>0){const c=ne.getRouteMetaDataByOptionIds(o,n);c&&(c.publishedAt=new Date().toISOString())}if(!e){const c=ne.generateParamCombinations({basePath:n.path,params:n.params,routeId:n.id,paramsOptions:n.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const r of c)r.routeMetaData??={},r.routeMetaData.publishedAt=new Date().toISOString()}}}}function me({page:t,route:e,state:a,routeId:s,routePathInfo:o}){u.logger.info(`Executing datasource data assembly, routeId: ${s}, routePathInfo: ${JSON.stringify(o)}`);const n={...Ae.default(t),id:s,slug:o?.path??e.path,createdAt:e.createdAt,updatedAt:o?.routeMetaData?.updatedAt??e.updatedAt,publishedAt:o?.routeMetaData?.publishedAt??e.publishedAt,isPublic:(o?.routeMetaData?.isPublic??e.isPublic)&&e.isPublic};for(const c of a.supportedLocales){if(e.dataSource){let r=e.id;o&&(r=o.paramOptionIds.join("-"));const l=e.dataSource.pathDataMappings?.[r]?.dataCache?.[c.locale]??e.dataSource.pathDataMappings?.[r]?.dataCache?.[a.config.defaultLocale||"en"];if(!l)continue;ct.setPageDataSource(n,a,c.locale,l)}o&&o.routeMetaData&&(o.routeMetaData.publishedAt=new Date().toISOString())}return n}["true","1","yes","y"].includes(process.env.USE_FS_CACHE_HTML??"");const Kt=60*60*1e3,J=new Ge.LRUCache({max:300,ttl:Kt,ttlResolution:10*1e3,allowStale:!0});function Wt(t,e=[]){let a=0;const s=Array.from(J.keys()),o=t.map(n=>_.withoutTrailingSlash(n));for(const n of s)for(const c of o){if($e.matchCacheKey(n,{currentPath:c})){J.delete(n),a++,u.logger.info(`[Cache CLEAR] key: ${n}`);break}for(const r of e)if($e.matchCacheKey(n,{currentPath:`/${r}${c}`})){J.delete(n),a++,u.logger.info(`[Cache CLEAR] key: ${n}`);break}}return u.logger.info(`[Cache CLEAR] cleared ${a} entries for paths:`,o),a}function Yt(){const t=J.size;return J.clear(),u.logger.info(`[Cache CLEAR ALL] cleared ${t} entries`),t}const Jt=Be.debounce(Yt,300);E.default.events.on(E.default.Events.envUpdate,Jt);const{uploadToMediaKit:Xt}=require("@blocklet/uploader-server"),ve=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,X=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,qe=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Qt=1e4,Zt=3e4,se=0,he=1,ea=0,ta=1,be=E.default,z=p.join(process.env.BLOCKLET_DATA_DIR,"site-state"),aa=["production","draft"],sa=["production"];function le(t){return t?.replace(/\//g,"|")||""}function Ke(){const t=be.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 C extends q.Doc{constructor(e){if(super(),this.options=e,Z.existsSync(this.draftYjsFilePath))try{q.applyUpdate(this,Z.readFileSync(this.draftYjsFilePath))}catch(a){u.logger.error("Failed to apply update from draft.yjs:",a)}this.syncedStore=mt.reactive(G.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new W.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 periodicCheckTimer;static async safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const a=p.join(z,e),s=p.join(z,`@del-${e}`);await D.rename(a,s)}catch(a){u.logger.error("Failed to safe delete project state dir:",a)}}static async getProjectIds(){return(await $.findAll({attributes:["id"],raw:!0}))?.map(e=>e.id)}static get projectIds(){return re.globSync("*/",{cwd:z,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*","undefined"]})}static get allShared(){return this.projectIds.map(e=>C.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let a=C.sharedInstances[e];return a||(a=new C({path:p.join(z,e)}),C.sharedInstances[e]=a,a)}static async getProductionState(e){const a=await $.findByPk(e,{attributes:["productionState"]});if(Oe.default(a?.productionState)){const s=p.join(z,e,"production"),o=await Le(s,{includeResources:!0})??Ke();if(!o?.config?.defaultLocale){o.config??={};const n=be.env.languages?.map(c=>({locale:c.code,name:c.name}))||[];o.config.defaultLocale=n[0]?.locale}return o}return a?.productionState}destroy(){this.cancelRelease(),this.save({flush:!0}),this.conns.forEach((a,s)=>this.closeConn(s)),this.awareness.destroy();const e=p.basename(this.options.path);delete C.sharedInstances[e],super.destroy()}initObserver(){Vt(this.syncedStore),zt(this.syncedStore)}get draftYjsFilePath(){return p.join(this.options.path,"draft.yjs")}static async getStateByProjectId({projectId:e,mode:a,clone:s=!0}){if(a==="draft"){const o=C.shared(e);return s?JSON.parse(JSON.stringify(o.syncedStore)):o.syncedStore}return C.getProductionState(e)}async getState(e){if(e==="draft")return JSON.parse(JSON.stringify(this.syncedStore));const a=p.basename(this.options.path);return C.getProductionState(a)}async setState(e,a){if(e!=="production")return;const s=p.basename(this.options.path),o=Ae.default(a);await F.transaction(async n=>{await $.update({productionState:o},{where:{id:s},transaction:n});const c=await $.findByPk(s,{attributes:["slug"],transaction:n}),r=await Bt({projectId:s,projectSlug:c?.slug,state:a,transaction:n});u.logger.info(`[SiteState] saved ${r} URL mappings for project ${s}`)}),await this.clearPageCacheForRoutes(void 0,a),setImmediate(async()=>{const n=await Xe(a,{exportAssets:!1,includeResources:!0}),c=this.getPublishDir(e);await D.mkdir(p.dirname(c),{recursive:!0}),await D.rm(c,{force:!0,recursive:!0}),await D.rename(n,c),u.logger.info(`[SiteState] saved package for project ${s} in ${e} mode`)})}getPublishDir(e){return p.join(this.options.path,e)}syncedStore;conns=new Map;awareness;releaseTimer;awarenessChangeHandler=({added:e,updated:a,removed:s},o)=>{const n=e.concat(a,s);if(o!==null){const l=this.conns.get(o);l&&(e.forEach(S=>{l.add(S)}),s.forEach(S=>{l.delete(S)}))}const c=v.createEncoder();v.writeVarUint(c,he),v.writeVarUint8Array(c,W.encodeAwarenessUpdate(this.awareness,n));const r=v.toUint8Array(c);this.conns.forEach((l,S)=>this.send(S,r))};updateHandler=e=>{const a=v.createEncoder();v.writeVarUint(a,se),fe.writeUpdate(a,e);const s=v.toUint8Array(a);this.conns.forEach((o,n)=>this.send(n,s))};ensureDataStructure=()=>{this.transact(()=>{const{supportedLocales:e,pages:a,pageIds:s,config:o,routes:n,routeIds:c}=this.syncedStore;{const r=new Set(Object.keys(a));let l=0;for(;l<s.length;){const S=s[l];r.has(S)?(r.delete(S),l++):s.splice(l,1)}}{const r=new Set(Object.keys(n));let l=0;for(;l<c.length;){const S=c[l];r.has(S)?(r.delete(S),l++):c.splice(l,1)}}e.splice(0,e.length),e.push(...be.env.languages.map(r=>({locale:r.code,name:r.name}))),o.defaultLocale=e[0]?.locale;{let r=0;const l=new Set;for(;r<e.length;){const{locale:S}=e[r];l.has(S)?e.splice(r,1):(r++,l.add(S))}}})};send=(e,a)=>{e.readyState!==ea&&e.readyState!==ta&&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&&W.removeAwarenessStates(this.awareness,Array.from(a),null)}e.close(),this.checkAndScheduleRelease()};checkAndScheduleRelease(){this.conns.size===0&&this.scheduleRelease()}scheduleRelease(){this.cancelRelease();const e=p.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())},C.RELEASE_DELAY),u.logger.info(`[SiteState] scheduled release for project ${e} in ${C.RELEASE_DELAY/1e3}s`)}cancelRelease(){if(this.releaseTimer){clearTimeout(this.releaseTimer),this.releaseTimer=void 0;const e=p.basename(this.options.path);u.logger.info(`[SiteState] cancelled scheduled release for project ${e}`)}}autoSave=Te.default(async()=>{await D.mkdir(p.dirname(this.draftYjsFilePath),{recursive:!0}),await D.writeFile(this.draftYjsFilePath,q.encodeStateAsUpdate(this))},Qt);save=({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()};publish=async({mode:e,routes:a})=>{const s=p.basename(this.options.path);await nt(s);const o=await this.getState("draft"),n=await this.getState("production");await je(o,n,{routes:a,mergeMode:"replace",deleteRoutes:!0,publishMode:e}),n.config.publishedAt=new Date().getTime(),setImmediate(()=>{this.transact(()=>{Ht(this.syncedStore,a)})}),await this.setState(e,n)};mergeState=async(e,a)=>{const s=JSON.parse(JSON.stringify(a));e.config.fontFamily??={};const o=s.config?.fontFamily,n=e.config?.fontFamily;e.config.fontFamily.title=o?.title||n?.title,e.config.fontFamily.description=o?.description||n?.description,await new Promise((c,r)=>{this.transact(async()=>{try{const l=await je(e,a);c(l)}catch(l){r(l)}})})};clearPageCacheForRoutes=async(e,a)=>{const s=p.basename(this.options.path),n=(await $.findByPk(s))?.slug||s;let c=e;(!c||c.length===0)&&(c=a.pageIds??[]),u.logger.info(`[SiteState] clearing page cache for project ${s}, routes:`,c||[]);const r=a.supportedLocales.map(j=>j.locale),l=[],S=c.filter(j=>a.pageIds?.includes(j));for(const j of S){const b=a.pages[j].slug;n&&n!==s&&(n==="/"?l.push(b):l.push(`${n.startsWith("/")?"":"/"}${n}${b}`)),l.push(`/${s}${b}`)}if(l.length>0)try{const j=Wt(l,r);u.logger.info(`[SiteState] cleared ${j} page cache entries for project ${s}, routes:`,c)}catch{}};addConnection=e=>{if(this.conns.has(e))return;this.cancelRelease(),e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",o=>this.messageListener(e,new Uint8Array(o)));let 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)}}},Zt);e.on("close",()=>{this.closeConn(e),clearInterval(s)}),e.on("pong",()=>{a=!0});{const o=v.createEncoder();v.writeVarUint(o,se),fe.writeSyncStep1(o,this),this.send(e,v.toUint8Array(o));const n=this.awareness.getStates();if(n.size>0){const c=v.createEncoder();v.writeVarUint(c,he),v.writeVarUint8Array(c,W.encodeAwarenessUpdate(this.awareness,Array.from(n.keys()))),this.send(e,v.toUint8Array(c))}}};messageListener=(e,a)=>{try{const s=v.createEncoder(),o=ge.createDecoder(a),n=ge.readVarUint(o);switch(u.logger.info(`[SiteState] messageListener, messageType: ${n}`),n){case se:v.writeVarUint(s,se),fe.readSyncMessage(o,s,this,null),u.logger.info(`[SiteState] messageListener, encoder length: ${v.length(s)}`),v.length(s)>1&&(this.ensureDataStructure(),this.send(e,v.toUint8Array(s)));break;case he:{W.applyAwarenessUpdate(this.awareness,ge.readVarUint8Array(o),e);break}default:u.logger.warn(`Unsupported messageType ${n}`)}}catch(s){u.logger.error(s)}this.save()};static async pageUrlMap(e,a){if(u.logger.info(`[SiteState] get pageUrlMap, mode: ${e}, projectId: ${a}`),e==="production"){const n=a?{projectId:a}:{},c=await ee.findAll({where:n,raw:!0}),r={};for(const l of c)r[l.urlPath]={projectId:l.projectId,projectSlug:l.projectSlug,pageSlug:l.pageSlug,pageId:l.pageId,routeId:l.routeId,locale:l.locale,defaultLocale:l.defaultLocale,shouldRedirect:l.shouldRedirect,mainPage:l.mainPage,isPublic:l.isPublic,publishedAt:l.publishedAt,locales:l.locales};return u.logger.info(`[SiteState] loaded ${c.length} URL mappings from database`),r}let s=[];a?s=[a]:s=await this.getProjectIds();let o={};if(s?.length){u.logger.info("[SiteState] find project infos from database, projectIds: ",s);const n=30,c=De.default(5);for(let r=0;r<s.length;r+=n){const l=s.slice(r,r+n);u.logger.info(`[SiteState] processing project batch ${r/n+1}, ids: `,l);const S=await $.findAll({where:{id:{[h.Op.in]:l}},attributes:{exclude:["relatedBlocklets"]}});await Promise.all(S?.map(j=>c(async()=>{const T=j.id,b=j.slug||T,m={},d=await C.getStateByProjectId({projectId:j.id,mode:e,clone:!1}),P=Tt.default(E.default.env.languages?.map(A=>A.code)||[],d.supportedLocales?.map(A=>A.locale)||[]),R=(A,I)=>{b&&(m[_.joinURL("/",b,A)]={...I,shouldRedirect:!0,mainPage:!0}),m[_.joinURL("/",T,A)]={...I,shouldRedirect:!0,mainPage:!0};for(const k of P){const y={...I,locale:k};m[_.joinURL("/",k,T,A)]=y,b&&(m[_.joinURL("/",k,b,A)]=y)}};if(e==="draft")for(const A of d.routeIds||[]){const I=d?.routes?.[A];if(!I)continue;if(I.params&&I.params.length>0){const w=ne.generateParamCombinations({basePath:I.path,params:I.params,routeId:I.id,paramsOptions:I.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const i of w){const f=i.path,g={projectId:T,projectSlug:b,pageSlug:f,pageId:I.displayTemplateId||"",routeId:A,defaultLocale:P?.[0],locales:P,publishedAt:d.config.publishedAt,isPublic:I.isPublic&&i?.routeMetaData?.isPublic};R(f,g)}}const k=I.path,y={projectId:T,projectSlug:b,pageSlug:k,pageId:I.displayTemplateId||"",routeId:A,defaultLocale:P?.[0],locales:P,publishedAt:d.config.publishedAt,isPublic:I.isPublic};R(k,y)}for(const A of d.pageIds||[]){const I=d.pages[A];if(!I)continue;const k=I.slug,y=j.slug||T,w={projectId:T,projectSlug:y,pageSlug:k,pageId:A,defaultLocale:P?.[0],locales:P,publishedAt:d.config.publishedAt,isPublic:I.isPublic,templateConfig:I.templateConfig};R(k,w)}o={...o,...m}})))}}return u.logger.info("[SiteState] success get pageUrlMap"),o}getDocumentSize(){return q.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const e=[];for(const[a,s]of Object.entries(C.sharedInstances)){const o=s.getDocumentSize();e.push({projectId:a,sizeInBytes:o,sizeInMB:`${(o/(1024*1024)).toFixed(2)} MB`,activeConnections:s.conns.size})}return e}static startPeriodicCheck(){this.periodicCheckTimer||(this.periodicCheckTimer=setInterval(()=>{this.performPeriodicCheck()},this.PERIODIC_CHECK_INTERVAL),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(C.sharedInstances).length,a=[],s=[];for(const[o,n]of Object.entries(C.sharedInstances))n.conns.size===0?a.push({projectId:o,instance:n}):s.push({projectId:o,connections:n.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(n=>n.projectId));let o=0;for(const{projectId:n,instance:c}of a)try{u.logger.info(`[SiteState] releasing instance due to periodic check: ${n}`),c.destroy(),o++}catch(r){u.logger.error(`[SiteState] failed to release instance ${n} during periodic check:`,r)}u.logger.info(`[SiteState] periodic check completed: ${o}/${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 oa(t,e,a){if(!t||!await x(t)||!(await D.lstat(t)).isFile())return null;let o=a[t];return o||(o=(async()=>{try{return(await Xt({filePath:t,fileName:e}))?.data?.filename}catch(n){return u.logger.error(`Failed to upload asset ${t}:`,n),null}})(),a[t]=o),o}const We=async(t,e)=>{const a=p.basename(t),s=await Ee.call({name:Ce,path:_.joinURL("/uploads",a),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const o=Z.createWriteStream(e);await jt.pipeline(s.data,o)}else throw new Error(`download asset failed ${s.status}`)},Ye=async(t,e)=>{await Promise.all(t.map(async a=>{try{await We(a,p.join(e,p.basename(a)))}catch(s){u.logger.error(`Failed to export assets: ${a}, ${s}`)}}))};function Je(t){return ve.test(t)?[t]:X.test(t)?(qe.lastIndex=0,Array.from(t.matchAll(qe)).map(a=>a[1]).filter(a=>!!a)):[]}async function oe(t,e,a){const{getFilename:s,exportAssets:o,useWorker:n}=a,c=p.join(e,s(t));await D.mkdir(p.dirname(c),{recursive:!0});const r=n?await Gt(t):H.stringify(t);if(await D.writeFile(c,r),o){const S=ce(t,j=>typeof j=="string"&&(ve.test(j)||X.test(j))).map(j=>{const T=Re.default(t,j);return Je(T)}).flat().filter(Boolean);await Ye(S,p.dirname(c))}}const Pe=new Ge.LRUCache({max:100,ttl:1*60*1e3});async function xe(t,e,a){const s=ce(t,r=>typeof r=="string"&&(ve.test(r)||X.test(r))),o=De.default(2),n=s.map(r=>o(async()=>{try{const l=Re.default(t,r),S=Je(l);for(const j of S){const T=p.basename(j),b=a.getFilePath(j,r),m=b?`${b}:${T}`:T,d=Pe.get(m);if(d){X.test(l)||Me.default(t,r,d);return}const P=await oa(b,T,e);P&&(X.test(l)||Me.default(t,r,P),Pe.set(m,P))}}catch(l){u.logger.error(`Failed to process upload for path ${r.join(".")}:`,l.message||l.reason)}})),c=await Promise.allSettled(n);a.onFinish?.(c)}async function Xe(t,{exportAssets:e,pageIds:a="all",componentIds:s="all",rawConfig:o,includeResources:n=!1,routeIds:c="all"}={}){const r=a==="all"?t.pageIds:a,l=gt.getComponentDependencies({state:t,pageIds:r,componentIds:s==="all"?Object.keys(t.components):s});Object.entries(t.components).forEach(([i,f])=>{f.data?.renderer?.type==="component-template"&&l.push(i)});const S=c==="all"?t.routeIds:c,j=i=>({id:i.id,name:i.name,isTemplateSection:i.isTemplateSection??!1,templateDescription:i.templateDescription,component:i.component,config:i.config,visibility:i.visibility,sections:i?.sectionIds?U(i?.sectionIds?.map(f=>{const g=i.sections?.[f];return g&&j(g)})):void 0}),T=(i,f)=>({id:i.id,createdAt:i.createdAt,updatedAt:i.updatedAt,publishedAt:i.publishedAt,isPublic:i.isPublic??!0,templateConfig:i.templateConfig,meta:i.locales?.[f]??{},sections:U(i.sectionIds.map(g=>{const O=i.sections[g];return O&&j(O)})),dataSource:Object.fromEntries(Object.entries(i.dataSource||{}).map(([g,O])=>[g,O?.[f]??{}]))}),b=i=>({id:i.id,createdAt:i.createdAt,updatedAt:i.updatedAt,publishedAt:i.publishedAt,path:i.path,handler:i.handler,isPublic:i.isPublic??!0,params:i.params??[],enabledGenerate:i.enabledGenerate??!1,displayTemplateId:i.displayTemplateId,dataSource:i.dataSource}),m=U(S.map(i=>{const f=t.routes[i];return f&&b(f)})),d=U(t.supportedLocales.map(i=>i.locale).flatMap(i=>r.map(f=>{const g=t.pages[f];return g&&{locale:i,slug:g.slug,page:T(g,i)}}))),P=He(),R=p.join(P,"pages");await D.mkdir(R,{recursive:!0});const A=p.join(P,"components");await D.mkdir(A,{recursive:!0});const I=p.join(P,"routes");await D.mkdir(I,{recursive:!0});for(const{locale:i,slug:f,page:g}of d)await oe(g,R,{getFilename:()=>`${le(f)||"index"}.${i}.yml`,exportAssets:e,useWorker:!0});for(const i of m)await oe(i,I,{getFilename:()=>`${le(i.path)||"index"}.yml`,exportAssets:e});for(const i of l){const f=t.components[i]?.data;f&&await oe(f,A,{getFilename:g=>`${g.name||"unnamed"}.${g.id}.yml`,exportAssets:e})}const k=p.join(P,".blocklet/pages/pages.config.yml");await D.mkdir(p.dirname(k),{recursive:!0});const y={pages:U(r.map(i=>{const f=t.pages[i];return f&&{id:i,slug:f.slug}})),routes:U(S.map(i=>{const f=t.routes[i];return f&&{id:i,path:f.path}})),components:U(l.map(i=>{const f=t.components[i]?.data;return f&&{id:i,name:f.name}})),...n?{resources:{components:U(Object.keys(t.resources?.components||{}).filter(i=>l.includes(i)).map(i=>({id:i,name:t.resources?.components?.[i]?.component?.name})))}}:{},supportedLocales:t.supportedLocales,config:t.config};await D.writeFile(k,H.stringify(y));const w=p.join(P,"config.source.json");if(o&&await D.writeFile(w,JSON.stringify(o)),n){const i=p.join(P,"resources"),f=p.join(i,"components");await D.mkdir(f,{recursive:!0});for(const N of Object.keys(t?.resources?.components??{}).filter(L=>l.includes(L))){const L=t.resources?.components?.[N]?.component;L&&await oe(L,f,{getFilename:B=>`${B.name||"unnamed"}.${B.id}.yml`,exportAssets:e})}const g=p.join(P,"chunks");await D.mkdir(g,{recursive:!0});const O=await na();for(const N of Object.keys(t?.resources?.components??{}).filter(L=>l.includes(L))){const L=t.resources?.components?.[N]?.component;if(L&&L.renderer?.type==="react-component"){const B=L.renderer?.chunks??[];if(B?.length>0)for(const K of B){const _e=p.join(g,K),de=O?.[K];try{de&&await x(de)&&!await x(_e)&&await D.copyFile(de,_e)}catch(rt){u.logger.error(`copy chunk ${K} error`,rt.message)}}}}}return P}async function Le(t,{importAssets:e,includeResources:a}={}){if(!await x(t))return null;let s,o=!1;try{(await D.lstat(t)).isDirectory()?s=t:/\.(tgz|gz|tar)$/.test(t)&&(o=!0,s=He(),await Et.x({file:t,C:s}));const r=(await re.glob("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}))[0],l=r&&p.join(p.dirname(r),"../../pages"),S=r&&p.join(p.dirname(r),"../../components"),j=r&&p.join(p.dirname(r),"../../routes");if(!r)return null;const T=await D.readFile(r,"utf-8"),b=H.parse(T),m=async(y,w,i)=>{let f=p.join(y,`${w}${i?`.${i}`:""}.yml`);if(!await x(f)&&(f=p.join(y,w,`index${i?`.${i}`:""}.yml`),!await x(f))||!(await D.lstat(f)).isFile())return null;const O=await D.readFile(f,"utf-8");return H.parse(O)},d=async(y,w)=>{try{const f=(await re.glob(`*.${w}.yml`,{cwd:y,absolute:!0}))[0];if(!f)return null;const g=await D.readFile(f,"utf-8");return H.parse(g)}catch(i){u.logger.error("parse component error",i)}return null},P=async(y,w)=>{let i=p.join(y,`${w}.yml`);if(!await x(i)&&(i=p.join(y,w,"index.yml"),!await x(i))||!(await D.lstat(i)).isFile())return null;const g=await D.readFile(i,"utf-8");return H.parse(g)},R=U(await Promise.all(b.pages.map(async({slug:y})=>{const w=U(await Promise.all(b.supportedLocales.map(async({locale:g})=>{const O=l?await m(l,le(y),g):void 0;if(O)return{locale:g,page:O};const N=l?await m(l,y,g):void 0;return N&&{locale:g,page:N}}))),i=w[0]?.page;if(!i)return null;const f=i.sections.map(ft.unzipSection);return{id:i.id||Ue.nextId(),createdAt:i.createdAt,updatedAt:i.updatedAt,publishedAt:i.publishedAt,isPublic:i.isPublic??!0,templateConfig:i.templateConfig,slug:y,sections:Object.fromEntries(f.map(g=>[g.id,g])),sectionIds:f.map(g=>g.id),locales:Object.fromEntries(w.map(({locale:g,page:O})=>[g,O.meta])),dataSource:i.dataSource?Object.fromEntries([...new Set(w.flatMap(({page:g})=>Object.keys(g.dataSource??{})))].map(g=>[g,Object.fromEntries(w.map(({locale:O,page:N})=>{const L=N.dataSource?.[g];return[O,L||{}]}))])):Object.fromEntries([...new Set(w.flatMap(({page:g})=>g.sections.map(O=>O.id)))].map(g=>[g,Object.fromEntries(w.map(({locale:O,page:N})=>{const L=N.dataSource?.[g];if(L)return[O,L];const B=N.sections.find(K=>K.id===g);return[O,B?.properties||{}]}))]))}}))),A=U(await Promise.all((b?.routes||[]).map(async({path:y})=>{const w=j?await P(j,le(y)):void 0;return{...w,id:w?.id||Ue.nextId(),createdAt:w?.createdAt??new Date().toISOString(),updatedAt:w?.updatedAt??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:w?.path??`/${w?.id}`,params:w?.params,handler:w?.handler??"Pages Kit",isPublic:w?.isPublic??!0,enabledGenerate:w?.enabledGenerate??!1,displayTemplateId:w?.displayTemplateId??void 0,dataSource:w?.dataSource??{}}}))),I=S?U(await Promise.all((b.components||[]).map(async({id:y})=>d(S,y)))):[];if(e){const y=(...w)=>{u.logger.info(`[${o?p.basename(t):p.basename(p.join(t,"../../../../"))}] importAssets:`,...w)};try{y("wait image-bin api ready"),await Rt.default({resources:[`${Ee.getComponentWebEndpoint(u.IMAGE_BIN_NAME)}/api/sdk/uploads`],validateStatus:f=>f>=200&&f<=500}),y("image-bin api is ready");const w={},i={};y("start to upload assets"),await Promise.allSettled([xe(I,w,{getFilePath:f=>S&&p.join(S,f),onFinish:f=>{y(`upload ${f.length} component assets`)}}),xe(R,i,{getFilePath:(f,g)=>{const O=Re.default(R,g.slice(0,1));return l&&p.join(l,p.dirname(O.slug),f)},onFinish:f=>{y(`upload ${f.length} page assets`)}})]),y("upload assets done"),Pe.clear(),global.gc&&global.gc()}catch(w){y("Error during asset import:",w)}}const k={};if(a){const y=r&&p.join(p.dirname(r),"../../resources/components"),w=U(await Promise.all((b.resources?.components||[]).map(async({id:i})=>d(y,i))));w.length>0&&(k.components=Object.fromEntries(w.map((i,f)=>[i.id,{index:f,component:i}])))}return{supportedLocales:b.supportedLocales,pageIds:R.map(y=>y.id),components:Object.fromEntries(I.map((y,w)=>[y.id,{index:w,data:y}])),pages:Object.fromEntries(R.map(y=>[y.id,y])),config:b.config||{},resources:k,routeIds:A.map(y=>y.id),routes:Object.fromEntries(A.map(y=>[y.id,y])),dataSourceIds:[],dataSources:{}}}finally{o&&s&&await D.rm(s,{force:!0,recursive:!0})}}async function je(t,e,{routes:a,mergeMode:s="byUpdateTime",deleteRoutes:o=!1,publishMode:n=void 0}={}){try{n&&u.clearPreloadComponentsCacheByMode(n)}catch(b){u.logger.error("clear preload page cache error",{error:b})}const{pages:c,pageIds:r,routeIds:l,routes:S,supportedLocales:j}=t;if(n==="production"){let b=a??[],m=null;for(const d of l??[]){const P=S?.[d];if(P?.params&&P?.params.length>0&&P?.paramsOptions&&P?.paramsOptions.length>0){const R=ne.generateParamCombinations({basePath:P.path,params:P.params,routeId:P.id,paramsOptions:P.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),A=Object.fromEntries(R.map(I=>[`${d}-${I.paramOptionIds.join("-")}`,I]));m={...m||{},...A},a||(b=[...b,...R.map(I=>`${d}-${I.paramOptionIds.join("-")}`)])}else a||b.push(d)}u.logger.info("routeIds to be published: ",b);for(const d of b){let P=d;if(P.includes("-")){const[I]=P.split("-");P=I}const R=S?.[P];if(!R){const I=e.pageIds.indexOf(P);I!==-1&&o&&(e.pageIds.splice(I,1),delete e.pages[P]);for(const k of e.pageIds)k.includes(`${P}-`)&&(e.pageIds.splice(e.pageIds.indexOf(k),1),delete e.pages[k]);u.logger.info("delete main route page",P);continue}if(d.includes("-")&&!m?.[d]){const I=e.pageIds.indexOf(d);I!==-1&&o&&(e.pageIds.splice(I,1),delete e.pages[d]),u.logger.info("delete page",d);continue}if(!R.displayTemplateId){u.logger.info("no display template",d);continue}const A=c[R.displayTemplateId];if(!A){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]=me({page:A,route:R,state:t,routeId:d,routePathInfo:m?.[d]}),u.logger.info("replace page",d);else if(s==="byUpdateTime"){const I=e.pages[R.id];(!I||R.updatedAt&&R.updatedAt>I.updatedAt)&&(e.pages[d]=me({page:A,route:R,state:t,routeId:d,routePathInfo:m?.[d]}),u.logger.info("replace page by update time",d))}}else e.pageIds.push(d),e.pages[d]=me({page:A,route:R,state:t,routeId:d,routePathInfo:m?.[d]}),u.logger.info("add page",d)}if(o&&!a)for(const d of e.pageIds)b?.includes(d)||(delete e.pages[d],u.logger.info("delete page",d)),e.pageIds=[...e.pageIds].filter(P=>b?.includes(P))}else{for(const b of r){const m=c[b];if(m)if(e.pageIds.includes(m.id)){if(s==="replace")e.pages[m.id]=m;else if(s==="byUpdateTime"){const d=e.pages[m.id];(!d||m.updatedAt&&m.updatedAt>d.updatedAt)&&(e.pages[m.id]=m)}}else e.pageIds.push(m.id),e.pages[m.id]=m}for(const b of l){const m=S[b];if(m)if(e.routeIds.includes(m.id)){if(s==="replace")e.routes[m.id]=m;else if(s==="byUpdateTime"){const d=e.routes[m.id];(!d||m.updatedAt&&m.updatedAt>d.updatedAt)&&(e.routes[m.id]=m)}}else e.routeIds.push(m.id),e.routes[m.id]=m}}if(e.supportedLocales.splice(0,e.supportedLocales.length),e.supportedLocales.push(...Ae.default(j)),o)for(const b of Object.keys(e.components))delete e.components[b];let T=JSON.parse(JSON.stringify(t.components));T=Object.fromEntries(await Promise.all(Object.entries(T).map(async([b,m])=>{const d=await Qe(m?.data);return[b,{...m,data:d}]}))),Object.assign(e.components,T),Object.assign(e.config,JSON.parse(JSON.stringify(t.config))),Oe.default(t.resources.components)||(e.resources.components=JSON.parse(JSON.stringify(t.resources.components||{})))}const Qe=u.memoizeWithFs(async t=>{if(!Oe.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((o,n)=>{t?.properties&&(t.properties[o.id]={index:n,data:o})}))}catch(s){u.logger.error("getPropertiesFromCode error",{componentId:t.id,name:t.name},{error:s})}}return t},{subdir:"getPropertiesFromCode"});let ue,Q,te,ae;const Ze=()=>Ee.getResources({types:[{did:Ce,type:we},{did:vt,type:we}]}),na=async()=>{const t=Ze(),e={};for(const a of t){const o=(await re.glob("**/.blocklet/pages/pages.config.yml",{cwd:a.path,absolute:!0}))[0],n=o&&p.join(p.dirname(o),"../../chunks");if(n&&await x(n)){const c=await D.readdir(n);for(const r of c)e[r]=p.join(n,r)}}return e};function et(){return ue=(async()=>{const t=Ze();Q=(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),te=Q.reduce((a,s)=>Object.assign(a,Object.fromEntries(Object.values(s.state.pages).map(o=>o?[o?.id,{page:o,blockletId:s.blockletId}]:[]))),{});const e=Q.reduce((a,s)=>Object.assign(a,Object.fromEntries(Object.values(s.state.components).map(o=>[o.data.id,{blockletId:s.blockletId,component:o.data}]))),{});ae=Object.fromEntries(await Promise.all(Object.entries(e).map(async([a,s])=>{const o=await Qe(s.component);return[a,{...s,component:o}]}))),u.logger.info(`reloadResourceStates success: ${Object.keys(ae||{}).length} components, ${Object.keys(te||{}).length} pages`)})(),ue}function tt(t){const e=Te.default(async()=>{await et().catch(a=>{u.logger.error("load resource states error",{error:a})}),await t?.({states:Q,pages:te,components:ae})},3e3,{leading:!1,trailing:!0});return 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(Ie,e),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(Ie,e)}}const at=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),st=globalThis;st[at]?.();st[at]=tt(async({pages:t,components:e})=>{const a=await C.getProjectIds();u.logger.info(`start update resource states projects(${a.length})`,a);const s=De.default(10);await Promise.race([new Promise(o=>{setTimeout(()=>{o({})},30*1e3)}),Promise.all(a.map(o=>s(async()=>{ot({projectId:o,pages:t,components:e})})))]).catch(o=>{u.logger.error("update resource states failed:",o)})});C.startPeriodicCheck();process.on("beforeExit",()=>{C.stopPeriodicCheck()});process.on("SIGINT",()=>{C.stopPeriodicCheck(),process.exit(0)});process.on("SIGTERM",()=>{C.stopPeriodicCheck(),process.exit(0)});async function ot({projectId:t,pages:e,components:a}){const s=C.sharedInstances[t];if(!s){u.logger.info(`projectId: ${t} not found in sharedInstances`);return}const o=await $.findByPk(t,{attributes:{exclude:["productionState","relatedBlocklets"]}});let n;if(o?.useAllResources)n=a;else{const r=(await ke.findAll({where:{projectId:t}})).map(l=>l.componentId);n=Object.fromEntries(Object.entries(a||{}).filter(([l])=>r.includes(l)))}s.transact(()=>{s.syncedStore.resources.pages=e,u.logger.info(`[${t}] pages resources updated: ${Object.keys(e||{}).length} pages`),s.syncedStore.resources.components=n,u.logger.info(`[${t}] components resources updated: ${Object.keys(n||{}).length} components`)}),u.logger.info(`update [${t}] resource states summary:`,{pages:Object.keys(s.syncedStore.resources.pages||{}).length,components:Object.keys(s.syncedStore.resources.components||{}).length})}const ye=new Map;async function nt(t){if(!ye.has(t)){const e=Te.default(async a=>ot({projectId:a,pages:te,components:ae}),3e3);ye.set(t,e)}return ye.get(t)(t)}async function ra(){u.logger.info("trigger reload all project resource"),E.default.events.emit(Ie)}async function ia({ensureLoaded:t=!0}={}){return t&&(ue??=et(),await ue),{states:Q,pages:te,components:ae}}exports.COMPONENT_DID=Ce;exports.PUBLISH_MODES=sa;exports.Project=$;exports.RESOURCE_TYPE=we;exports.SITE_STATE_PATH=z;exports.STATE_MODES=aa;exports.SiteState=C;exports.copyRecursive=Ft;exports.downloadAsset=We;exports.downloadAssets=Ye;exports.fromPackage=Le;exports.getDefaultState=Ke;exports.getResourceStates=ia;exports.initPackResourceStates=tt;exports.mergeState=je;exports.toPackage=Xe;exports.triggerReloadAllProjectResource=ra;exports.updateResourceStatesByProjectId=nt;
@@ -1 +0,0 @@
1
- "use strict";const ge=require("react/jsx-runtime"),D=require("ufo"),Se=require("@blocklet/js-sdk"),Ie=require("lodash/isEmpty"),Pe=require("yaml"),ye=require("@arcblock/ux/lib/Locale/context"),ee=require("@blocklet/pages-kit/hooks/use-deep-compare-memo"),J=require("@blocklet/pages-kit/utils/common"),Ce=require("@blocklet/pages-kit/utils/page-model");require("@mui/material");const te=require("@syncedstore/core"),we=require("@syncedstore/react"),he=require("ahooks"),A=require("immer"),be=require("lodash/cloneDeep"),ve=require("lodash/debounce"),S=require("react"),oe=require("react-router-dom"),Oe=require("y-indexeddb"),xe=require("y-websocket"),ke=require("yjs");require("@blocklet/pages-kit/types");const G=o=>o&&o.__esModule?o:{default:o};function Ee(o){if(o&&o.__esModule)return o;const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const g in o)if(g!=="default"){const f=Object.getOwnPropertyDescriptor(o,g);Object.defineProperty(n,g,f.get?f:{enumerable:!0,get:()=>o[g]})}}return n.default=o,Object.freeze(n)}const Te=G(Ie),je=Ee(Pe),Me=G(te),R=G(be),ne=G(ve);function ce(){const{pathname:o}=window.location,g=o.match(/\/admin\/(maker|previewer)\/([^/]+)/)?.[2],f=window.__PROJECT_ID__;if(!g&&!f)throw new Error("Unable to get projectId from pathname");return g||f}function Ne(o){return`${o}:pages:version`}function Le(o,n){return n==="yaml"?Te.default(o)?"":je.stringify(o,{indent:2}):n==="json"?JSON.parse(JSON.stringify(o||{})):n==="array"?JSON.parse(JSON.stringify(o||[])):o}const K=window.blocklet?.prefix||"/",z=Se.createAxios({timeout:200*1e3}),_e=window.location.protocol==="https:"?"wss":"ws",Ae=o=>D.joinURL(`${_e}://${window.location.hostname}`,K,`api/${o}/ws/pages`),Re="z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";blocklet?.componentMountPoints.find(o=>o.did===Re)?.mountPoint||D.joinURL(K,"/image-bin");function De(o){return o&&!/^(https?:\/\/|\/)/.test(o)?window.location.origin+D.joinURL(K,"uploads",o):o}const $e=window.innerWidth<=750;function qe(o,n,g){if(!o||/\.gif/.test(o))return o;const f=($e?n/1.5:n)*(g==="quality"?1.5:1);return Je(o,{imageFilter:"resize",w:f,f:"webp"})}function Je(o,n){return!o||!n?o:D.withQuery(o,n)}async function Ue(o){return z.get(`/api/projects/${o}`).then(n=>n.data)}async function Be(o){return z.post(`/api/projects/${o.id}/update`,o).then(n=>n.data)}const X="@COMPONENT-TEMPLATE-",W=o=>`${X}${o}`,F=o=>o.startsWith(X),Z=o=>F(o)?o.slice(X.length):null;function re(o,n={}){return n[o.id]=o,o.sectionIds&&o.sections&&o.sectionIds.forEach(g=>{const f=o.sections?.[g];f&&re(f,n)}),n}function se(o,n){const g=W(o.id),f=n.section,O=re(f);n.dataSource??={};const w=n.dataSource;return{id:g,createdAt:o.createdAt,updatedAt:o.updatedAt,publishedAt:o.updatedAt,slug:o.id,sections:O,sectionIds:[f.id],isPublic:!0,templateConfig:{isTemplate:!0},locales:{},dataSource:w}}const Fe=500,ie=S.createContext(null);function Ge({url:o,name:n,children:g,waitingSynced:f}){const[O,w]=S.useState(!1),{locale:L}=ye.useLocaleContext(),b=Q(),j=`${b}:MakerLocalState`,x=`${b}:${n}`,[v,P]=he.useLocalStorageState(j,{defaultValue:{},listenStorageChange:!0}),$=S.useRef(v);$.current=v;const q=S.useMemo(()=>Me.default({dataSourceIds:[],dataSources:{},pages:{},pageIds:[],routes:{},routeIds:[],components:{},supportedLocales:[],config:{},resources:{}}),[]),C=S.useMemo(()=>te.getYjsDoc(q),[q]);S.useMemo(()=>new Oe.IndexeddbPersistence(x,C),[x,C]);const h=S.useMemo(()=>new xe.WebsocketProvider(o,x,C,{params:{},resyncInterval:5*60*1e3}),[o,x,C]),B=S.useCallback(()=>{h&&(h.wsconnected?(h.disconnect(),setTimeout(()=>h.connect(),100)):h.connect())},[h]),e=S.useMemo(()=>new ke.UndoManager([C.getArray("pageIds"),C.getMap("pages"),C.getArray("supportedLocales"),C.getMap("config"),C.getMap("dataSources"),C.getArray("dataSourceIds"),C.getArray("routeIds"),C.getMap("routes")],{doc:C}),[C]),[t,c]=S.useState(null),[r,d]=S.useState(!1),[i,l]=S.useState(void 0),m=S.useCallback(async()=>{if(b){d(!0);try{const s=await Ue(b);c(s)}catch(s){console.error("Failed to fetch project:",s)}finally{d(!1)}}},[b]),u=S.useCallback(async(s,a)=>{if(l(void 0),!!b){a?.optimisticUpdate&&t&&c(I=>({...I,...s}));try{const I=await Be({...s});c(I)}catch(I){console.error("Failed to update project:",I),a?.optimisticUpdate&&c(t),l(I?.response?.data)}}},[b,t]);S.useEffect(()=>{b&&m()},[b,m]);const p=ee.useDeepCompareMemo(()=>({doc:C,state:q,localState:{...v,currentLocale:L},setLocalState:s=>P(typeof s=="function"?a=>s(a??{}):s),undoManager:e,projectState:{project:t,isLoadingProject:r,error:i},updateProject:u,forceSync:B}),[C,q,v,P,e,t,r,u,i,L,B]);return S.useEffect(()=>{e.on("stack-item-added",({stackItem:s})=>{const{currentPageId:a,currentLocale:I,pages:y}=$.current;s.meta.set("localState",{currentPageId:a,currentLocale:I,pages:y})}),e.on("stack-item-popped",({stackItem:s})=>{const a=s.meta.get("localState");a&&P(I=>({...I,...a}))})},[e,P]),S.useEffect(()=>{h.awareness.setLocalState(v)},[h,v]),S.useEffect(()=>{h.once("synced",()=>{w(!0)});let s=0,a=null;const I=3,y=5e3,M=15e3,k=()=>{s=0,P(T=>({...T,networkStatus:void 0}))},E=()=>{P(T=>({...T,networkStatus:"offline"}))},N=ne.default(({status:T})=>{if(T==="connected")k(),a&&(clearTimeout(a),a=null);else if(T==="disconnected"){if(s++,!a){const pe=Date.now();let Y=0;const fe=Math.ceil(M/y),H=()=>{Y++;const me=Date.now()-pe;if(h.wsconnected){k();return}if(me>=M||Y>=fe){E();return}a=setTimeout(H,y)};a=setTimeout(H,y)}s>=I&&E()}},Fe),_=()=>{h.wsconnected||h.connect(),k()},U=()=>{E()};return h.on("status",N),window.addEventListener("online",_),window.addEventListener("offline",U),h.wsconnected&&k(),()=>{a&&clearTimeout(a),h.off("status",N),window.removeEventListener("online",_),window.removeEventListener("offline",U)}},[h,P]),f&&!O?null:ge.jsx(ie.Provider,{value:p,children:g})}const ae=()=>{const o=S.useContext(ie);if(!o)throw new Error("Context is null");const n=we.useSyncedStore(o.state),{setLocalState:g,localState:f}=o,O=oe.useNavigate(),w=Q(),L=S.useRef({}),b=S.useCallback(e=>{const t=n.components[e]?.data;return!t||t.renderer?.type!=="component-template"?void 0:(L.current[e]||(L.current[e]={page:se(t,t.renderer)}),L.current[e]?.page)},[n.components]),j=S.useCallback(e=>{const t=n.components[e]?.data;if(!t||t.renderer?.type!=="component-template")return;const c=b(e);if(c)return{componentId:e,component:t,renderer:t.renderer,page:c}},[b,n.components]),x=S.useCallback(e=>{const t=n.pages[e];if(t)return{kind:"page",pageId:e,page:t};if(!F(e))return;const c=Z(e);if(!c)return;const r=j(c);if(r)return{kind:"component-template",pageId:e,page:r.page,componentId:r.componentId,component:r.component,renderer:r.renderer}},[j,n.pages]),v=S.useCallback(e=>{const t=x(e);if(!t)throw new Error(`Page ${e} is not exists`);return t},[x]),P=ee.useDeepCompareMemo(()=>({get currentPage(){const{localState:{currentPageId:e,currentComponentId:t}}=o;if(e){const c=x(e);if(c)return c.page}if(t){const c=j(t);if(c)return c.page}},get currentSection(){const{localState:{currentPageId:e,...t}}=o,{currentPage:c}=this;if(!c||!e)return;const r=t.pages?.[e]?.currentSectionId;if(r)return c.sections?.[r]??this.currentPageModel?.getComponentById(r)?.model},get currentSectionProperties(){const{localState:{currentPageId:e,...t}}=o,{currentPage:c}=this;if(!c||!e)return;const r=t.pages?.[e]?.currentSectionId;if(!r)return;const d=c.dataSource?.[r];if(!d)return;const{currentLocale:i}=this.currentLocaleMap;return i?d[i]:void 0},get currentSectionPropertiesWithFallback(){const{localState:{currentPageId:e,...t}}=o,{currentPage:c}=this;if(!c||!e)return;const r=t.pages?.[e]?.currentSectionId;if(!r)return;const d=c.dataSource?.[r];if(!d)return;const{currentLocale:i,defaultLocale:l,fallbackLocale:m}=this.currentLocaleMap;if(i&&d[i])return d[i];if(l&&d[l])return d[l];if(m&&d[m])return d[m]},get currentLocaleMap(){const{localState:{currentLocale:e},state:{supportedLocales:t,config:{defaultLocale:c}}}=o;return{currentLocale:e,defaultLocale:c,fallbackLocale:t?.[0]?.locale??"en"}},get currentRoute(){const{localState:{currentRouteId:e}}=o;return e?n.routes?.[e]:void 0},get currentPageModel(){const e=this.currentPage??null;if(e)return Ce.getPageTemplateModel(e,!1)}}),[f,n]),$=S.useMemo(()=>{if(f.currentPageId){const e=x(f.currentPageId);if(e?.kind==="component-template")return e}if(f.currentComponentId){const e=j(f.currentComponentId);if(e)return{kind:"component-template",pageId:W(e.componentId),page:e.page,componentId:e.componentId,component:e.component,renderer:e.renderer}}},[f.currentPageId,f.currentComponentId,x,j]),q=S.useCallback(()=>$?.kind==="component-template"?$:void 0,[$]),C=S.useMemo(()=>({setCurrentSectionId:(e,t)=>{const c=F(e),r=c?Z(e):null;e===f.currentPageId&&t===f.pages?.[e]?.currentSectionId&&(!c||r===f.currentComponentId)||(O(c&&r?D.joinURL("/admin/maker",w??"","components",r):D.joinURL("/admin/maker",w??"","pages",e)),g(d=>A.produce(d,i=>{i.currentPageId=e,c?r&&(i.currentComponentId=r):i.currentComponentId=void 0,i.pages??={},i.pages[e]??={},i.pages[e].currentSectionId=t??void 0,t?window.sessionStorage.setItem("iframe_show_id",`"${t}"`):window.sessionStorage.removeItem("iframe_show_id")})))},setCurrentComponentId:e=>{if(!e){g(d=>A.produce(d,i=>{i.currentComponentId=void 0}));return}const c=n.components[e]?.data?.renderer?.type==="component-template",r=c?W(e):void 0;e===f.currentComponentId&&(!c||f.currentPageId===r)||(O(D.joinURL("/admin/maker",w??"","components",e)),g(d=>A.produce(d,i=>{i.currentComponentId=e,c&&r?(i.currentPageId=r,i.pages??={},i.pages[r]??={}):i.currentPageId&&F(i.currentPageId)&&(i.currentPageId=void 0)})))},setCurrentRouteId:({routeId:e,dynamicParams:t})=>{g(c=>A.produce(c,r=>{r.currentRouteId=e,r.currentDynamicParams=t}))},setCustomComponentPreviewerProperties:(()=>{const e={};let t="";const c=ne.default(()=>{g(r=>A.produce(r,d=>{d.customComponentPreviewerProperties??={},d.customComponentPreviewerProperties[t]={...d.customComponentPreviewerProperties[t],...R.default(e[t])},delete e[t]}))},5);return(r,d)=>{const i=e[r]??{};Object.assign(i,d),e[r]=i,t=r,c()}})(),setRouteGenerateProcess:e=>{g(t=>A.produce(t,c=>{e?c.routeGenerateProcess={...c.routeGenerateProcess,...e}:c.routeGenerateProcess={}}))},resetRouteGenerateProcess:()=>{g(e=>A.produce(e,t=>{t.routeGenerateProcess={progress:"complete"}}))}}),[g,O,w,P]),h=S.useCallback((e,t,c,r,d)=>{const i=v(e),{page:l}=i,m=R.default(t),u=c?R.default(c):void 0,p=V(m);return o.doc.transact(()=>{if(d&&d.component==="layout-block"){const s=P.currentPageModel?.getComponentById(d.id);s&&(s.model.sections??={},s.model.sections[p.id]=p,s.model.sectionIds??=[],s.model.sectionIds.push(p.id))}else if(i.kind==="component-template"){const s=i.renderer.section;s.sections??={},s.sections[p.id]=p,s.sectionIds??=[],s.sectionIds.push(p.id)}else l.sections[p.id]=p,l.sectionIds.splice(r??l.sectionIds.length,0,p.id);if(u){l.dataSource??={};const s=(a,I)=>{const y=u[a.id];y&&(l.dataSource[I.id]=R.default(y)),a.component==="layout-block"&&a.sectionIds?.length&&a.sectionIds.forEach((M,k)=>{const E=a.sections?.[M],N=I.sectionIds?.[k],_=N?I.sections?.[N]:void 0;E&&_&&s(E,_)})};s(m,p)}}),C.setCurrentSectionId(e,p.id),p},[v,P,o.doc,C]),B=S.useMemo(()=>({addPage:(e,t)=>{const c=e?.id??J.nextId(),r={...e,id:c,createdAt:e?.createdAt??new Date().toISOString(),updatedAt:e?.updatedAt??new Date().toISOString(),publishedAt:new Date(0).toISOString(),slug:e?.slug??`/${c}`,sections:e?.sections??{},sectionIds:e?.sectionIds??[],isPublic:e?.isPublic??!0,templateConfig:e?.templateConfig??{isTemplate:e?.templateConfig?.isTemplate??!0,displayTemplateId:e?.templateConfig?.displayTemplateId??void 0,dataSourceIds:e?.templateConfig?.dataSourceIds??void 0,dataSourceParameters:e?.templateConfig?.dataSourceParameters??{},enabledGenerate:e?.templateConfig?.enabledGenerate??!1,agentId:e?.templateConfig?.agentId??void 0}};return o.doc.transact(()=>{n.pages[r.id]=r,n.pageIds.splice(t??n.pageIds.length,0,r.id)}),r},addRoute:(e,t)=>{const c=e?.id??J.nextId(),r={...e,id:c,createdAt:e?.createdAt??new Date().toISOString(),updatedAt:e?.updatedAt??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:e?.path??`/${c}`,handler:e?.handler??"Pages Kit",isPublic:e?.isPublic??!0,params:e?.params??[],enabledGenerate:e?.enabledGenerate??!1,displayTemplateId:e?.displayTemplateId??void 0,dataSource:e?.dataSource??{}};return o.doc.transact(()=>{n.routes??={},n.routeIds??=[],n.routes[r.id]=r,n.routeIds.splice(t??n.routeIds.length,0,r.id)}),r},deleteRoute:e=>{if(!e)return;const t=n.routeIds?.indexOf(e);t!==void 0&&t!==-1&&o.doc.transact(()=>{n.routeIds?.splice(t,1),delete n.routes?.[e]})},deletePage:e=>{const t=n.pageIds.indexOf(e);t!==-1&&o.doc.transact(()=>{n.pageIds.splice(t,1),delete n.pages[e]})},movePage:(e,t)=>{const{pageIds:c}=n,r=c.indexOf(e);r>=0&&c.splice(t,0,...c.splice(r,1))},addSection:(e,t,c,r)=>{const d=v(e),{page:i}=d,l=t?.config,m=typeof l?.componentId=="string"?l.componentId:void 0;if(t.component==="custom-component"&&m){const a=(n.components[m]?.data??n.resources?.components?.[m]?.component)?.renderer;if(a?.type==="component-template")return h(e,a.section,a.dataSource,c,r)}const u={...t,id:t.id??J.nextId(),isTemplateSection:t.isTemplateSection??!0},p=R.default(u.locales);return delete u.locales,o.doc.transact(()=>{if(r&&r.component==="layout-block"){const s=P.currentPageModel?.getComponentById(r.id);s&&(s.model.sections??={},s.model.sections[u.id]=u,s.model.sectionIds??=[],s.model.sectionIds.push(u.id))}else if(d.kind==="component-template"){const s=d.renderer.section;s.sections??={},s.sections[u.id]=u,s.sectionIds??=[],s.sectionIds.push(u.id)}else i.sections[u.id]=u,i.sectionIds.splice(c??i.sectionIds.length,0,u.id);p&&(i.dataSource??={},i.dataSource[u.id]=p)}),u},deleteSection:(e,t)=>{const c=v(e),{page:r}=c;o.doc.transact(()=>{const d=[],i=P.currentPageModel?.getComponentById(t),l=i?.parent;if(i&&(d.push(i.model.id,...i.all().map(m=>m.model.id)),l?.model.component==="layout-block")){const m=l.model.sectionIds?.indexOf(t);m!==void 0&&m!==-1&&(l.model.sectionIds?.splice(m,1),delete l.model.sections?.[t]),l.model.config?.gridSettings&&Object.keys(l.model.config.gridSettings).forEach(u=>{try{delete l.model.config.gridSettings[u]?.[t]}catch{}}),l.model.config?.backgroundSectionId===t&&(l.model.config.backgroundSectionId=void 0)}d.forEach(m=>{const u=r.sectionIds.indexOf(m);u!==-1&&r.sectionIds.splice(u,1),r.sections[m]&&delete r.sections[m],r.dataSource?.[m]&&delete r.dataSource?.[m]})})},lockSection:(e,t)=>{v(e);const c=P.currentPageModel?.getComponentById(t)?.model;c&&(c.locked=!c.locked)},toggleSectionVisibility:(e,t,c)=>{v(e);const r=P.currentPageModel?.getComponentById(t)?.model;r&&(r.visibility=c)},moveSection:(e,t,c,r)=>{const d=v(e),{page:i}=d,l=P.currentPageModel;if(!l)throw new Error(`Page model for ${e} is not available`);const m=p=>{const s=l.getComponentById(p);if(!s)return null;const a=s.model,I=s.parent;if(!I)return{section:a,container:i,containerType:"root",index:i.sectionIds.indexOf(p)};const y=I.model;return{section:a,container:y,containerType:"layout-block",index:y.sectionIds.indexOf(p)}},u=m(t);if(!u)throw new Error(`Section ${t} not found`);o.doc.transact(()=>{if(c.startsWith("layout-")){const a=c.replace("layout-",""),y=l.getComponentById(a)?.model;if(!y||y.component!=="layout-block")throw new Error(`Layout block ${a} not found`);if(a===t||((E,N)=>{const _=l.getComponentById(E),U=l.getComponentById(N);if(!_||!U||_.model.component!=="layout-block")return!1;let T=U.parent;for(;T;){if(T.model.id===E)return!0;T=T.parent}return!1})(t,a))return;const k=JSON.parse(JSON.stringify(u.section));y.sections||(y.sections={}),y.sectionIds||(y.sectionIds=[]),y.sections[t]=k,y.sectionIds.push(t),u.container.sectionIds.splice(u.index,1),u.containerType==="layout-block"&&delete u.container.sections[t];return}const p=m(c);if(!p)throw new Error(`Target section ${c} not found`);let s=p.index;if(r==="bottom"&&(s=p.index+1),u.container===p.container){const{sectionIds:a}=u.container;a.splice(u.index,1),u.index<s&&(s-=1),a.splice(s,0,t)}else{const a=JSON.parse(JSON.stringify(u.section));p.containerType==="root"||(p.container.sections||(p.container.sections={}),p.container.sections[t]=a),p.container.sectionIds.splice(s,0,t),u.container.sectionIds.splice(u.index,1),u.containerType==="layout-block"&&delete u.container.sections[t]}})},copySection:(e,t)=>{v(e);const c=P.currentPageModel?.getComponentById(t);if(!c?.model)throw new Error(`Section ${t} is not exists`);const r=JSON.parse(JSON.stringify(c.model)),d=V(r),i=d.id,l=c?.parent;if(l){if(l.model.sections[i]=d,l.model.sectionIds.push(i),P.currentPage?.dataSource?.[t]&&(P.currentPage.dataSource[i]=JSON.parse(JSON.stringify(P.currentPage.dataSource[t])),d.component==="layout-block")){const m=(u,p)=>{const s=u.sectionIds,a=p.sectionIds;s?.forEach((I,y)=>{const M=a?.[y];if(M){if(M&&P.currentPage?.dataSource){const N=P.currentPage.dataSource[M];N&&(P.currentPage.dataSource[I]=JSON.parse(JSON.stringify(N)))}const k=u.sections?.[I],E=p?.sections?.[M];k?.component==="layout-block"&&k.sectionIds&&E?.sectionIds&&m(k,E)}})};d.sectionIds&&r.sectionIds&&m(d,r)}C.setCurrentSectionId(e,i)}return d},extractSectionToComponentTemplate:(e,t)=>{const c=v(e),{page:r}=c,i=P.currentPageModel?.getComponentById(t)?.model;if(!i){console.warn(`Section ${t} is not exists`);return}const l=JSON.parse(JSON.stringify(i));if(l.component!=="layout-block"||!(l.sectionIds?.length??0)){console.warn(`Section ${t} is not eligible for component template extraction.`);return}const m=(s,a=[])=>(s&&(a.push(s.id),s.sectionIds?.forEach(I=>{const y=s.sections?.[I];m(y,a)})),a),p=m(i).reduce((s,a)=>{const I=r.dataSource?.[a];return I&&(s[a]=JSON.parse(JSON.stringify(I))),s},{});return{section:l,dataSource:Object.keys(p).length?p:void 0}},addComponentTemplate:({name:e,description:t,section:c,dataSource:r})=>{const d=J.nextId(),i=new Date().toISOString(),l=R.default(c),m=r?R.default(r):void 0;return o.doc.transact(()=>{const u=Object.values(n.components).length;n.components[d]={index:u,data:{id:d,name:e.trim()||void 0,description:t?.trim()||void 0,createdAt:i,updatedAt:i,renderer:{type:"component-template",section:l,dataSource:m}}}}),n.components[d]},addDataSource:e=>{const t=e.id??J.nextId(),c={...e??{},id:t,createdAt:new Date().toISOString()};return o.doc.transact(()=>{n.dataSourceIds??=[],n.dataSources??={},n.dataSourceIds.push(t),n.dataSources[t]=c}),n.dataSources[t]},deleteDataSource:e=>{const t=n.dataSourceIds.indexOf(e);t!==-1&&o.doc.transact(()=>{n.dataSourceIds.splice(t,1),delete n.dataSources[e]})}}),[n,o.doc,P]);return{...o,state:n,actions:B,localActions:C,...P,getComponentTemplateContext:q}},Q=()=>{const{projectId:o}=oe.useParams();return o??ce()??""},We=()=>window.__PROJECT_SLUG__??"";function de(o){const{resources:n}=o;if(!n.components)return{};const g={};return window?.blocklet?.componentMountPoints?.forEach(f=>{g[f.did]=f}),Object.fromEntries(Object.entries(n.components).map(([f,{blockletId:O,component:w}])=>[f,{data:w,blockletId:O,blockletTitle:g[O]?.title||O}]))}function ue(o){const{components:n}=o;return n||{}}function le(o){return{...de(o),...ue(o)}}const Ve=()=>le(ae().state);function V(o){const n=JSON.parse(JSON.stringify(o)),g=J.nextId();if(n.component==="layout-block"){const f={...n.config??{}},O=n.sectionIds?.map(w=>{const L=n.sections?.[w],b=V(n.sections?.[w]),j=b.id;return L?.id===n.config?.backgroundSectionId&&(f.backgroundSectionId=b.id),n.config?.gridSettings&&Object.keys(n.config.gridSettings).forEach(x=>{f.gridSettings[x]={...f.gridSettings[x]??{},[j]:{...n.config?.gridSettings?.[x]?.[w],id:j}},delete n.config?.gridSettings?.[x]?.[w]}),b});n.sections=Object.fromEntries(O?.map(w=>[w.id,w])??[]),n.sectionIds=O?.map(w=>w.id)??[],n.config=f}return{...n,id:g}}exports.StoreProvider=Ge;exports.api=z;exports.autoResizeImage=qe;exports.createComponentTemplatePage=se;exports.getAllComponents=le;exports.getCustomComponents=ue;exports.getImageAbsoluteUrl=De;exports.getProjectIdFromPathnameOrWindow=ce;exports.getProjectPageVersionKey=Ne;exports.getResourceComponents=de;exports.getWssURL=Ae;exports.transformValue=Le;exports.useAllComponents=Ve;exports.useProjectId=Q;exports.useProjectSlug=We;exports.useStore=ae;