@blocklet/pages-kit-inner-components 0.5.18 → 0.5.20

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.
Files changed (33) hide show
  1. package/lib/cjs/add-component.js +2 -2
  2. package/lib/cjs/chunks/{array-BChVGKFh.js → array-C0IVbCmb.js} +1 -1
  3. package/lib/cjs/chunks/{config-string-DnwpUGUo.js → config-string-CqKhhXBA.js} +1 -1
  4. package/lib/cjs/chunks/{draft-data-DPZIakr4.js → draft-data-BLL0M7MI.js} +1 -1
  5. package/lib/cjs/chunks/{home-BkGblT4S.js → home-DH9Z8Tuv.js} +3 -3
  6. package/lib/cjs/chunks/publish-button-Cw_MfRfv.js +1 -0
  7. package/lib/cjs/chunks/site-state-JgP3yURe.js +57 -0
  8. package/lib/cjs/chunks/state-CA6q2h83.js +1 -0
  9. package/lib/cjs/components.js +1 -1
  10. package/lib/cjs/home.js +1 -1
  11. package/lib/cjs/project-html.js +1 -1
  12. package/lib/cjs/resources.js +1 -1
  13. package/lib/cjs/setting.js +1 -1
  14. package/lib/cjs/site-state.js +1 -1
  15. package/lib/es/add-component.js +5 -6
  16. package/lib/es/chunks/{array-DcMaqKTM.js → array-B1QKSYbX.js} +1 -1
  17. package/lib/es/chunks/{config-string-CNgatAMw.js → config-string-D8tamRZ1.js} +1 -1
  18. package/lib/es/chunks/{draft-data-DB1pDB18.js → draft-data-DyeHwihR.js} +1 -1
  19. package/lib/es/chunks/{home-CYM8qSuo.js → home-BjT8iYTg.js} +4 -4
  20. package/lib/es/chunks/{publish-button-BxpOFbAK.js → publish-button-eIyM_BsP.js} +49 -49
  21. package/lib/es/chunks/site-state-BB9-Tm4i.js +1930 -0
  22. package/lib/es/chunks/{state-BcZbsEn6.js → state-j8jViBMV.js} +62 -63
  23. package/lib/es/components.js +1 -1
  24. package/lib/es/home.js +3 -3
  25. package/lib/es/project-html.js +1 -1
  26. package/lib/es/resources.js +1 -1
  27. package/lib/es/setting.js +2 -2
  28. package/lib/es/site-state.js +14 -15
  29. package/package.json +15 -15
  30. package/lib/cjs/chunks/publish-button-DvXGUgra.js +0 -1
  31. package/lib/cjs/chunks/site-state-VeQ4nMmB.js +0 -57
  32. package/lib/cjs/chunks/state-D4MG-uJB.js +0 -1
  33. package/lib/es/chunks/site-state-C9oPw4Cx.js +0 -1862
@@ -1,4 +1,4 @@
1
- import { jsx as L } from "react/jsx-runtime";
1
+ import { jsx as k } from "react/jsx-runtime";
2
2
  import { Box as z, Alert as K } from "@mui/material";
3
3
  import { joinURL as b, withQuery as q } from "ufo";
4
4
  import { createAxios as Q } from "@blocklet/js-sdk";
@@ -9,60 +9,59 @@ import H, { getYjsDoc as ee } from "@syncedstore/core";
9
9
  import { useSyncedStore as te } from "@syncedstore/react";
10
10
  import { useLocalStorageState as ne } from "ahooks";
11
11
  import { produce as C } from "immer";
12
- import oe from "js-cookie";
13
12
  import N from "lodash/debounce";
14
- import { customAlphabet as re } from "nanoid";
15
- import { createContext as se, useState as E, useRef as ce, useMemo as v, useCallback as k, useEffect as O, useContext as ie } from "react";
16
- import { useParams as ae, useNavigate as de } from "react-router-dom";
17
- import { IndexeddbPersistence as le } from "y-indexeddb";
18
- import { WebsocketProvider as ue } from "y-websocket";
19
- import { UndoManager as me } from "yjs";
13
+ import { customAlphabet as oe } from "nanoid";
14
+ import { createContext as re, useState as E, useRef as se, useMemo as v, useCallback as L, useEffect as O, useContext as ce } from "react";
15
+ import { useParams as ie, useNavigate as ae } from "react-router-dom";
16
+ import { IndexeddbPersistence as de } from "y-indexeddb";
17
+ import { WebsocketProvider as le } from "y-websocket";
18
+ import { UndoManager as ue } from "yjs";
20
19
  import "@blocklet/pages-kit/types";
21
- const Ve = (n) => {
20
+ const Je = (n) => {
22
21
  const t = blocklet == null ? void 0 : blocklet.componentMountPoints.find((a) => a.name === n);
23
22
  return t ? t.mountPoint : "/";
24
23
  };
25
- function fe() {
24
+ function me() {
26
25
  const { pathname: n } = window.location, t = n.match(/\/admin\/(maker|previewer)\/([^/]+)/), a = t == null ? void 0 : t[2], f = window.__PROJECT_ID__;
27
26
  if (!a && !f)
28
27
  throw new Error("Unable to get projectId from pathname");
29
28
  return a || f;
30
29
  }
31
- function We(n) {
30
+ function Be(n) {
32
31
  return `${n}:pages:version`;
33
32
  }
34
- function ze(n, t) {
33
+ function Ve(n, t) {
35
34
  return t === "yaml" ? X(n) ? "" : Y.stringify(n, { indent: 2 }) : t === "json" ? JSON.parse(JSON.stringify(n || {})) : t === "array" ? JSON.parse(JSON.stringify(n || [])) : n;
36
35
  }
37
- function Ke({ error: n }) {
38
- return /* @__PURE__ */ L(z, { children: /* @__PURE__ */ L(K, { severity: "error", children: n.message }) });
36
+ function We({ error: n }) {
37
+ return /* @__PURE__ */ k(z, { children: /* @__PURE__ */ k(K, { severity: "error", children: n.message }) });
39
38
  }
40
39
  var U;
41
40
  const D = ((U = window.blocklet) == null ? void 0 : U.prefix) || "/", J = Q({
42
41
  timeout: 200 * 1e3
43
- }), Se = window.location.protocol === "https:" ? "wss" : "ws", qe = (n) => b(`${Se}://${window.location.hostname}`, D, `api/${n}/ws/pages`), pe = "z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";
42
+ }), fe = window.location.protocol === "https:" ? "wss" : "ws", ze = (n) => b(`${fe}://${window.location.hostname}`, D, `api/${n}/ws/pages`), Se = "z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";
44
43
  var F;
45
- (F = blocklet == null ? void 0 : blocklet.componentMountPoints.find((n) => n.did === pe)) != null && F.mountPoint || b(D, "/image-bin");
46
- function Qe(n) {
44
+ (F = blocklet == null ? void 0 : blocklet.componentMountPoints.find((n) => n.did === Se)) != null && F.mountPoint || b(D, "/image-bin");
45
+ function Ke(n) {
47
46
  return n && !/^(https?:\/\/|\/)/.test(n) ? window.location.origin + b(D, "uploads", n) : n;
48
47
  }
49
- const we = window.innerWidth <= 750;
50
- function Xe(n, t, a) {
48
+ const pe = window.innerWidth <= 750;
49
+ function qe(n, t, a) {
51
50
  if (!n || /\.gif/.test(n)) return n;
52
- const f = (we ? t / 1.5 : t) * (a === "quality" ? 1.5 : 1);
53
- return Pe(n, { imageFilter: "resize", w: f, f: "webp" });
51
+ const f = (pe ? t / 1.5 : t) * (a === "quality" ? 1.5 : 1);
52
+ return we(n, { imageFilter: "resize", w: f, f: "webp" });
54
53
  }
55
- function Pe(n, t) {
54
+ function we(n, t) {
56
55
  return !n || !t ? n : q(n, t);
57
56
  }
58
- async function Ie(n) {
57
+ async function Pe(n) {
59
58
  return J.get(`/api/projects/${n}`).then((t) => t.data);
60
59
  }
61
- async function he(n) {
60
+ async function Ie(n) {
62
61
  return J.post(`/api/projects/${n.id}/update`, n).then((t) => t.data);
63
62
  }
64
- const ye = 500, A = re("abcdefghijklmnopqrstuvwxyz0123456789", 16), B = se(null);
65
- function Ye({
63
+ const he = 500, A = oe("abcdefghijklmnopqrstuvwxyz0123456789", 16), B = re(null);
64
+ function Qe({
66
65
  url: n,
67
66
  name: t,
68
67
  children: a,
@@ -71,7 +70,7 @@ function Ye({
71
70
  const [I, w] = E(!1), { locale: h } = Z(), S = V(), e = `${S}:MakerLocalState`, o = `${S}:${t}`, [s, r] = ne(e, {
72
71
  defaultValue: {},
73
72
  listenStorageChange: !0
74
- }), c = ce(s);
73
+ }), c = se(s);
75
74
  c.current = s;
76
75
  const i = v(
77
76
  () => H({
@@ -88,26 +87,26 @@ function Ye({
88
87
  }),
89
88
  []
90
89
  ), d = v(() => ee(i), [i]);
91
- v(() => new le(o, d), [o, d]);
90
+ v(() => new de(o, d), [o, d]);
92
91
  const p = v(
93
- () => new ue(n, o, d, {
94
- params: { token: oe.get("login_token") },
92
+ () => new le(n, o, d, {
93
+ params: {},
95
94
  resyncInterval: 5 * 60 * 1e3
96
95
  }),
97
96
  [n, o, d]
98
- ), g = k(() => {
97
+ ), g = L(() => {
99
98
  p && (p.disconnect(), p.connect());
100
99
  }, [p]), y = v(
101
- () => new me(
100
+ () => new ue(
102
101
  [d.getArray("pageIds"), d.getMap("pages"), d.getArray("supportedLocales"), d.getMap("config")],
103
102
  { doc: d }
104
103
  ),
105
104
  [d]
106
- ), [j, x] = E(null), [R, $] = E(!1), [T, _] = E(void 0), G = k(async () => {
105
+ ), [j, x] = E(null), [R, $] = E(!1), [T, _] = E(void 0), G = L(async () => {
107
106
  if (S) {
108
107
  $(!0);
109
108
  try {
110
- const l = await Ie(S);
109
+ const l = await Pe(S);
111
110
  x(l);
112
111
  } catch (l) {
113
112
  console.error("Failed to fetch project:", l);
@@ -115,7 +114,7 @@ function Ye({
115
114
  $(!1);
116
115
  }
117
116
  }
118
- }, [S]), M = k(
117
+ }, [S]), M = L(
119
118
  async (l, u) => {
120
119
  var P;
121
120
  if (_(void 0), !!S) {
@@ -124,7 +123,7 @@ function Ye({
124
123
  ...l
125
124
  }));
126
125
  try {
127
- const m = await he({
126
+ const m = await Ie({
128
127
  ...l
129
128
  });
130
129
  x(m);
@@ -197,17 +196,17 @@ function Ye({
197
196
  }));
198
197
  }, P = N(({ status: m }) => {
199
198
  m === "connected" ? l() : m === "disconnected" && u();
200
- }, ye);
199
+ }, he);
201
200
  return p.on("status", P), window.addEventListener("online", l), window.addEventListener("offline", u), () => {
202
201
  p.off("status", P), window.removeEventListener("online", l), window.removeEventListener("offline", u);
203
202
  };
204
- }, [p, r]), f && !I ? null : /* @__PURE__ */ L(B.Provider, { value: W, children: a });
203
+ }, [p, r]), f && !I ? null : /* @__PURE__ */ k(B.Provider, { value: W, children: a });
205
204
  }
206
- const ve = () => {
207
- const n = ie(B);
205
+ const ye = () => {
206
+ const n = ce(B);
208
207
  if (!n)
209
208
  throw new Error("Context is null");
210
- const t = te(n.state), { setLocalState: a, localState: f } = n, I = de(), w = V(), h = v(
209
+ const t = te(n.state), { setLocalState: a, localState: f } = n, I = ae(), w = V(), h = v(
211
210
  () => ({
212
211
  setCurrentSectionId: (e, o) => {
213
212
  var s, r;
@@ -421,10 +420,10 @@ const ve = () => {
421
420
  }
422
421
  };
423
422
  }, V = () => {
424
- const { projectId: n } = ae();
425
- return n ?? fe() ?? "";
423
+ const { projectId: n } = ie();
424
+ return n ?? me() ?? "";
426
425
  };
427
- function Ce(n) {
426
+ function ve(n) {
428
427
  var f, I;
429
428
  const { resources: t } = n;
430
429
  if (!t.components)
@@ -442,33 +441,33 @@ function Ce(n) {
442
441
  })
443
442
  );
444
443
  }
445
- function ge(n) {
444
+ function Ce(n) {
446
445
  const { components: t } = n;
447
446
  return t || {};
448
447
  }
449
- function je(n) {
448
+ function ge(n) {
450
449
  return {
451
- ...Ce(n),
452
- ...ge(n)
450
+ ...ve(n),
451
+ ...Ce(n)
453
452
  };
454
453
  }
455
- const Ze = () => je(ve().state);
454
+ const Xe = () => ge(ye().state);
456
455
  export {
457
- Ke as E,
458
- Ye as S,
459
- qe as a,
460
- ve as b,
461
- We as c,
462
- je as d,
463
- Xe as e,
464
- Ze as f,
465
- Qe as g,
456
+ We as E,
457
+ Qe as S,
458
+ ze as a,
459
+ ye as b,
460
+ Be as c,
461
+ ge as d,
462
+ qe as e,
463
+ Xe as f,
464
+ Ke as g,
466
465
  J as h,
467
- Ve as i,
468
- ge as j,
469
- Ce as k,
470
- fe as l,
466
+ Je as i,
467
+ Ce as j,
468
+ ve as k,
469
+ me as l,
471
470
  A as n,
472
- ze as t,
471
+ Ve as t,
473
472
  V as u
474
473
  };
@@ -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-C9oPw4Cx.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-BB9-Tm4i.js";
11
11
  export {
12
12
  _ as CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS,
13
13
  E as GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS,
package/lib/es/home.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import "react/jsx-runtime";
2
- import "./chunks/state-BcZbsEn6.js";
2
+ import "./chunks/state-j8jViBMV.js";
3
3
  import "@arcblock/ux/lib/Locale/context";
4
4
  import "@arcblock/ux/lib/Result";
5
5
  import "@blocklet/pages-kit/builtin/page/header";
@@ -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/array-DcMaqKTM.js";
25
- import { a as R, P as S, d as W, c as j, b as k, T as q, H as v } from "./chunks/home-CYM8qSuo.js";
24
+ import "./chunks/array-B1QKSYbX.js";
25
+ import { a as R, P as S, d as W, c as j, b as k, T as q, H as v } from "./chunks/home-BjT8iYTg.js";
26
26
  import "./chunks/session-CVblGhSp.js";
27
27
  export {
28
28
  R as HomeView,
@@ -5,7 +5,7 @@ import K from "@blocklet/sdk/lib/wallet";
5
5
  import z from "@blocklet/sdk/lib/wallet-authenticator";
6
6
  import Q from "@blocklet/sdk/lib/wallet-handler";
7
7
  import V, { resolve as x } from "path";
8
- import { l as I, g as X } from "./chunks/site-state-C9oPw4Cx.js";
8
+ import { l as I, g as X } from "./chunks/site-state-BB9-Tm4i.js";
9
9
  import { initCronCrawlBlocklet as Y, cancelCronCrawlBlocklet as Z, initSEOMiddleware as q } from "@blocklet/crawler/middlewares";
10
10
  import { PreloadComponentScriptModule as F } from "@blocklet/pages-kit/types";
11
11
  import { isMuiColorKey as ee } 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-C9oPw4Cx.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-BB9-Tm4i.js";
2
2
  import { AsyncLocalStorage as K } from "async_hooks";
3
3
  import { Router as Y } from "express";
4
4
  import d from "fs";
package/lib/es/setting.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { jsx as t, jsxs as O, Fragment as X } from "react/jsx-runtime";
2
- import { t as ye, g as Te, b as ce, E as ot, n as Ke, f as ve } from "./chunks/state-BcZbsEn6.js";
2
+ import { t as ye, g as Te, b as ce, E as ot, n as Ke, f as ve } from "./chunks/state-j8jViBMV.js";
3
3
  import de from "@arcblock/ux/lib/Empty";
4
4
  import { useLocaleContext as C } from "@arcblock/ux/lib/Locale/context";
5
5
  import { CodeEditor as xe } from "@blocklet/code-editor";
@@ -12,7 +12,7 @@ import A from "lodash/sortBy";
12
12
  import { useCallback as D, useMemo as ne, useRef as J, useId as gt, useEffect as $, useState as Q } from "react";
13
13
  import { useUpdate as _e } from "react-use";
14
14
  import { ColorItem as Pt, ConfigColorDialog as wt } from "@blocklet/pages-kit/builtin/color-picker";
15
- import { C as kt } from "./chunks/config-string-CNgatAMw.js";
15
+ import { C as kt } from "./chunks/config-string-D8tamRZ1.js";
16
16
  import Pe from "lodash/isEmpty";
17
17
  import He from "lodash/set";
18
18
  import * as me from "yaml";
@@ -1,7 +1,6 @@
1
- import { q, o as v, p as B, S as L, r as U, s as h, u as y, b as z, w as C, v as F, n as G, t as J, x as K } from "./chunks/site-state-C9oPw4Cx.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-BB9-Tm4i.js";
2
2
  import "@blocklet/pages-kit/utils/property";
3
3
  import "@blocklet/pages-kit/utils/route";
4
- import "@blocklet/quickjs";
5
4
  import "@blocklet/sdk/lib/component";
6
5
  import "@blocklet/sdk/lib/config";
7
6
  import "@reactivedata/reactive";
@@ -32,17 +31,17 @@ import "yaml";
32
31
  import "yjs";
33
32
  export * from "@blocklet/pages-kit/types/state";
34
33
  export {
35
- q as PUBLISH_MODES,
36
- v as SITE_STATE_PATH,
37
- B as STATE_MODES,
38
- L as default,
39
- U as downloadAsset,
40
- h as downloadAssets,
41
- y as fromPackage,
42
- z as getResourceStates,
43
- C as initPackResourceStates,
44
- F as mergeState,
45
- G as nextId,
46
- J as toPackage,
47
- K as triggerReloadAllProjectResource
34
+ j as PUBLISH_MODES,
35
+ q as SITE_STATE_PATH,
36
+ v as STATE_MODES,
37
+ B as default,
38
+ L as downloadAsset,
39
+ U as downloadAssets,
40
+ h as fromPackage,
41
+ y as getResourceStates,
42
+ z as initPackResourceStates,
43
+ C as mergeState,
44
+ F as nextId,
45
+ G as toPackage,
46
+ J as triggerReloadAllProjectResource
48
47
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blocklet/pages-kit-inner-components",
3
- "version": "0.5.18",
3
+ "version": "0.5.20",
4
4
  "description": "Pages Kit inner components library",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -71,23 +71,23 @@
71
71
  "dependencies": {
72
72
  "@arcblock/did-auth": "^1.20.11",
73
73
  "@arcblock/did-auth-storage-nedb": "^1.7.1",
74
- "@arcblock/did-connect": "^2.13.41",
75
- "@arcblock/react-hooks": "^2.13.41",
76
- "@arcblock/ux": "^2.13.41",
77
- "@blocklet/ai-kit": "^0.1.76",
78
- "@blocklet/ai-runtime": "^0.4.270",
79
- "@blocklet/code-editor": "^0.4.270",
80
- "@blocklet/crawler": "^2.3.36",
74
+ "@arcblock/did-connect": "^2.13.47",
75
+ "@arcblock/react-hooks": "^2.13.47",
76
+ "@arcblock/ux": "^2.13.47",
77
+ "@blocklet/ai-kit": "^0.1.78",
78
+ "@blocklet/ai-runtime": "^0.4.271",
79
+ "@blocklet/code-editor": "^0.4.271",
80
+ "@blocklet/crawler": "^2.3.46",
81
81
  "@blocklet/embed": "^0.2.4",
82
82
  "@blocklet/js-sdk": "^1.16.43",
83
83
  "@blocklet/logger": "1.16.36",
84
- "@blocklet/quickjs": "^0.4.270",
84
+ "@blocklet/quickjs": "^0.4.271",
85
85
  "@blocklet/sdk": "^1.16.43",
86
- "@blocklet/studio-ui": "^0.4.270",
86
+ "@blocklet/studio-ui": "^0.4.271",
87
87
  "@blocklet/tracker": "^1.16.43",
88
- "@blocklet/ui-react": "^2.13.41",
89
- "@blocklet/uploader": "^0.1.91",
90
- "@blocklet/uploader-server": "^0.1.98",
88
+ "@blocklet/ui-react": "^2.13.47",
89
+ "@blocklet/uploader": "^0.1.93",
90
+ "@blocklet/uploader-server": "^0.1.99",
91
91
  "@emotion/cache": "^11.13.1",
92
92
  "@emotion/css": "^11.13.0",
93
93
  "@emotion/react": "^11.13.0",
@@ -205,8 +205,8 @@
205
205
  "yaml": "^2.5.0",
206
206
  "yjs": "^13.6.18",
207
207
  "zustand": "^4.5.5",
208
- "@blocklet/pages-kit": "^0.5.18",
209
- "@blocklet/pages-kit-block-studio": "^0.5.18"
208
+ "@blocklet/pages-kit": "^0.5.20",
209
+ "@blocklet/pages-kit-block-studio": "^0.5.20"
210
210
  },
211
211
  "devDependencies": {
212
212
  "@trivago/prettier-plugin-sort-imports": "^5.2.1",
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),F=require("./state-D4MG-uJB.js"),$=require("@arcblock/ux/lib/Locale/context"),ee=require("@arcblock/ux/lib/Toast"),te=require("@blocklet/pages-kit/utils/route"),P=require("@mui/icons-material"),J=require("@mui/lab"),s=require("@mui/material"),se=require("immer"),ne=require("lodash/difference"),l=require("react"),ie=require("react-use"),re=require("./home-BkGblT4S.js"),U=require("./array-BChVGKFh.js"),G=r=>r&&r.__esModule?r:{default:r},W=G(ee),H=G(ne);function oe(r){const[j,k]=l.useState(!1);return e.jsx(J.LoadingButton,{...r,loading:r.loading||j,onClick:u=>{var b;const p=(b=r.onClick)==null?void 0:b.call(r,u);p instanceof Promise&&(k(!0),p.finally(()=>{k(!1)}))}})}const ae=s.createSvgIcon(e.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("path",{d:"M7.75732 16.2426L16.2426 7.75736",stroke:"#4B5563",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M16.2426 16.2426L7.75732 7.75735",stroke:"#4B5563",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),"Close");function le(){const[r,j]=l.useState(),k=l.useMemo(()=>r?e.jsx(s.Dialog,{...r}):null,[r]),u=l.useCallback(()=>{j(void 0)},[]),p=l.useCallback(({title:b,content:d,cancelText:S="Cancel",okText:f="Ok",onOk:g,onClose:c,okIcon:O,okColor:w="primary",cancelColor:y="primary",DialogContentProps:A,form:M,...z})=>{j({...z,open:!0,children:e.jsxs("form",{onSubmit:R=>R.preventDefault(),children:[b&&e.jsxs(s.DialogTitle,{className:"between",zIndex:"appBar",bgcolor:"background.paper",sx:{borderBottom:"1px solid #E5E7EB"},children:[e.jsx(s.Box,{children:b}),e.jsx(s.IconButton,{size:"small",onClick:async()=>{u(),c==null||c()},children:e.jsx(ae,{})})]}),d&&e.jsx(s.DialogContent,{...A,sx:{mt:-3,...A==null?void 0:A.sx},children:e.jsx(s.Box,{pt:3,children:d})}),e.jsxs(s.DialogActions,{children:[e.jsx(s.Button,{variant:"outlined",color:y||"primary",onClick:c??u,children:S}),e.jsx(oe,{variant:"contained",color:w||"primary",startIcon:O,loadingPosition:O?"start":"center",onClick:async()=>{await(g==null?void 0:g()),u()},type:"submit",children:f})]})]}),onClose:c??u})},[u]);return{dialog:k,showDialog:p,closeDialog:u}}const ce=l.forwardRef(({mode:r,state:j},k)=>{const{t:u}=$.useLocaleContext(),[p,b]=l.useState(!1),{dialog:d,showDialog:S}=le(),f=F.useProjectId(),g=l.useCallback(O=>{let w=[];S({title:u("maker.publishToProduction"),content:e.jsxs(s.Box,{sx:{minWidth:300},children:[e.jsx(s.Alert,{color:"warning",icon:e.jsx(P.Warning,{}),children:u("maker.publishToProductionTip")}),e.jsx(s.Box,{maxHeight:"50vh",overflow:"auto",mt:2,children:e.jsx(de,{state:j,toMode:r,onChange:y=>w=y,defaultRouteIds:O})})]}),okText:u("maker.publish"),cancelText:u("common.cancel"),onOk:async()=>{if((w==null?void 0:w.length)===0){const y=u("maker.publishSelectPagesMessage");throw W.default.error(y),new Error(y)}localStorage.setItem(F.getProjectPageVersionKey(f??""),String(new Date().getTime())),b(!0);try{await U.publishPages({mode:r,routes:w}),W.default.success(u("maker.publishSuccessMessage"))}catch(y){throw W.default.error(y.message),y}finally{b(!1)}}})},[r,j,u,f,S]);l.useImperativeHandle(k,()=>({openPublishDialog:g}));const c=l.useCallback(()=>{g()},[g]);return e.jsxs(e.Fragment,{children:[e.jsx(J.LoadingButton,{color:"primary",variant:"contained",size:"small",sx:{mr:1},onClick:c,loading:p,disabled:p,children:u("maker.publishToProduction")}),d]})});function ue({routePathInfo:r,checked:j,onClick:k,route:u}){var d,S,f,g,c;const{t:p}=$.useLocaleContext(),b=!((d=r.routeMetaData)!=null&&d.publishedAt)||((S=r.routeMetaData)==null?void 0:S.updatedAt)&&new Date((f=r.routeMetaData)==null?void 0:f.updatedAt)>new Date((g=r.routeMetaData)==null?void 0:g.publishedAt);return e.jsx(s.ListItem,{sx:{pl:4,pr:3},disablePadding:!0,secondaryAction:e.jsxs(s.Box,{display:"flex",alignItems:"center",sx:{minWidth:"auto"},children:[b&&e.jsx(s.Box,{mr:.35,className:"visible",color:"warning.main",sx:{display:"flex",alignItems:"center"},title:p("maker.pages.needPublish"),children:e.jsx(s.Tooltip,{title:p("maker.pages.needPublish"),children:e.jsx(P.Sync,{fontSize:"small",sx:{fontSize:"16px"}})})}),(!((c=r.routeMetaData)!=null&&c.isPublic)||!u.isPublic)&&e.jsx(s.Box,{className:"visible",color:"warning.main",children:e.jsx(s.Tooltip,{title:p("maker.pages.notPublic"),children:e.jsx(P.VisibilityOff,{fontSize:"small",sx:{fontSize:"16px"}})})})]}),children:e.jsxs(s.ListItemButton,{onClick:k,dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:j,tabIndex:-1})}),e.jsx(s.ListItemText,{primary:r.path,primaryTypographyProps:{fontSize:"0.8rem",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",pr:1}})]})})}function de({state:r,toMode:j,onChange:k,defaultRouteIds:u}){const{t:p,locale:b}=$.useLocaleContext(),[d,S]=l.useState(!1),[f,g]=l.useState(()=>u?Object.fromEntries(u.filter(t=>!t.includes("-")).map(t=>[t,!0])):{}),[c,O]=l.useState({}),[w,y]=l.useState(()=>u?Object.fromEntries(u.filter(t=>t.includes("-")).map(t=>[t,!0])):{}),[A,M]=l.useState({}),{loading:z,error:R,value:x}=ie.useAsync(()=>U.getPages({mode:j}),[j]);if(R)throw R;const T=l.useMemo(()=>r.routeIds||[],[r]),I=l.useMemo(()=>(x==null?void 0:x.pageIds)||[],[x]),D=l.useMemo(()=>!T||!r.routes?[]:JSON.parse(JSON.stringify(T)).sort((o,i)=>{var h,m;const n=(h=r.routes)==null?void 0:h[o],a=(m=r.routes)==null?void 0:m[i];return n!=null&&n.publishedAt&&new Date(n.publishedAt).getTime()<new Date(n.updatedAt).getTime()?-1:a!=null&&a.publishedAt&&new Date(a.publishedAt).getTime()<new Date(a.updatedAt).getTime()?1:new Date((n==null?void 0:n.updatedAt)??"").getTime()-new Date((a==null?void 0:a.updatedAt)??"").getTime()}),[r,T]),q=l.useMemo(()=>{if(!D)return[];if(!c)return D;const t=[...D].filter(o=>!c[o]);return Object.values(c).forEach(o=>{o.forEach(i=>{t.push(`${i.originalRouteId}-${i.paramOptionIds.join("-")}`)})}),t},[D,c]),L=l.useMemo(()=>!x||!I||!q?[]:H.default(I,q),[q,x,I]),C=l.useMemo(()=>T?[...T].concat(L):L,[T,L]),_=l.useCallback(()=>{const t={};D==null||D.forEach(o=>{var n;const i=(n=r.routes)==null?void 0:n[o];if(i&&i.params&&i.params.length>0&&i.paramsOptions&&i.paramsOptions.length>0){const a=te.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});a.length>0&&(t[i.id]=a)}}),O(t)},[D,r.routes]);l.useEffect(()=>{_()},[_]),l.useEffect(()=>{M(t=>{const o={...t};return Object.keys(c).forEach(i=>{var n;c[i]&&((n=c[i])==null?void 0:n.length)>0&&o[i]===void 0&&(o[i]=!0)}),o})},[c]);const K=l.useRef(!0);l.useEffect(()=>{y(t=>{const o={...t};return Object.keys(c).length===0||(Object.keys(c).forEach(i=>{const n=c[i]||[],a=d||!!f[i];n.forEach(h=>{const m=`${i}-${h.paramOptionIds.join("-")}`;K.current?o[m]=a||t[m]||!1:o[m]=a})}),K.current=!1),o})},[f,c,d]);const Q=(t,o)=>{o.stopPropagation(),M(i=>{const n={...i};return n[t]=!n[t],n})},N=l.useCallback(t=>{g(o=>{const i=se.produce(o,n=>{d?(Object.assign(n,Object.fromEntries(C.map(a=>[a,!0]))),delete n[t]):n[t]?(delete n[t],L.includes(t)&&(T||[]).filter(a=>{var h,m;return((h=r.pages[a])==null?void 0:h.slug)===((m=x==null?void 0:x.pages[t])==null?void 0:m.slug)}).forEach(a=>{delete n[a]})):(n[t]=!0,T&&T.includes(t)&&L.filter(a=>{var h,m;return((h=x==null?void 0:x.pages[a])==null?void 0:h.slug)===((m=r.pages[t])==null?void 0:m.slug)}).forEach(a=>{n[a]=!0}))});return S(H.default(C,Object.keys(i)).length===0),i})},[d,C,L,r,x,T]),X=l.useCallback((t,o)=>{const i=`${t}-${o.paramOptionIds.join("-")}`;y(n=>{var m;const a={...n};a[i]=!a[i];const h=((m=c[t])==null?void 0:m.every(B=>a[`${t}-${B.paramOptionIds.join("-")}`]))??!1;return g(B=>{if(h&&!B[t])return{...B,[t]:!0};if(!h&&B[t]){const v={...B};return delete v[t],v}return B}),a})},[c]),Y=l.useCallback(()=>{S(t=>(t&&g({}),!t))},[]);return l.useEffect(()=>{const t=d?C:Object.keys(f),o=Object.entries(w).filter(([,n])=>n).map(([n])=>n).filter(n=>n!==void 0),i=Array.from(new Set([...t,...o]));k(d?null:i)},[d,f,w,C,k]),z?e.jsx(re.Loading,{sx:{my:4}}):e.jsxs(s.List,{disablePadding:!0,sx:{maxWidth:700},children:[e.jsx(s.ListItem,{sx:{position:"sticky",top:0,bgcolor:"background.paper",zIndex:1},disablePadding:!0,children:e.jsxs(s.ListItemButton,{onClick:Y,dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:d,tabIndex:-1})}),e.jsx(s.ListItemText,{primary:p("common.all")})]})}),D.map(t=>{var B,v;const o=(B=r.routes)==null?void 0:B[t];if(!o)return null;const i=!1,n=c&&c[t]&&((v=c[t])==null?void 0:v.length)>0,a=A[t]!==!1,h=c[t]||[],m=!o.publishedAt||o.updatedAt&&new Date(o.updatedAt).getTime()>new Date(o.publishedAt).getTime();return e.jsxs(s.Box,{children:[e.jsx(s.ListItem,{sx:{pr:4},disablePadding:!0,secondaryAction:e.jsxs(s.Box,{sx:{display:"flex",alignItems:"center"},children:[m&&e.jsx(s.Tooltip,{title:p("maker.pages.needPublish"),children:e.jsx(P.Sync,{fontSize:"small",sx:{color:"warning.main",fontSize:16,mr:.35}})}),!o.isPublic&&e.jsx(s.Tooltip,{title:p("maker.pages.notPublic"),children:e.jsx(P.VisibilityOff,{fontSize:"small",sx:{color:"warning.main",fontSize:16,mr:.35}})}),i,n&&e.jsx(s.Box,{onClick:E=>Q(t,E),sx:{display:"inline-flex",alignItems:"center",mr:.35,cursor:"pointer",color:"info.main"},children:a?e.jsx(P.KeyboardArrowDown,{fontSize:"small",sx:{fontSize:"18px"}}):e.jsx(P.KeyboardArrowRight,{fontSize:"small",sx:{fontSize:"18px"}})})]}),children:e.jsxs(s.ListItemButton,{onClick:()=>N(t),dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:d||!!f[t],tabIndex:-1})}),e.jsx(s.ListItemText,{primary:o.path,primaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"},secondaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"}})]})}),n&&e.jsx(s.Collapse,{in:a,children:e.jsx(s.Box,{children:h.map(E=>{const V=`${t}-${E.paramOptionIds.join("-")}`,Z=w[V]||!1;return e.jsx(ue,{routePathInfo:E,checked:d||Z,onClick:()=>X(t,E),route:o},V)})})})]},t)}),L.map(t=>{var i,n;const o=x==null?void 0:x.pages[t];return o?e.jsx(s.ListItem,{disablePadding:!0,secondaryAction:e.jsx(s.Chip,{color:"warning",label:"deleted",size:"small"}),children:e.jsxs(s.ListItemButton,{onClick:()=>N(t),dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:d||!!f[t],tabIndex:-1})}),e.jsx(s.ListItemText,{primary:o.slug,secondary:(n=(i=o.locales)==null?void 0:i[b])==null?void 0:n.title,primaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"},secondaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"}})]})},t):null})]})}exports.default=ce;
@@ -1,57 +0,0 @@
1
- "use strict";var Ot=Object.defineProperty;var At=(e,s,t)=>s in e?Ot(e,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[s]=t;var x=(e,s,t)=>At(e,typeof s!="symbol"?s+"":s,t);const Tt=require("@blocklet/pages-kit/builtin/utils"),ye=require("@blocklet/pages-kit/types"),ie=require("@blocklet/pages-kit/utils/property"),Q=require("@blocklet/quickjs"),Pt=require("@blocklet/sdk/lib/config"),Fe=require("lru-cache"),st=require("node-fetch"),M=require("ufo"),ee=require("crypto"),jt=require("@blocklet/logger"),_t=require("@blocklet/pages-kit/utils/builtin"),nt=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),qe=require("@blocklet/sdk/lib/component"),Ct=require("autoprefixer"),Dt=require("esbuild"),b=require("fs"),vt=require("postcss"),xt=require("tailwindcss"),kt=require("typescript"),W=require("@syncedstore/core"),Nt=require("yjs"),S=require("path"),Rt=require("@blocklet/pages-kit/utils/data-source"),be=require("@blocklet/pages-kit/utils/route"),Lt=require("lodash"),Mt=require("@reactivedata/reactive"),ke=require("glob"),Ut=require("lib0/decoding"),Ft=require("lib0/encoding"),qt=require("lodash/cloneDeep"),$t=require("lodash/debounce"),Bt=require("lodash/get"),Gt=require("lodash/isEmpty"),Ht=require("lodash/pick"),Vt=require("lodash/set"),Jt=require("lodash/union"),zt=require("nanoid"),Kt=require("p-limit"),Yt=require("stream/promises"),Wt=require("tar"),Qt=require("wait-on"),ne=require("y-protocols/awareness"),Ce=require("y-protocols/sync"),Xt=require("yaml"),Zt=require("lodash/isNil"),C=require("sequelize");require("sqlite3");require("@blocklet/pages-kit/types/state");const N=e=>e&&e.__esModule?e:{default:e};function pe(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 O=N(Pt),es=N(st),ts=N(jt),ss=N(Ct),ns=pe(Dt),os=N(vt),as=N(xt),L=N(kt),B=pe(Nt),rs=N(S),De=pe(Ut),k=pe(Ft),is=N(qt),ot=N($t),$e=N(Bt),cs=N(Gt),ls=N(Ht),Ye=N(Vt),ps=N(Jt),ds=N(Kt),us=N(Qt),X=pe(Xt),fs=N(Zt);O.default.env.mode;O.default.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY;O.default.env.OPENAI_BASE_URL||process.env.OPENAI_BASE_URL;O.default.env.TRANSLATE_ADDITIONAL_PROMPT||process.env.TRANSLATE_ADDITIONAL_PROMPT;O.default.env.PAGE_CONTENT_ADDITIONAL_PROMPT||process.env.PAGE_CONTENT_ADDITIONAL_PROMPT;const ms="image-bin";O.default.env.INIT_TEMPLATE_PATH;const gs=process.env.DATABASE_URL||rs.default.join(O.default.env.dataDir,"db/pages-kit.db"),We=O.default,hs=()=>O.default.env.tenantMode==="multiple",ys=()=>{var e;return(fs.default(We.env.preferences.multiTenantAllProjectAccessPassports)?[]:(e=We.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:e.split(","))||[]},I=ts.default("pages-kit"),Ss=C.DataTypes.sqlite.DATE.parse;C.DataTypes.sqlite.DATE.parse=(e,s)=>typeof e=="number"?new Date(e):Ss(e,s);const de=new C.Sequelize({dialect:"sqlite",storage:gs,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});de.query("pragma journal_mode = WAL;");de.query("pragma synchronous = normal;");de.query("pragma journal_size_limit = 67108864;");class Te extends C.Model{}Te.init({id:{type:C.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:C.DataTypes.UUIDV4},projectId:{type:C.DataTypes.UUID,allowNull:!1},componentId:{type:C.DataTypes.STRING,allowNull:!1}},{sequelize:de,tableName:"ProjectComponents",timestamps:!1});class J extends C.Model{static async getProjectByIdOrSlug(s){return J.findOne({where:{[C.Op.or]:[{id:s},{slug:s}]}})}}J.init({id:{type:C.DataTypes.UUID,defaultValue:C.DataTypes.UUIDV4,primaryKey:!0},name:{type:C.DataTypes.STRING,allowNull:!1},description:C.DataTypes.TEXT,createdAt:C.DataTypes.DATE,updatedAt:C.DataTypes.DATE,createdBy:{type:C.DataTypes.STRING,allowNull:!1},updatedBy:{type:C.DataTypes.STRING,allowNull:!1},slug:C.DataTypes.STRING,icon:C.DataTypes.STRING,pinnedAt:C.DataTypes.DATE,useAllResources:C.DataTypes.BOOLEAN,npmSecret:C.DataTypes.STRING,relatedBlocklets:{type:C.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(e){this.setDataValue("relatedBlocklets",JSON.stringify(e||{}))}}},{sequelize:de,paranoid:!0});J.hasMany(Te,{foreignKey:"projectId",as:"components"});const ws=async(e,{componentId:s})=>{const t=`@tailwind components;
2
- @tailwind utilities;
3
- `,n=`.CustomComponent_${s}`;return(await os.default([as.default({content:[{raw:e,extension:"tsx"}]}),ss.default({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),a=>{a.walkRules(d=>{d.selectors=d.selectors.map(l=>l.replace(/\.(.+)/g,`${n}.$1,${n} .$1`))})}]).process(t)).css},bs=async(e,{componentId:s})=>{const t=await ws(e,{componentId:s});return`export const __PagesKit_CSS__ = ${JSON.stringify(t)};
4
-
5
- ${e}
6
- `},Qe=Q.memoize(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:[nt.createBuiltinModuleTransformer(L.default)]}}).outputText;if(s.tailwind&&(t=await bs(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:Is(s.moduleName,n)},{keyGenerator:(e,s)=>{const t=ee.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}}),Es=async(e,s)=>{var d,l;const n=(l=(d=(await ns.build({entryPoints:["index.tsx"],external:Object.keys(_t.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(u){let c=null;u.onResolve({filter:/.*/},p=>p.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:p.path==="./component"?{path:"component.tsx",namespace:"vfs"}:null),u.onLoad({filter:/.*/,namespace:"vfs"},async p=>{var g;if(p.path==="index.tsx")return{contents:`export { ${s} } from './component'`,loader:"tsx"};if(p.path==="component.tsx")return{contents:e,loader:"tsx"};if(nt.isRelativeModule(p.path)){const y=p.path.split("/").pop();if(c||(c=await Pe({ensureLoaded:!1})),(g=c==null?void 0:c.chunks)!=null&&g[y])try{const r=b.readFileSync(c.chunks[y],"utf-8");return I.info("get chunk from local file system",y),{contents:r,loader:"tsx"}}catch{}}return null})}}]})).outputFiles)==null?void 0:d[0])==null?void 0:l.contents;if(!n)throw new Error("Failed to build server code");const o=Buffer.from(n).toString();return L.default.transpileModule(o,{compilerOptions:{module:L.default.ModuleKind.ESNext,target:L.default.ScriptTarget.ES2020}}).outputText},at=Q.memoize(async(e,s)=>{const t=await Es(e,s);return new RegExp(`export\\s+\\{\\s+${s}\\s+\\}`,"m").test(t)?t:void 0},{keyGenerator:(e,s)=>{const t=ee.createHash("md5").update(e).digest("hex");return JSON.stringify(["extractExportValueSchema",t,s])},lruOptions:{max:100,ttl:1e3*60*60}}),Is=(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 Fe.LRUCache({max:100}),rt=60*60,Ne=60;function it(e){I.info("clear preload components cache",{cacheKey:e}),ae.delete(e)}function ct(e){for(const s of ae.keys())s.includes(e)&&(I.info("clear preload components cache",{cacheKey:s}),it(s))}function lt({mode:e,instanceId:s,componentId:t,locale:n}){return["getPreloadComponents",e,s,t,n].join("-")}async function Os({mode:e,req:s,state:t,locale:n,instances:o,module:a}){const{supportedLocales:d,config:{defaultLocale:l}}=t;if(!l)return null;const u=(await Promise.all(o.map(async r=>{try{const i=lt({mode:e,instanceId:r.id,componentId:r.componentId,locale:n});if(e!=="draft"&&r.useCache&&ae.has(i))return I.info(`get preload component from cache: ${i}`),ae.get(i);const f=ce({state:t,componentId:r.componentId});if(!f)return null;const E=await pt({req:s,state:t,componentId:f.id,locale:n,defaultLocale:l,properties:r.properties});if(!E)return null;const v={instanceId:r.id,preload:E};if(e!=="draft"&&r.useCache){let T=rt;r.cacheDuration&&(T=r.cacheDuration),I.info(`set preload component to cache(${T}s): ${i}`),ae.set(i,v,{ttl:T*1e3})}return v}catch(i){return I.error("get preload component error",{instanceId:r.id,componentId:r.componentId},{error:i}),null}}))).filter(r=>!!r),c=Object.values(u.reduce((r,i)=>({...r,...i.preload.components}),{}));async function p(){const r=await Promise.all(c.map(async i=>{const f=ie.componentUMDName({componentId:i.component.id}),E=a===ye.PreloadComponentScriptModule.ESM?{module:a,script:await Qe(i.script,{componentId:i.component.id,module:a,tailwind:e!=="draft"})}:{module:a,script:await Qe(i.script,{componentId:i.component.id,module:a,moduleName:f,tailwind:e!=="draft"}),moduleName:f};return[i.component.id,{component:i.component,script:E}]}));return Object.fromEntries(r)}const g=await p();return{config:{defaultLocale:l,supportedLocales:d},components:g,instances:u.map(r=>({id:r.instanceId,componentId:r.preload.component.id,locales:{[r.preload.locale]:{props:r.preload.props}}}))}}async function pt({req:e,state:s,componentId:t,locale:n,defaultLocale:o,properties:a}){const{supportedLocales:d}=s,l=ce({state:s,componentId:t});if(!l)return null;const u=d.some(p=>p.locale===n)?n:o;if(!u)return null;const c=await dt({req:e,state:s,componentId:t,locale:u,defaultLocale:o,properties:a});return c?{component:l,...c}:null}const As=20;async function dt({req:e,depth:s=0,state:t,componentId:n,locale:o,defaultLocale:a,properties:d}){if(s>As)throw new RangeError("max component depth exceeded");const l=Ts({state:t,componentId:n,properties:d,locale:o});if(!l)return null;const{props:u}=l,c={locale:o||a,components:{[l.component.id]:{component:l.component,script:l.script}},props:{...u}};try{const p=await js({...l,req:e});p!=null&&p.props&&Object.assign(c.props,p.props)}catch(p){I.error("preload data at server side error",{componentId:n,name:l.component.name},{error:p})}return await Promise.all(Object.entries(u).map(async([p,g])=>{if((g==null?void 0:g.type)===ie.RenderNestedComponent){const y=await dt({req:e,depth:s+1,state:t,componentId:g.componentId,locale:o,defaultLocale:a,properties:g.properties});y&&(Object.assign(c.components,y.components),Object.assign(c.props,{[p]:{type:ie.RenderNestedComponent,componentId:g.componentId,props:y.props}}))}})),c}function Ts({state:e,componentId:s,locale:t,properties:n}){const o=ce({state:e,componentId:s});if(!o)return null;const a=ie.mergeComponent({componentId:s,getComponent:d=>ce({state:e,componentId:d}),locale:t,defaultLocale:e.config.defaultLocale,properties:n});return a?{component:o,script:a.script,props:{locale:t,...a.props}}:null}function ce({state:e,componentId:s}){var t,n,o;return((t=e.components[s])==null?void 0:t.data)??((o=(n=e.resources.components)==null?void 0:n[s])==null?void 0:o.component)}function Ps({state:e,name:s}){var n,o;const t=s.toLowerCase();return((n=Object.values(e.components).find(a=>{var d;return((d=a.data.name)==null?void 0:d.toLowerCase())===t}))==null?void 0:n.data)??((o=e.resources.components&&Object.values(e.resources.components).find(a=>{var d;return((d=a.component.name)==null?void 0:d.toLowerCase())===t}))==null?void 0:o.component)}async function js({component:e,script:s,props:t,req:n}){if(!(s!=null&&s.includes("getServerSideProps")))return null;const o=await at(s,"getServerSideProps");if(!o)return null;const a=new Promise(l=>{setTimeout(()=>{l({})},Ne*1e3)});return await Promise.race([a,Q.Sandbox.callFunction({code:`${o}
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:l=>{if(l==="@blocklet/pages-kit/builtin/utils")return`const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
50
- export { joinURL, withQuery, getQuery, getComponentMountPoint }
51
- `;if(l==="@blocklet/pages-kit/builtin/dayjs")return Q.BuiltinModules.dayjs},global:{console:{log:(...l)=>{I.info(...l)},warn:(...l)=>{I.warn(...l)},error:(...l)=>{I.error(...l)}},getComponentMountPoint:Tt.getComponentMountPoint,joinURL:M.joinURL,withQuery:M.withQuery,getQuery:M.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:M.joinURL(M.withHttps(n.hostname),n.originalUrl)},fetch:(l,{...u}={})=>{const c=typeof l=="string"&&l.startsWith("/")?M.joinURL(O.default.env.appUrl,l):l;if(typeof c=="string"&&M.parseURL(c).host===M.parseURL(O.default.env.appUrl).host){const p=n.get("cookie");if(p){const g=new st.Headers(u.headers);g.set("cookie",p),u.headers=g}}return es.default(c,{...u,timeout:Ne*1e3}).then(p=>({ok:p.ok,status:p.status,statusText:p.statusText,headers:Object.fromEntries(p.headers.entries()),json:()=>p.json()}))},props:t}]})])}const ut=Q.memoize(async(e,s,t)=>{if(!(e!=null&&e.includes(s)))return null;const n=await at(e,s);if(n)try{return await Q.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(o){return I.error(`获取 ${s} 失败`,{componentId:t,error:o}),null}return null},{keyGenerator:(e,s,t)=>{const n=ee.createHash("md5").update(e).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",n,s,t])},lruOptions:{max:100,ttl:1e3*60*60}}),_s="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",Re="page",Le="trigger-reload-project-resource",Be=_s,Cs="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 ft(){return b.mkdtempSync(S.join(O.default.env.dataDir,"tmp-"))}function Ie(e,s,t=[]){return Array.isArray(e)?e.flatMap((n,o)=>Ie(n,s,[...t,o])):typeof e=="object"?e===null?[]:Object.entries(e).flatMap(([n,o])=>Ie(o,s,[...t,n])):s(e)?[t]:[]}function U(e){return e.filter(s=>s!=null)}function Ds(e){e.pages&&Object.keys(e.pages).forEach(t=>{const n=W.getYjsValue(e.pages[t]);n&&n instanceof B.Map&&Ee(n)});const s=W.getYjsValue(e.pages);s&&s instanceof B.Map&&s.observe(t=>{t.changes.keys.forEach((n,o)=>{if(n.action==="add"){const a=W.getYjsValue(e.pages[o]);a&&a instanceof B.Map&&Ee(a)}})})}function vs(e){e.routes&&Object.keys(e.routes).forEach(t=>{var o;const n=W.getYjsValue((o=e.routes)==null?void 0:o[t]);n&&n instanceof B.Map&&Ee(n)});const s=W.getYjsValue(e.routes);s&&s instanceof B.Map&&s.observe(t=>{t.changes.keys.forEach((n,o)=>{var a;if(n.action==="add"){const d=W.getYjsValue((a=e.routes)==null?void 0:a[o]);d&&d instanceof B.Map&&Ee(d)}})})}function xs(e,s){var t;for(const n of s||Object.keys(e.routes||{})){let o=n,a=[];if(n.includes("-")){const[d,...l]=n.split("-");o=d,a=l||[]}if(((t=e.routes)==null?void 0:t[o])!==void 0){e.routes[o].publishedAt=new Date().toISOString();const d=e.routes[o];if(!d||!d.params||d.params.length===0)continue;if(n.includes("-")&&a.length>0){const l=be.getRouteMetaDataByOptionIds(a,d);l&&(l.publishedAt=new Date().toISOString())}if(!s){const l=be.generateParamCombinations({basePath:d.path,params:d.params,routeId:d.id,paramsOptions:d.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const u of l)u.routeMetaData??(u.routeMetaData={}),u.routeMetaData.publishedAt=new Date().toISOString()}}}}function ve({page:e,route:s,state:t,routeId:n,routePathInfo:o}){var d,l,u,c,p,g,y,r,i;I.info(`Executing datasource data assembly, routeId: ${n}, routePathInfo: ${JSON.stringify(o)}`);const a={...Lt.cloneDeep(e),id:n,slug:(o==null?void 0:o.path)??s.path,createdAt:s.createdAt,updatedAt:((d=o==null?void 0:o.routeMetaData)==null?void 0:d.updatedAt)??s.updatedAt,publishedAt:((l=o==null?void 0:o.routeMetaData)==null?void 0:l.publishedAt)??s.publishedAt,isPublic:(((u=o==null?void 0:o.routeMetaData)==null?void 0:u.isPublic)??s.isPublic)&&s.isPublic};for(const f of t.supportedLocales){if(s.dataSource){let E=s.id;o&&(E=o.paramOptionIds.join("-"));const v=((g=(p=(c=s.dataSource.pathDataMappings)==null?void 0:c[E])==null?void 0:p.dataCache)==null?void 0:g[f.locale])??((i=(r=(y=s.dataSource.pathDataMappings)==null?void 0:y[E])==null?void 0:r.dataCache)==null?void 0:i[t.config.defaultLocale||"en"]);if(!v)continue;Rt.setPageDataSource(a,t,f.locale,v)}o&&o.routeMetaData&&(o.routeMetaData.publishedAt=new Date().toISOString())}return a}const{uploadToMediaKit:ks}=require("@blocklet/uploader-server"),Se=zt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),Ge=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,re=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Xe=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Ns=1e4,Rs=3e4,ge=0,xe=1,Ls=0,Ms=1,Me=O.default,oe=S.join(process.env.BLOCKLET_DATA_DIR,"site-state"),Us=["production","draft"],Fs=["production"];function Oe(e){return(e==null?void 0:e.replace(/\//g,"|"))||""}function qs(){var t;const e=Me.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:o},a)=>{const d=t.concat(n,o);if(a!==null){const c=this.conns.get(a);c&&(t.forEach(p=>{c.add(p)}),o.forEach(p=>{c.delete(p)}))}const l=k.createEncoder();k.writeVarUint(l,xe),k.writeVarUint8Array(l,ne.encodeAwarenessUpdate(this.awareness,d));const u=k.toUint8Array(l);this.conns.forEach((c,p)=>this.send(p,u))});x(this,"updateHandler",t=>{const n=k.createEncoder();k.writeVarUint(n,ge),Ce.writeUpdate(n,t);const o=k.toUint8Array(n);this.conns.forEach((a,d)=>this.send(d,o))});x(this,"ensureDataStructure",()=>{var u;const{supportedLocales:t,pages:n,pageIds:o,config:a,routes:d,routeIds:l}=this.syncedStore;{const c=new Set(Object.keys(n));let p=0;for(;p<o.length;){const g=o[p];c.has(g)?(c.delete(g),p++):o.splice(p,1)}}{const c=new Set(Object.keys(d));let p=0;for(;p<l.length;){const g=l[p];c.has(g)?(c.delete(g),p++):l.splice(p,1)}}t.splice(0,t.length),t.push(...Me.env.languages.map(c=>({locale:c.code,name:c.name}))),a.defaultLocale=(u=t[0])==null?void 0:u.locale;{let c=0;const p=new Set;for(;c<t.length;){const{locale:g}=t[c];p.has(g)?t.splice(c,1):(c++,p.add(g))}}});x(this,"send",(t,n)=>{t.readyState!==Ls&&t.readyState!==Ms&&this.closeConn(t);try{t.send(n,o=>{o&&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&&ne.removeAwarenessStates(this.awareness,Array.from(n),null)}t.close()});x(this,"autoSave",ot.default(()=>{b.mkdirSync(S.dirname(this.draftYjsFilePath),{recursive:!0}),b.writeFileSync(this.draftYjsFilePath,B.encodeStateAsUpdate(this))},Ns));x(this,"save",({flush:t=!1}={})=>{this.autoSave(),t&&this.autoSave.flush()});x(this,"publish",async({mode:t,routes:n})=>{const o=await this.getState("draft"),a=await this.getState("production");await Ue(o,a,{routes:n,mergeMode:"replace",deleteRoutes:!0,publishMode:t}),a.config.publishedAt=new Date().getTime(),xs(this.syncedStore,n),await this.setState(t,a)});x(this,"mergeState",async(t,n)=>{var l,u,c;const o=JSON.parse(JSON.stringify(n));(l=t.config).fontFamily??(l.fontFamily={});const a=(u=o.config)==null?void 0:u.fontFamily,d=(c=t.config)==null?void 0:c.fontFamily;t.config.fontFamily.title=(a==null?void 0:a.title)||(d==null?void 0:d.title),t.config.fontFamily.description=(a==null?void 0:a.description)||(d==null?void 0:d.description),await new Promise((p,g)=>{this.transact(async()=>{try{const y=await Ue(t,n);p(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",a=>this.messageListener(t,new Uint8Array(a)));let n=!0;const o=setInterval(()=>{if(!n)this.conns.has(t)&&this.closeConn(t),clearInterval(o);else if(this.conns.has(t)){n=!1;try{t.ping()}catch{this.closeConn(t),clearInterval(o)}}},Rs);t.on("close",()=>{this.closeConn(t),clearInterval(o)}),t.on("pong",()=>{n=!0});{const a=k.createEncoder();k.writeVarUint(a,ge),Ce.writeSyncStep1(a,this),this.send(t,k.toUint8Array(a));const d=this.awareness.getStates();if(d.size>0){const l=k.createEncoder();k.writeVarUint(l,xe),k.writeVarUint8Array(l,ne.encodeAwarenessUpdate(this.awareness,Array.from(d.keys()))),this.send(t,k.toUint8Array(l))}}});x(this,"messageListener",(t,n)=>{try{const o=k.createEncoder(),a=De.createDecoder(n),d=De.readVarUint(a);switch(d){case ge:k.writeVarUint(o,ge),Ce.readSyncMessage(a,o,this,null),k.length(o)>1&&(this.ensureDataStructure(),this.send(t,k.toUint8Array(o)));break;case xe:{ne.applyAwarenessUpdate(this.awareness,De.readVarUint8Array(a),t);break}default:I.warn(`Unsupported messageType ${d}`)}}catch(o){I.error(o)}this.save()});this.options=t,b.existsSync(this.draftYjsFilePath)&&B.applyUpdate(this,b.readFileSync(this.draftYjsFilePath)),this.syncedStore=Mt.reactive(W.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new ne.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=S.join(oe,t),o=S.join(oe,`@del-${t}`);b.renameSync(n,o)}catch(n){I.error("Failed to safe delete project state dir:",n)}}static get projectIds(){return ke.globSync("*/",{cwd:oe,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:S.join(oe,t)}),this.sharedInstances.set(t,n),n)}destroy(){this.conns.forEach((t,n)=>this.closeConn(n)),this.awareness.destroy(),super.destroy()}initObserver(){Ds(this.syncedStore),vs(this.syncedStore)}get draftYjsFilePath(){return S.join(this.options.path,"draft.yjs")}async getState(t){var n,o,a,d;if(t==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[t]&&(this.states[t]=await He(this.getPublishDir(t),{includeResources:!0})??qs(),!((o=(n=this.states[t])==null?void 0:n.config)!=null&&o.defaultLocale))){(a=this.states[t]).config??(a.config={});const l=Me.env.languages.map(u=>({locale:u.code,name:u.name}));this.states[t].config.defaultLocale=(d=l[0])==null?void 0:d.locale}return{...this.states[t],resources:await Pe().then(async l=>{var r,i,f,E;const{pages:u,components:c}=ls.default(l,"pages","components");let p=c;const g=S.basename(this.options.path),y=await J.findByPk(g);if(y!=null&&y.useAllResources)p=c;else{const T=(await Te.findAll({where:{projectId:g}})).map(F=>F.componentId);p=Object.fromEntries(Object.entries(c||{}).filter(([F])=>T.includes(F)))}return Object.keys(((i=(r=this.states[t])==null?void 0:r.resources)==null?void 0:i.components)||{}).length>0&&(p={...p,...(E=(f=this.states[t])==null?void 0:f.resources)==null?void 0:E.components}),{pages:u,components:p}}).catch(()=>({}))}}async setState(t,n){const o=await yt(n,{exportAssets:!1,includeResources:!0}),a=this.getPublishDir(t);b.mkdirSync(S.dirname(a),{recursive:!0}),b.rmSync(a,{force:!0,recursive:!0}),b.renameSync(o,a),this.states[t]=n}getPublishDir(t){return S.join(this.options.path,t)}static async pageUrlMap(t){var a,d;const{projectIds:n}=this,o={};for(const l of n){const u=await J.findByPk(l);if(!u)continue;const c=await V.shared(l).getState(t),p=u.slug||l,g=ps.default(O.default.env.languages.map(r=>r.code),c.supportedLocales.map(r=>r.locale)),y=(r,i)=>{p&&(o[M.joinURL("/",p,r)]={...i,shouldRedirect:!0,mainPage:!0}),o[M.joinURL("/",l,r)]={...i,shouldRedirect:!0,mainPage:!0};for(const f of g){const E={...i,locale:f};o[M.joinURL("/",f,l,r)]=E,p&&(o[M.joinURL("/",f,p,r)]=E)}};if(t==="draft")for(const r of c.routeIds||[]){const i=(a=c==null?void 0:c.routes)==null?void 0:a[r];if(!i)continue;if(i.params&&i.params.length>0){const v=be.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const T of v){const R=T.path,F={projectId:l,projectSlug:p,pageSlug:R,pageId:i.displayTemplateId||"",routeId:r,defaultLocale:g==null?void 0:g[0],locales:g,publishedAt:c.config.publishedAt,isPublic:i.isPublic&&((d=T==null?void 0:T.routeMetaData)==null?void 0:d.isPublic)};y(R,F)}}const f=i.path,E={projectId:l,projectSlug:p,pageSlug:f,pageId:i.displayTemplateId||"",routeId:r,defaultLocale:g==null?void 0:g[0],locales:g,publishedAt:c.config.publishedAt,isPublic:i.isPublic};y(f,E)}for(const r of c.pageIds){const i=c.pages[r];if(!i||t==="production"&&!i.isPublic)continue;const f=i.slug,E=u.slug||l,v={projectId:l,projectSlug:E,pageSlug:f,pageId:r,defaultLocale:g==null?void 0:g[0],locales:g,publishedAt:c.config.publishedAt,isPublic:i.isPublic,templateConfig:i.templateConfig};y(f,v)}}return o}getDocumentSize(){return B.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const t=[];for(const[n,o]of this.sharedInstances.entries()){const a=o.getDocumentSize();t.push({projectId:n,sizeInBytes:a,sizeInMB:`${(a/(1024*1024)).toFixed(2)} MB`,activeConnections:o.conns.size})}return t}};x(V,"INSTANCE_TTL",30*60*1e3),x(V,"sharedInstances",new Fe.LRUCache({max:100,ttl:V.INSTANCE_TTL,dispose:t=>{t.destroy()}}));let le=V;async function $s(e,s,t){if(!e||!b.existsSync(e)||!b.lstatSync(e).isFile())return null;let n=t[e];return n||(n=(async()=>{var o;try{const a=(o=await ks({filePath:e,fileName:s}))==null?void 0:o.data;return a==null?void 0:a.filename}catch(a){return I.error(`Failed to upload asset ${e}:`,a),null}})(),t[e]=n),n}const mt=async(e,s)=>{const t=S.basename(e),n=await qe.call({name:Be,path:M.joinURL("/uploads",t),responseType:"stream",method:"GET"});if(n.status>=200&&n.status<400){const o=b.createWriteStream(s);await Yt.pipeline(n.data,o)}else throw new Error(`download asset failed ${n.status}`)},gt=async(e,s)=>{await Promise.all(e.map(async t=>{try{await mt(t,S.join(s,S.basename(t)))}catch(n){I.error(`Failed to export assets: ${t}, ${n}`)}}))};function ht(e){return Ge.test(e)?[e]:re.test(e)?(Xe.lastIndex=0,Array.from(e.matchAll(Xe)).map(t=>t[1]).filter(t=>!!t)):[]}async function he(e,s,t){const{getFilename:n,exportAssets:o}=t,a=S.join(s,n(e));if(b.mkdirSync(S.dirname(a),{recursive:!0}),b.writeFileSync(a,X.stringify(e)),o){const l=Ie(e,u=>typeof u=="string"&&(Ge.test(u)||re.test(u))).map(u=>{const c=$e.default(e,u);return ht(c)}).flat().filter(Boolean);await gt(l,S.dirname(a))}}const Ze=new Fe.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function et(e,s,t){var l;const n=Ie(e,u=>typeof u=="string"&&(Ge.test(u)||re.test(u))),o=ds.default(2),a=n.map(u=>o(async()=>{try{const c=$e.default(e,u),p=ht(c);for(const g of p){const y=S.basename(g),r=t.getFilePath(g,u),i=r?`${r}:${y}`:y,f=Ze.get(i);if(f){re.test(c)||Ye.default(e,u,f);return}const E=await $s(r,y,s);E&&(re.test(c)||Ye.default(e,u,E),Ze.set(i,E))}}catch(c){I.error(`Failed to process upload for path ${u.join(".")}:`,c.message||c.reason)}})),d=await Promise.allSettled(a);(l=t.onFinish)==null||l.call(t,d)}async function yt(e,{exportAssets:s,pageIds:t="all",componentIds:n="all",rawConfig:o,includeResources:a=!1,routeIds:d="all"}={}){var te,w,m,A,j,z,_,q,K,fe,se,me;const l=t==="all"?e.pageIds:t,u=ie.getComponentDependencies({state:e,pageIds:l,componentIds:n==="all"?Object.keys(e.components):n}),c=d==="all"?e.routeIds:d,p=(h,P)=>{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[P])??{}}},g=(h,P)=>{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[P])??{},sections:U(h.sectionIds.map(H=>{const G=h.sections[H];return G&&p(G,P)}))}},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}),r=U(c.map(h=>{const P=e.routes[h];return P&&y(P)})),i=U(e.supportedLocales.map(h=>h.locale).flatMap(h=>l.map(P=>{const D=e.pages[P];return D&&{locale:h,slug:D.slug,page:g(D,h)}}))),f=ft(),E=S.join(f,"pages");b.mkdirSync(E,{recursive:!0});const v=S.join(f,"components");b.mkdirSync(v,{recursive:!0});const T=S.join(f,"routes");b.mkdirSync(T,{recursive:!0});for(const{locale:h,slug:P,page:D}of i)await he(D,E,{getFilename:()=>`${Oe(P)||"index"}.${h}.yml`,exportAssets:s});for(const h of r)await he(h,T,{getFilename:()=>`${Oe(h.path)||"index"}.yml`,exportAssets:s});for(const h of u){const P=(te=e.components[h])==null?void 0:te.data;P&&await he(P,v,{getFilename:D=>`${D.name||"unnamed"}.${D.id}.yml`,exportAssets:s})}const R=S.join(f,".blocklet/pages/pages.config.yml");b.mkdirSync(S.dirname(R),{recursive:!0});const F={pages:U(l.map(h=>{const P=e.pages[h];return P&&{id:h,slug:P.slug}})),routes:U(c.map(h=>{const P=e.routes[h];return P&&{id:h,path:P.path}})),components:U(u.map(h=>{var D;const P=(D=e.components[h])==null?void 0:D.data;return P&&{id:h,name:P.name}})),...a?{resources:{components:U(Object.keys(((w=e.resources)==null?void 0:w.components)||{}).filter(h=>u.includes(h)).map(h=>{var P,D,H,G;return{id:h,name:(G=(H=(D=(P=e.resources)==null?void 0:P.components)==null?void 0:D[h])==null?void 0:H.component)==null?void 0:G.name}}))}}:{},supportedLocales:e.supportedLocales,config:e.config};b.writeFileSync(R,X.stringify(F));const ue=S.join(f,"config.source.json");if(o&&b.writeFileSync(ue,JSON.stringify(o)),a){const h=S.join(f,"resources"),P=S.join(h,"components");b.mkdirSync(P,{recursive:!0});for(const G of Object.keys(((m=e==null?void 0:e.resources)==null?void 0:m.components)??{}).filter($=>u.includes($))){const $=(z=(j=(A=e.resources)==null?void 0:A.components)==null?void 0:j[G])==null?void 0:z.component;$&&await he($,P,{getFilename:Y=>`${Y.name||"unnamed"}.${Y.id}.yml`,exportAssets:s})}const D=S.join(f,"chunks");b.mkdirSync(D,{recursive:!0});const{chunks:H}=await Pe();for(const G of Object.keys(((_=e==null?void 0:e.resources)==null?void 0:_.components)??{}).filter($=>u.includes($))){const $=(fe=(K=(q=e.resources)==null?void 0:q.components)==null?void 0:K[G])==null?void 0:fe.component;if($&&((se=$.renderer)==null?void 0:se.type)==="react-component"){const Y=((me=$.renderer)==null?void 0:me.chunks)??[];if((Y==null?void 0:Y.length)>0)for(const je of Y){const Ke=S.join(D,je),_e=H==null?void 0:H[je];try{_e&&b.existsSync(_e)&&!b.existsSync(Ke)&&b.copyFileSync(_e,Ke)}catch(It){I.error(`copy chunk ${je} error`,It.message)}}}}}return f}async function He(e,{importAssets:s,includeResources:t}={}){var a,d,l,u;if(!b.existsSync(e))return null;let n,o=!1;try{b.lstatSync(e).isDirectory()?n=e:/\.(tgz|gz|tar)$/.test(e)&&(o=!0,n=ft(),await Wt.x({file:e,C:n}));const c=ke.globSync("**/.blocklet/pages/pages.config.yml",{cwd:n,absolute:!0}).at(0),p=c&&S.join(S.dirname(c),"../../pages"),g=c&&S.join(S.dirname(c),"../../components"),y=c&&S.join(S.dirname(c),"../../chunks"),r=c&&S.join(S.dirname(c),"../../routes");if(!c)return null;const i=X.parse(b.readFileSync(c).toString()),f=(w,m,A)=>{let j=S.join(w,`${m}${A?`.${A}`:""}.yml`);return(!b.existsSync(j)||!b.lstatSync(j).isFile())&&(j=S.join(w,m,`index${A?`.${A}`:""}.yml`),!b.existsSync(j)||!b.lstatSync(j))?null:X.parse(b.readFileSync(j).toString())},E=(w,m)=>{try{const A=ke.globSync(`*.${m}.yml`,{cwd:w,absolute:!0})[0];return A?X.parse(b.readFileSync(A).toString()):null}catch(A){I.error("parse component error",A)}return null},v=(w,m)=>{let A=S.join(w,`${m}.yml`);return(!b.existsSync(A)||!b.lstatSync(A).isFile())&&(A=S.join(w,m,"index.yml"),!b.existsSync(A)||!b.lstatSync(A))?null:X.parse(b.readFileSync(A).toString())},T=U(i.pages.map(({slug:w})=>{var z;const m=U(i.supportedLocales.map(({locale:_})=>{const q=p?f(p,Oe(w),_):void 0;if(q)return{locale:_,page:q};const K=p?f(p,w,_):void 0;return K&&{locale:_,page:K}})),A=(z=m[0])==null?void 0:z.page;if(!A)return null;const j=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 se=fe.sections.find(me=>me.id===q);return se&&[K,se.properties]})))}});return{id:A.id||Se(),createdAt:A.createdAt,updatedAt:A.updatedAt,publishedAt:A.publishedAt,isPublic:A.isPublic??!0,templateConfig:A.templateConfig,slug:w,sections:Object.fromEntries(j.map(_=>[_.id,_])),sectionIds:j.map(_=>_.id),locales:Object.fromEntries(m.map(({locale:_,page:q})=>[_,q.meta]))}})),R=U(((a=i==null?void 0:i.routes)==null?void 0:a.map(({path:w})=>{const m=r?v(r,Oe(w)):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=i.components)==null?void 0:d.map(({id:w})=>E(g,w)))??[]):[];if(s){const w=(...m)=>{I.info(`[${o?S.basename(e):S.basename(S.join(e,"../../../../"))}] importAssets:`,...m)};try{w("wait image-bin api ready"),await us.default({resources:[`${qe.getComponentWebEndpoint(ms)}/api/sdk/uploads`],validateStatus:j=>j>=200&&j<=500}),w("image-bin api is ready");const m={},A={};w("start to upload assets"),await Promise.allSettled([et(F,m,{getFilePath:j=>g&&S.join(g,j),onFinish:j=>{w(`upload ${j.length} component assets`)}}),et(T,A,{getFilePath:(j,z)=>{const _=$e.default(T,z.slice(0,1));return p&&S.join(p,S.dirname(_.slug),j)},onFinish:j=>{w(`upload ${j.length} page assets`)}})]),w("upload assets done"),global.gc&&global.gc()}catch(m){w("Error during asset import:",m)}}const ue={};if(t){const w=c&&S.join(S.dirname(c),"../../resources/components"),m=U(((u=(l=i.resources)==null?void 0:l.components)==null?void 0:u.map(({id:A})=>E(w,A)))??[]);m.length>0&&(ue.components=Object.fromEntries(m.map((A,j)=>[A.id,{index:j,component:A}])))}const te={};if(y&&b.existsSync(y)){const w=b.readdirSync(y);for(const m of w)te[m]=S.join(y,m)}return{supportedLocales:i.supportedLocales,pageIds:T.map(w=>w.id),components:Object.fromEntries(F.map((w,m)=>[w.id,{index:m,data:w}])),pages:Object.fromEntries(T.map(w=>[w.id,w])),config:i.config||{},resources:ue,chunks:te,routeIds:R.map(w=>w.id),routes:Object.fromEntries(R.map(w=>[w.id,w])),dataSourceIds:[],dataSources:{}}}finally{o&&n&&b.rmSync(n,{force:!0,recursive:!0})}}async function Ue(e,s,{routes:t,mergeMode:n="byUpdateTime",deleteRoutes:o=!1,publishMode:a=void 0}={}){try{a&&ct(a)}catch(y){I.error("clear preload page cache error",{error:y})}const{pages:d,pageIds:l,routeIds:u,routes:c,supportedLocales:p}=e;if(a==="production"){let y=t??[],r=null;for(const i of u??[]){const f=c==null?void 0:c[i];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=>[`${i}-${T.paramOptionIds.join("-")}`,T]));r={...r||{},...v},t||(y=[...y,...E.map(T=>`${i}-${T.paramOptionIds.join("-")}`)])}else t||y.push(i)}I.info("routeIds to be published: ",y);for(const i of y){let f=i;if(f.includes("-")){const[T]=f.split("-");f=T}const E=c==null?void 0:c[f];if(!E){const T=s.pageIds.indexOf(f);T!==-1&&o&&(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]);I.info("delete main route page",f);continue}if(i.includes("-")&&!(r!=null&&r[i])){const T=s.pageIds.indexOf(i);T!==-1&&o&&(s.pageIds.splice(T,1),delete s.pages[i]),I.info("delete page",i);continue}if(!E.displayTemplateId){I.info("no display template",i);continue}const v=d[E.displayTemplateId];if(!v){I.info("no template page",i);continue}if(s.pageIds.includes(i)){if(I.info("has need update page",i),n==="replace")s.pages[i]=ve({page:v,route:E,state:e,routeId:i,routePathInfo:r==null?void 0:r[i]}),I.info("replace page",i);else if(n==="byUpdateTime"){const T=s.pages[E.id];(!T||E.updatedAt&&E.updatedAt>T.updatedAt)&&(s.pages[i]=ve({page:v,route:E,state:e,routeId:i,routePathInfo:r==null?void 0:r[i]}),I.info("replace page by update time",i))}}else s.pageIds.push(i),s.pages[i]=ve({page:v,route:E,state:e,routeId:i,routePathInfo:r==null?void 0:r[i]}),I.info("add page",i)}if(o&&!t)for(const i of s.pageIds)y!=null&&y.includes(i)||(delete s.pages[i],I.info("delete page",i)),s.pageIds=[...s.pageIds].filter(f=>y==null?void 0:y.includes(f))}else{for(const y of l){const r=d[y];if(r)if(s.pageIds.includes(r.id)){if(n==="replace")s.pages[r.id]=r;else if(n==="byUpdateTime"){const i=s.pages[r.id];(!i||r.updatedAt&&r.updatedAt>i.updatedAt)&&(s.pages[r.id]=r)}}else s.pageIds.push(r.id),s.pages[r.id]=r}for(const y of u){const r=c[y];if(r)if(s.routeIds.includes(r.id)){if(n==="replace")s.routes[r.id]=r;else if(n==="byUpdateTime"){const i=s.routes[r.id];(!i||r.updatedAt&&r.updatedAt>i.updatedAt)&&(s.routes[r.id]=r)}}else s.routeIds.push(r.id),s.routes[r.id]=r}}if(s.supportedLocales.splice(0,s.supportedLocales.length),s.supportedLocales.push(...is.default(p)),o)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,r])=>{const i=await St(r==null?void 0:r.data);return[y,{...r,data:i}]}))),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 St=Q.memoize(async e=>{var s;if(!cs.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 ut(t,"PROPERTIES_SCHEMA",e.id);n&&n.length>0&&e&&(e.properties={},n.forEach((o,a)=>{e!=null&&e.properties&&(e.properties[o.id]={index:a,data:o})}))}catch(n){I.error("checkPropertiesFromCode error",{componentId:e.id,name:e.name},{error:n})}}return e},{keyGenerator:e=>{var c,p,g,y;const s=(e==null?void 0:e.id)||"",t=(e==null?void 0:e.name)||"",n=((c=e==null?void 0:e.renderer)==null?void 0:c.type)||"",o=(e==null?void 0:e.properties)||{},a=(e==null?void 0:e.updatedAt)||"",d=ee.createHash("md5").update(JSON.stringify(o)).digest("hex");let l="",u="";return((p=e==null?void 0:e.renderer)==null?void 0:p.type)==="react-component"&&(l=ee.createHash("md5").update(((g=e==null?void 0:e.renderer)==null?void 0:g.script)||"").digest("hex"),u=ee.createHash("md5").update(((y=e==null?void 0:e.renderer)==null?void 0:y.editComponent)||"").digest("hex")),JSON.stringify(["checkPropertiesFromCode",s,t,n,d,a,l,u])},lruOptions:{max:100,ttl:1e3*60*60}});let Ae,Z,Ve,Je,ze;function wt(){return Ae=(async()=>{const e=qe.getResources({types:[{did:Be,type:Re},{did:Cs,type:Re}]});Z=(await Promise.all(e.map(async t=>{const n=t.path?await He(t.path,{importAssets:!1}):void 0;return n?{blockletId:t.did,state:n,blockletTitle:t.title}:void 0}))).filter(t=>!!t),Ve=Z.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.pages).map(o=>o?[o==null?void 0:o.id,{page:o,blockletId:n.blockletId}]:[]))),{});const s=Z.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.components).map(o=>[o.data.id,{blockletId:n.blockletId,component:o.data}]))),{});Je=Object.fromEntries(await Promise.all(Object.entries(s).map(async([t,n])=>{const o=await St(n.component);return[t,{...n,component:o}]}))),ze=Z.reduce((t,n)=>Object.assign(t,n.state.chunks),{})})(),Ae}function bt(e){const s=ot.default(async()=>{await wt().catch(t=>{I.error("load resource states error",{error:t})}),await(e==null?void 0:e({states:Z,pages:Ve,components:Je,chunks:ze}))},3e3,{leading:!1,trailing:!0});return s(),O.default.events.on(O.default.Events.componentAdded,s),O.default.events.on(O.default.Events.componentRemoved,s),O.default.events.on(O.default.Events.componentStarted,s),O.default.events.on(O.default.Events.componentStopped,s),O.default.events.on(O.default.Events.componentUpdated,s),O.default.events.on(Le,s),()=>{O.default.events.off(O.default.Events.componentAdded,s),O.default.events.off(O.default.Events.componentRemoved,s),O.default.events.off(O.default.Events.componentStarted,s),O.default.events.off(O.default.Events.componentStopped,s),O.default.events.off(O.default.Events.componentUpdated,s),O.default.events.off(Le,s)}}const Et=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),we=globalThis;var tt;(tt=we[Et])==null||tt.call(we);we[Et]=bt(async({pages:e,components:s})=>{const{projectIds:t}=le;I.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 o=le.shared(n);o.syncedStore.resources.pages=e;const a=await J.findByPk(n);if(a!=null&&a.useAllResources)o.syncedStore.resources.components=s;else{const l=(await Te.findAll({where:{projectId:n}})).map(c=>c.componentId),u=Object.fromEntries(Object.entries(s||{}).filter(([c])=>l.includes(c)));o.syncedStore.resources.components=u}I.info(`update [${n}] resource states:`,{pages:Object.keys(o.syncedStore.resources.pages||{}).length,components:Object.keys(o.syncedStore.resources.components||{}).length})}))]).catch(n=>{I.error("update resource states failed:",n)})});async function Bs(){I.info("trigger reload all project resource"),O.default.events.emit(Le)}async function Pe({ensureLoaded:e=!0}={}){return e&&(Ae??(Ae=wt()),await Ae),{states:Z,pages:Ve,components:Je,chunks:ze}}exports.COMPONENT_DID=Be;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=rt;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=Ne;exports.PUBLISH_MODES=Fs;exports.Project=J;exports.RESOURCE_TYPE=Re;exports.SITE_STATE_PATH=oe;exports.STATE_MODES=Us;exports.SiteState=le;exports.clearPreloadComponentsCache=it;exports.clearPreloadComponentsCacheByMode=ct;exports.downloadAsset=mt;exports.downloadAssets=gt;exports.fromPackage=He;exports.getComponentFromState=ce;exports.getComponentFromStateByName=Ps;exports.getExportSchemaValueFromCode=ut;exports.getMultiTenantAllProjectAccessPassports=ys;exports.getPreloadComponent=pt;exports.getPreloadComponents=Os;exports.getPreloadComponentsCacheKey=lt;exports.getResourceStates=Pe;exports.initPackResourceStates=bt;exports.isMultiTenant=hs;exports.logger=I;exports.mergeState=Ue;exports.nextId=Se;exports.toPackage=yt;exports.triggerReloadAllProjectResource=Bs;
@@ -1 +0,0 @@
1
- "use strict";const _=require("react/jsx-runtime"),T=require("@mui/material"),b=require("ufo"),Z=require("@blocklet/js-sdk"),H=require("lodash/isEmpty"),ee=require("yaml"),te=require("@arcblock/ux/lib/Locale/context"),N=require("@syncedstore/core"),ne=require("@syncedstore/react"),oe=require("ahooks"),C=require("immer"),re=require("js-cookie"),se=require("lodash/debounce"),ce=require("nanoid"),d=require("react"),V=require("react-router-dom"),ie=require("y-indexeddb"),ae=require("y-websocket"),de=require("yjs");require("@blocklet/pages-kit/types");const E=t=>t&&t.__esModule?t:{default:t};function ue(t){if(t&&t.__esModule)return t;const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const i in t)if(i!=="default"){const S=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,S.get?S:{enumerable:!0,get:()=>t[i]})}}return n.default=t,Object.freeze(n)}const le=E(H),fe=ue(ee),me=E(N),Se=E(re),W=E(se),we=t=>{const n=blocklet==null?void 0:blocklet.componentMountPoints.find(i=>i.name===t);return n?n.mountPoint:"/"};function z(){const{pathname:t}=window.location,n=t.match(/\/admin\/(maker|previewer)\/([^/]+)/),i=n==null?void 0:n[2],S=window.__PROJECT_ID__;if(!i&&!S)throw new Error("Unable to get projectId from pathname");return i||S}function pe(t){return`${t}:pages:version`}function Pe(t,n){return n==="yaml"?le.default(t)?"":fe.stringify(t,{indent:2}):n==="json"?JSON.parse(JSON.stringify(t||{})):n==="array"?JSON.parse(JSON.stringify(t||[])):t}function Ie({error:t}){return _.jsx(T.Box,{children:_.jsx(T.Alert,{severity:"error",children:t.message})})}var G;const k=((G=window.blocklet)==null?void 0:G.prefix)||"/",L=Z.createAxios({timeout:200*1e3}),ge=window.location.protocol==="https:"?"wss":"ws",je=t=>b.joinURL(`${ge}://${window.location.hostname}`,k,`api/${t}/ws/pages`),ye="z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";var F;(F=blocklet==null?void 0:blocklet.componentMountPoints.find(t=>t.did===ye))!=null&&F.mountPoint||b.joinURL(k,"/image-bin");function Ce(t){return t&&!/^(https?:\/\/|\/)/.test(t)?window.location.origin+b.joinURL(k,"uploads",t):t}const be=window.innerWidth<=750;function he(t,n,i){if(!t||/\.gif/.test(t))return t;const S=(be?n/1.5:n)*(i==="quality"?1.5:1);return ve(t,{imageFilter:"resize",w:S,f:"webp"})}function ve(t,n){return!t||!n?t:b.withQuery(t,n)}async function xe(t){return L.get(`/api/projects/${t}`).then(n=>n.data)}async function Oe(t){return L.post(`/api/projects/${t.id}/update`,t).then(n=>n.data)}const Ee=500,x=ce.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),J=d.createContext(null);function _e({url:t,name:n,children:i,waitingSynced:S}){const[g,P]=d.useState(!1),{locale:j}=te.useLocaleContext(),w=R(),e=`${w}:MakerLocalState`,o=`${w}:${n}`,[s,r]=oe.useLocalStorageState(e,{defaultValue:{},listenStorageChange:!0}),c=d.useRef(s);c.current=s;const a=d.useMemo(()=>me.default({dataSourceIds:[],dataSources:{},pages:{},pageIds:[],routes:{},routeIds:[],components:{},supportedLocales:[],config:{},resources:{}}),[]),u=d.useMemo(()=>N.getYjsDoc(a),[a]);d.useMemo(()=>new ie.IndexeddbPersistence(o,u),[o,u]);const p=d.useMemo(()=>new ae.WebsocketProvider(t,o,u,{params:{token:Se.default.get("login_token")},resyncInterval:5*60*1e3}),[t,o,u]),h=d.useCallback(()=>{p&&(p.disconnect(),p.connect())},[p]),y=d.useMemo(()=>new de.UndoManager([u.getArray("pageIds"),u.getMap("pages"),u.getArray("supportedLocales"),u.getMap("config")],{doc:u}),[u]),[v,O]=d.useState(null),[A,M]=d.useState(!1),[q,D]=d.useState(void 0),U=d.useCallback(async()=>{if(w){M(!0);try{const l=await xe(w);O(l)}catch(l){console.error("Failed to fetch project:",l)}finally{M(!1)}}},[w]),$=d.useCallback(async(l,f)=>{var I;if(D(void 0),!!w){f!=null&&f.optimisticUpdate&&v&&O(m=>({...m,...l}));try{const m=await Oe({...l});O(m)}catch(m){console.error("Failed to update project:",m),f!=null&&f.optimisticUpdate&&O(v),D((I=m==null?void 0:m.response)==null?void 0:I.data)}}},[w,v]);d.useEffect(()=>{w&&U()},[w,U]);const Y=d.useMemo(()=>({doc:u,state:a,localState:{...s,currentLocale:j},setLocalState:l=>r(typeof l=="function"?f=>l(f??{}):l),undoManager:y,projectState:{project:v,isLoadingProject:A,error:q},updateProject:$,forceSync:h}),[u,a,JSON.stringify(s),r,y,v,A,$,q,j,h]);return d.useEffect(()=>{y.on("stack-item-added",({stackItem:l})=>{const{currentPageId:f,currentLocale:I,pages:m}=c.current;l.meta.set("localState",{currentPageId:f,currentLocale:I,pages:m})}),y.on("stack-item-popped",({stackItem:l})=>{const f=l.meta.get("localState");f&&r(I=>({...I,...f}))})},[y,r]),d.useEffect(()=>{p.awareness.setLocalState(s)},[p,s]),d.useEffect(()=>{p.once("synced",()=>P(!0));const l=()=>{r(m=>({...m,networkStatus:void 0}))},f=()=>{r(m=>({...m,networkStatus:"offline"}))},I=W.default(({status:m})=>{m==="connected"?l():m==="disconnected"&&f()},Ee);return p.on("status",I),window.addEventListener("online",l),window.addEventListener("offline",f),()=>{p.off("status",I),window.removeEventListener("online",l),window.removeEventListener("offline",f)}},[p,r]),S&&!g?null:_.jsx(J.Provider,{value:Y,children:i})}const B=()=>{const t=d.useContext(J);if(!t)throw new Error("Context is null");const n=ne.useSyncedStore(t.state),{setLocalState:i,localState:S}=t,g=V.useNavigate(),P=R(),j=d.useMemo(()=>({setCurrentSectionId:(e,o)=>{var s,r;e===S.currentPageId&&o===((r=(s=S.pages)==null?void 0:s[e])==null?void 0:r.currentSectionId)||(g(b.joinURL("/admin/maker",P??"","pages",e)),i(c=>C.produce(c,a=>{var u;a.currentPageId=e,a.currentComponentId=void 0,a.customComponentPreviewerProperties={},o!==void 0&&(a.pages??(a.pages={}),(u=a.pages)[e]??(u[e]={}),a.pages[e].currentSectionId=o??void 0),o?window.sessionStorage.setItem("iframe_show_id",`"${o}"`):window.sessionStorage.removeItem("iframe_show_id")})))},setCurrentComponentId:e=>{e!==S.currentComponentId&&(g(b.joinURL("/admin/maker",P??"","components",e)),i(o=>C.produce(o,s=>{s.currentComponentId=e,s.customComponentPreviewerProperties={}})))},setCurrentRouteId:({routeId:e,dynamicParams:o})=>{i(s=>C.produce(s,r=>{r.currentRouteId=e,r.currentDynamicParams=o}))},setCustomComponentPreviewerProperties:(()=>{const e={},o=W.default(()=>{i(s=>C.produce(s,r=>{r.customComponentPreviewerProperties={...r==null?void 0:r.customComponentPreviewerProperties,...e},Object.keys(e).forEach(c=>delete e[c])}))},5);return s=>{Object.assign(e,s),o()}})(),setRouteGenerateProcess:e=>{i(o=>C.produce(o,s=>{e?s.routeGenerateProcess={...s.routeGenerateProcess,...e}:s.routeGenerateProcess={}}))},resetRouteGenerateProcess:()=>{i(e=>C.produce(e,o=>{o.routeGenerateProcess={progress:"complete"}}))}}),[i,g,P]),w=d.useMemo(()=>({addPage:(e,o)=>{var c,a,u,p,h,y;const s=(e==null?void 0:e.id)??x(),r={...e,id:s,createdAt:(e==null?void 0:e.createdAt)??new Date().toISOString(),updatedAt:(e==null?void 0:e.updatedAt)??new Date().toISOString(),publishedAt:new Date(0).toISOString(),slug:(e==null?void 0:e.slug)??`/${s}`,sections:(e==null?void 0:e.sections)??{},sectionIds:(e==null?void 0:e.sectionIds)??[],isPublic:(e==null?void 0:e.isPublic)??!0,templateConfig:(e==null?void 0:e.templateConfig)??{isTemplate:((c=e==null?void 0:e.templateConfig)==null?void 0:c.isTemplate)??!0,displayTemplateId:((a=e==null?void 0:e.templateConfig)==null?void 0:a.displayTemplateId)??void 0,dataSourceIds:((u=e==null?void 0:e.templateConfig)==null?void 0:u.dataSourceIds)??void 0,dataSourceParameters:((p=e==null?void 0:e.templateConfig)==null?void 0:p.dataSourceParameters)??{},enabledGenerate:((h=e==null?void 0:e.templateConfig)==null?void 0:h.enabledGenerate)??!1,agentId:((y=e==null?void 0:e.templateConfig)==null?void 0:y.agentId)??void 0}};return t.doc.transact(()=>{n.pages[r.id]=r,n.pageIds.splice(o??n.pageIds.length,0,r.id)}),r},addRoute:(e,o)=>{const s=(e==null?void 0:e.id)??x(),r={...e,id:s,createdAt:(e==null?void 0:e.createdAt)??new Date().toISOString(),updatedAt:(e==null?void 0:e.updatedAt)??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:(e==null?void 0:e.path)??`/${s}`,handler:(e==null?void 0:e.handler)??"Pages Kit",isPublic:(e==null?void 0:e.isPublic)??!0,params:(e==null?void 0:e.params)??[],enabledGenerate:(e==null?void 0:e.enabledGenerate)??!1,displayTemplateId:(e==null?void 0:e.displayTemplateId)??void 0,dataSource:(e==null?void 0:e.dataSource)??{}};return t.doc.transact(()=>{n.routes??(n.routes={}),n.routeIds??(n.routeIds=[]),n.routes[r.id]=r,n.routeIds.splice(o??n.routeIds.length,0,r.id)}),r},deleteRoute:e=>{var s;if(!e)return;const o=(s=n.routeIds)==null?void 0:s.indexOf(e);o!==void 0&&o!==-1&&t.doc.transact(()=>{var r,c;(r=n.routeIds)==null||r.splice(o,1),(c=n.routes)==null||delete c[e]})},deletePage:e=>{const o=n.pageIds.indexOf(e);o!==-1&&t.doc.transact(()=>{n.pageIds.splice(o,1),delete n.pages[e]})},movePage:(e,o)=>{const{pageIds:s}=n,r=s.indexOf(e);r>=0&&s.splice(o,0,...s.splice(r,1))},addSection:(e,o,s)=>{const r=n.pages[e];if(!r)throw new Error(`Page ${e} is not exists`);const c={...o,id:o.id??x(),isTemplateSection:o.isTemplateSection??!0,llmConfig:o.llmConfig??{}};return t.doc.transact(()=>{r.sections[c.id]=c,r.sectionIds.splice(s??r.sectionIds.length,0,c.id)}),c},deleteSection:(e,o)=>{const s=n.pages[e];if(!s)throw new Error(`Page ${e} is not exists`);const r=s.sectionIds.indexOf(o);r!==-1&&t.doc.transact(()=>{s.sectionIds.splice(r,1),delete s.sections[o]})},toggleSectionVisibility:(e,o,s)=>{const r=n.pages[e];if(!r)throw new Error(`Page ${e} is not exists`);const c=r.sections[o];c&&(c.visibility=s)},moveSection:(e,o,s)=>{const r=n.pages[e];if(!r)throw new Error(`Page ${e} is not exists`);const{sectionIds:c}=r,a=c.indexOf(o);a>=0&&c.splice(s,0,...c.splice(a,1))},addDataSource:e=>{const o=e.id??x(),s={...e??{},id:o,createdAt:new Date().toISOString()};return t.doc.transact(()=>{n.dataSourceIds??(n.dataSourceIds=[]),n.dataSources??(n.dataSources={}),n.dataSourceIds.push(o),n.dataSources[o]=s}),n.dataSources[o]},deleteDataSource:e=>{const o=n.dataSourceIds.indexOf(e);o!==-1&&t.doc.transact(()=>{n.dataSourceIds.splice(o,1),delete n.dataSources[e]})}}),[n,t.doc]);return{...t,state:n,actions:w,localActions:j,get currentPage(){const{localState:{currentPageId:e}}=t;return e?n.pages[e]:void 0},get currentSection(){var r,c,a;const{localState:{currentPageId:e,...o}}=t;if(!e)return;const s=(c=(r=o.pages)==null?void 0:r[e])==null?void 0:c.currentSectionId;if(s)return(a=n.pages[e])==null?void 0:a.sections[s]},get currentRoute(){var o;const{localState:{currentRouteId:e}}=t;return e?(o=n.routes)==null?void 0:o[e]:void 0}}},R=()=>{const{projectId:t}=V.useParams();return t??z()??""};function K(t){var S,g;const{resources:n}=t;if(!n.components)return{};const i={};return(g=(S=window==null?void 0:window.blocklet)==null?void 0:S.componentMountPoints)==null||g.forEach(P=>{i[P.did]=P}),Object.fromEntries(Object.entries(n.components).map(([P,{blockletId:j,component:w}])=>{var e;return[P,{data:w,blockletId:j,blockletTitle:((e=i[j])==null?void 0:e.title)||j}]}))}function Q(t){const{components:n}=t;return n||{}}function X(t){return{...K(t),...Q(t)}}const ke=()=>X(B().state);exports.ErrorView=Ie;exports.StoreProvider=_e;exports.api=L;exports.autoResizeImage=he;exports.getAllComponents=X;exports.getCustomComponents=Q;exports.getImageAbsoluteUrl=Ce;exports.getMountPoint=we;exports.getProjectIdFromPathnameOrWindow=z;exports.getProjectPageVersionKey=pe;exports.getResourceComponents=K;exports.getWssURL=je;exports.nextId=x;exports.transformValue=Pe;exports.useAllComponents=ke;exports.useProjectId=R;exports.useStore=B;