@blocklet/pages-kit-inner-components 0.6.1 → 0.6.3
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 +1 -420
- package/lib/cjs/chunks/draft-data-CfIMszE7.js +1 -0
- package/lib/cjs/chunks/home-DUjl5PbP.js +6 -0
- package/lib/cjs/chunks/publish-button-C522nNv6.js +1 -0
- package/lib/cjs/chunks/site-state-BG2d2tBl.js +57 -0
- package/lib/cjs/chunks/state-CtNs8GrN.js +1 -0
- package/lib/cjs/home.js +1 -1
- package/lib/cjs/project-html.js +11 -4
- package/lib/cjs/resources.js +1 -1
- package/lib/es/add-component.js +2 -1089
- package/lib/es/chunks/{draft-data-CafrGKeh.js → draft-data-bRUHvvzp.js} +5 -4
- package/lib/es/chunks/home-VWWdvIPQ.js +69 -0
- package/lib/es/chunks/{publish-button-XSZrDaTQ.js → publish-button-Ceet-m88.js} +158 -140
- package/lib/es/chunks/site-state-BoVWlYLn.js +2096 -0
- package/lib/es/chunks/state-BdNIIXJP.js +502 -0
- package/lib/es/home.js +3 -28
- package/lib/es/project-html.js +114 -130
- package/lib/es/resources.js +93 -137
- package/package.json +11 -11
- package/lib/cjs/chunks/draft-data-D44_IEV2.js +0 -1
- package/lib/cjs/chunks/home-BYk01EUy.js +0 -39
- package/lib/cjs/chunks/index-BRgYwvuv.js +0 -475
- package/lib/cjs/chunks/publish-button-C8XPA4g_.js +0 -1
- package/lib/cjs/chunks/session-BRtsDvA-.js +0 -1
- package/lib/cjs/chunks/site-state-gSkcvhcV.js +0 -57
- package/lib/cjs/chunks/state-B6BF5wJ-.js +0 -1
- package/lib/cjs/chunks-map.json +0 -1
- package/lib/cjs/components.js +0 -1
- package/lib/cjs/locales.js +0 -3
- package/lib/cjs/setting.js +0 -11
- package/lib/cjs/site-state.js +0 -1
- package/lib/cjs/theme.js +0 -1
- package/lib/cjs/uploader.js +0 -1
- package/lib/es/chunks/home-DW8SdyfO.js +0 -594
- package/lib/es/chunks/index-D5gXPe_7.js +0 -2326
- package/lib/es/chunks/session-C72Dq8zg.js +0 -19
- package/lib/es/chunks/site-state-W2H7XCSQ.js +0 -2077
- package/lib/es/chunks/state-0gvZF3k2.js +0 -573
- package/lib/es/chunks-map.json +0 -1
- package/lib/es/components.js +0 -22
- package/lib/es/locales.js +0 -1032
- package/lib/es/setting.js +0 -2294
- package/lib/es/site-state.js +0 -48
- package/lib/es/theme.js +0 -484
- package/lib/es/uploader.js +0 -8
package/lib/cjs/add-component.js
CHANGED
|
@@ -1,420 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
.color-item {
|
|
3
|
-
position: relative;
|
|
4
|
-
}
|
|
5
|
-
.color-item__checked {
|
|
6
|
-
position: absolute;
|
|
7
|
-
top: 0;
|
|
8
|
-
bottom: 0;
|
|
9
|
-
left: 0;
|
|
10
|
-
right: 0;
|
|
11
|
-
display: flex;
|
|
12
|
-
justify-content: center;
|
|
13
|
-
align-items: center;
|
|
14
|
-
color: rgba(255, 255, 255, 0.85);
|
|
15
|
-
}
|
|
16
|
-
.color-item__delete {
|
|
17
|
-
position: absolute;
|
|
18
|
-
top: 0;
|
|
19
|
-
right: 0;
|
|
20
|
-
}
|
|
21
|
-
`;const z=.5;e.styled(e.Box)`
|
|
22
|
-
display: flex;
|
|
23
|
-
align-items: center;
|
|
24
|
-
padding: 8px;
|
|
25
|
-
border-bottom: ${({theme:o})=>`1px solid ${o.palette.divider}`};
|
|
26
|
-
user-select: none;
|
|
27
|
-
cursor: pointer;
|
|
28
|
-
position: relative;
|
|
29
|
-
|
|
30
|
-
:hover {
|
|
31
|
-
background-color: rgba(200, 200, 200, 0.3);
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
&.selected {
|
|
35
|
-
background-color: rgba(200, 200, 200, 0.3);
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
&.sub-selected {
|
|
39
|
-
background-color: rgba(200, 200, 200, 0.3);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
&.disabledDrag {
|
|
43
|
-
cursor: default;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
> .drag,
|
|
47
|
-
> .actions {
|
|
48
|
-
line-height: 1;
|
|
49
|
-
|
|
50
|
-
svg {
|
|
51
|
-
font-size: 16px;
|
|
52
|
-
vertical-align: middle;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
> .drag {
|
|
57
|
-
cursor: grab;
|
|
58
|
-
opacity: ${z};
|
|
59
|
-
position: relative;
|
|
60
|
-
|
|
61
|
-
&.disabledDrag {
|
|
62
|
-
cursor: default;
|
|
63
|
-
|
|
64
|
-
&:has(.origin-drag-icon):after {
|
|
65
|
-
content: '';
|
|
66
|
-
position: absolute;
|
|
67
|
-
top: 50%;
|
|
68
|
-
left: 50%;
|
|
69
|
-
width: 120%;
|
|
70
|
-
height: 1px;
|
|
71
|
-
background-color: ${({theme:o})=>o.palette.error.main};
|
|
72
|
-
transform: translate(-50%, -50%) rotate(-45deg);
|
|
73
|
-
z-index: 1;
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
> .actions {
|
|
79
|
-
display: flex;
|
|
80
|
-
align-items: center;
|
|
81
|
-
overflow: hidden;
|
|
82
|
-
|
|
83
|
-
> * {
|
|
84
|
-
margin-right: 0.5em;
|
|
85
|
-
opacity: 0;
|
|
86
|
-
display: inline-block;
|
|
87
|
-
cursor: pointer;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
> .visible {
|
|
91
|
-
display: inline-block;
|
|
92
|
-
opacity: ${z};
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
&:hover {
|
|
97
|
-
> .actions {
|
|
98
|
-
> * {
|
|
99
|
-
display: inline-block;
|
|
100
|
-
opacity: ${z} !important;
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
> .name {
|
|
106
|
-
flex: 1;
|
|
107
|
-
overflow: hidden;
|
|
108
|
-
text-overflow: ellipsis;
|
|
109
|
-
padding: 0 4px;
|
|
110
|
-
font-size: 14px;
|
|
111
|
-
}
|
|
112
|
-
`;e.styled(e.Box)`
|
|
113
|
-
position: relative;
|
|
114
|
-
border: 1px solid #c0c0c0;
|
|
115
|
-
min-height: 40px;
|
|
116
|
-
border-radius: 4px;
|
|
117
|
-
padding: 14px 14px;
|
|
118
|
-
.label-box__label {
|
|
119
|
-
left: 6px;
|
|
120
|
-
height: 1em;
|
|
121
|
-
padding: 0 6px;
|
|
122
|
-
line-height: 1;
|
|
123
|
-
}
|
|
124
|
-
.label-box__actions {
|
|
125
|
-
right: 6px;
|
|
126
|
-
}
|
|
127
|
-
.label-box__label,
|
|
128
|
-
.label-box__actions {
|
|
129
|
-
position: absolute;
|
|
130
|
-
background: ${({theme:o})=>o.palette.background.default};
|
|
131
|
-
overflow: visible;
|
|
132
|
-
display: inline-block;
|
|
133
|
-
top: 0;
|
|
134
|
-
transform: translateY(-50%);
|
|
135
|
-
}
|
|
136
|
-
`;const ce=u.createContext({embed:!1}),{Provider:xe}=ce;u.createContext(void 0);A.createStatusApi({axios:v.api,path:"/api/ai/status"});A.createStatusApi({axios:v.api,path:"/api/ai/agent-status"});A.createTextCompletionApi({fetch:ee.createFetch(),path:"/api/ai/completions"});W.default.extend(le.default);W.default.extend(ae.default);m.styled(e.Box)`
|
|
137
|
-
flex-grow: 1;
|
|
138
|
-
display: flex;
|
|
139
|
-
flex-direction: column;
|
|
140
|
-
|
|
141
|
-
> .actions {
|
|
142
|
-
position: sticky;
|
|
143
|
-
bottom: 0px;
|
|
144
|
-
margin-top: 20px;
|
|
145
|
-
z-index: 1;
|
|
146
|
-
|
|
147
|
-
@media (max-height: 700px) {
|
|
148
|
-
position: static;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
> .connect-tip {
|
|
152
|
-
font-weight: 600;
|
|
153
|
-
font-size: 14px;
|
|
154
|
-
line-height: 17px;
|
|
155
|
-
text-align: center;
|
|
156
|
-
color: #9397a1;
|
|
157
|
-
margin-bottom: 20px;
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
.submit {
|
|
161
|
-
height: 43px;
|
|
162
|
-
width: 100%;
|
|
163
|
-
background: linear-gradient(90deg, #45e4fa 0%, #8a45fa 52.08%, #fa45bc 100%);
|
|
164
|
-
border-radius: 30px;
|
|
165
|
-
box-shadow: none;
|
|
166
|
-
text-transform: none;
|
|
167
|
-
width: 100%;
|
|
168
|
-
border: 0;
|
|
169
|
-
margin: 0;
|
|
170
|
-
padding: 8.5px 14px;
|
|
171
|
-
font-size: 100%;
|
|
172
|
-
|
|
173
|
-
&.Mui-disabled {
|
|
174
|
-
color: rgba(0, 0, 0, 0.26);
|
|
175
|
-
background: rgba(0, 0, 0, 0.12);
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
.MuiFormHelperText-root {
|
|
181
|
-
font-style: normal;
|
|
182
|
-
font-weight: 500;
|
|
183
|
-
font-size: 12px;
|
|
184
|
-
line-height: 14px;
|
|
185
|
-
color: #9397a1;
|
|
186
|
-
margin: 0;
|
|
187
|
-
margin-top: 4px;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
.MuiOutlinedInput-root {
|
|
191
|
-
background: #fbfbfb;
|
|
192
|
-
border-radius: 4px;
|
|
193
|
-
|
|
194
|
-
fieldset {
|
|
195
|
-
border: 1px solid #f6f6f6;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
&:hover fieldset {
|
|
199
|
-
border: 1px solid #a482fe;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
input {
|
|
203
|
-
width: 100%;
|
|
204
|
-
border: 0;
|
|
205
|
-
margin: 0;
|
|
206
|
-
border-radius: 4px;
|
|
207
|
-
padding: 8.5px 14px;
|
|
208
|
-
font-size: 100%;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
.Mui-focused {
|
|
213
|
-
&.MuiFormLabel-root {
|
|
214
|
-
color: #a482fe;
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
&.MuiOutlinedInput-root {
|
|
218
|
-
fieldset {
|
|
219
|
-
border: 1px solid #a482fe;
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
.Mui-error {
|
|
225
|
-
&.MuiFormLabel-root {
|
|
226
|
-
color: #f16e6e;
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
&.MuiOutlinedInput-root + .MuiFormHelperText-root {
|
|
230
|
-
color: #f16e6e;
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
&.MuiOutlinedInput-root {
|
|
234
|
-
fieldset {
|
|
235
|
-
border: 1px solid #f16e6e;
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
`;u.createContext({});m.styled(e.Box)`
|
|
240
|
-
display: flex;
|
|
241
|
-
flex-direction: column;
|
|
242
|
-
flex: 1;
|
|
243
|
-
|
|
244
|
-
.lazy-image-wrapper {
|
|
245
|
-
border-radius: 12px;
|
|
246
|
-
|
|
247
|
-
img {
|
|
248
|
-
border-radius: 12px;
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
`;m.styled(e.Box)`
|
|
252
|
-
background: #fbfbfb;
|
|
253
|
-
border: 1px solid #f6f6f6;
|
|
254
|
-
border-radius: 4px;
|
|
255
|
-
|
|
256
|
-
&:has(.selected) {
|
|
257
|
-
border: 1px solid #a482fe;
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
&:has(.Mui-focused) {
|
|
261
|
-
border: 1px solid #a482fe;
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
> .input {
|
|
265
|
-
padding: 12px;
|
|
266
|
-
font-weight: 500;
|
|
267
|
-
font-size: 16px;
|
|
268
|
-
line-height: 19px;
|
|
269
|
-
color: #25292f;
|
|
270
|
-
cursor: pointer;
|
|
271
|
-
}
|
|
272
|
-
`;m.styled(se.default)`
|
|
273
|
-
background: #f6f2ff;
|
|
274
|
-
margin-bottom: 20px;
|
|
275
|
-
|
|
276
|
-
.title {
|
|
277
|
-
font-style: normal;
|
|
278
|
-
font-weight: 700;
|
|
279
|
-
font-size: 24px;
|
|
280
|
-
line-height: 33px;
|
|
281
|
-
color: #25292f;
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
.subtitle {
|
|
285
|
-
font-style: normal;
|
|
286
|
-
font-weight: 500;
|
|
287
|
-
font-size: 16px;
|
|
288
|
-
line-height: 22px;
|
|
289
|
-
color: #9397a1;
|
|
290
|
-
margin-top: 4px;
|
|
291
|
-
}
|
|
292
|
-
`;m.styled(e.Box)`
|
|
293
|
-
display: block;
|
|
294
|
-
padding: 16px;
|
|
295
|
-
text-decoration: none;
|
|
296
|
-
border-radius: 12px;
|
|
297
|
-
cursor: pointer;
|
|
298
|
-
box-shadow:
|
|
299
|
-
rgb(255, 255, 255) 0 0 0 0,
|
|
300
|
-
rgb(226, 232, 240) 0 0 0 1px,
|
|
301
|
-
rgba(0, 0, 0, 0.05) 0 1px 2px 0;
|
|
302
|
-
color: inherit;
|
|
303
|
-
height: 100%;
|
|
304
|
-
position: relative;
|
|
305
|
-
|
|
306
|
-
&:hover {
|
|
307
|
-
box-shadow:
|
|
308
|
-
rgb(255, 255, 255) 0 0 0 0,
|
|
309
|
-
rgb(203, 213, 225) 0 0 0 2px,
|
|
310
|
-
rgba(0, 0, 0, 0.1) 0 10px 15px -3px,
|
|
311
|
-
rgba(0, 0, 0, 0.1) 0 4px 6px -4px;
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
.description {
|
|
315
|
-
word-break: break-all;
|
|
316
|
-
text-overflow: ellipsis;
|
|
317
|
-
display: -webkit-box;
|
|
318
|
-
-webkit-box-orient: vertical;
|
|
319
|
-
-webkit-line-clamp: 2;
|
|
320
|
-
overflow: hidden;
|
|
321
|
-
}
|
|
322
|
-
`;Z.css`
|
|
323
|
-
.MuiMenu-root {
|
|
324
|
-
z-index: 13010 !important;
|
|
325
|
-
}
|
|
326
|
-
`;m.styled(e.Box)`
|
|
327
|
-
display: flex;
|
|
328
|
-
flex-direction: column;
|
|
329
|
-
flex: 1;
|
|
330
|
-
|
|
331
|
-
.lazy-image-wrapper {
|
|
332
|
-
border-radius: 12px;
|
|
333
|
-
|
|
334
|
-
img {
|
|
335
|
-
border-radius: 12px;
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
`;m.styled(e.Box)`
|
|
339
|
-
background: #fbfbfb;
|
|
340
|
-
border: 1px solid #f6f6f6;
|
|
341
|
-
border-radius: 4px;
|
|
342
|
-
position: relative;
|
|
343
|
-
cursor: pointer;
|
|
344
|
-
|
|
345
|
-
&:has(.selected) {
|
|
346
|
-
border: 1px solid #a482fe;
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
&:has(.Mui-focused) {
|
|
350
|
-
border: 1px solid #a482fe;
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
> .input {
|
|
354
|
-
padding: 12px;
|
|
355
|
-
font-weight: 500;
|
|
356
|
-
font-size: 16px;
|
|
357
|
-
line-height: 19px;
|
|
358
|
-
color: #25292f;
|
|
359
|
-
cursor: pointer;
|
|
360
|
-
}
|
|
361
|
-
`;m.styled(e.Box)`
|
|
362
|
-
> .ai-button {
|
|
363
|
-
display: none;
|
|
364
|
-
z-index: 1;
|
|
365
|
-
|
|
366
|
-
&.active {
|
|
367
|
-
display: inline-flex;
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
.MuiCircularProgress-root {
|
|
371
|
-
position: absolute;
|
|
372
|
-
left: 0;
|
|
373
|
-
top: 0;
|
|
374
|
-
right: 0;
|
|
375
|
-
bottom: 0;
|
|
376
|
-
margin: auto;
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
`;m.styled(e.Box)`
|
|
380
|
-
> .language-button {
|
|
381
|
-
display: none;
|
|
382
|
-
z-index: 1;
|
|
383
|
-
|
|
384
|
-
&.active {
|
|
385
|
-
display: inline-flex;
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
.MuiCircularProgress-root {
|
|
389
|
-
position: absolute;
|
|
390
|
-
left: 0;
|
|
391
|
-
top: 0;
|
|
392
|
-
right: 0;
|
|
393
|
-
bottom: 0;
|
|
394
|
-
margin: auto;
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
`;m.styled(e.Box)`
|
|
398
|
-
position: relative;
|
|
399
|
-
|
|
400
|
-
.action {
|
|
401
|
-
position: absolute;
|
|
402
|
-
right: 4px;
|
|
403
|
-
top: 4px;
|
|
404
|
-
z-index: 1;
|
|
405
|
-
display: flex;
|
|
406
|
-
align-items: center;
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
&:hover {
|
|
410
|
-
.language-button {
|
|
411
|
-
display: inline-flex;
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
&:hover {
|
|
416
|
-
.ai-button {
|
|
417
|
-
display: inline-flex;
|
|
418
|
-
}
|
|
419
|
-
}
|
|
420
|
-
`;G.nextId();const de={type:"default",title:"Section CardList",description:"This is Section CardList",center:!0,dark:!1,background:"",col:3,gap:2,align:"top",textAlign:"left",iconSize:100,padding:"normal",list:[{id:G.nextId(),title:"Simplified Service Delivery",description:"Block Server's Service Gateway makes networking easy with access to load balancing, SSL termination, automatic and customizable URL mapping, and redirects.",image:"https://www.arcblock.io/static/ead0cabde7f2b7ff34db8f3e8ceca271/afc4b/builder.png"}]};function pe({componentId:o,locale:c,components:l}){const{state:{config:{defaultLocale:d}},localState:{customComponentPreviewerProperties:f}}=v.useStore(),n=v.useAllComponents();return t.jsx(ie.CustomComponentRenderer,{componentId:o,locale:c,dev:{mode:"draft",components:l||n,defaultLocale:d},properties:f?.[o]??{}})}const P=260,ue=5,F="IGNORE_RENDER_BLOCKLET_TITLE",E=(o,c)=>o?Object.entries(o).map(([l,d])=>({id:l,component:l,name:d?.data?.name||d?.component?.name||l,properties:d?.data||d.component,previewImage:d?.data?.previewImage||null,type:c,blockletId:d?.blockletId,blockletTitle:d?.blockletTitle})):[],H=[{id:"section",name:"Section",properties:S.SectionBlockDefaultProps},{id:"section-card-list",name:"Section Card List",properties:de},{id:"toc",name:"Toc",properties:S.TocDefaultProps},{id:"iframe",name:"Embed",properties:S.IFrameBlockDefaultProps},{id:"layout-block",name:"Section Layout",properties:{}}].map(o=>({...o,type:"basic",component:o.id}));function V({state:o,open:c,onClose:l,onSelect:d,defaultTab:f,title:n,componentGroups:q,components:b,multiple:x=!1,defaultSelected:h,emptyText:B}){const{t:a}=N.useLocaleContext(),r=D.useReactive({selectedComponent:null,activeTab:f,searchQuery:""}),y=u.useMemo(()=>q||[{name:"basic",label:a("maker.components.basicGroup"),components:H},o&&{name:"custom",label:a("maker.components.customGroup"),components:E(v.getCustomComponents(o),"custom")},o&&{name:"resource",label:a("maker.components.resourceGroup"),components:E(v.getResourceComponents(o),"resource")}].filter(Boolean),[q,a,o,c]),C=r.activeTab||y[0]?.name,j=()=>{r.selectedComponent&&(d(r.selectedComponent),l())},M=i=>{if(i){if(w(i)){x?r.selectedComponent=r.selectedComponent.filter(s=>s.id!==i.id):r.selectedComponent=null;return}if(x){const s=Array.isArray(r.selectedComponent)?r.selectedComponent:[],g=s.some(R=>R.id===i.id);r.selectedComponent=g?s.filter(R=>R.id!==i.id):[...s,i]}else r.selectedComponent=i}},w=i=>r.selectedComponent?x?r.selectedComponent.some(s=>s.id===i.id):r.selectedComponent.id===i.id:!1,k=y?.length===0,T=u.useMemo(()=>{const i=y.find(s=>s?.name===C)?.components||[];return r.searchQuery?i.filter(s=>s.name.toLowerCase().includes(r.searchQuery.toLowerCase())):i},[C,y,r.searchQuery]);u.useEffect(()=>{r.searchQuery="",c&&h?r.selectedComponent=x?Array.isArray(h)?h:[h]:h:r.selectedComponent=null},[c,h,x]);const I=T?.length===0,L=B||a(C==="resource"?"maker.components.needAddResource":"maker.components.noComponents"),X=u.useMemo(()=>T?T.reduce((i,s)=>{const g=s.blockletId||F,R=s.blockletTitle||a("maker.components.defaultGroup");return i[g]||(i[g]={title:R,components:[]}),i[g].components.push(s),i},{}):{},[T]);return t.jsxs(e.Dialog,{open:c,onClose:l,maxWidth:"lg",fullWidth:!0,slotProps:{paper:{sx:{height:"80vh",maxHeight:"80vh",display:"flex",flexDirection:"column"}}},children:[t.jsxs(e.DialogTitle,{className:"between",sx:{display:"flex",gap:2},children:[t.jsx(e.Box,{children:n||a("maker.components.addComponent")}),t.jsx(e.TextField,{size:"small",placeholder:a("maker.components.searchComponent"),value:r.searchQuery,onChange:i=>r.searchQuery=i.target.value,sx:{flex:1,maxWidth:350},slotProps:{input:{startAdornment:t.jsx(O.Icon,{icon:"tabler:search",style:{marginRight:8}})}}}),t.jsx(e.IconButton,{size:"small",onClick:l,children:t.jsx(e.Box,{component:O.Icon,icon:"tabler:x",sx:{color:"text.primary"}})})]}),t.jsxs(e.DialogContent,{sx:{display:"flex",gap:2,pl:"8px !important",flex:1,overflow:"hidden"},children:[!k&&t.jsx(e.Box,{sx:{width:150,borderRight:1,borderColor:"divider"},children:t.jsx(e.Tabs,{orientation:"vertical",value:C,onChange:(i,s)=>r.activeTab=s,sx:{"& .MuiTab-root":{alignItems:"flex-start",textAlign:"left",minHeight:48,py:1.5,px:2}},children:y.map((i,s)=>t.jsx(e.Tab,{label:i?.label,value:i?.name},s))})}),t.jsx(e.Box,{sx:{flex:1,overflowX:"hidden",overflowY:"auto",pr:1},children:I?t.jsx($.default,{children:L}):t.jsx(U,{wrapperComponent:e.Grid,wrapperComponentProps:{container:!0,spacing:2,sx:I?{height:"100%"}:{}},groups:X,emptyText:L,renderItem:i=>{const s=w(i);return t.jsx(e.Grid,{sx:{width:"100%","& .add-component-card":{boxShadow:"none",border:1,borderColor:s?"primary.main":"grey.200","& .check-container":{display:s?"flex":"none",position:"absolute",right:0,bottom:0,justifyContent:"flex-end",alignItems:"flex-end",width:30,height:30,overflow:"hidden",transition:"all 0.3s ease",color:"white","&::after":{position:"absolute",zIndex:0,display:"block",width:0,height:0,borderTop:"transparent solid 15px",borderLeft:"transparent solid 15px",borderBottom:g=>`solid 15px ${g.palette.primary.main}`,borderRight:g=>`solid 15px ${g.palette.primary.main}`,transition:"all 0.1s ease",content:'""'},"& .check-icon":{position:"relative",zIndex:2,margin:"0 1px 1px 0",fontSize:16,transition:"all 0.2s ease"}}}},size:{xs:12,md:6,lg:4},children:t.jsxs(e.Card,{className:"add-component-card",sx:{position:"relative",width:"100%",cursor:"pointer"},onClick:()=>M(i),children:[t.jsx(e.CardMedia,{sx:{width:"100%",height:P,overflow:"auto",position:"relative"},children:t.jsx(Q,{components:b,containerHeight:P,component:i},i.id)}),t.jsx(e.CardContent,{sx:{bgcolor:"background.paper",borderTop:1,borderColor:s?"primary.main":"grey.200"},children:t.jsx(e.Typography,{variant:"body1",noWrap:!0,sx:{fontWeight:"bold"},children:i.name})}),t.jsx(e.Box,{className:"check-container",children:t.jsx(ne.default,{className:"check-icon"})})]})},i.id)}})})]}),t.jsxs(e.DialogActions,{sx:{borderTop:1,borderColor:"divider",p:2},children:[t.jsx(e.Button,{onClick:l,variant:"outlined",children:a("common.cancel")}),t.jsx(e.Button,{onClick:j,variant:"contained",disabled:!r.selectedComponent||x&&Array.isArray(r.selectedComponent)&&r.selectedComponent.length===0,children:x&&Array.isArray(r.selectedComponent)&&r.selectedComponent.length>0?a("common.addMultiple",{count:r.selectedComponent.length}):a("common.add")})]})]})}function Q({containerHeight:o,component:c,minScale:l=.1,components:d}){const{locale:f}=N.useLocaleContext(),n=D.useReactive({scale:1,shouldScroll:!1,isVisible:!1,hadInit:!1}),{currentPage:q}=v.useStore(),b=u.useRef(null),x=u.useRef(null),h=u.useRef(0),B=u.useRef(null);u.useEffect(()=>{const w=new IntersectionObserver(([k])=>{n.isVisible=k.isIntersecting},{root:null,rootMargin:"50px",threshold:0});return x.current&&w.observe(x.current),()=>w.disconnect()},[]),u.useEffect(()=>{const w=()=>{if(h.current+=1,h.current>ue){k.disconnect();return}if(!c.previewImage&&b.current){const T=b.current.scrollHeight,I=o/T;I<l?(n.scale=l,n.shouldScroll=!0):I<1?(n.scale=I,n.shouldScroll=!1):(n.scale=1,n.shouldScroll=!1)}B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{n.hadInit=!0},200)},k=new ResizeObserver(()=>{setTimeout(w,20)});return b.current&&n.isVisible&&k.observe(b.current),()=>{k.disconnect()}},[o,l,n.isVisible,c]);const{id:a,type:r,component:y,properties:C,previewImage:j}=c,M=u.useMemo(()=>n.isVisible?j?t.jsx(e.Box,{component:"img",loading:"lazy",src:v.getImageAbsoluteUrl(j),alt:c.name,sx:{width:"100%",height:"100%",objectFit:"cover",borderRadius:1,cursor:"pointer"}},a):r==="basic"?t.jsx(S.BlockRenderer,{id:a,type:y,section:C,config:{...C,locale:f,editing:!1,dev:{mode:"draft"}},page:q},a):t.jsx(pe,{componentId:a,locale:f,components:d},a):null,[a,r,y,C,f,j,n.isVisible]);return t.jsx(e.Box,{ref:x,sx:{position:"relative",width:"100%",height:"100%",overflowX:"hidden",overflowY:n.shouldScroll?"auto":"hidden",transition:"all 0.3s ease"},children:t.jsxs(e.Box,{sx:{transform:`scale(${n.scale})`,transformOrigin:"top left",width:`${100/n.scale}%`,height:n.hadInit&&n.shouldScroll?"100%":`${100/n.scale}%`},children:[!n.hadInit&&t.jsx(e.Skeleton,{variant:"rectangular",width:"100%",height:"100%"}),t.jsx(e.Box,{ref:b,sx:{width:"100%",height:j?"100%":"auto",pointerEvents:"none",opacity:n.hadInit?1:0},children:M})]})})}function U({groups:o,emptyText:c,renderItem:l,wrapperComponent:d=e.Box,wrapperComponentProps:f={display:"inline-flex",flexWrap:"wrap",gap:1}}){return t.jsx(e.Box,{children:Object.keys(o).length>0?Object.entries(o).map(([n,{title:q,components:b}])=>t.jsxs(e.Box,{sx:{mb:3},children:[n!==F&&t.jsxs(e.Typography,{className:"blocklet-title",variant:"subtitle2",sx:{mb:2,fontWeight:500,color:"text.primary",display:"flex",alignItems:"center",gap:1},children:[t.jsx(e.Box,{component:"span",sx:{width:4,height:20,backgroundColor:"primary.main",borderRadius:1,display:"inline-block"}}),q]}),t.jsx(d,{...f,children:b.map(x=>l(x))})]},n)):t.jsx($.default,{children:c})})}exports.AddComponent=V;exports.AutoScaledComponentRenderer=Q;exports.BASIC_COMPONENT_LIST=H;exports.GroupedComponentsList=U;exports.default=V;exports.formatComponent=E;
|
|
1
|
+
"use strict";var e=AddComponent;module.exports=e;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),o=require("./home-DUjl5PbP.js"),r=require("./state-CtNs8GrN.js");function n({children:t}){const e=r.useProjectId();return s.jsx(r.StoreProvider,{url:o.getWssURL(e??""),name:"root",waitingSynced:!0,children:s.jsx(u,{children:t})})}function u({children:t}){const{state:e}=r.useStore();return t({state:e})}exports.default=n;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";const d=require("@arcblock/ux/lib/Theme"),p=require("@blocklet/ui-react/lib/Header"),h=require("@mui/material"),s=require("react"),w=require("react-router-dom"),g=require("@arcblock/did-connect/lib/Session"),P=require("@blocklet/js-sdk"),l=require("ufo");require("lodash/isEmpty");require("yaml");const f=require("react/jsx-runtime"),q=e=>e&&e.__esModule?e:{default:e},S=q(p),{SessionProvider:F,SessionContext:_,SessionConsumer:C,withSession:$}=g.createAuthServiceSessionContext();function r(){return s.useContext(_)}function j(...e){const{session:t}=r();return e.includes(t.user?.role)}function I(...e){const{session:t}=r(),o=j(...e);return window.blocklet?.tenantMode==="multiple"?!!t.user:o}const m=window.blocklet?.prefix||"/",i=P.createAxios({timeout:200*1e3}),R=window.location.protocol==="https:"?"wss":"ws",b=e=>l.joinURL(`${R}://${window.location.hostname}`,m,`api/${e}/ws/pages`),y="z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";blocklet?.componentMountPoints.find(e=>e.did===y)?.mountPoint||l.joinURL(m,"/image-bin");function u(){const{pathname:e}=window.location,o=e.match(/\/admin\/(maker|previewer)\/([^/]+)/)?.[2],n=window.__PROJECT_ID__;if(!o&&!n)throw new Error("Unable to get projectId from pathname");return o||n}function M(e){return`${e}:pages:version`}const k=["production","draft"];function x({mode:e,version:t}={}){const o=t&&typeof t=="number"?{mode:e,version:t}:{mode:e};return i.get(`/api/${u()}/pages`,{params:o}).then(n=>n.data)}function E({mode:e,routes:t}){return i.post(`/api/${u()}/pages/publish`,{mode:e,routes:t}).then(o=>o.data)}function D(){const[e]=w.useSearchParams(),{session:t}=r(),o=I("owner","admin","pagesEditor","member"),n=s.useMemo(()=>{const a=e.get("mode");return k.includes(a)?a:"production"},[e]),c=n==="production"?n:t.user?o?n:"production":null;return c?f.jsx(HomeView,{mode:c}):null}s.lazy(()=>Promise.resolve().then(()=>require("./publish-button-C522nNv6.js")));s.lazy(()=>Promise.resolve().then(()=>require("./draft-data-CfIMszE7.js")));d.styled(S.default)`
|
|
2
|
+
&.sticky {
|
|
3
|
+
position: sticky;
|
|
4
|
+
top: 0;
|
|
5
|
+
}
|
|
6
|
+
`;d.styled(h.Button)``;exports.api=i;exports.d=D;exports.getPages=x;exports.getProjectIdFromPathnameOrWindow=u;exports.getProjectPageVersionKey=M;exports.getWssURL=b;exports.publishPages=E;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),q=require("./home-DUjl5PbP.js"),$=require("@arcblock/ux/lib/Locale/context"),X=require("@arcblock/ux/lib/Toast"),Y=require("@blocklet/pages-kit/utils/route"),O=require("@mui/icons-material"),F=require("@mui/lab"),s=require("@mui/material"),Z=require("immer"),ee=require("lodash/difference"),a=require("react"),te=require("react-use"),se=require("./state-CtNs8GrN.js"),H=n=>n&&n.__esModule?n:{default:n},E=H(X),V=H(ee);function ne(n){return e.jsx(s.Box,{...n,sx:[{display:"flex",flex:1,height:"100%",alignItems:"center",justifyContent:"center"},...Array.isArray(n.sx)?n.sx:[n.sx]],children:e.jsx(s.CircularProgress,{size:30})})}function ie(n){const[x,g]=a.useState(!1);return e.jsx(F.LoadingButton,{...n,loading:n.loading||x,onClick:c=>{const m=n.onClick?.(c);m instanceof Promise&&(g(!0),m.finally(()=>{g(!1)}))}})}const oe=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 re(){const[n,x]=a.useState(),g=a.useMemo(()=>n?e.jsx(s.Dialog,{...n}):null,[n]),c=a.useCallback(()=>{x(void 0)},[]),m=a.useCallback(({title:b,content:d,cancelText:P="Cancel",okText:f="Ok",onOk:y,onClose:u,okIcon:B,okColor:k="primary",cancelColor:h="primary",DialogContentProps:v,form:I,...M})=>{x({...M,open:!0,children:e.jsxs("form",{onSubmit:L=>L.preventDefault(),children:[b&&e.jsxs(s.DialogTitle,{className:"between",zIndex:"appBar",bgcolor:"background.paper",sx:{borderBottom:L=>`1px solid ${L.palette.divider}`},children:[e.jsx(s.Box,{children:b}),e.jsx(s.IconButton,{size:"small",onClick:async()=>{c(),u?.()},children:e.jsx(oe,{})})]}),d&&e.jsx(s.DialogContent,{...v,sx:{mt:-3,...v?.sx,bgcolor:"background.paper"},children:e.jsx(s.Box,{sx:{pt:3},children:d})}),e.jsxs(s.DialogActions,{sx:{bgcolor:"background.paper"},children:[e.jsx(s.Button,{variant:"outlined",color:h||"primary",onClick:u??c,children:P}),e.jsx(ie,{variant:"contained",color:k||"primary",startIcon:B,loadingPosition:B?"start":"center",onClick:async()=>{await y?.(),c()},type:"submit",children:f})]})]}),onClose:u??c})},[c]);return{dialog:g,showDialog:m,closeDialog:c}}const ae=({ref:n,mode:x,state:g})=>{const{t:c}=$.useLocaleContext(),[m,b]=a.useState(!1),{dialog:d,showDialog:P}=re(),f=se.useProjectId(),y=a.useCallback(B=>{let k=[];P({title:c("maker.publishToProduction"),content:e.jsxs(s.Box,{sx:{minWidth:300},children:[e.jsx(s.Alert,{color:"warning",icon:e.jsx(O.Warning,{}),children:c("maker.publishToProductionTip")}),e.jsx(s.Box,{sx:{maxHeight:"50vh",overflow:"auto",mt:2},children:e.jsx(ce,{state:g,toMode:x,onChange:h=>k=h,defaultRouteIds:B})})]}),okText:c("maker.publish"),cancelText:c("common.cancel"),onOk:async()=>{if(k?.length===0){const h=c("maker.publishSelectPagesMessage");throw E.default.error(h),new Error(h)}localStorage.setItem(q.getProjectPageVersionKey(f??""),String(new Date().getTime())),b(!0);try{await q.publishPages({mode:x,routes:k}),E.default.success(c("maker.publishSuccessMessage"))}catch(h){throw E.default.error(h.message),h}finally{b(!1)}}})},[x,g,c,f,P]);a.useImperativeHandle(n,()=>({openPublishDialog:y}));const u=a.useCallback(()=>{y()},[y]);return e.jsxs(e.Fragment,{children:[e.jsx(F.LoadingButton,{color:"primary",variant:"contained",size:"small",sx:{mr:1},onClick:u,loading:m,disabled:m,children:c("maker.publish")}),d]})};function le({routePathInfo:n,checked:x,onClick:g,route:c}){const{t:m}=$.useLocaleContext(),b=!n.routeMetaData?.publishedAt||n.routeMetaData?.updatedAt&&new Date(n.routeMetaData?.updatedAt)>new Date(n.routeMetaData?.publishedAt);return e.jsx(s.ListItem,{sx:{pl:4,pr:3},disablePadding:!0,secondaryAction:e.jsxs(s.Box,{sx:{display:"flex",alignItems:"center",minWidth:"auto"},children:[b&&e.jsx(s.Box,{className:"visible",title:m("maker.pages.needPublish"),sx:{mr:.35,color:"warning.main",display:"flex",alignItems:"center"},children:e.jsx(s.Tooltip,{title:m("maker.pages.needPublish"),children:e.jsx(O.Sync,{fontSize:"small",sx:{fontSize:"16px"}})})}),(!n.routeMetaData?.isPublic||!c.isPublic)&&e.jsx(s.Box,{className:"visible",sx:{color:"warning.main"},children:e.jsx(s.Tooltip,{title:m("maker.pages.notPublic"),children:e.jsx(O.VisibilityOff,{fontSize:"small",sx:{fontSize:"16px"}})})})]}),children:e.jsxs(s.ListItemButton,{onClick:g,dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:x,tabIndex:-1})}),e.jsx(s.ListItemText,{primary:n.path,slotProps:{primary:{fontSize:"0.8rem",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",pr:1}}})]})})}function ce({state:n,toMode:x,onChange:g,defaultRouteIds:c}){const{t:m,locale:b}=$.useLocaleContext(),[d,P]=a.useState(!1),[f,y]=a.useState(()=>c?Object.fromEntries(c.filter(t=>!t.includes("-")).map(t=>[t,!0])):{}),[u,B]=a.useState({}),[k,h]=a.useState(()=>c?Object.fromEntries(c.filter(t=>t.includes("-")).map(t=>[t,!0])):{}),[v,I]=a.useState({}),{loading:M,error:L,value:w}=te.useAsync(()=>q.getPages({mode:x}),[x]);if(L)throw L;const j=a.useMemo(()=>n.routeIds||[],[n]),R=a.useMemo(()=>w?.pageIds||[],[w]),D=a.useMemo(()=>!j||!n.routes?[]:JSON.parse(JSON.stringify(j)).sort((i,o)=>{const r=n.routes?.[i],l=n.routes?.[o];return r?.publishedAt&&new Date(r.publishedAt).getTime()<new Date(r.updatedAt).getTime()?-1:l?.publishedAt&&new Date(l.publishedAt).getTime()<new Date(l.updatedAt).getTime()?1:new Date(r?.updatedAt??"").getTime()-new Date(l?.updatedAt??"").getTime()}),[n,j]),z=a.useMemo(()=>{if(!D)return[];if(!u)return D;const t=[...D].filter(i=>!u[i]);return Object.values(u).forEach(i=>{i.forEach(o=>{t.push(`${o.originalRouteId}-${o.paramOptionIds.join("-")}`)})}),t},[D,u]),C=a.useMemo(()=>!w||!R||!z?[]:V.default(R,z),[z,w,R]),T=a.useMemo(()=>j?[...j].concat(C):C,[j,C]),W=a.useCallback(()=>{const t={};D?.forEach(i=>{const o=n.routes?.[i];if(o&&o.params&&o.params.length>0&&o.paramsOptions&&o.paramsOptions.length>0){const r=Y.generateParamCombinations({basePath:o.path,params:o.params,routeId:o.id,paramsOptions:o.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});r.length>0&&(t[o.id]=r)}}),B(t)},[D,n.routes]);a.useEffect(()=>{W()},[W]),a.useEffect(()=>{I(t=>{const i={...t};return Object.keys(u).forEach(o=>{u[o]&&u[o]?.length>0&&i[o]===void 0&&(i[o]=!0)}),i})},[u]);const _=a.useRef(!0);a.useEffect(()=>{h(t=>{const i={...t};return Object.keys(u).length===0||(Object.keys(u).forEach(o=>{const r=u[o]||[],l=d||!!f[o];r.forEach(A=>{const p=`${o}-${A.paramOptionIds.join("-")}`;_.current?i[p]=l||t[p]||!1:i[p]=l})}),_.current=!1),i})},[f,u,d]);const J=(t,i)=>{i.stopPropagation(),I(o=>{const r={...o};return r[t]=!r[t],r})},K=a.useCallback(t=>{y(i=>{const o=Z.produce(i,r=>{d?(Object.assign(r,Object.fromEntries(T.map(l=>[l,!0]))),delete r[t]):r[t]?(delete r[t],C.includes(t)&&(j||[]).filter(l=>n.pages[l]?.slug===w?.pages[t]?.slug).forEach(l=>{delete r[l]})):(r[t]=!0,j&&j.includes(t)&&C.filter(l=>w?.pages[l]?.slug===n.pages[t]?.slug).forEach(l=>{r[l]=!0}))});return P(V.default(T,Object.keys(o)).length===0),o})},[d,T,C,n,w,j]),U=a.useCallback((t,i)=>{const o=`${t}-${i.paramOptionIds.join("-")}`;h(r=>{const l={...r};l[o]=!l[o];const A=u[t]?.every(p=>l[`${t}-${p.paramOptionIds.join("-")}`])??!1;return y(p=>{if(A&&!p[t])return{...p,[t]:!0};if(!A&&p[t]){const S={...p};return delete S[t],S}return p}),l})},[u]),G=a.useCallback(()=>{P(t=>(t&&y({}),!t))},[]);return a.useEffect(()=>{const t=d?T:Object.keys(f),i=Object.entries(k).filter(([,r])=>r).map(([r])=>r).filter(r=>r!==void 0),o=Array.from(new Set([...t,...i]));g(d?null:o)},[d,f,k,T,g]),M?e.jsx(ne,{sx:{my:4}}):e.jsxs(s.List,{disablePadding:!0,sx:{maxWidth:700},children:[e.jsx(s.ListItem,{sx:{position:"sticky",top:0,zIndex:1},disablePadding:!0,children:e.jsxs(s.ListItemButton,{onClick:G,dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:d,tabIndex:-1})}),e.jsx(s.ListItemText,{primary:m("common.all")})]})}),D.map(t=>{const i=n.routes?.[t];if(!i)return null;const o=!1,r=u&&u[t]&&u[t]?.length>0,l=v[t]!==!1,A=u[t]||[],p=!i.publishedAt||i.updatedAt&&new Date(i.updatedAt).getTime()>new Date(i.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:[p&&e.jsx(s.Tooltip,{title:m("maker.pages.needPublish"),children:e.jsx(O.Sync,{fontSize:"small",sx:{color:"warning.main",fontSize:16,mr:.35}})}),!i.isPublic&&e.jsx(s.Tooltip,{title:m("maker.pages.notPublic"),children:e.jsx(O.VisibilityOff,{fontSize:"small",sx:{color:"warning.main",fontSize:16,mr:.35}})}),o,r&&e.jsx(s.Box,{onClick:S=>J(t,S),sx:{display:"inline-flex",alignItems:"center",mr:.35,cursor:"pointer",color:"info.main"},children:l?e.jsx(O.KeyboardArrowDown,{fontSize:"small",sx:{fontSize:"18px"}}):e.jsx(O.KeyboardArrowRight,{fontSize:"small",sx:{fontSize:"18px"}})})]}),children:e.jsxs(s.ListItemButton,{onClick:()=>K(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:i.path,slotProps:{primary:{noWrap:!0,textOverflow:"ellipsis"},secondary:{noWrap:!0,textOverflow:"ellipsis"}}})]})}),r&&e.jsx(s.Collapse,{in:l,children:e.jsx(s.Box,{children:A.map(S=>{const N=`${t}-${S.paramOptionIds.join("-")}`,Q=k[N]||!1;return e.jsx(le,{routePathInfo:S,checked:d||Q,onClick:()=>U(t,S),route:i},N)})})})]},t)}),C.map(t=>{const i=w?.pages[t];return i?e.jsx(s.ListItem,{disablePadding:!0,secondaryAction:e.jsx(s.Chip,{color:"warning",label:"deleted",size:"small"}),children:e.jsxs(s.ListItemButton,{onClick:()=>K(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:i.slug,secondary:i.locales?.[b]?.title,slotProps:{primary:{noWrap:!0,textOverflow:"ellipsis"},secondary:{noWrap:!0,textOverflow:"ellipsis"}}})]})},t):null})]})}exports.default=ae;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";var pt=Object.create;var ke=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,mt=Object.prototype.hasOwnProperty;var ht=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dt(e))!mt.call(t,o)&&o!==n&&ke(t,o,{get:()=>e[o],enumerable:!(s=ut(e,o))||s.enumerable});return t};var q=(t,e,n)=>(n=t!=null?pt(ft(t)):{},ht(e||!t||!t.__esModule?ke(n,"default",{value:t,enumerable:!0}):n,t));const gt=require("@blocklet/pages-kit/builtin/utils"),be=require("@blocklet/pages-kit/types"),W=require("@blocklet/pages-kit/utils/property"),ee=require("@blocklet/quickjs"),Ie=require("@blocklet/pages-kit/utils/builtin"),yt=require("@blocklet/sdk/lib/config"),le=require("lru-cache"),Be=require("node-fetch"),R=require("ufo"),St=require("lodash/isEmpty"),wt=require("crypto"),w=require("fs"),h=require("path"),bt=require("lodash/isNil"),It=require("@blocklet/logger"),Ve=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),Ce=require("@blocklet/sdk/lib/component"),F=require("@syncedstore/core"),Et=require("yjs"),Pt=require("@blocklet/pages-kit/utils/data-source"),te=require("@blocklet/pages-kit/utils/route"),Ct=require("lodash"),Re=require("@blocklet/pages-kit/utils/common"),At=require("@blocklet/pages-kit/utils/page-model"),Ot=require("@reactivedata/reactive"),ne=require("glob"),Tt=require("lib0/decoding"),jt=require("lib0/encoding"),vt=require("lodash/cloneDeep"),Dt=require("lodash/debounce"),kt=require("lodash/get"),Rt=require("lodash/set"),xt=require("lodash/union"),_t=require("p-limit"),v=require("sequelize"),Mt=require("stream/promises"),Lt=require("tar"),$t=require("wait-on"),z=require("y-protocols/awareness"),ge=require("y-protocols/sync"),Nt=require("yaml");require("sqlite3");require("@blocklet/pages-kit/types/state");const _=t=>t&&t.__esModule?t:{default:t};function pe(t){if(t&&t.__esModule)return t;const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,s.get?s:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const P=_(yt),Ut=_(Be),Ae=_(St),Ge=_(h),Ft=_(bt),qt=_(It),$=pe(Et),ye=pe(Tt),k=pe(jt),Bt=_(vt),Je=_(Dt),Oe=_(kt),xe=_(Rt),Vt=_(xt),Gt=_(_t),Jt=_($t),B=pe(Nt);P.default.env.mode;P.default.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY;P.default.env.OPENAI_BASE_URL||process.env.OPENAI_BASE_URL;P.default.env.TRANSLATE_ADDITIONAL_PROMPT||process.env.TRANSLATE_ADDITIONAL_PROMPT;P.default.env.PAGE_CONTENT_ADDITIONAL_PROMPT||process.env.PAGE_CONTENT_ADDITIONAL_PROMPT;const zt="image-bin";P.default.env.INIT_TEMPLATE_PATH;const ze=process.env.DATABASE_URL||Ge.default.join(P.default.env.dataDir,"db/pages-kit.db"),_e=P.default,Kt=()=>P.default.env.tenantMode==="multiple",Ht=()=>(Ft.default(_e.env.preferences.multiTenantAllProjectAccessPassports)?[]:_e.env.preferences.multiTenantAllProjectAccessPassports?.split(","))||[],Yt=Ge.default.join(P.default.env.dataDir,"fs-memoize-cache"),Wt=P.default.env.FS_MEMOIZE_CACHE_VERSION||"v1.0.0",f=qt.default("pages-kit"),Qt=v.DataTypes.sqlite.DATE.parse;v.DataTypes.sqlite.DATE.parse=(t,e)=>typeof t=="number"?new Date(t):Qt(t,e);const N=new v.Sequelize({dialect:"sqlite",storage:ze,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});N.query("pragma journal_mode = WAL;");N.query("pragma synchronous = normal;");N.query("pragma journal_size_limit = 33554432;");N.query("pragma cache_size = -2000;");N.query("pragma mmap_size = 33554432;");process.on("SIGINT",async()=>{await N.close(),process.exit(0)});process.on("SIGTERM",async()=>{await N.close(),process.exit(0)});async function Xt(t,e){try{if(t.getDialect()!=="sqlite")return;const[n]=await t.query("SELECT 1");if(!n||n.length===0)return;await t.query("PRAGMA shrink_memory;")}catch(n){if(n.name==="SequelizeConnectionError"||n?.message&&/closed!/.test(n.message))return;console.error("Failed to cleanup SQLite memory",e,n)}}setInterval(async()=>{f.info("Start cleanupSqliteMemory"),await Xt(N,ze),f.info("End cleanupSqliteMemory")},60*1e3*10);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:N,tableName:"ProjectComponents",timestamps:!1});class M extends v.Model{static async getProjectByIdOrSlug(e){return M.findOne({where:{[v.Op.or]:[{id:e},{slug:e}]}})}}M.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(){const t=this.getDataValue("relatedBlocklets");if(typeof t=="object")return t??{};try{return t?JSON.parse(t):{}}catch(e){return f.error("Failed to parse relatedBlocklets",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("relatedBlocklets",t?JSON.stringify(t):"{}")}catch(e){f.error("Failed to set relatedBlocklets",{error:e,value:t}),this.setDataValue("relatedBlocklets","{}")}}},productionState:{type:v.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){const t=this.getDataValue("productionState");if(typeof t=="object")return t??{};try{return t?JSON.parse(t):{}}catch(e){return f.error("Failed to parse productionState",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("productionState",t?JSON.stringify(t):"{}")}catch(e){f.error("Failed to set productionState",{error:e,value:t}),this.setDataValue("productionState","{}")}}}},{sequelize:N,paranoid:!0});M.hasMany(Te,{foreignKey:"projectId",as:"components"});const Zt=Yt,en=Wt,se=30*24*60*60*1e3,tn=24*60*60*1e3,Ke=async(t="")=>{const e=h.join(Zt,t);try{if(!(await w.promises.stat(e)).isDirectory())throw new Error(`${e} is not a directory`)}catch{await w.promises.mkdir(e,{recursive:!0})}return e},Me=(t,...e)=>t.keyGenerator?t.keyGenerator(...e):JSON.stringify([t.subdir||"",...e]),nn=(t,e)=>{const n=wt.createHash("md5").update(e).digest("hex");return h.join(t,`${en}-${n}.json`)},sn=async(t="")=>{const e=await Ke(t),n=Date.now();try{const s=await w.promises.readdir(e);await Promise.all(s.filter(o=>o.endsWith(".json")).map(async o=>{const r=h.join(e,o);try{const c=await w.promises.readFile(r,"utf-8"),a=JSON.parse(c);a.createdAt&&n-a.createdAt>se&&await w.promises.unlink(r)}catch{try{const a=await w.promises.stat(r);n-a.mtimeMs>se&&await w.promises.unlink(r)}catch{}}}))}catch(s){console.error(`Failed to cleanup cache in ${e}:`,s)}},on=(()=>{const t=new Set;return setInterval(async()=>{await Promise.all(Array.from(t).map(s=>sn(s)))},tn).unref(),s=>{t.add(s)}})();function ue(t,e){return e.subdir&&on(e.subdir),ee.memoize(async(...s)=>{const o=await Ke(e.subdir||""),r=Me(e,...s),c=nn(o,r);try{const a=await w.promises.readFile(c,"utf-8"),{value:p,createdAt:d}=JSON.parse(a);if(d&&Date.now()-d>se)throw await w.promises.unlink(c).catch(()=>{}),new Error("Cache expired");return p}catch{const p=await t(...s),d=JSON.stringify({value:p,createdAt:Date.now()});return w.promises.writeFile(c,d,"utf-8").catch(E=>{console.error("Failed to write fs cache:",E)}),p}},{keyGenerator:(...s)=>Me(e,...s),lruOptions:e.lruOptions||{max:100,ttl:se}})}const He=async()=>await import("typescript"),rn=async()=>await import("esbuild"),an=async()=>(await import("postcss")).default,cn=async()=>(await import("tailwindcss")).default,ln=async()=>(await import("autoprefixer")).default,pn=async(t,{componentId:e})=>{const n=`@tailwind components;
|
|
2
|
+
@tailwind utilities;
|
|
3
|
+
`,s=`.CustomComponent_${e}`,o=await an(),r=await cn(),c=await ln();return(await o([r({content:[{raw:t,extension:"tsx"}]}),c({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),p=>{p.walkRules(d=>{d.selectors=d.selectors.map(E=>E.replace(/\.(.+)/g,`${s}.$1,${s} .$1`))})}]).process(n)).css},un=async(t,{componentId:e})=>{const n=await pn(t,{componentId:e});return`export const __PagesKit_CSS__ = ${JSON.stringify(n)};
|
|
4
|
+
|
|
5
|
+
${t}
|
|
6
|
+
`},Le=ue(async(t,e)=>{const n=await He();let s=n.transpileModule(t,{compilerOptions:{jsx:n.JsxEmit.React,target:n.ScriptTarget.ES2016,module:n.ModuleKind.ESNext},transformers:{before:[Ve.createBuiltinModuleTransformer(n)]}}).outputText;if(e.tailwind&&(s=await un(s,{componentId:e.componentId})),e.module===be.PreloadComponentScriptModule.ESM)return s;const o=n.transpileModule(s,{compilerOptions:{jsx:n.JsxEmit.React,target:n.ScriptTarget.ES2016,module:n.ModuleKind.CommonJS,moduleResolution:n.ModuleResolutionKind.Node16}}).outputText;return e.module===be.PreloadComponentScriptModule.CJS?o:mn(e.moduleName,o)},{subdir:"transpileModule"}),dn=async(t,e)=>{const{build:n}=await rn(),o=(await n({entryPoints:["index.tsx"],external:Object.keys(Ie.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(p){let d=null;p.onResolve({filter:/.*/},E=>E.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:E.path==="./component"?{path:"component.tsx",namespace:"vfs"}:null),p.onLoad({filter:/.*/,namespace:"vfs"},async E=>{if(E.path==="index.tsx")return{contents:`export { ${e} } from './component'`,loader:"tsx"};if(E.path==="component.tsx")return{contents:t,loader:"tsx"};if(Ve.isRelativeModule(E.path)){const g=E.path.split("/").pop();if(d||(d=await ct({ensureLoaded:!1})),d?.chunks?.[g])try{const b=w.readFileSync(d.chunks[g],"utf-8");return f.info("get chunk from local file system",g),{contents:b,loader:"tsx"}}catch{}}return null})}}]})).outputFiles?.[0]?.contents;if(!o)throw new Error("Failed to build server code");const r=Buffer.from(o).toString(),c=await He();return c.transpileModule(r,{compilerOptions:{module:c.ModuleKind.ESNext,target:c.ScriptTarget.ES2020}}).outputText},fn=(t,e)=>new RegExp(`export\\s+\\{[^}]*(?:\\w+\\s+as\\s+${e}\\b|\\b${e}\\b)[^}]*\\}`,"m").test(t)?t:void 0,Ye=ue(async(t,e)=>{const n=await dn(t,e);return fn(n,e)},{subdir:"extractExportValueSchema"}),mn=(t,e)=>`// GENERATED FILE. DO NOT EDIT.
|
|
7
|
+
var ${t} = 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
|
+
${e}
|
|
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
|
+
`,We=async()=>{const{Sandbox:t}=await import("@blocklet/quickjs");return t};function hn(t){return t?.type==="react-component"}const K=new le.LRUCache({max:100,ttl:1e3*60*60*24}),gn=60*60,$e=10;function yn(t){f.info("clear preload components cache",{cacheKey:t}),K.delete(t)}function Sn(t){for(const e of K.keys())e.includes(t)&&(f.info("clear preload components cache",{cacheKey:e}),yn(e))}function wn({mode:t,instanceId:e,componentId:n,locale:s}){return["getPreloadComponents",t,e,n,s].join("-")}async function bn({mode:t,req:e,state:n,locale:s,instances:o,module:r}){const{supportedLocales:c,config:{defaultLocale:a}}=n;if(!a)return null;const p=(await Promise.all(o.map(async l=>{try{const i=wn({mode:t,instanceId:l.id,componentId:l.componentId,locale:s});if(t!=="draft"&&l.useCache&&K.has(i))return f.info(`get preload component from cache: ${i}`),K.get(i);const S=oe({state:n,componentId:l.componentId});if(!S)return null;const A=await In({req:e,state:n,componentId:S.id,locale:s,defaultLocale:a,properties:l.properties});if(!A)return null;const y={instanceId:l.id,preload:A};if(t!=="draft"&&l.useCache){let m=gn;l.cacheDuration&&(m=l.cacheDuration),f.info(`set preload component to cache(${m}s): ${i}`),K.set(i,y,{ttl:m*1e3})}return y}catch(i){return f.error("get preload component error",{instanceId:l.id,componentId:l.componentId},{error:i}),null}}))).filter(l=>!!l),d=Object.values(p.reduce((l,i)=>({...l,...i.preload.components}),{}));async function E(){const l=await Promise.all(d.map(async i=>{const S=W.componentUMDName({componentId:i.component.id}),A=r===be.PreloadComponentScriptModule.ESM?{module:r,script:await Le(i.script,{componentId:i.component.id,module:r,tailwind:t!=="draft"})}:{module:r,script:await Le(i.script,{componentId:i.component.id,module:r,moduleName:S,tailwind:t!=="draft"}),moduleName:S};return[i.component.id,{component:i.component,script:A}]}));return Object.fromEntries(l)}const g=await E();return{config:{defaultLocale:a,supportedLocales:c},components:g,instances:p.map(l=>({id:l.instanceId,componentId:l.preload.component.id,locales:{[l.preload.locale]:{props:l.preload.props}}}))}}async function In({req:t,state:e,componentId:n,locale:s,defaultLocale:o,properties:r}){const{supportedLocales:c}=e,a=oe({state:e,componentId:n});if(!a)return null;const p=c.some(E=>E.locale===s)?s:o;if(!p)return null;const d=await Qe({req:t,state:e,componentId:n,locale:p,defaultLocale:o,properties:r});return d?{component:a,...d}:null}const En=20;async function Qe({req:t,depth:e=0,state:n,componentId:s,locale:o,defaultLocale:r,properties:c}){if(e>En)throw new RangeError("max component depth exceeded");const a=Pn({state:n,componentId:s,properties:c,locale:o});if(!a)return null;const{props:p,component:d}=a,E={locale:o||r,components:{[a.component.id]:{component:a.component,script:a.script}},props:{...p}};try{const g=hn(d.renderer)?d.renderer.getServerSideProps:void 0,b=await Cn({...a,req:t,serverSideProps:g});b?.props&&Object.assign(E.props,b.props)}catch(g){f.error("preload data at server side error",{componentId:s,name:a.component.name},{error:g})}return await Promise.all(Object.entries(p).map(async([g,b])=>{if(b?.type===W.RenderNestedComponent){const l=await Qe({req:t,depth:e+1,state:n,componentId:b.componentId,locale:o,defaultLocale:r,properties:b.properties});l&&(Object.assign(E.components,l.components),Object.assign(E.props,{[g]:{type:W.RenderNestedComponent,componentId:b.componentId,props:l.props}}))}})),E}function Pn({state:t,componentId:e,locale:n,properties:s}){const o=oe({state:t,componentId:e});if(!o)return null;const r=W.mergeComponent({componentId:e,getComponent:c=>oe({state:t,componentId:c}),locale:n,defaultLocale:t.config.defaultLocale,properties:s});return r?{component:o,script:r.script,props:{locale:n,...r.props}}:null}function oe({state:t,componentId:e}){return t.components[e]?.data??t.resources.components?.[e]?.component}async function Cn({component:t,script:e,props:n,req:s,serverSideProps:o}){if(!o&&!e?.includes("getServerSideProps"))return null;const r=o??await Ye(e,"getServerSideProps");if(!r)return null;const a=(r.match(/export\s*{\s*(\w+)\s+as\s+getServerSideProps\s*}/)||r.match(/export\s*{\s*getServerSideProps\s*}/))?.[1]||"getServerSideProps",p=new Promise(g=>{setTimeout(()=>{g({})},$e*1e3)}),d=await We();return await Promise.race([p,d.callFunction({code:`${r}
|
|
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 ${a}(componentProps);
|
|
44
|
+
} finally {
|
|
45
|
+
// 清理全局状态
|
|
46
|
+
if (originalLocation) globalThis.location = originalLocation;
|
|
47
|
+
if (originalFetch) globalThis.fetch = originalFetch;
|
|
48
|
+
}
|
|
49
|
+
}`,filename:`${t.name||t.id}.js`,moduleLoader:g=>{if(g==="@blocklet/pages-kit/builtin/utils")return` const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
|
|
50
|
+
export { joinURL, withQuery, getQuery, getComponentMountPoint }
|
|
51
|
+
`;if(g==="@blocklet/pages-kit/builtin/dayjs")return ee.BuiltinModules.dayjs;if(g in ee.BuiltinModules)return ee.BuiltinModules[g];if(g in Ie.BuiltinModules){const b=Ie.BuiltinModules[g];return Ae.default(b)?void 0:b}},global:{console:{log:(...g)=>{f.info(...g)},warn:(...g)=>{f.warn(...g)},error:(...g)=>{f.error(...g)}},getComponentMountPoint:gt.getComponentMountPoint,joinURL:R.joinURL,withQuery:R.withQuery,getQuery:R.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:R.joinURL(R.withHttps(s.hostname),s.originalUrl)},fetch:(g,{...b}={})=>{const l=typeof g=="string"&&g.startsWith("/")?R.joinURL(P.default.env.appUrl,g):g;if(typeof l=="string"&&R.parseURL(l).host===R.parseURL(P.default.env.appUrl).host){const i=s.get("cookie");if(i){const S=new Be.Headers(b.headers);S.set("cookie",i),b.headers=S}}return Ut.default(l,{...b,timeout:$e*1e3}).then(i=>({ok:i.ok,status:i.status,statusText:i.statusText,headers:Object.fromEntries(i.headers.entries()),json:()=>i.json()}))},props:n}]})])}const An=ue(async(t,e,n,s)=>{if(!t?.includes(e)&&!s)return null;const o=s??await Ye(t,e);if(o)try{return await(await We()).callFunction({code:`
|
|
52
|
+
${o}
|
|
53
|
+
|
|
54
|
+
export function get${e}SchemaWrapper() {
|
|
55
|
+
return ${e};
|
|
56
|
+
}
|
|
57
|
+
`,filename:`${n}.js`,functionName:`get${e}SchemaWrapper`})}catch(r){return f.error(`获取 ${e} 失败`,{componentId:n,error:r}),null}return null},{subdir:"getExportSchemaValueFromCode"}),On="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",Ee="page",Ne="trigger-reload-project-resource",je=On,Tn="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM";function re(t){t.observeDeep(e=>{e.some(n=>n.changes.keys.has("updatedAt")||n.changes.keys.has("publishedAt"))||t.set("updatedAt",new Date().toISOString())})}function Xe(){return w.mkdtempSync(h.join(P.default.env.dataDir,"tmp-"))}function ae(t,e,n=[]){return Array.isArray(t)?t.flatMap((s,o)=>ae(s,e,[...n,o])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([s,o])=>ae(o,e,[...n,s])):e(t)?[n]:[]}function x(t){return t.filter(e=>e!=null)}function jn(t){t.pages&&Object.keys(t.pages).forEach(n=>{const s=F.getYjsValue(t.pages[n]);s&&s instanceof $.Map&&re(s)});const e=F.getYjsValue(t.pages);e&&e instanceof $.Map&&e.observe(n=>{n.changes.keys.forEach((s,o)=>{if(s.action==="add"){const r=F.getYjsValue(t.pages[o]);r&&r instanceof $.Map&&re(r)}})})}function vn(t){t.routes&&Object.keys(t.routes).forEach(n=>{const s=F.getYjsValue(t.routes?.[n]);s&&s instanceof $.Map&&re(s)});const e=F.getYjsValue(t.routes);e&&e instanceof $.Map&&e.observe(n=>{n.changes.keys.forEach((s,o)=>{if(s.action==="add"){const r=F.getYjsValue(t.routes?.[o]);r&&r instanceof $.Map&&re(r)}})})}function Dn(t,e){for(const n of e||Object.keys(t.routes||{})){let s=n,o=[];if(n.includes("-")){const[r,...c]=n.split("-");s=r,o=c||[]}if(t.routes?.[s]!==void 0){t.routes[s].publishedAt=new Date().toISOString();const r=t.routes[s];if(!r||!r.params||r.params.length===0)continue;if(n.includes("-")&&o.length>0){const c=te.getRouteMetaDataByOptionIds(o,r);c&&(c.publishedAt=new Date().toISOString())}if(!e){const c=te.generateParamCombinations({basePath:r.path,params:r.params,routeId:r.id,paramsOptions:r.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const a of c)a.routeMetaData??={},a.routeMetaData.publishedAt=new Date().toISOString()}}}}function Se({page:t,route:e,state:n,routeId:s,routePathInfo:o}){f.info(`Executing datasource data assembly, routeId: ${s}, routePathInfo: ${JSON.stringify(o)}`);const r={...Ct.cloneDeep(t),id:s,slug:o?.path??e.path,createdAt:e.createdAt,updatedAt:o?.routeMetaData?.updatedAt??e.updatedAt,publishedAt:o?.routeMetaData?.publishedAt??e.publishedAt,isPublic:(o?.routeMetaData?.isPublic??e.isPublic)&&e.isPublic};for(const c of n.supportedLocales){if(e.dataSource){let a=e.id;o&&(a=o.paramOptionIds.join("-"));const p=e.dataSource.pathDataMappings?.[a]?.dataCache?.[c.locale]??e.dataSource.pathDataMappings?.[a]?.dataCache?.[n.config.defaultLocale||"en"];if(!p)continue;Pt.setPageDataSource(r,n,c.locale,p)}o&&o.routeMetaData&&(o.routeMetaData.publishedAt=new Date().toISOString())}return r}const V=new le.LRUCache({max:100,ttl:10*60*1e3});function kn(t,e=[]){let n=0;const s=Array.from(V.keys()),o=[];for(const r of t){o.push(`page-html:prod:${r}:lang-path=none`);for(const c of e)o.push(`page-html:prod:/${c}${r}:lang-path=${c}`)}for(const r of s){const c=r.split(":lang-path=")[0]||"";for(const a of o){const d=(a.split(":lang-path=")[0]||"").replace(/\/:[^/]+/g,"");if(c.startsWith(d)){V.delete(r),n++,f.info(`[Cache CLEAR] key: ${r}`);break}}}return f.info(`[Cache CLEAR] cleared ${n} entries for patterns:`,o),n}function Rn({projectId:t,projectSlug:e,supportedLocales:n=[]}){let s=0;const o=Array.from(V.keys()),r=[];r.push(`page-html:prod:/${t}`),e&&e!==t&&r.push(`page-html:prod:/${e}`);for(const c of n)r.push(`page-html:prod:/${c}/${t}`),e&&e!==t&&(e!=="/"?r.push(`page-html:prod:/${c}/${e}`):r.push(`page-html:prod:/${c}`));for(const c of o)for(const a of r)if(c.startsWith(a)){V.delete(c),s++,f.info(`[Cache CLEAR PROJECT] key: ${c}`);break}return f.info(`[Cache CLEAR PROJECT] cleared ${s} entries for project ${t}${e?` (slug: ${e})`:""}`),s}function xn(){const t=V.size;return V.clear(),f.info(`[Cache CLEAR ALL] cleared ${t} entries`),t}P.default.events.on(P.default.Events.envUpdate,xn);const{uploadToMediaKit:_n}=require("@blocklet/uploader-server"),ve=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,H=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Ue=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Mn=1e4,Ln=3e4,Q=0,we=1,$n=0,Nn=1,Ze=P.default,X=h.join(process.env.BLOCKLET_DATA_DIR,"site-state");function ie(t){return t?.replace(/\//g,"|")||""}function Un(){const t=Ze.env.languages.map(n=>({locale:n.code,name:n.name})),e=t[0]?.locale;return{pageIds:[],pages:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{},components:{},supportedLocales:t,config:{defaultLocale:e},resources:{}}}class j extends $.Doc{constructor(e){super(),this.options=e,w.existsSync(this.draftYjsFilePath)&&$.applyUpdate(this,w.readFileSync(this.draftYjsFilePath)),this.syncedStore=Ot.reactive(F.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new z.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static RELEASE_DELAY=5*60*1e3;static PERIODIC_CHECK_INTERVAL=2*60*60*1e3;static sharedInstances={};static pageUrlMapCache=new le.LRUCache({max:100,ttl:1e3*60*60*24});static periodicCheckTimer;static safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const n=h.join(X,e),s=h.join(X,`@del-${e}`);w.renameSync(n,s)}catch(n){f.error("Failed to safe delete project state dir:",n)}}static async getProjectIds(){return(await M.findAll({attributes:["id"],raw:!0})).map(e=>e.id)}static get projectIds(){return ne.globSync("*/",{cwd:X,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*","undefined"]})}static get allShared(){return this.projectIds.map(e=>j.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let n=j.sharedInstances[e];return n||(n=new j({path:h.join(X,e)}),j.sharedInstances[e]=n,it({projectId:e,pages:de,components:fe}),n)}static async getProductionState(e){return(await M.findByPk(e,{attributes:["productionState"]}))?.productionState??Un()}destroy(){this.cancelRelease(),this.save({flush:!0}),this.conns.forEach((n,s)=>this.closeConn(s)),this.awareness.destroy();const e=h.basename(this.options.path);delete j.sharedInstances[e],super.destroy()}initObserver(){jn(this.syncedStore),vn(this.syncedStore)}get draftYjsFilePath(){return h.join(this.options.path,"draft.yjs")}static async getStateByProjectId(e,n){if(n==="draft"){const s=j.shared(e);return JSON.parse(JSON.stringify(s.syncedStore))}return j.getProductionState(e)}async getState(e){if(e==="draft")return JSON.parse(JSON.stringify(this.syncedStore));const n=h.basename(this.options.path);return j.getProductionState(n)}async setState(e,n){const s=await tt(n,{exportAssets:!1,includeResources:!0}),o=this.getPublishDir(e);if(w.mkdirSync(h.dirname(o),{recursive:!0}),w.rmSync(o,{force:!0,recursive:!0}),w.renameSync(s,o),e==="production"){const r=h.basename(this.options.path);j.pageUrlMapCache.delete(r),await M.update({productionState:n},{where:{id:r}})}}getPublishDir(e){return h.join(this.options.path,e)}syncedStore;conns=new Map;awareness;releaseTimer;awarenessChangeHandler=({added:e,updated:n,removed:s},o)=>{const r=e.concat(n,s);if(o!==null){const p=this.conns.get(o);p&&(e.forEach(d=>{p.add(d)}),s.forEach(d=>{p.delete(d)}))}const c=k.createEncoder();k.writeVarUint(c,we),k.writeVarUint8Array(c,z.encodeAwarenessUpdate(this.awareness,r));const a=k.toUint8Array(c);this.conns.forEach((p,d)=>this.send(d,a))};updateHandler=e=>{const n=k.createEncoder();k.writeVarUint(n,Q),ge.writeUpdate(n,e);const s=k.toUint8Array(n);this.conns.forEach((o,r)=>this.send(r,s))};ensureDataStructure=()=>{const{supportedLocales:e,pages:n,pageIds:s,config:o,routes:r,routeIds:c}=this.syncedStore;{const a=new Set(Object.keys(n));let p=0;for(;p<s.length;){const d=s[p];a.has(d)?(a.delete(d),p++):s.splice(p,1)}}{const a=new Set(Object.keys(r));let p=0;for(;p<c.length;){const d=c[p];a.has(d)?(a.delete(d),p++):c.splice(p,1)}}e.splice(0,e.length),e.push(...Ze.env.languages.map(a=>({locale:a.code,name:a.name}))),o.defaultLocale=e[0]?.locale;{let a=0;const p=new Set;for(;a<e.length;){const{locale:d}=e[a];p.has(d)?e.splice(a,1):(a++,p.add(d))}}};send=(e,n)=>{e.readyState!==$n&&e.readyState!==Nn&&this.closeConn(e);try{e.send(n,s=>{s&&this.closeConn(e)})}catch{this.closeConn(e)}};closeConn=e=>{if(e.removeAllListeners(),this.conns.has(e)){const n=this.conns.get(e);this.conns.delete(e),n&&z.removeAwarenessStates(this.awareness,Array.from(n),null)}e.close(),this.checkAndScheduleRelease()};checkAndScheduleRelease(){this.conns.size===0&&this.scheduleRelease()}scheduleRelease(){this.cancelRelease();const e=h.basename(this.options.path);this.releaseTimer=setTimeout(()=>{f.info(`[SiteState] releasing instance due to no active connections: ${e}`),this.conns.size===0&&(this.releaseTimer=void 0,this.destroy())},j.RELEASE_DELAY),f.info(`[SiteState] scheduled release for project ${e} in ${j.RELEASE_DELAY/1e3}s`)}cancelRelease(){if(this.releaseTimer){clearTimeout(this.releaseTimer),this.releaseTimer=void 0;const e=h.basename(this.options.path);f.info(`[SiteState] cancelled scheduled release for project ${e}`)}}autoSave=Je.default(()=>{w.mkdirSync(h.dirname(this.draftYjsFilePath),{recursive:!0}),w.writeFileSync(this.draftYjsFilePath,$.encodeStateAsUpdate(this))},Mn);save=({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()};publish=async({mode:e,routes:n})=>{const s=await this.getState("draft"),o=await this.getState("production");await qe(s,o,{routes:n,mergeMode:"replace",deleteRoutes:!0,publishMode:e}),o.config.publishedAt=new Date().getTime(),Dn(this.syncedStore,n),await this.setState(e,o),await this.clearPageCacheForRoutes(n,o)};mergeState=async(e,n)=>{const s=JSON.parse(JSON.stringify(n));e.config.fontFamily??={};const o=s.config?.fontFamily,r=e.config?.fontFamily;e.config.fontFamily.title=o?.title||r?.title,e.config.fontFamily.description=o?.description||r?.description,await new Promise((c,a)=>{this.transact(async()=>{try{const p=await qe(e,n);c(p)}catch(p){a(p)}})})};clearPageCacheForRoutes=async(e,n)=>{const s=h.basename(this.options.path),r=(await M.findByPk(s))?.slug||s;if(f.info(`[SiteState] clearing page cache for project ${s}, routes:`,e||[]),!e||e.length===0){Rn({projectId:s,projectSlug:r,supportedLocales:n.supportedLocales.map(d=>d.locale)});return}const c=n.supportedLocales.map(d=>d.locale),a=[],p=e.filter(d=>n.pages[d]);for(const d of p){const g=n.pages[d].slug;r&&r!==s&&(r==="/"?a.push(g):a.push(`/${r}${g}`)),a.push(`/${s}${g}`)}if(f.info(`[SiteState] clearing page cache for project ${s}, pathPatterns:`,a),a.length>0){const d=kn(a,c);f.info(`[SiteState] cleared ${d} page cache entries for project ${s}, routes:`,e)}};addConnection=e=>{if(this.conns.has(e))return;this.cancelRelease(),e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",o=>this.messageListener(e,new Uint8Array(o)));let n=!0;const s=setInterval(()=>{if(!n)this.conns.has(e)&&this.closeConn(e),clearInterval(s);else if(this.conns.has(e)){n=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(s)}}},Ln);e.on("close",()=>{this.closeConn(e),clearInterval(s)}),e.on("pong",()=>{n=!0});{const o=k.createEncoder();k.writeVarUint(o,Q),ge.writeSyncStep1(o,this),this.send(e,k.toUint8Array(o));const r=this.awareness.getStates();if(r.size>0){const c=k.createEncoder();k.writeVarUint(c,we),k.writeVarUint8Array(c,z.encodeAwarenessUpdate(this.awareness,Array.from(r.keys()))),this.send(e,k.toUint8Array(c))}}};messageListener=(e,n)=>{try{const s=k.createEncoder(),o=ye.createDecoder(n),r=ye.readVarUint(o);switch(r){case Q:k.writeVarUint(s,Q),ge.readSyncMessage(o,s,this,null),k.length(s)>1&&(this.ensureDataStructure(),this.send(e,k.toUint8Array(s)));break;case we:{z.applyAwarenessUpdate(this.awareness,ye.readVarUint8Array(o),e);break}default:f.warn(`Unsupported messageType ${r}`)}}catch(s){f.error(s)}this.save()};static async pageUrlMap(e,n){let s=[];n?s=[n]:s=await this.getProjectIds();let o={};if(e==="production"&&s?.length){const r=new Map(s.map(c=>[c,!0]));for(const c of s){const a=j.pageUrlMapCache.get(c);a&&(o={...o,...a},r.delete(c))}s=Array.from(r.keys())}if(s?.length){const r=await M.findAll({where:{id:{[v.Op.in]:s}}});await Promise.all(r.map(async c=>{const a=c.id,p=c.slug||a,d={},E=e==="production"&&c?.productionState?c.productionState:await j.getStateByProjectId(c.id,e),g=Vt.default(P.default.env.languages.map(l=>l.code),E.supportedLocales.map(l=>l.locale)),b=(l,i)=>{p&&(d[R.joinURL("/",p,l)]={...i,shouldRedirect:!0,mainPage:!0}),d[R.joinURL("/",a,l)]={...i,shouldRedirect:!0,mainPage:!0};for(const S of g){const A={...i,locale:S};d[R.joinURL("/",S,a,l)]=A,p&&(d[R.joinURL("/",S,p,l)]=A)}};if(e==="draft")for(const l of E.routeIds||[]){const i=E?.routes?.[l];if(!i)continue;if(i.params&&i.params.length>0){const y=te.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const m of y){const I=m.path,O={projectId:a,projectSlug:p,pageSlug:I,pageId:i.displayTemplateId||"",routeId:l,defaultLocale:g?.[0],locales:g,publishedAt:E.config.publishedAt,isPublic:i.isPublic&&m?.routeMetaData?.isPublic};b(I,O)}}const S=i.path,A={projectId:a,projectSlug:p,pageSlug:S,pageId:i.displayTemplateId||"",routeId:l,defaultLocale:g?.[0],locales:g,publishedAt:E.config.publishedAt,isPublic:i.isPublic};b(S,A)}for(const l of E.pageIds){const i=E.pages[l];if(!i||e==="production"&&!i.isPublic)continue;const S=i.slug,A=c.slug||a,y={projectId:a,projectSlug:A,pageSlug:S,pageId:l,defaultLocale:g?.[0],locales:g,publishedAt:E.config.publishedAt,isPublic:i.isPublic,templateConfig:i.templateConfig};b(S,y)}e==="production"&&j.pageUrlMapCache.set(a,d),o={...o,...d}}))}return o}getDocumentSize(){return $.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const e=[];for(const[n,s]of Object.entries(j.sharedInstances)){const o=s.getDocumentSize();e.push({projectId:n,sizeInBytes:o,sizeInMB:`${(o/(1024*1024)).toFixed(2)} MB`,activeConnections:s.conns.size})}return e}static startPeriodicCheck(){this.periodicCheckTimer||(this.periodicCheckTimer=setInterval(()=>{this.performPeriodicCheck()},this.PERIODIC_CHECK_INTERVAL),f.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,f.info("[SiteState] periodic check stopped"))}static performPeriodicCheck(){const e=Object.keys(j.sharedInstances).length,n=[],s=[];for(const[o,r]of Object.entries(j.sharedInstances))r.conns.size===0?n.push({projectId:o,instance:r}):s.push({projectId:o,connections:r.conns.size});if(f.info(`[SiteState] periodic check summary: total instances: ${e}, with connections: ${s.length}, without connections: ${n.length}`),n.length>0){f.info(`[SiteState] releasing ${n.length} instances without connections:`,n.map(r=>r.projectId));let o=0;for(const{projectId:r,instance:c}of n)try{f.info(`[SiteState] releasing instance due to periodic check: ${r}`),c.destroy(),o++}catch(a){f.error(`[SiteState] failed to release instance ${r} during periodic check:`,a)}f.info(`[SiteState] periodic check completed: ${o}/${n.length} instances released successfully`)}else e>0?f.debug("[SiteState] periodic check: all instances have active connections"):f.debug("[SiteState] periodic check: no instances exist")}}async function Fn(t,e,n){if(!t||!w.existsSync(t)||!w.lstatSync(t).isFile())return null;let s=n[t];return s||(s=(async()=>{try{return(await _n({filePath:t,fileName:e}))?.data?.filename}catch(o){return f.error(`Failed to upload asset ${t}:`,o),null}})(),n[t]=s),s}const qn=async(t,e)=>{const n=h.basename(t),s=await Ce.call({name:je,path:R.joinURL("/uploads",n),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const o=w.createWriteStream(e);await Mt.pipeline(s.data,o)}else throw new Error(`download asset failed ${s.status}`)},Bn=async(t,e)=>{await Promise.all(t.map(async n=>{try{await qn(n,h.join(e,h.basename(n)))}catch(s){f.error(`Failed to export assets: ${n}, ${s}`)}}))};function et(t){return ve.test(t)?[t]:H.test(t)?(Ue.lastIndex=0,Array.from(t.matchAll(Ue)).map(n=>n[1]).filter(n=>!!n)):[]}async function Z(t,e,n){const{getFilename:s,exportAssets:o}=n,r=h.join(e,s(t));if(w.mkdirSync(h.dirname(r),{recursive:!0}),w.writeFileSync(r,B.stringify(t)),o){const a=ae(t,p=>typeof p=="string"&&(ve.test(p)||H.test(p))).map(p=>{const d=Oe.default(t,p);return et(d)}).flat().filter(Boolean);await Bn(a,h.dirname(r))}}const Pe=new le.LRUCache({max:100,ttl:1*60*1e3});async function Fe(t,e,n){const s=ae(t,a=>typeof a=="string"&&(ve.test(a)||H.test(a))),o=Gt.default(2),r=s.map(a=>o(async()=>{try{const p=Oe.default(t,a),d=et(p);for(const E of d){const g=h.basename(E),b=n.getFilePath(E,a),l=b?`${b}:${g}`:g,i=Pe.get(l);if(i){H.test(p)||xe.default(t,a,i);return}const S=await Fn(b,g,e);S&&(H.test(p)||xe.default(t,a,S),Pe.set(l,S))}}catch(p){f.error(`Failed to process upload for path ${a.join(".")}:`,p.message||p.reason)}})),c=await Promise.allSettled(r);n.onFinish?.(c)}async function tt(t,{exportAssets:e,pageIds:n="all",componentIds:s="all",rawConfig:o,includeResources:r=!1,routeIds:c="all"}={}){const a=n==="all"?t.pageIds:n,p=W.getComponentDependencies({state:t,pageIds:a,componentIds:s==="all"?Object.keys(t.components):s}),d=c==="all"?t.routeIds:c,E=u=>({id:u.id,name:u.name,isTemplateSection:u.isTemplateSection??!1,templateDescription:u.templateDescription,llmConfig:u.llmConfig,component:u.component,config:u.config,visibility:u.visibility,sections:u?.sectionIds?x(u?.sectionIds?.map(C=>{const D=u.sections?.[C];return D&&E(D)})):void 0}),g=(u,C)=>({id:u.id,createdAt:u.createdAt,updatedAt:u.updatedAt,publishedAt:u.publishedAt,isPublic:u.isPublic??!0,templateConfig:u.templateConfig,meta:u.locales?.[C]??{},sections:x(u.sectionIds.map(D=>{const U=u.sections[D];return U&&E(U)})),dataSource:Object.fromEntries(Object.entries(u.dataSource||{}).map(([D,U])=>[D,U?.[C]??{}]))}),b=u=>({id:u.id,createdAt:u.createdAt,updatedAt:u.updatedAt,publishedAt:u.publishedAt,path:u.path,handler:u.handler,isPublic:u.isPublic??!0,params:u.params??[],enabledGenerate:u.enabledGenerate??!1,displayTemplateId:u.displayTemplateId,dataSource:u.dataSource}),l=x(d.map(u=>{const C=t.routes[u];return C&&b(C)})),i=x(t.supportedLocales.map(u=>u.locale).flatMap(u=>a.map(C=>{const D=t.pages[C];return D&&{locale:u,slug:D.slug,page:g(D,u)}}))),S=Xe(),A=h.join(S,"pages");w.mkdirSync(A,{recursive:!0});const y=h.join(S,"components");w.mkdirSync(y,{recursive:!0});const m=h.join(S,"routes");w.mkdirSync(m,{recursive:!0});for(const{locale:u,slug:C,page:D}of i)await Z(D,A,{getFilename:()=>`${ie(C)||"index"}.${u}.yml`,exportAssets:e});for(const u of l)await Z(u,m,{getFilename:()=>`${ie(u.path)||"index"}.yml`,exportAssets:e});for(const u of p){const C=t.components[u]?.data;C&&await Z(C,y,{getFilename:D=>`${D.name||"unnamed"}.${D.id}.yml`,exportAssets:e})}const I=h.join(S,".blocklet/pages/pages.config.yml");w.mkdirSync(h.dirname(I),{recursive:!0});const O={pages:x(a.map(u=>{const C=t.pages[u];return C&&{id:u,slug:C.slug}})),routes:x(d.map(u=>{const C=t.routes[u];return C&&{id:u,path:C.path}})),components:x(p.map(u=>{const C=t.components[u]?.data;return C&&{id:u,name:C.name}})),...r?{resources:{components:x(Object.keys(t.resources?.components||{}).filter(u=>p.includes(u)).map(u=>({id:u,name:t.resources?.components?.[u]?.component?.name})))}}:{},supportedLocales:t.supportedLocales,config:t.config};w.writeFileSync(I,B.stringify(O));const T=h.join(S,"config.source.json");if(o&&w.writeFileSync(T,JSON.stringify(o)),r){const u=h.join(S,"resources"),C=h.join(u,"components");w.mkdirSync(C,{recursive:!0});for(const G of Object.keys(t?.resources?.components??{}).filter(L=>p.includes(L))){const L=t.resources?.components?.[G]?.component;L&&await Z(L,C,{getFilename:J=>`${J.name||"unnamed"}.${J.id}.yml`,exportAssets:e})}const D=h.join(S,"chunks");w.mkdirSync(D,{recursive:!0});const U=Gn();for(const G of Object.keys(t?.resources?.components??{}).filter(L=>p.includes(L))){const L=t.resources?.components?.[G]?.component;if(L&&L.renderer?.type==="react-component"){const J=L.renderer?.chunks??[];if(J?.length>0)for(const me of J){const De=h.join(D,me),he=U?.[me];try{he&&w.existsSync(he)&&!w.existsSync(De)&&w.copyFileSync(he,De)}catch(lt){f.error(`copy chunk ${me} error`,lt.message)}}}}}return S}async function Vn(t,{importAssets:e,includeResources:n}={}){if(!w.existsSync(t))return null;let s,o=!1;try{w.lstatSync(t).isDirectory()?s=t:/\.(tgz|gz|tar)$/.test(t)&&(o=!0,s=Xe(),await Lt.x({file:t,C:s}));const r=ne.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}).at(0),c=r&&h.join(h.dirname(r),"../../pages"),a=r&&h.join(h.dirname(r),"../../components"),p=r&&h.join(h.dirname(r),"../../routes");if(!r)return null;const d=B.parse(w.readFileSync(r).toString()),E=(y,m,I)=>{let O=h.join(y,`${m}${I?`.${I}`:""}.yml`);return(!w.existsSync(O)||!w.lstatSync(O).isFile())&&(O=h.join(y,m,`index${I?`.${I}`:""}.yml`),!w.existsSync(O)||!w.lstatSync(O))?null:B.parse(w.readFileSync(O).toString())},g=(y,m)=>{try{const I=ne.globSync(`*.${m}.yml`,{cwd:y,absolute:!0})[0];return I?B.parse(w.readFileSync(I).toString()):null}catch(I){f.error("parse component error",I)}return null},b=(y,m)=>{let I=h.join(y,`${m}.yml`);return(!w.existsSync(I)||!w.lstatSync(I).isFile())&&(I=h.join(y,m,"index.yml"),!w.existsSync(I)||!w.lstatSync(I))?null:B.parse(w.readFileSync(I).toString())},l=x(d.pages.map(({slug:y})=>{const m=x(d.supportedLocales.map(({locale:T})=>{const u=c?E(c,ie(y),T):void 0;if(u)return{locale:T,page:u};const C=c?E(c,y,T):void 0;return C&&{locale:T,page:C}})),I=m[0]?.page;if(!I)return null;const O=I.sections.map(At.unzipSection);return{id:I.id||Re.nextId(),createdAt:I.createdAt,updatedAt:I.updatedAt,publishedAt:I.publishedAt,isPublic:I.isPublic??!0,templateConfig:I.templateConfig,slug:y,sections:Object.fromEntries(O.map(T=>[T.id,T])),sectionIds:O.map(T=>T.id),locales:Object.fromEntries(m.map(({locale:T,page:u})=>[T,u.meta])),dataSource:I.dataSource?Object.fromEntries([...new Set(m.flatMap(({page:T})=>Object.keys(T.dataSource??{})))].map(T=>[T,Object.fromEntries(m.map(({locale:u,page:C})=>{const D=C.dataSource?.[T];return[u,D||{}]}))])):Object.fromEntries([...new Set(m.flatMap(({page:T})=>T.sections.map(u=>u.id)))].map(T=>[T,Object.fromEntries(m.map(({locale:u,page:C})=>{const D=C.dataSource?.[T];if(D)return[u,D];const U=C.sections.find(G=>G.id===T);return[u,U?.properties||{}]}))]))}})),i=x(d?.routes?.map(({path:y})=>{const m=p?b(p,ie(y)):void 0;return{...m,id:m?.id||Re.nextId(),createdAt:m?.createdAt??new Date().toISOString(),updatedAt:m?.updatedAt??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:m?.path??`/${m?.id}`,params:m?.params,handler:m?.handler??"Pages Kit",isPublic:m?.isPublic??!0,enabledGenerate:m?.enabledGenerate??!1,displayTemplateId:m?.displayTemplateId??void 0,dataSource:m?.dataSource??{}}})??[]),S=a?x(d.components?.map(({id:y})=>g(a,y))??[]):[];if(e){const y=(...m)=>{f.info(`[${o?h.basename(t):h.basename(h.join(t,"../../../../"))}] importAssets:`,...m)};try{y("wait image-bin api ready"),await Jt.default({resources:[`${Ce.getComponentWebEndpoint(zt)}/api/sdk/uploads`],validateStatus:O=>O>=200&&O<=500}),y("image-bin api is ready");const m={},I={};y("start to upload assets"),await Promise.allSettled([Fe(S,m,{getFilePath:O=>a&&h.join(a,O),onFinish:O=>{y(`upload ${O.length} component assets`)}}),Fe(l,I,{getFilePath:(O,T)=>{const u=Oe.default(l,T.slice(0,1));return c&&h.join(c,h.dirname(u.slug),O)},onFinish:O=>{y(`upload ${O.length} page assets`)}})]),y("upload assets done"),Pe.clear(),global.gc&&global.gc()}catch(m){y("Error during asset import:",m)}}const A={};if(n){const y=r&&h.join(h.dirname(r),"../../resources/components"),m=x(d.resources?.components?.map(({id:I})=>g(y,I))??[]);m.length>0&&(A.components=Object.fromEntries(m.map((I,O)=>[I.id,{index:O,component:I}])))}return{supportedLocales:d.supportedLocales,pageIds:l.map(y=>y.id),components:Object.fromEntries(S.map((y,m)=>[y.id,{index:m,data:y}])),pages:Object.fromEntries(l.map(y=>[y.id,y])),config:d.config||{},resources:A,routeIds:i.map(y=>y.id),routes:Object.fromEntries(i.map(y=>[y.id,y])),dataSourceIds:[],dataSources:{}}}finally{o&&s&&w.rmSync(s,{force:!0,recursive:!0})}}async function qe(t,e,{routes:n,mergeMode:s="byUpdateTime",deleteRoutes:o=!1,publishMode:r=void 0}={}){try{r&&Sn(r)}catch(b){f.error("clear preload page cache error",{error:b})}const{pages:c,pageIds:a,routeIds:p,routes:d,supportedLocales:E}=t;if(r==="production"){let b=n??[],l=null;for(const i of p??[]){const S=d?.[i];if(S?.params&&S?.params.length>0&&S?.paramsOptions&&S?.paramsOptions.length>0){const A=te.generateParamCombinations({basePath:S.path,params:S.params,routeId:S.id,paramsOptions:S.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),y=Object.fromEntries(A.map(m=>[`${i}-${m.paramOptionIds.join("-")}`,m]));l={...l||{},...y},n||(b=[...b,...A.map(m=>`${i}-${m.paramOptionIds.join("-")}`)])}else n||b.push(i)}f.info("routeIds to be published: ",b);for(const i of b){let S=i;if(S.includes("-")){const[m]=S.split("-");S=m}const A=d?.[S];if(!A){const m=e.pageIds.indexOf(S);m!==-1&&o&&(e.pageIds.splice(m,1),delete e.pages[S]);for(const I of e.pageIds)I.includes(`${S}-`)&&(e.pageIds.splice(e.pageIds.indexOf(I),1),delete e.pages[I]);f.info("delete main route page",S);continue}if(i.includes("-")&&!l?.[i]){const m=e.pageIds.indexOf(i);m!==-1&&o&&(e.pageIds.splice(m,1),delete e.pages[i]),f.info("delete page",i);continue}if(!A.displayTemplateId){f.info("no display template",i);continue}const y=c[A.displayTemplateId];if(!y){f.info("no template page",i);continue}if(e.pageIds.includes(i)){if(f.info("has need update page",i),s==="replace")e.pages[i]=Se({page:y,route:A,state:t,routeId:i,routePathInfo:l?.[i]}),f.info("replace page",i);else if(s==="byUpdateTime"){const m=e.pages[A.id];(!m||A.updatedAt&&A.updatedAt>m.updatedAt)&&(e.pages[i]=Se({page:y,route:A,state:t,routeId:i,routePathInfo:l?.[i]}),f.info("replace page by update time",i))}}else e.pageIds.push(i),e.pages[i]=Se({page:y,route:A,state:t,routeId:i,routePathInfo:l?.[i]}),f.info("add page",i)}if(o&&!n)for(const i of e.pageIds)b?.includes(i)||(delete e.pages[i],f.info("delete page",i)),e.pageIds=[...e.pageIds].filter(S=>b?.includes(S))}else{for(const b of a){const l=c[b];if(l)if(e.pageIds.includes(l.id)){if(s==="replace")e.pages[l.id]=l;else if(s==="byUpdateTime"){const i=e.pages[l.id];(!i||l.updatedAt&&l.updatedAt>i.updatedAt)&&(e.pages[l.id]=l)}}else e.pageIds.push(l.id),e.pages[l.id]=l}for(const b of p){const l=d[b];if(l)if(e.routeIds.includes(l.id)){if(s==="replace")e.routes[l.id]=l;else if(s==="byUpdateTime"){const i=e.routes[l.id];(!i||l.updatedAt&&l.updatedAt>i.updatedAt)&&(e.routes[l.id]=l)}}else e.routeIds.push(l.id),e.routes[l.id]=l}}if(e.supportedLocales.splice(0,e.supportedLocales.length),e.supportedLocales.push(...Bt.default(E)),o)for(const b of Object.keys(e.components))delete e.components[b];let g=JSON.parse(JSON.stringify(t.components));g=Object.fromEntries(await Promise.all(Object.entries(g).map(async([b,l])=>{const i=await nt(l?.data);return[b,{...l,data:i}]}))),Object.assign(e.components,g),Object.assign(e.config,JSON.parse(JSON.stringify(t.config))),Ae.default(t.resources.components)||(e.resources.components=JSON.parse(JSON.stringify(t.resources.components||{})))}const nt=ue(async t=>{if(!Ae.default(t?.properties))return t;if(t?.renderer?.type==="react-component"){const{script:e,PROPERTIES_SCHEMA:n}=t?.renderer||{};if(n||e&&e.includes("PROPERTIES_SCHEMA"))try{const s=await An(e??"","PROPERTIES_SCHEMA",t.id,n);s&&s.length>0&&t&&(t.properties={},s.forEach((o,r)=>{t?.properties&&(t.properties[o.id]={index:r,data:o})}))}catch(s){f.error("getPropertiesFromCode error",{componentId:t.id,name:t.name},{error:s})}}return t},{subdir:"getPropertiesFromCode"});let ce,Y,de,fe;const st=()=>Ce.getResources({types:[{did:je,type:Ee},{did:Tn,type:Ee}]}),Gn=()=>{const t=st(),e={};return t.forEach(n=>{const s=ne.globSync("**/.blocklet/pages/pages.config.yml",{cwd:n.path,absolute:!0}).at(0),o=s&&h.join(h.dirname(s),"../../chunks");if(o&&w.existsSync(o)){const r=w.readdirSync(o);for(const c of r)e[c]=h.join(o,c)}}),e};function ot(){return ce=(async()=>{const t=st();Y=(await Promise.all(t.map(async n=>{const s=n.path?await Vn(n.path,{importAssets:!1}):void 0;return s?{blockletId:n.did,state:s,blockletTitle:n.title}:void 0}))).filter(n=>!!n),de=Y.reduce((n,s)=>Object.assign(n,Object.fromEntries(Object.values(s.state.pages).map(o=>o?[o?.id,{page:o,blockletId:s.blockletId}]:[]))),{});const e=Y.reduce((n,s)=>Object.assign(n,Object.fromEntries(Object.values(s.state.components).map(o=>[o.data.id,{blockletId:s.blockletId,component:o.data}]))),{});fe=Object.fromEntries(await Promise.all(Object.entries(e).map(async([n,s])=>{const o=await nt(s.component);return[n,{...s,component:o}]})))})(),ce}function Jn(t){const e=Je.default(async()=>{await ot().catch(n=>{f.error("load resource states error",{error:n})}),await t?.({states:Y,pages:de,components:fe})},3e3,{leading:!1,trailing:!0});return e(),P.default.events.on(P.default.Events.componentAdded,e),P.default.events.on(P.default.Events.componentRemoved,e),P.default.events.on(P.default.Events.componentStarted,e),P.default.events.on(P.default.Events.componentStopped,e),P.default.events.on(P.default.Events.componentUpdated,e),P.default.events.on(Ne,e),()=>{P.default.events.off(P.default.Events.componentAdded,e),P.default.events.off(P.default.Events.componentRemoved,e),P.default.events.off(P.default.Events.componentStarted,e),P.default.events.off(P.default.Events.componentStopped,e),P.default.events.off(P.default.Events.componentUpdated,e),P.default.events.off(Ne,e)}}const rt=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),at=globalThis;at[rt]?.();at[rt]=Jn(async({pages:t,components:e})=>{const n=await j.getProjectIds();f.info(`start update resource states projects(${n.length})`,n),await Promise.race([new Promise(s=>{setTimeout(()=>{s({})},30*1e3)}),Promise.all(n.map(async s=>{it({projectId:s,pages:t,components:e})}))]).catch(s=>{f.error("update resource states failed:",s)})});j.startPeriodicCheck();process.on("beforeExit",()=>{j.stopPeriodicCheck()});process.on("SIGINT",()=>{j.stopPeriodicCheck(),process.exit(0)});process.on("SIGTERM",()=>{j.stopPeriodicCheck(),process.exit(0)});async function it({projectId:t,pages:e,components:n}){const s=j.sharedInstances[t];if(!s){f.info(`projectId: ${t} not found in sharedInstances`);return}if(s.syncedStore.resources.pages=e,(await M.findByPk(t))?.useAllResources)s.syncedStore.resources.components=n;else{const c=(await Te.findAll({where:{projectId:t}})).map(p=>p.componentId),a=Object.fromEntries(Object.entries(n||{}).filter(([p])=>c.includes(p)));s.syncedStore.resources.components=a}f.info(`update [${t}] resource states:`,{pages:Object.keys(s.syncedStore.resources.pages||{}).length,components:Object.keys(s.syncedStore.resources.components||{}).length})}async function ct({ensureLoaded:t=!0}={}){return t&&(ce??=ot(),await ce),{states:Y,pages:de,components:fe}}P.default.events.on(P.default.Events.envUpdate,()=>{j.pageUrlMapCache.clear(),f.info("clear all page url map cache")});exports.COMPONENT_DID=je;exports.Project=M;exports.RESOURCE_TYPE=Ee;exports.SiteState=j;exports.getMultiTenantAllProjectAccessPassports=Ht;exports.getPreloadComponents=bn;exports.getResourceStates=ct;exports.isMultiTenant=Kt;exports.logger=f;exports.toPackage=tt;
|