@blocklet/pages-kit-inner-components 0.5.45 → 0.5.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/add-component.js +19 -19
- package/lib/cjs/chunks/{array-Cip5uTnI.js → array-BqHuYyfx.js} +1 -1
- package/lib/cjs/chunks/{config-string-CEipCOnU.js → config-string-4bVR9Vc8.js} +1 -1
- package/lib/cjs/chunks/{draft-data-F0V4PcIs.js → draft-data-CuZfaQ4s.js} +1 -1
- package/lib/cjs/chunks/{home-BCFoaIEZ.js → home-CQTuGad2.js} +3 -3
- package/lib/cjs/chunks/{publish-button-Bbd4z1_d.js → publish-button-1xmfwN7o.js} +1 -1
- package/lib/cjs/chunks/site-state-BtZ8o3J2.js +57 -0
- package/lib/cjs/chunks/state-BVdbNJCA.js +1 -0
- package/lib/cjs/components.js +1 -1
- package/lib/cjs/home.js +1 -1
- package/lib/cjs/locales.js +2 -2
- package/lib/cjs/project-html.js +1 -1
- package/lib/cjs/resources.js +1 -1
- package/lib/cjs/setting.js +3 -3
- package/lib/cjs/site-state.js +1 -1
- package/lib/cjs/theme.js +1 -1
- package/lib/es/add-component.js +18 -17
- package/lib/es/chunks/{array-DM0x2Sjw.js → array-c6HYTLze.js} +1 -1
- package/lib/es/chunks/{config-string-Dw6sJMn_.js → config-string-WMpFf-7V.js} +1 -1
- package/lib/es/chunks/{draft-data-sTSk4UTm.js → draft-data-CWM--ooz.js} +1 -1
- package/lib/es/chunks/{home-ClxOpmCx.js → home-DQjaiv2F.js} +4 -4
- package/lib/es/chunks/{publish-button-CKXdANG9.js → publish-button-wYeS7m-g.js} +3 -3
- package/lib/es/chunks/{site-state-BeEHvakk.js → site-state-D-moj9fA.js} +527 -550
- package/lib/es/chunks/{state-COB6reM7.js → state-l--dTdHq.js} +87 -88
- package/lib/es/components.js +1 -1
- package/lib/es/home.js +3 -3
- package/lib/es/locales.js +2 -2
- package/lib/es/project-html.js +1 -1
- package/lib/es/resources.js +1 -1
- package/lib/es/setting.js +94 -93
- package/lib/es/site-state.js +6 -5
- package/lib/es/theme.js +34 -34
- package/package.json +7 -7
- package/lib/cjs/chunks/site-state-CeQEnrvX.js +0 -57
- package/lib/cjs/chunks/state-UwRWAZRe.js +0 -1
package/lib/es/site-state.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { p as j, n as q, o as v, S as B, q as L, r as U, s as h, b as y, v as z, u as C, t as F, w as G } from "./chunks/site-state-D-moj9fA.js";
|
|
2
|
+
import { nextId as K } from "@blocklet/pages-kit/utils/common";
|
|
3
|
+
import "@blocklet/pages-kit/utils/page-model";
|
|
2
4
|
import "@blocklet/pages-kit/utils/property";
|
|
3
5
|
import "@blocklet/pages-kit/utils/route";
|
|
4
6
|
import "@blocklet/sdk/lib/component";
|
|
@@ -18,7 +20,6 @@ import "lodash/pick";
|
|
|
18
20
|
import "lodash/set";
|
|
19
21
|
import "lodash/union";
|
|
20
22
|
import "lru-cache";
|
|
21
|
-
import "nanoid";
|
|
22
23
|
import "p-limit";
|
|
23
24
|
import "path";
|
|
24
25
|
import "stream/promises";
|
|
@@ -41,7 +42,7 @@ export {
|
|
|
41
42
|
y as getResourceStates,
|
|
42
43
|
z as initPackResourceStates,
|
|
43
44
|
C as mergeState,
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
45
|
+
K as nextId,
|
|
46
|
+
F as toPackage,
|
|
47
|
+
G as triggerReloadAllProjectResource
|
|
47
48
|
};
|
package/lib/es/theme.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { jsx as
|
|
1
|
+
import { jsx as r } from "react/jsx-runtime";
|
|
2
2
|
import { ConfigProvider as f } from "@arcblock/ux/lib/Config";
|
|
3
3
|
import { Icon as y } from "@iconify-icon/react";
|
|
4
4
|
import g from "@iconify-icons/tabler/chevron-down";
|
|
5
|
-
import { listItemIconClasses as z, switchClasses as
|
|
5
|
+
import { listItemIconClasses as z, switchClasses as v, svgIconClasses as l, sliderClasses as n, outlinedInputClasses as d, inputBaseClasses as t, filledInputClasses as m, inputLabelClasses as s, inputClasses as a, selectClasses as S, autocompleteClasses as p, Box as M } from "@mui/material";
|
|
6
6
|
import { S as b } from "./chunks/session-CVblGhSp.js";
|
|
7
7
|
import { translations as c } from "./locales.js";
|
|
8
8
|
var x;
|
|
@@ -22,7 +22,7 @@ const o = ((x = window.blocklet) == null ? void 0 : x.prefix) || "/", $ = o.ends
|
|
|
22
22
|
}
|
|
23
23
|
};
|
|
24
24
|
function u(e) {
|
|
25
|
-
return /* @__PURE__ */
|
|
25
|
+
return /* @__PURE__ */ r(M, { ...e, component: y, icon: g });
|
|
26
26
|
}
|
|
27
27
|
const I = {
|
|
28
28
|
typography: {
|
|
@@ -83,10 +83,10 @@ const I = {
|
|
|
83
83
|
styleOverrides: {
|
|
84
84
|
root: {
|
|
85
85
|
padding: 4,
|
|
86
|
-
[`.${
|
|
86
|
+
[`.${l.fontSizeMedium}`]: {
|
|
87
87
|
fontSize: "1.25rem"
|
|
88
88
|
},
|
|
89
|
-
[`.${
|
|
89
|
+
[`.${l.fontSizeSmall}`]: {
|
|
90
90
|
fontSize: "1.125rem"
|
|
91
91
|
}
|
|
92
92
|
}
|
|
@@ -96,10 +96,10 @@ const I = {
|
|
|
96
96
|
styleOverrides: {
|
|
97
97
|
root: {
|
|
98
98
|
padding: 4,
|
|
99
|
-
[`.${
|
|
99
|
+
[`.${l.fontSizeMedium}`]: {
|
|
100
100
|
fontSize: "1.25rem"
|
|
101
101
|
},
|
|
102
|
-
[`.${
|
|
102
|
+
[`.${l.fontSizeSmall}`]: {
|
|
103
103
|
fontSize: "1.125rem"
|
|
104
104
|
}
|
|
105
105
|
}
|
|
@@ -111,7 +111,7 @@ const I = {
|
|
|
111
111
|
height: 28,
|
|
112
112
|
width: 48,
|
|
113
113
|
padding: 8,
|
|
114
|
-
[`&.${
|
|
114
|
+
[`&.${v.sizeSmall}`]: {
|
|
115
115
|
height: 26,
|
|
116
116
|
width: 40,
|
|
117
117
|
padding: 8
|
|
@@ -123,7 +123,7 @@ const I = {
|
|
|
123
123
|
}
|
|
124
124
|
},
|
|
125
125
|
MuiAutocomplete: {
|
|
126
|
-
defaultProps: { popupIcon: /* @__PURE__ */
|
|
126
|
+
defaultProps: { popupIcon: /* @__PURE__ */ r(u, { fontSize: 14 }) },
|
|
127
127
|
variants: [
|
|
128
128
|
{
|
|
129
129
|
props: {},
|
|
@@ -154,7 +154,7 @@ const I = {
|
|
|
154
154
|
{
|
|
155
155
|
props: {},
|
|
156
156
|
// @ts-ignore
|
|
157
|
-
style: ({ theme: e, ownerState:
|
|
157
|
+
style: ({ theme: e, ownerState: i }) => e.unstable_sx({
|
|
158
158
|
[`.${t.root}`]: {
|
|
159
159
|
borderRadius: 1,
|
|
160
160
|
lineHeight: "1.5rem",
|
|
@@ -164,7 +164,7 @@ const I = {
|
|
|
164
164
|
[`&.${a.multiline}`]: {
|
|
165
165
|
pl: 0,
|
|
166
166
|
pr: 0,
|
|
167
|
-
pt:
|
|
167
|
+
pt: i != null && i.label ? 2 : 1,
|
|
168
168
|
"& .MuiInputBase-inputMultiline": {
|
|
169
169
|
py: 0
|
|
170
170
|
}
|
|
@@ -176,19 +176,19 @@ const I = {
|
|
|
176
176
|
[`&.${t.hiddenLabel}`]: {
|
|
177
177
|
mt: 0,
|
|
178
178
|
pt: 0,
|
|
179
|
-
[`.${
|
|
179
|
+
[`.${S.select}.${a.input}:focus`]: {
|
|
180
180
|
bgcolor: "transparent"
|
|
181
181
|
}
|
|
182
182
|
}
|
|
183
183
|
},
|
|
184
|
-
[`.${
|
|
184
|
+
[`.${s.standard}`]: {
|
|
185
185
|
transform: "translate(0px, 18px) scale(1)",
|
|
186
|
-
[`&.${
|
|
186
|
+
[`&.${s.sizeSmall}`]: {
|
|
187
187
|
transform: "translate(0px, 15px) scale(1)"
|
|
188
188
|
},
|
|
189
|
-
[`&.${
|
|
189
|
+
[`&.${s.shrink}`]: {
|
|
190
190
|
transform: "translate(0px, -1px) scale(0.8)",
|
|
191
|
-
[`&.${
|
|
191
|
+
[`&.${s.sizeSmall}`]: {
|
|
192
192
|
transform: "translate(0px, -1px) scale(0.8)"
|
|
193
193
|
}
|
|
194
194
|
}
|
|
@@ -198,15 +198,15 @@ const I = {
|
|
|
198
198
|
":before,:after": { display: "none" },
|
|
199
199
|
[`.${t.input}`]: {
|
|
200
200
|
pb: 0.5,
|
|
201
|
-
pt:
|
|
201
|
+
pt: i != null && i.label ? 2 : 0.5,
|
|
202
202
|
px: 1,
|
|
203
203
|
":focus": {
|
|
204
204
|
borderRadius: 1
|
|
205
205
|
},
|
|
206
206
|
[`&.${t.inputSizeSmall}`]: {
|
|
207
207
|
pb: 0.25,
|
|
208
|
-
pt:
|
|
209
|
-
...
|
|
208
|
+
pt: i != null && i.label ? 1.25 : 0.25,
|
|
209
|
+
...i != null && i.multiline ? {
|
|
210
210
|
pt: 0
|
|
211
211
|
} : {}
|
|
212
212
|
},
|
|
@@ -218,14 +218,14 @@ const I = {
|
|
|
218
218
|
}
|
|
219
219
|
}
|
|
220
220
|
},
|
|
221
|
-
[`.${
|
|
221
|
+
[`.${s.filled}`]: {
|
|
222
222
|
transform: "translate(8px, 11px) scale(1)",
|
|
223
|
-
[`&.${
|
|
223
|
+
[`&.${s.sizeSmall}`]: {
|
|
224
224
|
transform: "translate(8px, 7px) scale(1)"
|
|
225
225
|
},
|
|
226
|
-
[`&.${
|
|
226
|
+
[`&.${s.shrink}`]: {
|
|
227
227
|
transform: "translate(8px, 2px) scale(0.8)",
|
|
228
|
-
[`&.${
|
|
228
|
+
[`&.${s.sizeSmall}`]: {
|
|
229
229
|
transform: "translate(8px, 0) scale(0.8)"
|
|
230
230
|
}
|
|
231
231
|
}
|
|
@@ -246,12 +246,12 @@ const I = {
|
|
|
246
246
|
}
|
|
247
247
|
}
|
|
248
248
|
},
|
|
249
|
-
[`.${
|
|
249
|
+
[`.${s.outlined}`]: {
|
|
250
250
|
transform: "translate(8px, 10px) scale(1)",
|
|
251
|
-
[`&.${
|
|
251
|
+
[`&.${s.sizeSmall}`]: {
|
|
252
252
|
transform: "translate(8px, 7px) scale(1)"
|
|
253
253
|
},
|
|
254
|
-
[`&.${
|
|
254
|
+
[`&.${s.shrink}`]: {
|
|
255
255
|
transform: "translate(16px, -7px) scale(0.8)"
|
|
256
256
|
}
|
|
257
257
|
}
|
|
@@ -347,16 +347,16 @@ const I = {
|
|
|
347
347
|
props: {},
|
|
348
348
|
style: ({ theme: e }) => e.unstable_sx({
|
|
349
349
|
height: 3,
|
|
350
|
-
[`.${
|
|
350
|
+
[`.${n.track}`]: {
|
|
351
351
|
borderWidth: 0
|
|
352
352
|
},
|
|
353
|
-
[`.${
|
|
353
|
+
[`.${n.thumb}`]: {
|
|
354
354
|
width: 16,
|
|
355
355
|
height: 16
|
|
356
356
|
},
|
|
357
|
-
[`&.${
|
|
357
|
+
[`&.${n.sizeSmall}`]: {
|
|
358
358
|
height: 2,
|
|
359
|
-
[`.${
|
|
359
|
+
[`.${n.thumb}`]: {
|
|
360
360
|
width: 12,
|
|
361
361
|
height: 12
|
|
362
362
|
}
|
|
@@ -462,23 +462,23 @@ const I = {
|
|
|
462
462
|
WebkitTextTransform: "none"
|
|
463
463
|
}
|
|
464
464
|
}
|
|
465
|
-
}, B = ({ children: e }) => /* @__PURE__ */
|
|
465
|
+
}, B = ({ children: e }) => /* @__PURE__ */ r(
|
|
466
466
|
f,
|
|
467
467
|
{
|
|
468
468
|
theme: I,
|
|
469
469
|
translations: c,
|
|
470
470
|
fallbackLocale: "en",
|
|
471
471
|
injectFirst: !0,
|
|
472
|
-
children: /* @__PURE__ */
|
|
472
|
+
children: /* @__PURE__ */ r(b, { serviceHost: o, protectedRoutes: [`${$}/*`], children: e })
|
|
473
473
|
}
|
|
474
|
-
), H = ({ children: e }) => /* @__PURE__ */
|
|
474
|
+
), H = ({ children: e }) => /* @__PURE__ */ r(
|
|
475
475
|
f,
|
|
476
476
|
{
|
|
477
477
|
theme: C,
|
|
478
478
|
translations: c,
|
|
479
479
|
fallbackLocale: "en",
|
|
480
480
|
injectFirst: !0,
|
|
481
|
-
children: /* @__PURE__ */
|
|
481
|
+
children: /* @__PURE__ */ r(b, { serviceHost: o, protectedRoutes: [`${$}/*`], children: e })
|
|
482
482
|
}
|
|
483
483
|
);
|
|
484
484
|
export {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blocklet/pages-kit-inner-components",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.48",
|
|
4
4
|
"description": "Pages Kit inner components library",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -71,9 +71,9 @@
|
|
|
71
71
|
"dependencies": {
|
|
72
72
|
"@arcblock/did-auth": "^1.20.14",
|
|
73
73
|
"@arcblock/did-auth-storage-nedb": "^1.7.1",
|
|
74
|
-
"@arcblock/did-connect": "^2.13.
|
|
75
|
-
"@arcblock/react-hooks": "^2.13.
|
|
76
|
-
"@arcblock/ux": "^2.13.
|
|
74
|
+
"@arcblock/did-connect": "^2.13.70",
|
|
75
|
+
"@arcblock/react-hooks": "^2.13.70",
|
|
76
|
+
"@arcblock/ux": "^2.13.70",
|
|
77
77
|
"@blocklet/ai-kit": "^0.1.79",
|
|
78
78
|
"@blocklet/ai-runtime": "^0.4.274",
|
|
79
79
|
"@blocklet/code-editor": "^0.4.274",
|
|
@@ -84,7 +84,7 @@
|
|
|
84
84
|
"@blocklet/sdk": "^1.16.44",
|
|
85
85
|
"@blocklet/studio-ui": "^0.4.274",
|
|
86
86
|
"@blocklet/tracker": "^1.16.44",
|
|
87
|
-
"@blocklet/ui-react": "^2.13.
|
|
87
|
+
"@blocklet/ui-react": "^2.13.70",
|
|
88
88
|
"@blocklet/uploader": "^0.1.95",
|
|
89
89
|
"@blocklet/uploader-server": "^0.1.101",
|
|
90
90
|
"@emotion/cache": "^11.13.1",
|
|
@@ -204,8 +204,8 @@
|
|
|
204
204
|
"yaml": "^2.5.0",
|
|
205
205
|
"yjs": "^13.6.18",
|
|
206
206
|
"zustand": "^4.5.5",
|
|
207
|
-
"@blocklet/pages-kit": "^0.5.
|
|
208
|
-
"@blocklet/pages-kit-block-studio": "^0.5.
|
|
207
|
+
"@blocklet/pages-kit": "^0.5.48",
|
|
208
|
+
"@blocklet/pages-kit-block-studio": "^0.5.48"
|
|
209
209
|
},
|
|
210
210
|
"devDependencies": {
|
|
211
211
|
"@trivago/prettier-plugin-sort-imports": "^5.2.1",
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
"use strict";var kt=Object.defineProperty;var _t=(e,n,t)=>n in e?kt(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var R=(e,n,t)=>_t(e,typeof n!="symbol"?n+"":n,t);const vt=require("@blocklet/pages-kit/builtin/utils"),ye=require("@blocklet/pages-kit/types"),de=require("@blocklet/pages-kit/utils/property"),pe=require("@blocklet/quickjs"),Rt=require("@blocklet/sdk/lib/config"),Pe=require("lru-cache"),at=require("node-fetch"),B=require("ufo"),ee=require("crypto"),xt=require("@blocklet/logger"),w=require("fs"),S=require("path"),Lt=require("lodash/isNil"),Nt=require("@blocklet/pages-kit/utils/builtin"),rt=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),Ge=require("@blocklet/sdk/lib/component"),Mt=require("autoprefixer"),$t=require("esbuild"),Ut=require("postcss"),Ft=require("tailwindcss"),qt=require("typescript"),te=require("@syncedstore/core"),Bt=require("yjs"),Ht=require("@blocklet/pages-kit/utils/data-source"),we=require("@blocklet/pages-kit/utils/route"),Gt=require("lodash"),Vt=require("@reactivedata/reactive"),Me=require("glob"),Jt=require("lib0/decoding"),Kt=require("lib0/encoding"),zt=require("lodash/cloneDeep"),Yt=require("lodash/debounce"),Wt=require("lodash/get"),Qt=require("lodash/isEmpty"),Xt=require("lodash/pick"),Zt=require("lodash/set"),es=require("lodash/union"),ts=require("nanoid"),ss=require("p-limit"),ns=require("stream/promises"),os=require("tar"),as=require("wait-on"),ie=require("y-protocols/awareness"),Re=require("y-protocols/sync"),rs=require("yaml"),v=require("sequelize");require("sqlite3");require("@blocklet/pages-kit/types/state");const L=e=>e&&e.__esModule?e:{default:e};function fe(e){if(e&&e.__esModule)return e;const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const t in e)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,s.get?s:{enumerable:!0,get:()=>e[t]})}}return n.default=e,Object.freeze(n)}const O=L(Rt),is=L(at),cs=L(xt),it=L(S),ls=L(Lt),ds=L(Mt),ps=fe($t),us=L(Ut),fs=L(Ft),q=L(qt),K=fe(Bt),xe=fe(Jt),x=fe(Kt),ms=L(zt),ct=L(Yt),Ve=L(Wt),lt=L(Qt),hs=L(Xt),Xe=L(Zt),gs=L(es),ys=L(ss),Ss=L(as),oe=fe(rs);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 Es="image-bin";O.default.env.INIT_TEMPLATE_PATH;const ws=process.env.DATABASE_URL||it.default.join(O.default.env.dataDir,"db/pages-kit.db"),Ze=O.default,bs=()=>O.default.env.tenantMode==="multiple",Is=()=>{var e;return(ls.default(Ze.env.preferences.multiTenantAllProjectAccessPassports)?[]:(e=Ze.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:e.split(","))||[]},Cs=it.default.join(O.default.env.dataDir,"fs-memoize-cache"),Os=O.default.env.FS_MEMOIZE_CACHE_VERSION||"v1.0.0",y=cs.default("pages-kit"),As=v.DataTypes.sqlite.DATE.parse;v.DataTypes.sqlite.DATE.parse=(e,n)=>typeof e=="number"?new Date(e):As(e,n);const me=new v.Sequelize({dialect:"sqlite",storage:ws,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});me.query("pragma journal_mode = WAL;");me.query("pragma synchronous = normal;");me.query("pragma journal_size_limit = 67108864;");class Te extends v.Model{}Te.init({id:{type:v.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:v.DataTypes.UUIDV4},projectId:{type:v.DataTypes.UUID,allowNull:!1},componentId:{type:v.DataTypes.STRING,allowNull:!1}},{sequelize:me,tableName:"ProjectComponents",timestamps:!1});class z extends v.Model{static async getProjectByIdOrSlug(n){return z.findOne({where:{[v.Op.or]:[{id:n},{slug:n}]}})}}z.init({id:{type:v.DataTypes.UUID,defaultValue:v.DataTypes.UUIDV4,primaryKey:!0},name:{type:v.DataTypes.STRING,allowNull:!1},description:v.DataTypes.TEXT,createdAt:v.DataTypes.DATE,updatedAt:v.DataTypes.DATE,createdBy:{type:v.DataTypes.STRING,allowNull:!1},updatedBy:{type:v.DataTypes.STRING,allowNull:!1},slug:v.DataTypes.STRING,icon:v.DataTypes.STRING,pinnedAt:v.DataTypes.DATE,useAllResources:v.DataTypes.BOOLEAN,npmSecret:v.DataTypes.STRING,relatedBlocklets:{type:v.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(e){this.setDataValue("relatedBlocklets",JSON.stringify(e||{}))}}},{sequelize:me,paranoid:!0});z.hasMany(Te,{foreignKey:"projectId",as:"components"});const Ps=Cs,Ts=Os,$e=7*24*60*60*1e3,js=24*60*60*1e3,dt=async(e="")=>{const n=S.join(Ps,e);try{if(!(await w.promises.stat(n)).isDirectory())throw new Error(`${n} is not a directory`)}catch{await w.promises.mkdir(n,{recursive:!0})}return n},Ds=(e,n)=>{const t=ee.createHash("md5").update(n).digest("hex");return S.join(e,`${Ts}-${t}.json`)},ks=async(e="")=>{const n=await dt(e),t=Date.now();try{const s=await w.promises.readdir(n);await Promise.all(s.filter(o=>o.endsWith(".json")).map(async o=>{const a=S.join(n,o);try{const r=await w.promises.readFile(a,"utf-8"),u=JSON.parse(r);u.createdAt&&t-u.createdAt>$e&&await w.promises.unlink(a)}catch{try{const u=await w.promises.stat(a);t-u.mtimeMs>$e&&await w.promises.unlink(a)}catch{}}}))}catch(s){console.error(`Failed to cleanup cache in ${n}:`,s)}},_s=(()=>{const e=new Set;return setInterval(async()=>{await Promise.all(Array.from(e).map(s=>ks(s)))},js).unref(),s=>{e.add(s)}})();function Je(e,n){return n.subdir&&_s(n.subdir),pe.memoize(async(...s)=>{const o=await dt(n.subdir||""),a=n.keyGenerator?n.keyGenerator(...s):JSON.stringify(s),r=Ds(o,a);try{const u=await w.promises.readFile(r,"utf-8"),{value:c,createdAt:i}=JSON.parse(u);if(i&&Date.now()-i>$e)throw await w.promises.unlink(r).catch(()=>{}),new Error("Cache expired");return c}catch{const c=await e(...s),i=JSON.stringify({value:c,createdAt:Date.now()});return w.promises.writeFile(r,i,"utf-8").catch(d=>{console.error("Failed to write fs cache:",d)}),c}},{keyGenerator:n.keyGenerator,lruOptions:n.lruOptions})}const vs=async(e,{componentId:n})=>{const t=`@tailwind components;
|
|
2
|
-
@tailwind utilities;
|
|
3
|
-
`,s=`.CustomComponent_${n}`;return(await us.default([fs.default({content:[{raw:e,extension:"tsx"}]}),ds.default({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),a=>{a.walkRules(r=>{r.selectors=r.selectors.map(u=>u.replace(/\.(.+)/g,`${s}.$1,${s} .$1`))})}]).process(t)).css},Rs=async(e,{componentId:n})=>{const t=await vs(e,{componentId:n});return`export const __PagesKit_CSS__ = ${JSON.stringify(t)};
|
|
4
|
-
|
|
5
|
-
${e}
|
|
6
|
-
`},et=Je(async(e,n)=>{let t=q.default.transpileModule(e,{compilerOptions:{jsx:q.default.JsxEmit.React,target:q.default.ScriptTarget.ES2016,module:q.default.ModuleKind.ESNext},transformers:{before:[rt.createBuiltinModuleTransformer(q.default)]}}).outputText;if(n.tailwind&&(t=await Rs(t,{componentId:n.componentId})),n.module===ye.PreloadComponentScriptModule.ESM)return t;const s=q.default.transpileModule(t,{compilerOptions:{jsx:q.default.JsxEmit.React,target:q.default.ScriptTarget.ES2016,module:q.default.ModuleKind.CommonJS,moduleResolution:q.default.ModuleResolutionKind.Node16}}).outputText;return n.module===ye.PreloadComponentScriptModule.CJS?s:Ls(n.moduleName,s)},{keyGenerator:(e,n)=>{const t=ee.createHash("md5").update(e).digest("hex"),s={...n,componentId:n.componentId,module:n.module,...n.module!==ye.PreloadComponentScriptModule.ESM?{moduleName:n.moduleName}:{},tailwind:n.tailwind};return JSON.stringify(["transpileModule",t,s])},lruOptions:{max:100,ttl:1e3*60*60*24*7},subdir:"transpileModule"}),xs=async(e,n)=>{var r,u;const s=(u=(r=(await ps.build({entryPoints:["index.tsx"],external:Object.keys(Nt.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(c){let i=null;c.onResolve({filter:/.*/},d=>d.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:d.path==="./component"?{path:"component.tsx",namespace:"vfs"}:null),c.onLoad({filter:/.*/,namespace:"vfs"},async d=>{var E;if(d.path==="index.tsx")return{contents:`export { ${n} } from './component'`,loader:"tsx"};if(d.path==="component.tsx")return{contents:e,loader:"tsx"};if(rt.isRelativeModule(d.path)){const f=d.path.split("/").pop();if(i||(i=await ke({ensureLoaded:!1})),(E=i==null?void 0:i.chunks)!=null&&E[f])try{const p=w.readFileSync(i.chunks[f],"utf-8");return y.info("get chunk from local file system",f),{contents:p,loader:"tsx"}}catch{}}return null})}}]})).outputFiles)==null?void 0:r[0])==null?void 0:u.contents;if(!s)throw new Error("Failed to build server code");const o=Buffer.from(s).toString();return q.default.transpileModule(o,{compilerOptions:{module:q.default.ModuleKind.ESNext,target:q.default.ScriptTarget.ES2020}}).outputText},pt=Je(async(e,n)=>{const t=await xs(e,n);return new RegExp(`export\\s+\\{[^}]*(?:\\w+\\s+as\\s+${n}\\b|\\b${n}\\b)[^}]*\\}`,"m").test(t)?t:void 0},{keyGenerator:(e,n)=>{const t=ee.createHash("md5").update(e).digest("hex");return JSON.stringify(["extractExportValueSchema",t,n])},lruOptions:{max:100,ttl:1e3*60*60*24*7},subdir:"extractExportValueSchema"}),Ls=(e,n)=>`// 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
|
-
${n}
|
|
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
|
-
`,ce=new Pe.LRUCache({max:100}),ut=60*60,Ue=60;function ft(e){y.info("clear preload components cache",{cacheKey:e}),ce.delete(e)}function mt(e){for(const n of ce.keys())n.includes(e)&&(y.info("clear preload components cache",{cacheKey:n}),ft(n))}function ht({mode:e,instanceId:n,componentId:t,locale:s}){return["getPreloadComponents",e,n,t,s].join("-")}async function Ns({mode:e,req:n,state:t,locale:s,instances:o,module:a}){const{supportedLocales:r,config:{defaultLocale:u}}=t;if(!u)return null;const c=(await Promise.all(o.map(async p=>{try{const l=ht({mode:e,instanceId:p.id,componentId:p.componentId,locale:s});if(e!=="draft"&&p.useCache&&ce.has(l))return y.info(`get preload component from cache: ${l}`),ce.get(l);const m=ue({state:t,componentId:p.componentId});if(!m)return null;const b=await gt({req:n,state:t,componentId:m.id,locale:s,defaultLocale:u,properties:p.properties});if(!b)return null;const _={instanceId:p.id,preload:b};if(e!=="draft"&&p.useCache){let T=ut;p.cacheDuration&&(T=p.cacheDuration),y.info(`set preload component to cache(${T}s): ${l}`),ce.set(l,_,{ttl:T*1e3})}return _}catch(l){return y.error("get preload component error",{instanceId:p.id,componentId:p.componentId},{error:l}),null}}))).filter(p=>!!p),i=Object.values(c.reduce((p,l)=>({...p,...l.preload.components}),{}));async function d(){const p=await Promise.all(i.map(async l=>{const m=de.componentUMDName({componentId:l.component.id}),b=a===ye.PreloadComponentScriptModule.ESM?{module:a,script:await et(l.script,{componentId:l.component.id,module:a,tailwind:e!=="draft"})}:{module:a,script:await et(l.script,{componentId:l.component.id,module:a,moduleName:m,tailwind:e!=="draft"}),moduleName:m};return[l.component.id,{component:l.component,script:b}]}));return Object.fromEntries(p)}const E=await d();return{config:{defaultLocale:u,supportedLocales:r},components:E,instances:c.map(p=>({id:p.instanceId,componentId:p.preload.component.id,locales:{[p.preload.locale]:{props:p.preload.props}}}))}}async function gt({req:e,state:n,componentId:t,locale:s,defaultLocale:o,properties:a}){const{supportedLocales:r}=n,u=ue({state:n,componentId:t});if(!u)return null;const c=r.some(d=>d.locale===s)?s:o;if(!c)return null;const i=await yt({req:e,state:n,componentId:t,locale:c,defaultLocale:o,properties:a});return i?{component:u,...i}:null}const Ms=20;async function yt({req:e,depth:n=0,state:t,componentId:s,locale:o,defaultLocale:a,properties:r}){if(n>Ms)throw new RangeError("max component depth exceeded");const u=$s({state:t,componentId:s,properties:r,locale:o});if(!u)return null;const{props:c}=u,i={locale:o||a,components:{[u.component.id]:{component:u.component,script:u.script}},props:{...c}};try{const d=await Fs({...u,req:e});d!=null&&d.props&&Object.assign(i.props,d.props)}catch(d){y.error("preload data at server side error",{componentId:s,name:u.component.name},{error:d})}return await Promise.all(Object.entries(c).map(async([d,E])=>{if((E==null?void 0:E.type)===de.RenderNestedComponent){const f=await yt({req:e,depth:n+1,state:t,componentId:E.componentId,locale:o,defaultLocale:a,properties:E.properties});f&&(Object.assign(i.components,f.components),Object.assign(i.props,{[d]:{type:de.RenderNestedComponent,componentId:E.componentId,props:f.props}}))}})),i}function $s({state:e,componentId:n,locale:t,properties:s}){const o=ue({state:e,componentId:n});if(!o)return null;const a=de.mergeComponent({componentId:n,getComponent:r=>ue({state:e,componentId:r}),locale:t,defaultLocale:e.config.defaultLocale,properties:s});return a?{component:o,script:a.script,props:{locale:t,...a.props}}:null}function ue({state:e,componentId:n}){var t,s,o;return((t=e.components[n])==null?void 0:t.data)??((o=(s=e.resources.components)==null?void 0:s[n])==null?void 0:o.component)}function Us({state:e,name:n}){var s,o;const t=n.toLowerCase();return((s=Object.values(e.components).find(a=>{var r;return((r=a.data.name)==null?void 0:r.toLowerCase())===t}))==null?void 0:s.data)??((o=e.resources.components&&Object.values(e.resources.components).find(a=>{var r;return((r=a.component.name)==null?void 0:r.toLowerCase())===t}))==null?void 0:o.component)}async function Fs({component:e,script:n,props:t,req:s}){if(!(n!=null&&n.includes("getServerSideProps")))return null;const o=await pt(n,"getServerSideProps");if(!o)return null;const a=o.match(/export\s*{\s*(\w+)\s+as\s+getServerSideProps\s*}/)||o.match(/export\s*{\s*getServerSideProps\s*}/),r=(a==null?void 0:a[1])||"getServerSideProps",u=new Promise(i=>{setTimeout(()=>{i({})},Ue*1e3)});return await Promise.race([u,pe.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 ${r}(componentProps);
|
|
44
|
-
} finally {
|
|
45
|
-
// 清理全局状态
|
|
46
|
-
if (originalLocation) globalThis.location = originalLocation;
|
|
47
|
-
if (originalFetch) globalThis.fetch = originalFetch;
|
|
48
|
-
}
|
|
49
|
-
}`,filename:`${e.name||e.id}.js`,moduleLoader:i=>{if(i==="@blocklet/pages-kit/builtin/utils")return`const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
|
|
50
|
-
export { joinURL, withQuery, getQuery, getComponentMountPoint }
|
|
51
|
-
`;if(i==="@blocklet/pages-kit/builtin/dayjs")return pe.BuiltinModules.dayjs},global:{console:{log:(...i)=>{y.info(...i)},warn:(...i)=>{y.warn(...i)},error:(...i)=>{y.error(...i)}},getComponentMountPoint:vt.getComponentMountPoint,joinURL:B.joinURL,withQuery:B.withQuery,getQuery:B.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:B.joinURL(B.withHttps(s.hostname),s.originalUrl)},fetch:(i,{...d}={})=>{const E=typeof i=="string"&&i.startsWith("/")?B.joinURL(O.default.env.appUrl,i):i;if(typeof E=="string"&&B.parseURL(E).host===B.parseURL(O.default.env.appUrl).host){const f=s.get("cookie");if(f){const p=new at.Headers(d.headers);p.set("cookie",f),d.headers=p}}return is.default(E,{...d,timeout:Ue*1e3}).then(f=>({ok:f.ok,status:f.status,statusText:f.statusText,headers:Object.fromEntries(f.headers.entries()),json:()=>f.json()}))},props:t}]})])}const St=pe.memoize(async(e,n,t)=>{if(!(e!=null&&e.includes(n)))return null;const s=await pt(e,n);if(s)try{return await pe.Sandbox.callFunction({code:`
|
|
52
|
-
${s}
|
|
53
|
-
|
|
54
|
-
export function get${n}SchemaWrapper() {
|
|
55
|
-
return ${n};
|
|
56
|
-
}
|
|
57
|
-
`,filename:`${t}.js`,functionName:`get${n}SchemaWrapper`})}catch(o){return y.error(`获取 ${n} 失败`,{componentId:t,error:o}),null}return null},{keyGenerator:(e,n,t)=>{const s=ee.createHash("md5").update(e).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",s,n,t])},lruOptions:{max:100,ttl:1e3*60*60}}),qs="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",Fe="page",qe="trigger-reload-project-resource",Ke=qs,Bs="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM";function be(e){e.observeDeep(n=>{n.some(t=>t.changes.keys.has("updatedAt")||t.changes.keys.has("publishedAt"))||e.set("updatedAt",new Date().toISOString())})}function Et(){return w.mkdtempSync(S.join(O.default.env.dataDir,"tmp-"))}function Ie(e,n,t=[]){return Array.isArray(e)?e.flatMap((s,o)=>Ie(s,n,[...t,o])):typeof e=="object"?e===null?[]:Object.entries(e).flatMap(([s,o])=>Ie(o,n,[...t,s])):n(e)?[t]:[]}function H(e){return e.filter(n=>n!=null)}function Hs(e){e.pages&&Object.keys(e.pages).forEach(t=>{const s=te.getYjsValue(e.pages[t]);s&&s instanceof K.Map&&be(s)});const n=te.getYjsValue(e.pages);n&&n instanceof K.Map&&n.observe(t=>{t.changes.keys.forEach((s,o)=>{if(s.action==="add"){const a=te.getYjsValue(e.pages[o]);a&&a instanceof K.Map&&be(a)}})})}function Gs(e){e.routes&&Object.keys(e.routes).forEach(t=>{var o;const s=te.getYjsValue((o=e.routes)==null?void 0:o[t]);s&&s instanceof K.Map&&be(s)});const n=te.getYjsValue(e.routes);n&&n instanceof K.Map&&n.observe(t=>{t.changes.keys.forEach((s,o)=>{var a;if(s.action==="add"){const r=te.getYjsValue((a=e.routes)==null?void 0:a[o]);r&&r instanceof K.Map&&be(r)}})})}function Vs(e,n){var t;for(const s of n||Object.keys(e.routes||{})){let o=s,a=[];if(s.includes("-")){const[r,...u]=s.split("-");o=r,a=u||[]}if(((t=e.routes)==null?void 0:t[o])!==void 0){e.routes[o].publishedAt=new Date().toISOString();const r=e.routes[o];if(!r||!r.params||r.params.length===0)continue;if(s.includes("-")&&a.length>0){const u=we.getRouteMetaDataByOptionIds(a,r);u&&(u.publishedAt=new Date().toISOString())}if(!n){const u=we.generateParamCombinations({basePath:r.path,params:r.params,routeId:r.id,paramsOptions:r.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const c of u)c.routeMetaData??(c.routeMetaData={}),c.routeMetaData.publishedAt=new Date().toISOString()}}}}function Le({page:e,route:n,state:t,routeId:s,routePathInfo:o}){var r,u,c,i,d,E,f,p,l;y.info(`Executing datasource data assembly, routeId: ${s}, routePathInfo: ${JSON.stringify(o)}`);const a={...Gt.cloneDeep(e),id:s,slug:(o==null?void 0:o.path)??n.path,createdAt:n.createdAt,updatedAt:((r=o==null?void 0:o.routeMetaData)==null?void 0:r.updatedAt)??n.updatedAt,publishedAt:((u=o==null?void 0:o.routeMetaData)==null?void 0:u.publishedAt)??n.publishedAt,isPublic:(((c=o==null?void 0:o.routeMetaData)==null?void 0:c.isPublic)??n.isPublic)&&n.isPublic};for(const m of t.supportedLocales){if(n.dataSource){let b=n.id;o&&(b=o.paramOptionIds.join("-"));const _=((E=(d=(i=n.dataSource.pathDataMappings)==null?void 0:i[b])==null?void 0:d.dataCache)==null?void 0:E[m.locale])??((l=(p=(f=n.dataSource.pathDataMappings)==null?void 0:f[b])==null?void 0:p.dataCache)==null?void 0:l[t.config.defaultLocale||"en"]);if(!_)continue;Ht.setPageDataSource(a,t,m.locale,_)}o&&o.routeMetaData&&(o.routeMetaData.publishedAt=new Date().toISOString())}return a}const Ce=new Pe.LRUCache({max:20,ttl:10*60*1e3});function Js(e,n=[]){let t=0;const s=Array.from(Ce.keys()),o=[];for(const a of e){o.push(`page-html:prod:${a}:lang-path=none`);for(const r of n)o.push(`page-html:prod:/${r}${a}:lang-path=${r}`)}for(const a of s){const r=a.split(":lang-path=")[0]||"";for(const u of o){const i=(u.split(":lang-path=")[0]||"").replace(/\/:[^/]+/g,"");if(r.startsWith(i)){Ce.delete(a),t++,y.info(`[Cache CLEAR] key: ${a}`);break}}}return y.info(`[Cache CLEAR] cleared ${t} entries for patterns:`,o),t}function Ks({projectId:e,projectSlug:n,supportedLocales:t=[]}){let s=0;const o=Array.from(Ce.keys()),a=[];a.push(`page-html:prod:/${e}`),n&&n!==e&&a.push(`page-html:prod:/${n}`);for(const r of t)a.push(`page-html:prod:/${r}/${e}`),n&&n!==e&&(n!=="/"?a.push(`page-html:prod:/${r}/${n}`):a.push(`page-html:prod:/${r}`));for(const r of o)for(const u of a)if(r.startsWith(u)){Ce.delete(r),s++,y.info(`[Cache CLEAR PROJECT] key: ${r}`);break}return y.info(`[Cache CLEAR PROJECT] cleared ${s} entries for project ${e}${n?` (slug: ${n})`:""}`),s}const{uploadToMediaKit:zs}=require("@blocklet/uploader-server"),Se=ts.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),ze=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,le=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,tt=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Ys=1e4,Ws=3e4,he=0,Ne=1,Qs=0,Xs=1,Be=O.default,ne=S.join(process.env.BLOCKLET_DATA_DIR,"site-state"),Zs=["production","draft"],en=["production"];function Oe(e){return(e==null?void 0:e.replace(/\//g,"|"))||""}function tn(){var t;const e=Be.env.languages.map(s=>({locale:s.code,name:s.name})),n=(t=e[0])==null?void 0:t.locale;return{pageIds:[],pages:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{},components:{},supportedLocales:e,config:{defaultLocale:n},resources:{}}}const D=class D extends K.Doc{constructor(t){super();R(this,"syncedStore");R(this,"conns",new Map);R(this,"awareness");R(this,"releaseTimer");R(this,"awarenessChangeHandler",({added:t,updated:s,removed:o},a)=>{const r=t.concat(s,o);if(a!==null){const i=this.conns.get(a);i&&(t.forEach(d=>{i.add(d)}),o.forEach(d=>{i.delete(d)}))}const u=x.createEncoder();x.writeVarUint(u,Ne),x.writeVarUint8Array(u,ie.encodeAwarenessUpdate(this.awareness,r));const c=x.toUint8Array(u);this.conns.forEach((i,d)=>this.send(d,c))});R(this,"updateHandler",t=>{const s=x.createEncoder();x.writeVarUint(s,he),Re.writeUpdate(s,t);const o=x.toUint8Array(s);this.conns.forEach((a,r)=>this.send(r,o))});R(this,"ensureDataStructure",()=>{var c;const{supportedLocales:t,pages:s,pageIds:o,config:a,routes:r,routeIds:u}=this.syncedStore;{const i=new Set(Object.keys(s));let d=0;for(;d<o.length;){const E=o[d];i.has(E)?(i.delete(E),d++):o.splice(d,1)}}{const i=new Set(Object.keys(r));let d=0;for(;d<u.length;){const E=u[d];i.has(E)?(i.delete(E),d++):u.splice(d,1)}}t.splice(0,t.length),t.push(...Be.env.languages.map(i=>({locale:i.code,name:i.name}))),a.defaultLocale=(c=t[0])==null?void 0:c.locale;{let i=0;const d=new Set;for(;i<t.length;){const{locale:E}=t[i];d.has(E)?t.splice(i,1):(i++,d.add(E))}}});R(this,"send",(t,s)=>{t.readyState!==Qs&&t.readyState!==Xs&&this.closeConn(t);try{t.send(s,o=>{o&&this.closeConn(t)})}catch{this.closeConn(t)}});R(this,"closeConn",t=>{if(t.removeAllListeners(),this.conns.has(t)){const s=this.conns.get(t);this.conns.delete(t),s&&ie.removeAwarenessStates(this.awareness,Array.from(s),null)}t.close(),this.checkAndScheduleRelease()});R(this,"autoSave",ct.default(()=>{w.mkdirSync(S.dirname(this.draftYjsFilePath),{recursive:!0}),w.writeFileSync(this.draftYjsFilePath,K.encodeStateAsUpdate(this))},Ys));R(this,"save",({flush:t=!1}={})=>{this.autoSave(),t&&this.autoSave.flush()});R(this,"publish",async({mode:t,routes:s})=>{const o=await this.getState("draft"),a=await this.getState("production");await He(o,a,{routes:s,mergeMode:"replace",deleteRoutes:!0,publishMode:t}),a.config.publishedAt=new Date().getTime(),Vs(this.syncedStore,s),await this.setState(t,a),await this.clearPageCacheForRoutes(s,a)});R(this,"mergeState",async(t,s)=>{var u,c,i;const o=JSON.parse(JSON.stringify(s));(u=t.config).fontFamily??(u.fontFamily={});const a=(c=o.config)==null?void 0:c.fontFamily,r=(i=t.config)==null?void 0:i.fontFamily;t.config.fontFamily.title=(a==null?void 0:a.title)||(r==null?void 0:r.title),t.config.fontFamily.description=(a==null?void 0:a.description)||(r==null?void 0:r.description),await new Promise((d,E)=>{this.transact(async()=>{try{const f=await He(t,s);d(f)}catch(f){E(f)}})})});R(this,"clearPageCacheForRoutes",async(t,s)=>{const o=S.basename(this.options.path),a=await z.findByPk(o),r=(a==null?void 0:a.slug)||o;if(y.info(`[SiteState] clearing page cache for project ${o}, routes:`,t||[]),!t||t.length===0){Ks({projectId:o,projectSlug:r,supportedLocales:s.supportedLocales.map(d=>d.locale)});return}const u=s.supportedLocales.map(d=>d.locale),c=[],i=t.filter(d=>s.pages[d]);for(const d of i){const f=s.pages[d].slug;r&&r!==o&&(r==="/"?c.push(f):c.push(`/${r}${f}`)),c.push(`/${o}${f}`)}if(y.info(`[SiteState] clearing page cache for project ${o}, pathPatterns:`,c),c.length>0){const d=Js(c,u);y.info(`[SiteState] cleared ${d} page cache entries for project ${o}, routes:`,t)}});R(this,"addConnection",t=>{if(this.conns.has(t))return;this.cancelRelease(),t.binaryType="arraybuffer",this.conns.set(t,new Set),t.on("message",a=>this.messageListener(t,new Uint8Array(a)));let s=!0;const o=setInterval(()=>{if(!s)this.conns.has(t)&&this.closeConn(t),clearInterval(o);else if(this.conns.has(t)){s=!1;try{t.ping()}catch{this.closeConn(t),clearInterval(o)}}},Ws);t.on("close",()=>{this.closeConn(t),clearInterval(o)}),t.on("pong",()=>{s=!0});{const a=x.createEncoder();x.writeVarUint(a,he),Re.writeSyncStep1(a,this),this.send(t,x.toUint8Array(a));const r=this.awareness.getStates();if(r.size>0){const u=x.createEncoder();x.writeVarUint(u,Ne),x.writeVarUint8Array(u,ie.encodeAwarenessUpdate(this.awareness,Array.from(r.keys()))),this.send(t,x.toUint8Array(u))}}});R(this,"messageListener",(t,s)=>{try{const o=x.createEncoder(),a=xe.createDecoder(s),r=xe.readVarUint(a);switch(r){case he:x.writeVarUint(o,he),Re.readSyncMessage(a,o,this,null),x.length(o)>1&&(this.ensureDataStructure(),this.send(t,x.toUint8Array(o)));break;case Ne:{ie.applyAwarenessUpdate(this.awareness,xe.readVarUint8Array(a),t);break}default:y.warn(`Unsupported messageType ${r}`)}}catch(o){y.error(o)}this.save()});this.options=t,w.existsSync(this.draftYjsFilePath)&&K.applyUpdate(this,w.readFileSync(this.draftYjsFilePath)),this.syncedStore=Vt.reactive(te.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new ie.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(t){if(!t)throw new Error("Should provide project context");try{const s=S.join(ne,t),o=S.join(ne,`@del-${t}`);w.renameSync(s,o)}catch(s){y.error("Failed to safe delete project state dir:",s)}}static get projectIds(){return Me.globSync("*/",{cwd:ne,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(t=>D.shared(t))}static shared(t){if(!t)throw new Error("Should provide project context");let s=D.sharedInstances[t];return s||(s=new D({path:S.join(ne,t)}),D.sharedInstances[t]=s,jt({projectId:t,pages:je,components:De}),s)}static async getProductionState(t){var o,a;let s=D.productionStates.get(t);if(!s){const r=S.join(ne,t,"production");if(s=await Ye(r,{includeResources:!0})??tn(),!((o=s==null?void 0:s.config)!=null&&o.defaultLocale)){s.config??(s.config={});const u=Be.env.languages.map(c=>({locale:c.code,name:c.name}));s.config.defaultLocale=(a=u[0])==null?void 0:a.locale}D.productionStates.set(t,s)}return{...s,resources:await ke().then(async r=>{var E,f;const{pages:u,components:c}=hs.default(r,"pages","components");let i=c;const d=await z.findByPk(t);if(d!=null&&d.useAllResources)i=c;else{const l=(await Te.findAll({where:{projectId:t}})).map(b=>b.componentId);i=Object.fromEntries(Object.entries(c||{}).filter(([b])=>l.includes(b)))}return Object.keys(((E=s==null?void 0:s.resources)==null?void 0:E.components)||{}).length>0&&(i={...i,...(f=s==null?void 0:s.resources)==null?void 0:f.components}),{pages:u,components:i}}).catch(()=>({}))}}destroy(){this.cancelRelease(),this.save({flush:!0}),this.conns.forEach((s,o)=>this.closeConn(o)),this.awareness.destroy();const t=S.basename(this.options.path);delete D.sharedInstances[t],super.destroy()}initObserver(){Hs(this.syncedStore),Gs(this.syncedStore)}get draftYjsFilePath(){return S.join(this.options.path,"draft.yjs")}static async getStateByProjectId(t,s){if(s==="draft"){const o=D.shared(t);return JSON.parse(JSON.stringify(o.syncedStore))}return D.getProductionState(t)}async getState(t){if(t==="draft")return JSON.parse(JSON.stringify(this.syncedStore));const s=S.basename(this.options.path);return D.getProductionState(s)}async setState(t,s){const o=await Ct(s,{exportAssets:!1,includeResources:!0}),a=this.getPublishDir(t);if(w.mkdirSync(S.dirname(a),{recursive:!0}),w.rmSync(a,{force:!0,recursive:!0}),w.renameSync(o,a),t==="production"){const r=S.basename(this.options.path);D.productionStates.set(r,s)}}getPublishDir(t){return S.join(this.options.path,t)}checkAndScheduleRelease(){this.conns.size===0&&this.scheduleRelease()}scheduleRelease(){this.cancelRelease();const t=S.basename(this.options.path);this.releaseTimer=setTimeout(()=>{y.info(`[SiteState] releasing instance due to no active connections: ${t}`),this.conns.size===0&&(this.releaseTimer=void 0,this.destroy())},D.RELEASE_DELAY),y.info(`[SiteState] scheduled release for project ${t} in ${D.RELEASE_DELAY/1e3}s`)}cancelRelease(){if(this.releaseTimer){clearTimeout(this.releaseTimer),this.releaseTimer=void 0;const t=S.basename(this.options.path);y.info(`[SiteState] cancelled scheduled release for project ${t}`)}}static async pageUrlMap(t,s){var r,u;let{projectIds:o}=this;s&&(o=[s]);const a={};for(const c of o){const i=await z.findByPk(c);if(!i)continue;const d=await D.getStateByProjectId(c,t),E=i.slug||c,f=gs.default(O.default.env.languages.map(l=>l.code),d.supportedLocales.map(l=>l.locale)),p=(l,m)=>{E&&(a[B.joinURL("/",E,l)]={...m,shouldRedirect:!0,mainPage:!0}),a[B.joinURL("/",c,l)]={...m,shouldRedirect:!0,mainPage:!0};for(const b of f){const _={...m,locale:b};a[B.joinURL("/",b,c,l)]=_,E&&(a[B.joinURL("/",b,E,l)]=_)}};if(t==="draft")for(const l of d.routeIds||[]){const m=(r=d==null?void 0:d.routes)==null?void 0:r[l];if(!m)continue;if(m.params&&m.params.length>0){const T=we.generateParamCombinations({basePath:m.path,params:m.params,routeId:m.id,paramsOptions:m.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const $ of T){const Q=$.path,se={projectId:c,projectSlug:E,pageSlug:Q,pageId:m.displayTemplateId||"",routeId:l,defaultLocale:f==null?void 0:f[0],locales:f,publishedAt:d.config.publishedAt,isPublic:m.isPublic&&((u=$==null?void 0:$.routeMetaData)==null?void 0:u.isPublic)};p(Q,se)}}const b=m.path,_={projectId:c,projectSlug:E,pageSlug:b,pageId:m.displayTemplateId||"",routeId:l,defaultLocale:f==null?void 0:f[0],locales:f,publishedAt:d.config.publishedAt,isPublic:m.isPublic};p(b,_)}for(const l of d.pageIds){const m=d.pages[l];if(!m||t==="production"&&!m.isPublic)continue;const b=m.slug,_=i.slug||c,T={projectId:c,projectSlug:_,pageSlug:b,pageId:l,defaultLocale:f==null?void 0:f[0],locales:f,publishedAt:d.config.publishedAt,isPublic:m.isPublic,templateConfig:m.templateConfig};p(b,T)}}return a}getDocumentSize(){return K.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const t=[];for(const[s,o]of Object.entries(D.sharedInstances)){const a=o.getDocumentSize();t.push({projectId:s,sizeInBytes:a,sizeInMB:`${(a/(1024*1024)).toFixed(2)} MB`,activeConnections:o.conns.size})}return t}static startPeriodicCheck(){this.periodicCheckTimer||(this.periodicCheckTimer=setInterval(()=>{this.performPeriodicCheck()},this.PERIODIC_CHECK_INTERVAL),y.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,y.info("[SiteState] periodic check stopped"))}static performPeriodicCheck(){const t=Object.keys(D.sharedInstances).length,s=[],o=[];for(const[a,r]of Object.entries(D.sharedInstances))r.conns.size===0?s.push({projectId:a,instance:r}):o.push({projectId:a,connections:r.conns.size});if(y.info(`[SiteState] periodic check summary: total instances: ${t}, with connections: ${o.length}, without connections: ${s.length}`),s.length>0){y.info(`[SiteState] releasing ${s.length} instances without connections:`,s.map(r=>r.projectId));let a=0;for(const{projectId:r,instance:u}of s)try{y.info(`[SiteState] releasing instance due to periodic check: ${r}`),u.destroy(),a++}catch(c){y.error(`[SiteState] failed to release instance ${r} during periodic check:`,c)}y.info(`[SiteState] periodic check completed: ${a}/${s.length} instances released successfully`)}else t>0?y.debug("[SiteState] periodic check: all instances have active connections"):y.debug("[SiteState] periodic check: no instances exist")}};R(D,"PRODUCTION_CACHE_TTL",7*24*60*60*1e3),R(D,"RELEASE_DELAY",5*60*1e3),R(D,"PERIODIC_CHECK_INTERVAL",2*60*60*1e3),R(D,"sharedInstances",{}),R(D,"productionStates",new Pe.LRUCache({max:100,ttl:D.PRODUCTION_CACHE_TTL})),R(D,"periodicCheckTimer");let Y=D;async function sn(e,n,t){if(!e||!w.existsSync(e)||!w.lstatSync(e).isFile())return null;let s=t[e];return s||(s=(async()=>{var o;try{const a=(o=await zs({filePath:e,fileName:n}))==null?void 0:o.data;return a==null?void 0:a.filename}catch(a){return y.error(`Failed to upload asset ${e}:`,a),null}})(),t[e]=s),s}const wt=async(e,n)=>{const t=S.basename(e),s=await Ge.call({name:Ke,path:B.joinURL("/uploads",t),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const o=w.createWriteStream(n);await ns.pipeline(s.data,o)}else throw new Error(`download asset failed ${s.status}`)},bt=async(e,n)=>{await Promise.all(e.map(async t=>{try{await wt(t,S.join(n,S.basename(t)))}catch(s){y.error(`Failed to export assets: ${t}, ${s}`)}}))};function It(e){return ze.test(e)?[e]:le.test(e)?(tt.lastIndex=0,Array.from(e.matchAll(tt)).map(t=>t[1]).filter(t=>!!t)):[]}async function ge(e,n,t){const{getFilename:s,exportAssets:o}=t,a=S.join(n,s(e));if(w.mkdirSync(S.dirname(a),{recursive:!0}),w.writeFileSync(a,oe.stringify(e)),o){const u=Ie(e,c=>typeof c=="string"&&(ze.test(c)||le.test(c))).map(c=>{const i=Ve.default(e,c);return It(i)}).flat().filter(Boolean);await bt(u,S.dirname(a))}}const st=new Pe.LRUCache({max:20,ttl:30*24*60*60*1e3});async function nt(e,n,t){var u;const s=Ie(e,c=>typeof c=="string"&&(ze.test(c)||le.test(c))),o=ys.default(2),a=s.map(c=>o(async()=>{try{const i=Ve.default(e,c),d=It(i);for(const E of d){const f=S.basename(E),p=t.getFilePath(E,c),l=p?`${p}:${f}`:f,m=st.get(l);if(m){le.test(i)||Xe.default(e,c,m);return}const b=await sn(p,f,n);b&&(le.test(i)||Xe.default(e,c,b),st.set(l,b))}}catch(i){y.error(`Failed to process upload for path ${c.join(".")}:`,i.message||i.reason)}})),r=await Promise.allSettled(a);(u=t.onFinish)==null||u.call(t,r)}async function Ct(e,{exportAssets:n,pageIds:t="all",componentIds:s="all",rawConfig:o,includeResources:a=!1,routeIds:r="all"}={}){var re,I,g,A,k,X,C,N,G,V,U,W;const u=t==="all"?e.pageIds:t,c=de.getComponentDependencies({state:e,pageIds:u,componentIds:s==="all"?Object.keys(e.components):s}),i=r==="all"?e.routeIds:r,d=h=>{var P;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,sections:h!=null&&h.sectionIds?H((P=h==null?void 0:h.sectionIds)==null?void 0:P.map(j=>{var M;const F=(M=h.sections)==null?void 0:M[j];return F&&d(F)})):void 0}},E=(h,P)=>{var j;return{id:h.id,createdAt:h.createdAt,updatedAt:h.updatedAt,publishedAt:h.publishedAt,isPublic:h.isPublic??!0,templateConfig:h.templateConfig,meta:((j=h.locales)==null?void 0:j[P])??{},sections:H(h.sectionIds.map(F=>{const M=h.sections[F];return M&&d(M)})),dataSource:Object.fromEntries(Object.entries(h.dataSource||{}).map(([F,M])=>[F,(M==null?void 0:M[P])??{}]))}},f=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}),p=H(i.map(h=>{const P=e.routes[h];return P&&f(P)})),l=H(e.supportedLocales.map(h=>h.locale).flatMap(h=>u.map(P=>{const j=e.pages[P];return j&&{locale:h,slug:j.slug,page:E(j,h)}}))),m=Et(),b=S.join(m,"pages");w.mkdirSync(b,{recursive:!0});const _=S.join(m,"components");w.mkdirSync(_,{recursive:!0});const T=S.join(m,"routes");w.mkdirSync(T,{recursive:!0});for(const{locale:h,slug:P,page:j}of l)await ge(j,b,{getFilename:()=>`${Oe(P)||"index"}.${h}.yml`,exportAssets:n});for(const h of p)await ge(h,T,{getFilename:()=>`${Oe(h.path)||"index"}.yml`,exportAssets:n});for(const h of c){const P=(re=e.components[h])==null?void 0:re.data;P&&await ge(P,_,{getFilename:j=>`${j.name||"unnamed"}.${j.id}.yml`,exportAssets:n})}const $=S.join(m,".blocklet/pages/pages.config.yml");w.mkdirSync(S.dirname($),{recursive:!0});const Q={pages:H(u.map(h=>{const P=e.pages[h];return P&&{id:h,slug:P.slug}})),routes:H(i.map(h=>{const P=e.routes[h];return P&&{id:h,path:P.path}})),components:H(c.map(h=>{var j;const P=(j=e.components[h])==null?void 0:j.data;return P&&{id:h,name:P.name}})),...a?{resources:{components:H(Object.keys(((I=e.resources)==null?void 0:I.components)||{}).filter(h=>c.includes(h)).map(h=>{var P,j,F,M;return{id:h,name:(M=(F=(j=(P=e.resources)==null?void 0:P.components)==null?void 0:j[h])==null?void 0:F.component)==null?void 0:M.name}}))}}:{},supportedLocales:e.supportedLocales,config:e.config};w.writeFileSync($,oe.stringify(Q));const se=S.join(m,"config.source.json");if(o&&w.writeFileSync(se,JSON.stringify(o)),a){const h=S.join(m,"resources"),P=S.join(h,"components");w.mkdirSync(P,{recursive:!0});for(const M of Object.keys(((g=e==null?void 0:e.resources)==null?void 0:g.components)??{}).filter(J=>c.includes(J))){const J=(X=(k=(A=e.resources)==null?void 0:A.components)==null?void 0:k[M])==null?void 0:X.component;J&&await ge(J,P,{getFilename:Z=>`${Z.name||"unnamed"}.${Z.id}.yml`,exportAssets:n})}const j=S.join(m,"chunks");w.mkdirSync(j,{recursive:!0});const{chunks:F}=await ke();for(const M of Object.keys(((C=e==null?void 0:e.resources)==null?void 0:C.components)??{}).filter(J=>c.includes(J))){const J=(V=(G=(N=e.resources)==null?void 0:N.components)==null?void 0:G[M])==null?void 0:V.component;if(J&&((U=J.renderer)==null?void 0:U.type)==="react-component"){const Z=((W=J.renderer)==null?void 0:W.chunks)??[];if((Z==null?void 0:Z.length)>0)for(const _e of Z){const Qe=S.join(j,_e),ve=F==null?void 0:F[_e];try{ve&&w.existsSync(ve)&&!w.existsSync(Qe)&&w.copyFileSync(ve,Qe)}catch(Dt){y.error(`copy chunk ${_e} error`,Dt.message)}}}}}return m}async function Ye(e,{importAssets:n,includeResources:t}={}){var a,r,u,c;if(!w.existsSync(e))return null;let s,o=!1;try{w.lstatSync(e).isDirectory()?s=e:/\.(tgz|gz|tar)$/.test(e)&&(o=!0,s=Et(),await os.x({file:e,C:s}));const i=Me.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}).at(0),d=i&&S.join(S.dirname(i),"../../pages"),E=i&&S.join(S.dirname(i),"../../components"),f=i&&S.join(S.dirname(i),"../../chunks"),p=i&&S.join(S.dirname(i),"../../routes");if(!i)return null;const l=oe.parse(w.readFileSync(i).toString()),m=(I,g,A)=>{let k=S.join(I,`${g}${A?`.${A}`:""}.yml`);return(!w.existsSync(k)||!w.lstatSync(k).isFile())&&(k=S.join(I,g,`index${A?`.${A}`:""}.yml`),!w.existsSync(k)||!w.lstatSync(k))?null:oe.parse(w.readFileSync(k).toString())},b=(I,g)=>{try{const A=Me.globSync(`*.${g}.yml`,{cwd:I,absolute:!0})[0];return A?oe.parse(w.readFileSync(A).toString()):null}catch(A){y.error("parse component error",A)}return null},_=(I,g)=>{let A=S.join(I,`${g}.yml`);return(!w.existsSync(A)||!w.lstatSync(A).isFile())&&(A=S.join(I,g,"index.yml"),!w.existsSync(A)||!w.lstatSync(A))?null:oe.parse(w.readFileSync(A).toString())},T=H(l.pages.map(({slug:I})=>{var X;const g=H(l.supportedLocales.map(({locale:C})=>{const N=d?m(d,Oe(I),C):void 0;if(N)return{locale:C,page:N};const G=d?m(d,I,C):void 0;return G&&{locale:C,page:G}})),A=(X=g[0])==null?void 0:X.page;if(!A)return null;const k=A.sections.map(C=>{var U,W,h,P;const N=C.id||Se(),G=C.sections&&Object.keys(C.sections).length>0,V={};return G&&(V.sections=Object.fromEntries(((W=(U=C.sections)==null?void 0:U.map)==null?void 0:W.call(U,j=>[j.id,j]))??[])||{},V.sectionIds=((P=(h=C.sections)==null?void 0:h.map)==null?void 0:P.call(h,j=>j.id))??[]),{id:N,component:C.component,config:C.config,name:C.name,isTemplateSection:C.isTemplateSection??!1,templateDescription:C.templateDescription,llmConfig:C.llmConfig,visibility:C.visibility,...V}});return{id:A.id||Se(),createdAt:A.createdAt,updatedAt:A.updatedAt,publishedAt:A.publishedAt,isPublic:A.isPublic??!0,templateConfig:A.templateConfig,slug:I,sections:Object.fromEntries(k.map(C=>[C.id,C])),sectionIds:k.map(C=>C.id),locales:Object.fromEntries(g.map(({locale:C,page:N})=>[C,N.meta])),dataSource:A.dataSource?Object.fromEntries([...new Set(g.flatMap(({page:C})=>Object.keys(C.dataSource??{})))].map(C=>[C,Object.fromEntries(g.map(({locale:N,page:G})=>{var U;const V=(U=G.dataSource)==null?void 0:U[C];return[N,V||{}]}))])):Object.fromEntries([...new Set(g.flatMap(({page:C})=>C.sections.map(N=>N.id)))].map(C=>[C,Object.fromEntries(g.map(({locale:N,page:G})=>{var W;const V=(W=G.dataSource)==null?void 0:W[C];if(V)return[N,V];const U=G.sections.find(h=>h.id===C);return[N,(U==null?void 0:U.properties)||{}]}))]))}})),$=H(((a=l==null?void 0:l.routes)==null?void 0:a.map(({path:I})=>{const g=p?_(p,Oe(I)):void 0;return{...g,id:(g==null?void 0:g.id)||Se(),createdAt:(g==null?void 0:g.createdAt)??new Date().toISOString(),updatedAt:(g==null?void 0:g.updatedAt)??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:(g==null?void 0:g.path)??`/${g==null?void 0:g.id}`,params:g==null?void 0:g.params,handler:(g==null?void 0:g.handler)??"Pages Kit",isPublic:(g==null?void 0:g.isPublic)??!0,enabledGenerate:(g==null?void 0:g.enabledGenerate)??!1,displayTemplateId:(g==null?void 0:g.displayTemplateId)??void 0,dataSource:(g==null?void 0:g.dataSource)??{}}}))??[]),Q=E?H(((r=l.components)==null?void 0:r.map(({id:I})=>b(E,I)))??[]):[];if(n){const I=(...g)=>{y.info(`[${o?S.basename(e):S.basename(S.join(e,"../../../../"))}] importAssets:`,...g)};try{I("wait image-bin api ready"),await Ss.default({resources:[`${Ge.getComponentWebEndpoint(Es)}/api/sdk/uploads`],validateStatus:k=>k>=200&&k<=500}),I("image-bin api is ready");const g={},A={};I("start to upload assets"),await Promise.allSettled([nt(Q,g,{getFilePath:k=>E&&S.join(E,k),onFinish:k=>{I(`upload ${k.length} component assets`)}}),nt(T,A,{getFilePath:(k,X)=>{const C=Ve.default(T,X.slice(0,1));return d&&S.join(d,S.dirname(C.slug),k)},onFinish:k=>{I(`upload ${k.length} page assets`)}})]),I("upload assets done"),global.gc&&global.gc()}catch(g){I("Error during asset import:",g)}}const se={};if(t){const I=i&&S.join(S.dirname(i),"../../resources/components"),g=H(((c=(u=l.resources)==null?void 0:u.components)==null?void 0:c.map(({id:A})=>b(I,A)))??[]);g.length>0&&(se.components=Object.fromEntries(g.map((A,k)=>[A.id,{index:k,component:A}])))}const re={};if(f&&w.existsSync(f)){const I=w.readdirSync(f);for(const g of I)re[g]=S.join(f,g)}return{supportedLocales:l.supportedLocales,pageIds:T.map(I=>I.id),components:Object.fromEntries(Q.map((I,g)=>[I.id,{index:g,data:I}])),pages:Object.fromEntries(T.map(I=>[I.id,I])),config:l.config||{},resources:se,chunks:re,routeIds:$.map(I=>I.id),routes:Object.fromEntries($.map(I=>[I.id,I])),dataSourceIds:[],dataSources:{}}}finally{o&&s&&w.rmSync(s,{force:!0,recursive:!0})}}async function He(e,n,{routes:t,mergeMode:s="byUpdateTime",deleteRoutes:o=!1,publishMode:a=void 0}={}){try{a&&mt(a)}catch(f){y.error("clear preload page cache error",{error:f})}const{pages:r,pageIds:u,routeIds:c,routes:i,supportedLocales:d}=e;if(a==="production"){let f=t??[],p=null;for(const l of c??[]){const m=i==null?void 0:i[l];if(m!=null&&m.params&&(m==null?void 0:m.params.length)>0&&(m!=null&&m.paramsOptions)&&(m==null?void 0:m.paramsOptions.length)>0){const b=we.generateParamCombinations({basePath:m.path,params:m.params,routeId:m.id,paramsOptions:m.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),_=Object.fromEntries(b.map(T=>[`${l}-${T.paramOptionIds.join("-")}`,T]));p={...p||{},..._},t||(f=[...f,...b.map(T=>`${l}-${T.paramOptionIds.join("-")}`)])}else t||f.push(l)}y.info("routeIds to be published: ",f);for(const l of f){let m=l;if(m.includes("-")){const[T]=m.split("-");m=T}const b=i==null?void 0:i[m];if(!b){const T=n.pageIds.indexOf(m);T!==-1&&o&&(n.pageIds.splice(T,1),delete n.pages[m]);for(const $ of n.pageIds)$.includes(`${m}-`)&&(n.pageIds.splice(n.pageIds.indexOf($),1),delete n.pages[$]);y.info("delete main route page",m);continue}if(l.includes("-")&&!(p!=null&&p[l])){const T=n.pageIds.indexOf(l);T!==-1&&o&&(n.pageIds.splice(T,1),delete n.pages[l]),y.info("delete page",l);continue}if(!b.displayTemplateId){y.info("no display template",l);continue}const _=r[b.displayTemplateId];if(!_){y.info("no template page",l);continue}if(n.pageIds.includes(l)){if(y.info("has need update page",l),s==="replace")n.pages[l]=Le({page:_,route:b,state:e,routeId:l,routePathInfo:p==null?void 0:p[l]}),y.info("replace page",l);else if(s==="byUpdateTime"){const T=n.pages[b.id];(!T||b.updatedAt&&b.updatedAt>T.updatedAt)&&(n.pages[l]=Le({page:_,route:b,state:e,routeId:l,routePathInfo:p==null?void 0:p[l]}),y.info("replace page by update time",l))}}else n.pageIds.push(l),n.pages[l]=Le({page:_,route:b,state:e,routeId:l,routePathInfo:p==null?void 0:p[l]}),y.info("add page",l)}if(o&&!t)for(const l of n.pageIds)f!=null&&f.includes(l)||(delete n.pages[l],y.info("delete page",l)),n.pageIds=[...n.pageIds].filter(m=>f==null?void 0:f.includes(m))}else{for(const f of u){const p=r[f];if(p)if(n.pageIds.includes(p.id)){if(s==="replace")n.pages[p.id]=p;else if(s==="byUpdateTime"){const l=n.pages[p.id];(!l||p.updatedAt&&p.updatedAt>l.updatedAt)&&(n.pages[p.id]=p)}}else n.pageIds.push(p.id),n.pages[p.id]=p}for(const f of c){const p=i[f];if(p)if(n.routeIds.includes(p.id)){if(s==="replace")n.routes[p.id]=p;else if(s==="byUpdateTime"){const l=n.routes[p.id];(!l||p.updatedAt&&p.updatedAt>l.updatedAt)&&(n.routes[p.id]=p)}}else n.routeIds.push(p.id),n.routes[p.id]=p}}if(n.supportedLocales.splice(0,n.supportedLocales.length),n.supportedLocales.push(...ms.default(d)),o)for(const f of Object.keys(n.components))delete n.components[f];let E=JSON.parse(JSON.stringify(e.components));E=Object.fromEntries(await Promise.all(Object.entries(E).map(async([f,p])=>{const l=await Ot(p==null?void 0:p.data);return[f,{...p,data:l}]}))),Object.assign(n.components,E),Object.assign(n.config,JSON.parse(JSON.stringify(e.config))),lt.default(e.resources.components)||(n.resources.components=JSON.parse(JSON.stringify(e.resources.components||{})))}const Ot=Je(async e=>{var n;if(!lt.default(e==null?void 0:e.properties))return e;if(((n=e==null?void 0:e.renderer)==null?void 0:n.type)==="react-component"){const{script:t}=(e==null?void 0:e.renderer)||{};if(t&&t.includes("PROPERTIES_SCHEMA"))try{const s=await St(t,"PROPERTIES_SCHEMA",e.id);s&&s.length>0&&e&&(e.properties={},s.forEach((o,a)=>{e!=null&&e.properties&&(e.properties[o.id]={index:a,data:o})}))}catch(s){y.error("checkPropertiesFromCode error",{componentId:e.id,name:e.name},{error:s})}}return e},{keyGenerator:e=>{var i,d,E,f;const n=(e==null?void 0:e.id)||"",t=(e==null?void 0:e.name)||"",s=((i=e==null?void 0:e.renderer)==null?void 0:i.type)||"",o=(e==null?void 0:e.properties)||{},a=(e==null?void 0:e.updatedAt)||"",r=ee.createHash("md5").update(JSON.stringify(o)).digest("hex");let u="",c="";return((d=e==null?void 0:e.renderer)==null?void 0:d.type)==="react-component"&&(u=ee.createHash("md5").update(((E=e==null?void 0:e.renderer)==null?void 0:E.script)||"").digest("hex"),c=ee.createHash("md5").update(((f=e==null?void 0:e.renderer)==null?void 0:f.editComponent)||"").digest("hex")),JSON.stringify(["checkPropertiesFromCode",n,t,s,r,a,u,c])},lruOptions:{max:100,ttl:1e3*60*60},subdir:"checkPropertiesFromCode"});let Ae,ae,je,De,We;function At(){return Ae=(async()=>{const e=Ge.getResources({types:[{did:Ke,type:Fe},{did:Bs,type:Fe}]});ae=(await Promise.all(e.map(async t=>{const s=t.path?await Ye(t.path,{importAssets:!1}):void 0;return s?{blockletId:t.did,state:s,blockletTitle:t.title}:void 0}))).filter(t=>!!t),je=ae.reduce((t,s)=>Object.assign(t,Object.fromEntries(Object.values(s.state.pages).map(o=>o?[o==null?void 0:o.id,{page:o,blockletId:s.blockletId}]:[]))),{});const n=ae.reduce((t,s)=>Object.assign(t,Object.fromEntries(Object.values(s.state.components).map(o=>[o.data.id,{blockletId:s.blockletId,component:o.data}]))),{});De=Object.fromEntries(await Promise.all(Object.entries(n).map(async([t,s])=>{const o=await Ot(s.component);return[t,{...s,component:o}]}))),We=ae.reduce((t,s)=>Object.assign(t,s.state.chunks),{})})(),Ae}function Pt(e){const n=ct.default(async()=>{await At().catch(t=>{y.error("load resource states error",{error:t})}),await(e==null?void 0:e({states:ae,pages:je,components:De,chunks:We}))},3e3,{leading:!1,trailing:!0});return n(),O.default.events.on(O.default.Events.componentAdded,n),O.default.events.on(O.default.Events.componentRemoved,n),O.default.events.on(O.default.Events.componentStarted,n),O.default.events.on(O.default.Events.componentStopped,n),O.default.events.on(O.default.Events.componentUpdated,n),O.default.events.on(qe,n),()=>{O.default.events.off(O.default.Events.componentAdded,n),O.default.events.off(O.default.Events.componentRemoved,n),O.default.events.off(O.default.Events.componentStarted,n),O.default.events.off(O.default.Events.componentStopped,n),O.default.events.off(O.default.Events.componentUpdated,n),O.default.events.off(qe,n)}}const Tt=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),Ee=globalThis;var ot;(ot=Ee[Tt])==null||ot.call(Ee);Ee[Tt]=Pt(async({pages:e,components:n})=>{const{projectIds:t}=Y;y.info(`start update resource states projects(${t.length})`,t),await Promise.race([new Promise(s=>{setTimeout(()=>{s({})},30*1e3)}),Promise.all(t.map(async s=>{jt({projectId:s,pages:e,components:n})}))]).catch(s=>{y.error("update resource states failed:",s)})});Y.startPeriodicCheck();process.on("beforeExit",()=>{Y.stopPeriodicCheck()});process.on("SIGINT",()=>{Y.stopPeriodicCheck(),process.exit(0)});process.on("SIGTERM",()=>{Y.stopPeriodicCheck(),process.exit(0)});async function jt({projectId:e,pages:n,components:t}){const s=Y.sharedInstances[e];if(!s){y.info(`projectId: ${e} not found in sharedInstances`);return}s.syncedStore.resources.pages=n;const o=await z.findByPk(e);if(o!=null&&o.useAllResources)s.syncedStore.resources.components=t;else{const r=(await Te.findAll({where:{projectId:e}})).map(c=>c.componentId),u=Object.fromEntries(Object.entries(t||{}).filter(([c])=>r.includes(c)));s.syncedStore.resources.components=u}y.info(`update [${e}] resource states:`,{pages:Object.keys(s.syncedStore.resources.pages||{}).length,components:Object.keys(s.syncedStore.resources.components||{}).length})}async function nn(){y.info("trigger reload all project resource"),O.default.events.emit(qe)}async function ke({ensureLoaded:e=!0}={}){return e&&(Ae??(Ae=At()),await Ae),{states:ae,pages:je,components:De,chunks:We}}exports.COMPONENT_DID=Ke;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=ut;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=Ue;exports.PUBLISH_MODES=en;exports.Project=z;exports.RESOURCE_TYPE=Fe;exports.SITE_STATE_PATH=ne;exports.STATE_MODES=Zs;exports.SiteState=Y;exports.clearPreloadComponentsCache=ft;exports.clearPreloadComponentsCacheByMode=mt;exports.downloadAsset=wt;exports.downloadAssets=bt;exports.fromPackage=Ye;exports.getComponentFromState=ue;exports.getComponentFromStateByName=Us;exports.getExportSchemaValueFromCode=St;exports.getMultiTenantAllProjectAccessPassports=Is;exports.getPreloadComponent=gt;exports.getPreloadComponents=Ns;exports.getPreloadComponentsCacheKey=ht;exports.getResourceStates=ke;exports.initPackResourceStates=Pt;exports.isMultiTenant=bs;exports.logger=y;exports.mergeState=He;exports.nextId=Se;exports.toPackage=Ct;exports.triggerReloadAllProjectResource=nn;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const q=require("react/jsx-runtime"),U=require("@mui/material"),R=require("ufo"),H=require("@blocklet/js-sdk"),ee=require("lodash/isEmpty"),te=require("yaml"),oe=require("@arcblock/ux/lib/Locale/context"),ne=require("@blocklet/pages-kit/utils/page-model"),F=require("@syncedstore/core"),re=require("@syncedstore/react"),se=require("ahooks"),_=require("immer"),ce=require("lodash/cloneDeep"),ie=require("lodash/debounce"),ae=require("nanoid"),m=require("react"),W=require("react-router-dom"),de=require("y-indexeddb"),le=require("y-websocket"),ue=require("yjs");require("@blocklet/pages-kit/types");const A=o=>o&&o.__esModule?o:{default:o};function fe(o){if(o&&o.__esModule)return o;const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const l in o)if(l!=="default"){const w=Object.getOwnPropertyDescriptor(o,l);Object.defineProperty(n,l,w.get?w:{enumerable:!0,get:()=>o[l]})}}return n.default=o,Object.freeze(n)}const me=A(ee),Se=fe(te),pe=A(F),J=A(ce),V=A(ie),ge=o=>{const n=blocklet==null?void 0:blocklet.componentMountPoints.find(l=>l.name===o);return n?n.mountPoint:"/"};function z(){const{pathname:o}=window.location,n=o.match(/\/admin\/(maker|previewer)\/([^/]+)/),l=n==null?void 0:n[2],w=window.__PROJECT_ID__;if(!l&&!w)throw new Error("Unable to get projectId from pathname");return l||w}function Pe(o){return`${o}:pages:version`}function we(o,n){return n==="yaml"?me.default(o)?"":Se.stringify(o,{indent:2}):n==="json"?JSON.parse(JSON.stringify(o||{})):n==="array"?JSON.parse(JSON.stringify(o||[])):o}function Ie({error:o}){return q.jsx(U.Box,{children:q.jsx(U.Alert,{severity:"error",children:o.message})})}var G;const D=((G=window.blocklet)==null?void 0:G.prefix)||"/",$=H.createAxios({timeout:200*1e3}),ye=window.location.protocol==="https:"?"wss":"ws",he=o=>R.joinURL(`${ye}://${window.location.hostname}`,D,`api/${o}/ws/pages`),Ce="z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";var B;(B=blocklet==null?void 0:blocklet.componentMountPoints.find(o=>o.did===Ce))!=null&&B.mountPoint||R.joinURL(D,"/image-bin");function je(o){return o&&!/^(https?:\/\/|\/)/.test(o)?window.location.origin+R.joinURL(D,"uploads",o):o}const ve=window.innerWidth<=750;function be(o,n,l){if(!o||/\.gif/.test(o))return o;const w=(ve?n/1.5:n)*(l==="quality"?1.5:1);return Oe(o,{imageFilter:"resize",w,f:"webp"})}function Oe(o,n){return!o||!n?o:R.withQuery(o,n)}async function Me(o){return $.get(`/api/projects/${o}`).then(n=>n.data)}async function Le(o){return $.post(`/api/projects/${o.id}/update`,o).then(n=>n.data)}const Ee=500,k=ae.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),N=m.createContext(null);function xe({url:o,name:n,children:l,waitingSynced:w}){const[L,O]=m.useState(!1),{locale:p}=oe.useLocaleContext(),j=T(),x=`${j}:MakerLocalState`,e=`${j}:${n}`,[t,c]=se.useLocalStorageState(x,{defaultValue:{},listenStorageChange:!0}),s=m.useRef(t);s.current=t;const i=m.useMemo(()=>pe.default({dataSourceIds:[],dataSources:{},pages:{},pageIds:[],routes:{},routeIds:[],components:{},supportedLocales:[],config:{},resources:{}}),[]),r=m.useMemo(()=>F.getYjsDoc(i),[i]);m.useMemo(()=>new de.IndexeddbPersistence(e,r),[e,r]);const a=m.useMemo(()=>new le.WebsocketProvider(o,e,r,{params:{},resyncInterval:5*60*1e3}),[o,e,r]),d=m.useCallback(()=>{a&&(a.disconnect(),a.connect())},[a]),u=m.useMemo(()=>new ue.UndoManager([r.getArray("pageIds"),r.getMap("pages"),r.getArray("supportedLocales"),r.getMap("config"),r.getMap("dataSources"),r.getArray("dataSourceIds"),r.getArray("routeIds"),r.getMap("routes")],{doc:r}),[r]),[f,S]=m.useState(null),[E,I]=m.useState(!1),[y,v]=m.useState(void 0),g=m.useCallback(async()=>{if(j){I(!0);try{const P=await Me(j);S(P)}catch(P){console.error("Failed to fetch project:",P)}finally{I(!1)}}},[j]),b=m.useCallback(async(P,h)=>{var M;if(v(void 0),!!j){h!=null&&h.optimisticUpdate&&f&&S(C=>({...C,...P}));try{const C=await Le({...P});S(C)}catch(C){console.error("Failed to update project:",C),h!=null&&h.optimisticUpdate&&S(f),v((M=C==null?void 0:C.response)==null?void 0:M.data)}}},[j,f]);m.useEffect(()=>{j&&g()},[j,g]);const Z=m.useMemo(()=>({doc:r,state:i,localState:{...t,currentLocale:p},setLocalState:P=>c(typeof P=="function"?h=>P(h??{}):P),undoManager:u,projectState:{project:f,isLoadingProject:E,error:y},updateProject:b,forceSync:d}),[r,i,JSON.stringify(t),c,u,f,E,b,y,p,d]);return m.useEffect(()=>{u.on("stack-item-added",({stackItem:P})=>{const{currentPageId:h,currentLocale:M,pages:C}=s.current;P.meta.set("localState",{currentPageId:h,currentLocale:M,pages:C})}),u.on("stack-item-popped",({stackItem:P})=>{const h=P.meta.get("localState");h&&c(M=>({...M,...h}))})},[u,c]),m.useEffect(()=>{a.awareness.setLocalState(t)},[a,t]),m.useEffect(()=>{a.once("synced",()=>O(!0));const P=()=>{c(C=>({...C,networkStatus:void 0}))},h=()=>{c(C=>({...C,networkStatus:"offline"}))},M=V.default(({status:C})=>{C==="connected"?P():C==="disconnected"&&h()},Ee);return a.on("status",M),window.addEventListener("online",P),window.addEventListener("offline",h),()=>{a.off("status",M),window.removeEventListener("online",P),window.removeEventListener("offline",h)}},[a,c]),w&&!L?null:q.jsx(N.Provider,{value:Z,children:l})}const K=()=>{const o=m.useContext(N);if(!o)throw new Error("Context is null");const n=re.useSyncedStore(o.state),{setLocalState:l,localState:w}=o,L=W.useNavigate(),O=T(),p=m.useMemo(()=>({get currentPage(){const{localState:{currentPageId:e}}=o;return e?n.pages[e]:void 0},get currentSection(){var s,i,r,a,d;const{localState:{currentPageId:e,...t}}=o;if(!e)return;const c=(i=(s=t.pages)==null?void 0:s[e])==null?void 0:i.currentSectionId;if(c)return((r=n.pages[e])==null?void 0:r.sections[c])??((d=(a=this.currentPageModel)==null?void 0:a.getComponentById(c))==null?void 0:d.model)},get currentSectionProperties(){var r,a,d,u;const{localState:{currentPageId:e,...t}}=o;if(!e)return;const c=(a=(r=t.pages)==null?void 0:r[e])==null?void 0:a.currentSectionId;if(!c)return;const s=(u=(d=n.pages[e])==null?void 0:d.dataSource)==null?void 0:u[c];if(!s)return;const{currentLocale:i}=this.currentLocaleMap;return i?s[i]:void 0},get currentSectionPropertiesWithFallback(){var d,u,f,S;const{localState:{currentPageId:e,...t}}=o;if(!e)return;const c=(u=(d=t.pages)==null?void 0:d[e])==null?void 0:u.currentSectionId;if(!c)return;const s=(S=(f=n.pages[e])==null?void 0:f.dataSource)==null?void 0:S[c];if(!s)return;const{currentLocale:i,defaultLocale:r,fallbackLocale:a}=this.currentLocaleMap;if(i&&s[i])return s[i];if(r&&s[r])return s[r];if(a&&s[a])return s[a]},get currentLocaleMap(){var s;const{localState:{currentLocale:e},state:{supportedLocales:t,config:{defaultLocale:c}}}=o;return{currentLocale:e,defaultLocale:c,fallbackLocale:((s=t==null?void 0:t[0])==null?void 0:s.locale)??"en"}},get currentRoute(){var t;const{localState:{currentRouteId:e}}=o;return e?(t=n.routes)==null?void 0:t[e]:void 0},get currentPageModel(){const e=this.currentPage??null;if(e)return ne.getPageTemplateModel(e,!1)}}),[JSON.stringify(w),n]),j=m.useMemo(()=>({setCurrentSectionId:(e,t)=>{var c,s;e===w.currentPageId&&t===((s=(c=w.pages)==null?void 0:c[e])==null?void 0:s.currentSectionId)||(L(R.joinURL("/admin/maker",O??"","pages",e)),l(i=>_.produce(i,r=>{var a;r.currentPageId=e,r.currentComponentId=void 0,t!==void 0&&(r.pages??(r.pages={}),(a=r.pages)[e]??(a[e]={}),r.pages[e].currentSectionId=t??void 0),t?window.sessionStorage.setItem("iframe_show_id",`"${t}"`):window.sessionStorage.removeItem("iframe_show_id")})))},setCurrentComponentId:e=>{e!==w.currentComponentId&&(L(R.joinURL("/admin/maker",O??"","components",e)),l(t=>_.produce(t,c=>{c.currentComponentId=e})))},setCurrentRouteId:({routeId:e,dynamicParams:t})=>{l(c=>_.produce(c,s=>{s.currentRouteId=e,s.currentDynamicParams=t}))},setCustomComponentPreviewerProperties:(()=>{const e={};let t="";const c=V.default(()=>{l(s=>_.produce(s,i=>{i.customComponentPreviewerProperties??(i.customComponentPreviewerProperties={}),i.customComponentPreviewerProperties[t]={...i.customComponentPreviewerProperties[t],...J.default(e[t])},delete e[t]}))},5);return(s,i)=>{const r=e[s]??{};Object.assign(r,i),e[s]=r,t=s,c()}})(),setRouteGenerateProcess:e=>{l(t=>_.produce(t,c=>{e?c.routeGenerateProcess={...c.routeGenerateProcess,...e}:c.routeGenerateProcess={}}))},resetRouteGenerateProcess:()=>{l(e=>_.produce(e,t=>{t.routeGenerateProcess={progress:"complete"}}))}}),[l,L,O,p]),x=m.useMemo(()=>({addPage:(e,t)=>{var i,r,a,d,u,f;const c=(e==null?void 0:e.id)??k(),s={...e,id:c,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)??`/${c}`,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:((i=e==null?void 0:e.templateConfig)==null?void 0:i.isTemplate)??!0,displayTemplateId:((r=e==null?void 0:e.templateConfig)==null?void 0:r.displayTemplateId)??void 0,dataSourceIds:((a=e==null?void 0:e.templateConfig)==null?void 0:a.dataSourceIds)??void 0,dataSourceParameters:((d=e==null?void 0:e.templateConfig)==null?void 0:d.dataSourceParameters)??{},enabledGenerate:((u=e==null?void 0:e.templateConfig)==null?void 0:u.enabledGenerate)??!1,agentId:((f=e==null?void 0:e.templateConfig)==null?void 0:f.agentId)??void 0}};return o.doc.transact(()=>{n.pages[s.id]=s,n.pageIds.splice(t??n.pageIds.length,0,s.id)}),s},addRoute:(e,t)=>{const c=(e==null?void 0:e.id)??k(),s={...e,id:c,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)??`/${c}`,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 o.doc.transact(()=>{n.routes??(n.routes={}),n.routeIds??(n.routeIds=[]),n.routes[s.id]=s,n.routeIds.splice(t??n.routeIds.length,0,s.id)}),s},deleteRoute:e=>{var c;if(!e)return;const t=(c=n.routeIds)==null?void 0:c.indexOf(e);t!==void 0&&t!==-1&&o.doc.transact(()=>{var s,i;(s=n.routeIds)==null||s.splice(t,1),(i=n.routes)==null||delete i[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,s=c.indexOf(e);s>=0&&c.splice(t,0,...c.splice(s,1))},addSection:(e,t,c,s)=>{const i=n.pages[e];if(!i)throw new Error(`Page ${e} is not exists`);const r={...t,id:t.id??k(),isTemplateSection:t.isTemplateSection??!0,llmConfig:t.llmConfig??{}},a=J.default(r.locales);return delete r.locales,o.doc.transact(()=>{var d,u,f;if(s&&s.component==="layout-block"){const S=(d=p.currentPageModel)==null?void 0:d.getComponentById(s.id);S&&((u=S.model).sections??(u.sections={}),S.model.sections[r.id]=r,(f=S.model).sectionIds??(f.sectionIds=[]),S.model.sectionIds.push(r.id))}else i.sections[r.id]=r,i.sectionIds.splice(c??i.sectionIds.length,0,r.id);a&&(i.dataSource??(i.dataSource={}),i.dataSource[r.id]=a)}),r},deleteSection:(e,t)=>{const c=n.pages[e];if(!c)throw new Error(`Page ${e} is not exists`);o.doc.transact(()=>{var a,d,u,f,S,E;const s=[],i=(a=p.currentPageModel)==null?void 0:a.getComponentById(t),r=i==null?void 0:i.parent;if(i&&(s.push(i.model.id,...i.all().map(I=>I.model.id)),(r==null?void 0:r.model.component)==="layout-block")){const I=(d=r.model.sectionIds)==null?void 0:d.indexOf(t);I!==void 0&&I!==-1&&((u=r.model.sectionIds)==null||u.splice(I,1),(f=r.model.sections)==null||delete f[t]),(S=r.model.config)!=null&&S.gridSettings&&Object.keys(r.model.config.gridSettings).forEach(y=>{var v;try{(v=r.model.config.gridSettings[y])==null||delete v[t]}catch{}}),((E=r.model.config)==null?void 0:E.backgroundSectionId)===t&&(r.model.config.backgroundSectionId=void 0)}s.forEach(I=>{var v,g;const y=c.sectionIds.indexOf(I);y!==-1&&c.sectionIds.splice(y,1),c.sections[I]&&delete c.sections[I],(v=c.dataSource)!=null&&v[I]&&((g=c.dataSource)==null||delete g[I])})})},lockSection:(e,t)=>{var i,r;if(!n.pages[e])throw new Error(`Page ${e} is not exists`);const s=(r=(i=p.currentPageModel)==null?void 0:i.getComponentById(t))==null?void 0:r.model;s&&(s.locked=!s.locked)},toggleSectionVisibility:(e,t,c)=>{var r,a;if(!n.pages[e])throw new Error(`Page ${e} is not exists`);const i=(a=(r=p.currentPageModel)==null?void 0:r.getComponentById(t))==null?void 0:a.model;i&&(i.visibility=c)},moveSection:(e,t,c,s)=>{var r,a,d,u,f,S,E,I;if(!n.pages[e])throw new Error(`Page ${e} is not exists`);if(s&&s!==t){const y=(r=p.currentPageModel)==null?void 0:r.getComponentById(t),v=(a=p.currentPageModel)==null?void 0:a.getComponentById(s),g=y==null?void 0:y.parent,b=v==null?void 0:v.parent;b&&g&&((d=b==null?void 0:b.model)==null?void 0:d.id)===((u=g==null?void 0:g.model)==null?void 0:u.id)?o.doc.transact(()=>{g.model.sectionIds.splice(y.getIndex(),1),g.model.sectionIds.splice(v.getIndex(),0,t)}):b&&g&&((f=b==null?void 0:b.model)==null?void 0:f.id)!==((S=g==null?void 0:g.model)==null?void 0:S.id)&&t!==s&&!((I=(E=y==null?void 0:y.model)==null?void 0:E.sectionIds)!=null&&I.includes(s))&&o.doc.transact(()=>{b.model.sections[t]=JSON.parse(JSON.stringify(y.model)),b.model.sectionIds.splice(v.getIndex(),0,t),g.model.sectionIds.splice(y.getIndex(),1),delete g.model.sections[t]})}},copySection:(e,t)=>{var u,f,S;if(!n.pages[e])throw new Error(`Page ${e} is not exists`);const s=(u=p.currentPageModel)==null?void 0:u.getComponentById(t);if(!(s!=null&&s.model))throw new Error(`Section ${t} is not exists`);const i=JSON.parse(JSON.stringify(s.model)),r=Re(i),a=r.id,d=s==null?void 0:s.parent;return d&&(d.model.sections[a]=r,d.model.sectionIds.push(a),j.setCurrentSectionId(e,a),(S=(f=p.currentPage)==null?void 0:f.dataSource)!=null&&S[t]&&(p.currentPage.dataSource[a]=JSON.parse(JSON.stringify(p.currentPage.dataSource[t])))),r},addDataSource:e=>{const t=e.id??k(),c={...e??{},id:t,createdAt:new Date().toISOString()};return o.doc.transact(()=>{n.dataSourceIds??(n.dataSourceIds=[]),n.dataSources??(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:x,localActions:j,...p}},T=()=>{const{projectId:o}=W.useParams();return o??z()??""},_e=()=>window.__PROJECT_SLUG__??"";function Q(o){var w,L;const{resources:n}=o;if(!n.components)return{};const l={};return(L=(w=window==null?void 0:window.blocklet)==null?void 0:w.componentMountPoints)==null||L.forEach(O=>{l[O.did]=O}),Object.fromEntries(Object.entries(n.components).map(([O,{blockletId:p,component:j}])=>{var x;return[O,{data:j,blockletId:p,blockletTitle:((x=l[p])==null?void 0:x.title)||p}]}))}function X(o){const{components:n}=o;return n||{}}function Y(o){return{...Q(o),...X(o)}}const ke=()=>Y(K().state);function Re(o){const n=JSON.parse(JSON.stringify(o)),l=k();return{...n,id:l}}exports.ErrorView=Ie;exports.StoreProvider=xe;exports.api=$;exports.autoResizeImage=be;exports.getAllComponents=Y;exports.getCustomComponents=X;exports.getImageAbsoluteUrl=je;exports.getMountPoint=ge;exports.getProjectIdFromPathnameOrWindow=z;exports.getProjectPageVersionKey=Pe;exports.getResourceComponents=Q;exports.getWssURL=he;exports.nextId=k;exports.transformValue=we;exports.useAllComponents=ke;exports.useProjectId=T;exports.useProjectSlug=_e;exports.useStore=K;
|