@blocklet/pages-kit-inner-components 0.4.117 → 0.4.119
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 +8 -8
- package/lib/cjs/chunks/{array-C2Xw0f0u.js → array-DOclwySd.js} +16 -16
- package/lib/cjs/chunks/{config-color-C8L0QSPJ.js → config-color-C8kj-s2C.js} +1 -1
- package/lib/cjs/chunks/{draft-data-DPTVTTlh.js → draft-data-CRdesc3Z.js} +1 -1
- package/lib/cjs/chunks/home-DdhcZ60U.js +38 -0
- package/lib/cjs/chunks/publish-button-DrP2fRq-.js +1 -0
- package/lib/cjs/chunks/site-state-BMf96RZL.js +57 -0
- package/lib/cjs/chunks/state-oc52fQ0j.js +1 -0
- package/lib/cjs/components.js +1 -1
- package/lib/cjs/home.js +1 -1
- package/lib/cjs/locales.js +1 -1
- package/lib/cjs/project-html.js +1 -1
- package/lib/cjs/resources.js +1 -1
- package/lib/cjs/setting.js +1 -1
- package/lib/cjs/site-state.js +1 -1
- package/lib/es/add-component.js +125 -120
- package/lib/es/chunks/{array-HoE78hbE.js → array-BXCsMjKT.js} +295 -290
- package/lib/es/chunks/{config-color-JrBPRsTv.js → config-color-CXt_ZsC_.js} +1 -1
- package/lib/es/chunks/{draft-data-BFlmvWXx.js → draft-data-BwyMBf8Y.js} +1 -1
- package/lib/es/chunks/home-Cqrxr0ko.js +505 -0
- package/lib/es/chunks/publish-button-BFkn3oDY.js +295 -0
- package/lib/es/chunks/site-state-kjir-UCL.js +1718 -0
- package/lib/es/chunks/state-Dz3GnGWC.js +437 -0
- package/lib/es/components.js +1 -1
- package/lib/es/home.js +10 -8
- package/lib/es/locales.js +81 -17
- package/lib/es/project-html.js +1 -1
- package/lib/es/resources.js +1 -1
- package/lib/es/setting.js +2 -2
- package/lib/es/site-state.js +13 -12
- package/package.json +3 -3
- package/lib/cjs/chunks/home-B4-4gx2w.js +0 -38
- package/lib/cjs/chunks/publish-button-aUYadvYo.js +0 -1
- package/lib/cjs/chunks/site-state-D15mduKB.js +0 -57
- package/lib/cjs/chunks/state-DDwYX2mu.js +0 -1
- package/lib/es/chunks/home-DEsyT9zq.js +0 -475
- package/lib/es/chunks/publish-button-CFMTt6k_.js +0 -282
- package/lib/es/chunks/site-state-DJ_KkVbi.js +0 -1548
- package/lib/es/chunks/state-BgKqNapt.js +0 -425
package/lib/es/locales.js
CHANGED
|
@@ -40,7 +40,9 @@ const t = e({
|
|
|
40
40
|
data: "Data Source",
|
|
41
41
|
page: "Page"
|
|
42
42
|
},
|
|
43
|
-
dataSourceEmpty: 'No data sources yet, click "Add" button to create'
|
|
43
|
+
dataSourceEmpty: 'No data sources yet, click "Add" button to create',
|
|
44
|
+
selectDataSource: "Please select a data source from the list",
|
|
45
|
+
createDataSourceFirst: "Please create a data source first"
|
|
44
46
|
},
|
|
45
47
|
alert: {
|
|
46
48
|
delete: "Delete"
|
|
@@ -111,19 +113,31 @@ const t = e({
|
|
|
111
113
|
},
|
|
112
114
|
error: {
|
|
113
115
|
dataSourceNotFound: "Please configure the page data source in Site Map first",
|
|
114
|
-
refreshDataFailed: "Failed to refresh data, please try again later"
|
|
116
|
+
refreshDataFailed: "Failed to refresh data, please try again later",
|
|
117
|
+
missingRouteOrProject: "Missing route or project information"
|
|
115
118
|
},
|
|
116
119
|
export: "Export",
|
|
120
|
+
noPreviewAvailable: "No preview available",
|
|
117
121
|
pages: {
|
|
118
122
|
addPage: "Create Page",
|
|
119
123
|
createResource: "Create Resource",
|
|
120
124
|
addResource: "Add Resource from Store",
|
|
121
|
-
pages: "
|
|
125
|
+
pages: "Page Templates",
|
|
122
126
|
deleteTitle: "Delete {name} page?",
|
|
123
127
|
deleteSectionTitle: "Delete {name} section?",
|
|
124
128
|
empty: "No pages",
|
|
125
129
|
needPublish: "This page has unpublished changes",
|
|
126
|
-
notPublic: "This page is not public"
|
|
130
|
+
notPublic: "This page is not public",
|
|
131
|
+
expandAllRoutes: "Expand all associated routes",
|
|
132
|
+
collapseAllRoutes: "Collapse all associated routes",
|
|
133
|
+
addPageDialog: {
|
|
134
|
+
title: "Create New Page",
|
|
135
|
+
templateName: "Template Name",
|
|
136
|
+
templateNamePlaceholder: "Enter page template name",
|
|
137
|
+
autoCreateRoute: "Auto create route",
|
|
138
|
+
create: "Create",
|
|
139
|
+
cancel: "Cancel"
|
|
140
|
+
}
|
|
127
141
|
},
|
|
128
142
|
components: {
|
|
129
143
|
components: "Components",
|
|
@@ -196,6 +210,7 @@ const t = e({
|
|
|
196
210
|
pathCheckWhitespace: "Path cannot contain whitespace",
|
|
197
211
|
pathCheckInvalid: "Invalid path format",
|
|
198
212
|
pathCheckAlreadyExist: "Path is already exist",
|
|
213
|
+
pathCheckHelper: "This field now manages template names. To modify page access paths, please navigate to Site Map settings.",
|
|
199
214
|
embedUrl: "Embed url",
|
|
200
215
|
chooseEmbed: "Choose embed",
|
|
201
216
|
translateFrom: "Translate from",
|
|
@@ -243,12 +258,13 @@ const t = e({
|
|
|
243
258
|
llmConfigInstructions: "Configure which properties should be processed by AI and provide detailed descriptions.",
|
|
244
259
|
llmPropertyDescribe: "Description for AI",
|
|
245
260
|
loading: "Loading...",
|
|
246
|
-
componentNotFound: "Component not found"
|
|
261
|
+
componentNotFound: "Component not found",
|
|
262
|
+
templateName: "Template Name"
|
|
247
263
|
},
|
|
248
264
|
siteMap: {
|
|
249
265
|
routes: "Routes",
|
|
250
266
|
empty: "No Routes",
|
|
251
|
-
pageProperties: "
|
|
267
|
+
pageProperties: "Route Properties",
|
|
252
268
|
handler: "Handler",
|
|
253
269
|
data: "Data Source",
|
|
254
270
|
noDataSource: "No data source",
|
|
@@ -256,7 +272,17 @@ const t = e({
|
|
|
256
272
|
question: "Page Template Rules",
|
|
257
273
|
questionPlaceholder: "Enter page template rules, describe your requirements",
|
|
258
274
|
pageTemplate: "Page Template",
|
|
259
|
-
selectPageTemplate: "Select a page template"
|
|
275
|
+
selectPageTemplate: "Select a page template",
|
|
276
|
+
agent: "Agent",
|
|
277
|
+
noAgent: "No Agent",
|
|
278
|
+
noRouteSelected: "No route selected. Please select a route from the list or create a new one.",
|
|
279
|
+
enableGenerate: "Enable AI Generate",
|
|
280
|
+
path: "Path",
|
|
281
|
+
generate: "Generate Page Content",
|
|
282
|
+
generating: "Generating...",
|
|
283
|
+
deleteRouteTitle: "Delete Route",
|
|
284
|
+
deleteRouteConfirm: "Are you sure you want to delete this route? This action cannot be undone.",
|
|
285
|
+
routeDeleted: "Route deleted successfully"
|
|
260
286
|
}
|
|
261
287
|
},
|
|
262
288
|
error: {
|
|
@@ -304,7 +330,7 @@ const t = e({
|
|
|
304
330
|
},
|
|
305
331
|
status: {
|
|
306
332
|
install: "Check whether the ai-kit is installed",
|
|
307
|
-
|
|
333
|
+
unavailable: "Check whether the openai key is set properly"
|
|
308
334
|
}
|
|
309
335
|
},
|
|
310
336
|
translate: {
|
|
@@ -319,12 +345,18 @@ const t = e({
|
|
|
319
345
|
overlay: "Are you sure to continue the translation and override the {target} content after translation?",
|
|
320
346
|
success: "Translation success",
|
|
321
347
|
fail: "Translation failed, please try again",
|
|
348
|
+
failed: "Translation failed. Please check and try again",
|
|
322
349
|
localInput: "Local input",
|
|
323
350
|
abort: "Cancel translation",
|
|
324
351
|
sameLanguage: "Source language and target language cannot be the same",
|
|
325
352
|
noTargetLanguage: "Please select target language",
|
|
353
|
+
noValidTargetLanguage: "Source and target languages cannot be the same. Please select different target languages",
|
|
354
|
+
noSourceData: "No source data found for translation",
|
|
355
|
+
failedFor: "Translation failed for",
|
|
356
|
+
translating: "Translating...",
|
|
326
357
|
field: "Field",
|
|
327
|
-
unsavedChanges: "You have unsaved changes. Do you want to save before closing?"
|
|
358
|
+
unsavedChanges: "You have unsaved changes. Do you want to save before closing?",
|
|
359
|
+
templateSyncTip: "You only need to maintain one language version of your page template. We will automatically sync the template configuration while handling translations."
|
|
328
360
|
},
|
|
329
361
|
aiRuntime: {
|
|
330
362
|
aiSettings: "AI Settings",
|
|
@@ -454,7 +486,9 @@ const t = e({
|
|
|
454
486
|
data: "数据源",
|
|
455
487
|
page: "页面"
|
|
456
488
|
},
|
|
457
|
-
dataSourceEmpty: '暂无数据源,点击"添加"按钮创建'
|
|
489
|
+
dataSourceEmpty: '暂无数据源,点击"添加"按钮创建',
|
|
490
|
+
selectDataSource: "请选择左侧的数据源进行操作",
|
|
491
|
+
createDataSourceFirst: "请先创建一个数据源"
|
|
458
492
|
},
|
|
459
493
|
alert: {
|
|
460
494
|
delete: "删除"
|
|
@@ -525,19 +559,31 @@ const t = e({
|
|
|
525
559
|
},
|
|
526
560
|
error: {
|
|
527
561
|
dataSourceNotFound: "未找到数据源配置,请先在站点地图中配置页面数据源",
|
|
528
|
-
refreshDataFailed: "数据刷新失败,请稍后重试"
|
|
562
|
+
refreshDataFailed: "数据刷新失败,请稍后重试",
|
|
563
|
+
missingRouteOrProject: "缺少路由或项目信息"
|
|
529
564
|
},
|
|
530
565
|
export: "导出",
|
|
566
|
+
noPreviewAvailable: "无可用预览",
|
|
531
567
|
pages: {
|
|
532
568
|
addPage: "创建页面",
|
|
533
569
|
createResource: "创建资源",
|
|
534
570
|
addResource: "从商店添加资源",
|
|
535
|
-
pages: "
|
|
571
|
+
pages: "页面模板",
|
|
536
572
|
deleteTitle: "删除 {name} 页面?",
|
|
537
573
|
deleteSectionTitle: "删除 {name} 卡片?",
|
|
538
574
|
empty: "暂无页面",
|
|
539
575
|
needPublish: "此页面有可发布的新修改",
|
|
540
|
-
notPublic: "此页面未公开"
|
|
576
|
+
notPublic: "此页面未公开",
|
|
577
|
+
expandAllRoutes: "展开所有关联路由",
|
|
578
|
+
collapseAllRoutes: "折叠所有关联路由",
|
|
579
|
+
addPageDialog: {
|
|
580
|
+
title: "创建新页面",
|
|
581
|
+
templateName: "模板名称",
|
|
582
|
+
templateNamePlaceholder: "输入页面模板名称",
|
|
583
|
+
autoCreateRoute: "自动创建路由",
|
|
584
|
+
create: "创建",
|
|
585
|
+
cancel: "取消"
|
|
586
|
+
}
|
|
541
587
|
},
|
|
542
588
|
components: {
|
|
543
589
|
components: "组件",
|
|
@@ -610,6 +656,7 @@ const t = e({
|
|
|
610
656
|
pathCheckWhitespace: "路径中不能包含空白字符",
|
|
611
657
|
pathCheckInvalid: "非法的路径",
|
|
612
658
|
pathCheckAlreadyExist: "路径已存在",
|
|
659
|
+
pathCheckHelper: '此处用于设置模板名称,如需修改页面访问路径,请前往"站点地图"进行设置',
|
|
613
660
|
embedUrl: "部件地址",
|
|
614
661
|
chooseEmbed: "选择部件",
|
|
615
662
|
translateFrom: "翻译来自",
|
|
@@ -657,11 +704,12 @@ const t = e({
|
|
|
657
704
|
llmConfigInstructions: "配置需要AI处理的属性并提供详细描述",
|
|
658
705
|
llmPropertyDescribe: "AI提示描述",
|
|
659
706
|
loading: "加载中...",
|
|
660
|
-
componentNotFound: "未找到组件"
|
|
707
|
+
componentNotFound: "未找到组件",
|
|
708
|
+
templateName: "模板名称"
|
|
661
709
|
},
|
|
662
710
|
siteMap: {
|
|
663
711
|
routes: "路由列表",
|
|
664
|
-
pageProperties: "
|
|
712
|
+
pageProperties: "路由属性",
|
|
665
713
|
handler: "处理器",
|
|
666
714
|
parameters: "参数",
|
|
667
715
|
parametersHelper: "来自 URL、请求头等参数",
|
|
@@ -674,6 +722,16 @@ const t = e({
|
|
|
674
722
|
loading: "加载中...",
|
|
675
723
|
question: "页面模板规则",
|
|
676
724
|
questionPlaceholder: "输入页面模板规则,描述您的要求",
|
|
725
|
+
agent: "Agent",
|
|
726
|
+
noAgent: "无 Agent",
|
|
727
|
+
noRouteSelected: "未选择路由,请从左侧列表选择一个路由或创建新路由。",
|
|
728
|
+
enableGenerate: "启用 AI 生成",
|
|
729
|
+
path: "路径",
|
|
730
|
+
generate: "生成页面内容",
|
|
731
|
+
generating: "生成中...",
|
|
732
|
+
deleteRouteTitle: "删除路由",
|
|
733
|
+
deleteRouteConfirm: "你确定要删除此路由吗?此操作无法撤销。",
|
|
734
|
+
routeDeleted: "路由删除成功",
|
|
677
735
|
templates: {
|
|
678
736
|
default: "默认模板",
|
|
679
737
|
blog: "博客模板",
|
|
@@ -727,7 +785,7 @@ const t = e({
|
|
|
727
785
|
},
|
|
728
786
|
status: {
|
|
729
787
|
install: "请先检查 ai-kit 是否安装",
|
|
730
|
-
|
|
788
|
+
unavailable: "请先检查 openai key 是否正常设置"
|
|
731
789
|
}
|
|
732
790
|
},
|
|
733
791
|
translate: {
|
|
@@ -742,12 +800,18 @@ const t = e({
|
|
|
742
800
|
overlay: "确认继续翻译,并且翻译后覆盖 {target} 内容吗?",
|
|
743
801
|
success: "翻译成功",
|
|
744
802
|
fail: "翻译失败,请重试",
|
|
803
|
+
failed: "翻译失败,请检查后重试",
|
|
745
804
|
localInput: "本地输入",
|
|
746
805
|
abort: "取消翻译成功",
|
|
747
806
|
sameLanguage: "源语言和目标语言不能相同",
|
|
748
807
|
noTargetLanguage: "请选择目标语言",
|
|
808
|
+
noValidTargetLanguage: "源语言和目标语言不能相同,请选择不同的目标语言",
|
|
809
|
+
noSourceData: "未找到用于翻译的源数据",
|
|
810
|
+
failedFor: "翻译失败语言:",
|
|
811
|
+
translating: "翻译中...",
|
|
749
812
|
field: "字段",
|
|
750
|
-
unsavedChanges: "你有未保存的更改。是否在关闭前保存?"
|
|
813
|
+
unsavedChanges: "你有未保存的更改。是否在关闭前保存?",
|
|
814
|
+
templateSyncTip: "您只需维护一种语言版本的页面模板,我们会在处理翻译的同时,自动同步页面模板的配置。"
|
|
751
815
|
},
|
|
752
816
|
aiRuntime: {
|
|
753
817
|
aiSettings: "AI 设置",
|
package/lib/es/project-html.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { l as _, g as H } from "./chunks/site-state-
|
|
1
|
+
import { l as _, g as H } from "./chunks/site-state-kjir-UCL.js";
|
|
2
2
|
import { initCronCrawlBlocklet as W, cancelCronCrawlBlocklet as N, initSEOMiddleware as J } from "@blocklet/crawler/middlewares";
|
|
3
3
|
import { PreloadComponentScriptModule as G } from "@blocklet/pages-kit/types";
|
|
4
4
|
import { injectPreloadComponents as K } from "@blocklet/pages-kit/utils/preload";
|
package/lib/es/resources.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as S, i as b, a as M, l as x, C as J, R as X, S as N, t as W, b as G } from "./chunks/site-state-
|
|
1
|
+
import { P as S, i as b, a as M, l as x, C as J, R as X, S as N, t as W, b as G } from "./chunks/site-state-kjir-UCL.js";
|
|
2
2
|
import { AsyncLocalStorage as K } from "async_hooks";
|
|
3
3
|
import { Router as Y } from "express";
|
|
4
4
|
import d from "fs";
|
package/lib/es/setting.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { jsx as t, jsxs as O, Fragment as X } from "react/jsx-runtime";
|
|
2
|
-
import { t as ye, b as Te, a as ce, E as ot, n as Ke,
|
|
2
|
+
import { t as ye, b as Te, a as ce, E as ot, n as Ke, f as ve } from "./chunks/state-Dz3GnGWC.js";
|
|
3
3
|
import de from "@arcblock/ux/lib/Empty";
|
|
4
4
|
import { useLocaleContext as C } from "@arcblock/ux/lib/Locale/context";
|
|
5
5
|
import { CodeEditor as xe } from "@blocklet/code-editor";
|
|
@@ -11,7 +11,7 @@ import { Typography as M, TextField as V, Stack as R, FormLabel as ie, Box as j,
|
|
|
11
11
|
import A from "lodash/sortBy";
|
|
12
12
|
import { useCallback as D, useMemo as ne, useRef as F, useId as gt, useEffect as $, useState as Q } from "react";
|
|
13
13
|
import { useUpdate as _e } from "react-use";
|
|
14
|
-
import { C as Pt } from "./chunks/config-color-
|
|
14
|
+
import { C as Pt } from "./chunks/config-color-CXt_ZsC_.js";
|
|
15
15
|
import { ColorItem as wt, ConfigColorDialog as kt } from "@blocklet/pages-kit/builtin/color-picker";
|
|
16
16
|
import Pe from "lodash/isEmpty";
|
|
17
17
|
import He from "lodash/set";
|
package/lib/es/site-state.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { q, o as
|
|
1
|
+
import { q as v, o as B, p as L, S as U, r as h, b as w, u as y, s as z, n as C, t as F, v as G } from "./chunks/site-state-kjir-UCL.js";
|
|
2
|
+
import "@blocklet/pages-kit/utils/data-source";
|
|
2
3
|
import "@blocklet/pages-kit/utils/property";
|
|
3
4
|
import "@blocklet/quickjs";
|
|
4
5
|
import "@blocklet/sdk/lib/component";
|
|
@@ -31,15 +32,15 @@ import "yaml";
|
|
|
31
32
|
import "yjs";
|
|
32
33
|
export * from "@blocklet/pages-kit/types/state";
|
|
33
34
|
export {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
35
|
+
v as PUBLISH_MODES,
|
|
36
|
+
B as SITE_STATE_PATH,
|
|
37
|
+
L as STATE_MODES,
|
|
38
|
+
U as default,
|
|
39
|
+
h as fromPackage,
|
|
40
|
+
w as getResourceStates,
|
|
41
|
+
y as initPackResourceStates,
|
|
42
|
+
z as mergeState,
|
|
43
|
+
C as nextId,
|
|
44
|
+
F as toPackage,
|
|
45
|
+
G as triggerReloadAllProjectResource
|
|
45
46
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blocklet/pages-kit-inner-components",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.119",
|
|
4
4
|
"description": "Pages Kit inner components library",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -205,8 +205,8 @@
|
|
|
205
205
|
"yaml": "^2.5.0",
|
|
206
206
|
"yjs": "^13.6.18",
|
|
207
207
|
"zustand": "^4.5.5",
|
|
208
|
-
"@blocklet/pages-kit": "^0.4.
|
|
209
|
-
"@blocklet/pages-kit-block-studio": "^0.4.
|
|
208
|
+
"@blocklet/pages-kit": "^0.4.119",
|
|
209
|
+
"@blocklet/pages-kit-block-studio": "^0.4.119"
|
|
210
210
|
},
|
|
211
211
|
"devDependencies": {
|
|
212
212
|
"@trivago/prettier-plugin-sort-imports": "^5.2.1",
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
"use strict";const t=require("react/jsx-runtime"),k=require("./state-DDwYX2mu.js"),C=require("lodash"),Q=require("@arcblock/ux/lib/Locale/context"),re=require("@arcblock/ux/lib/Result"),ie=require("@blocklet/pages-kit/builtin/page/header"),ce=require("@blocklet/pages-kit/contexts/color"),le=require("@blocklet/ui-react/lib/Header"),X=require("@emotion/css"),T=require("@emotion/react"),ae=require("@emotion/styled"),y=require("@mui/material"),ue=require("ahooks"),de=require("isomorphic-dompurify"),fe=require("lodash/cloneDeep"),me=require("lodash/isEmpty"),ge=require("lodash/isEqual"),x=require("react"),pe=require("react-helmet"),w=require("react-router-dom"),H=require("react-use"),E=require("ufo"),P=require("./array-C2Xw0f0u.js"),N=require("@arcblock/ux/lib/Theme"),he=require("@blocklet/ui-react/lib/Footer"),xe=require("webfontloader"),je=require("@arcblock/did-connect/lib/Session"),v=e=>e&&e.__esModule?e:{default:e},Y=v(re),be=v(le),Z=v(ae),ye=v(de),J=v(fe),ve=v(me),we=v(ge),Se=v(he),ke=v(xe);function Pe(e,s,o,r){e.locales||(e.locales={}),e.locales[o]=C.cloneDeep(e.locales[o]||{}),e.locales[o].title=r.title??e.locales[o].title,e.locales[o].image=r.image??e.locales[o].image,e.locales[o].description=r.description??e.locales[o].description,Object.entries(r.sectionsData).forEach(([c,n])=>{var l,m,j,d;const i=Object.values(e.sections).find(a=>a.id===c||a.name===c);if(i&&i.isTemplateSection)if(i.locales=C.cloneDeep(i.locales||{}),i.locales[o]=C.cloneDeep(i.locales[o]||{}),i.component==="custom-component"){const a=(l=i.config)==null?void 0:l.componentId;if(!a)return;const g=((m=s.components[a])==null?void 0:m.data)||((d=(j=s.resources.components)==null?void 0:j[a])==null?void 0:d.component);if(!g)return;i.locales[o].properties=C.cloneDeep(i.locales[o].properties||{}),Object.entries(n||{}).forEach(([p,u])=>{var h,_;const f=((h=g==null?void 0:g.properties)==null?void 0:h[p])||Object.values((g==null?void 0:g.properties)||{}).find(M=>{var q;return((q=M.data)==null?void 0:q.key)===p});f&&(i.locales[o].properties[(_=f.data)==null?void 0:_.id]={value:u})})}else i.locales[o]={...C.cloneDeep(i.locales[o]),...n||{}}})}const _e=N.styled(Se.default,{shouldForwardProp:e=>!!e})`
|
|
2
|
-
& > div > .MuiContainer-root {
|
|
3
|
-
max-width: unset;
|
|
4
|
-
}
|
|
5
|
-
`;function qe({meta:e,...s}){const o=N.useTheme();return t.jsx(_e,{...s,meta:e,theme:o||{}})}function K(e){return t.jsx(y.Box,{display:"flex",flex:1,height:"100%",alignItems:"center",justifyContent:"center",...e,children:t.jsx(y.CircularProgress,{size:30})})}function Re(e){return t.jsx(Ce,{...e})}const Ce=N.styled(y.Box)`
|
|
6
|
-
position: fixed;
|
|
7
|
-
left: 0;
|
|
8
|
-
top: 0;
|
|
9
|
-
z-index: 999999999999;
|
|
10
|
-
width: 80px;
|
|
11
|
-
font-size: 12px;
|
|
12
|
-
text-align: center;
|
|
13
|
-
opacity: 0.7;
|
|
14
|
-
transform: translateX(-23%) translateY(70%) rotate(-45deg);
|
|
15
|
-
pointer-events: none;
|
|
16
|
-
`,Me=e=>new Promise((s,o)=>{(e==null?void 0:e.length)>0?ke.default.load({google:{families:e},fontactive:()=>{s("success")},fontinactive:()=>{o(new Error("load font fail"))}}):s("success")}),O=`Avenir, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
|
|
17
|
-
sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'`,F={};function Ee({titleFontFamily:e,descriptionFontFamily:s}){var n;const o=y.useTheme(),r=(n=o==null?void 0:o.typography)==null?void 0:n.fontFamily,c=async i=>{if(i&&!document.querySelectorAll(`link[href*="${i}" i]`).length)try{F[i]||(await Me([i]),F[i]=!0)}catch(l){console.error(l)}};return x.useEffect(()=>{e&&c(e),s&&c(s)},[e,s]),t.jsx(T.Global,{styles:T.css`
|
|
18
|
-
#app {
|
|
19
|
-
font-family: ${JSON.stringify(r)}, ${O};
|
|
20
|
-
|
|
21
|
-
.page-kit-section__title {
|
|
22
|
-
font-family: ${JSON.stringify(e??r)}, ${O};
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
.page-kit-section__description {
|
|
26
|
-
font-family: ${JSON.stringify(s??r)}, ${O};
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
`})}const{SessionProvider:De,SessionContext:Ie,SessionConsumer:$e,withSession:Ve}=je.createAuthServiceSessionContext();function A(){return x.useContext(Ie)}function Te(...e){var o;const{session:s}=A();return e.includes((o=s.user)==null?void 0:o.role)}function Be(...e){var r;const{session:s}=A(),o=Te(...e);return((r=window.blocklet)==null?void 0:r.tenantMode)==="multiple"?!!s.user:o}function Oe(){const[e]=w.useSearchParams(),{session:s}=A(),o=Be("owner","admin","pagesEditor","member"),r=x.useMemo(()=>{const n=e.get("mode");return P.STATE_MODES.includes(n)?n:"production"},[e]),c=r==="production"?r:s.user?o?r:"production":null;return c?t.jsx(ee,{mode:c}):null}function ee({mode:e}){if(e!=="draft"){const s=window.__PAGE_STATE__;return s?t.jsx(I,{mode:e,state:s}):t.jsx(Ne,{mode:e,children:({state:o})=>t.jsx(I,{mode:e,state:o})})}return t.jsx(He,{children:({state:s})=>t.jsx(I,{mode:e,state:s})})}const He=x.lazy(()=>Promise.resolve().then(()=>require("./draft-data-DPTVTTlh.js")));function Ne({mode:e,children:s}){const o=document.querySelector('meta[property="pages:version"]'),r=o==null?void 0:o.content,c=k.useProjectId(),n=x.useMemo(()=>{if(r==="{{pagesPublishedAt}}"){const m=localStorage.getItem(k.getProjectPageVersionKey(c??""));return Number(m)?Number(m):new Date().getTime()}return Number(r)},[r]),{loading:i,value:l}=H.useAsync(()=>P.getPages({mode:e,version:n}),[e,n]);return i?t.jsx(K,{}):l?s({state:l}):null}function I({mode:e,state:s}){const{t:o,locale:r}=Q.useLocaleContext(),{pageIds:c,pages:n,supportedLocales:i,config:{defaultLocale:l},resources:m}=s,j=k.getAllComponents(s),d=x.useMemo(()=>i!=null&&i.some(u=>u.locale===r)?r:void 0,[r,i]),a=Object.values(n).find(u=>(u==null?void 0:u.slug)==="/")?void 0:Object.values(n)[0],g=x.useMemo(()=>c.map(u=>{const f=n[u];return f&&{id:f.id,path:E.joinURL("/",d||"",f.slug,e!=="production"?`?mode=${e}`:"")}}).filter(P.nonNullable),[c,n,d,e]),p=([...u])=>(e!=="production"&&u.unshift(t.jsx(x.Suspense,{fallback:t.jsx("div",{}),children:t.jsx(Le,{mode:"production",state:s})})),u);return t.jsxs(P.Provider,{value:{pages:g},children:[t.jsxs(w.Routes,{children:[a&&t.jsx(w.Route,{index:!0,element:t.jsx(w.Navigate,{to:E.joinURL("/",d||"",a.slug)})}),c.map(u=>{const f=n[u];return f?t.jsx(w.Route,{path:E.joinURL(":projectIdOrSlug?",f.slug),element:t.jsx(B,{mode:e,components:j,page:f,locale:d,defaultLocale:l,headerAddons:p})},f.id):null}),m.pages&&Object.values(m.pages).map(({blockletId:u,page:f})=>t.jsx(w.Route,{path:E.joinURL("/",`@${u}`,f.slug),element:t.jsx(B,{mode:e,components:j,page:f,locale:d,defaultLocale:l,headerAddons:p})},f.id)),t.jsx(w.Route,{path:"*",element:t.jsx(y.Box,{width:"100vw",height:"100vh",display:"flex",justifyContent:"center",alignItems:"center",children:t.jsx(Y.default,{status:404,extra:t.jsx(ne,{href:"/",children:o("common.back")})})})})]}),e!=="production"&&t.jsx(Re,{sx:{bgcolor:"info.light"},children:e}),t.jsx(Ee,{})]})}function Ae({mode:e,state:s,path:o,pageData:r}){const{t:c,locale:n}=Q.useLocaleContext(),{pages:i,supportedLocales:l,config:{defaultLocale:m},resources:j}=s,d=Object.values(i).find(h=>(h==null?void 0:h.slug)===o),a=Object.values(j.pages||{}).find(h=>h.page.slug===o),g=x.useMemo(()=>l!=null&&l.some(h=>h.locale===n)?n:void 0,[n,l]),p=ue.useReactive({page:null});x.useEffect(()=>{const h=d||(a==null?void 0:a.page)||null;h?p.page=J.default(h):p.page=null},[d,a]);const u=x.useRef();if(x.useEffect(()=>{we.default(r,u.current)||r&&p.page&&(Pe(p.page,s,g,r),u.current=J.default(r))},[{}]),!d&&!(a!=null&&a.page))return t.jsx(y.Box,{width:"100vw",height:"100vh",display:"flex",justifyContent:"center",alignItems:"center",children:t.jsx(Y.default,{style:{background:"inherit"},status:404,extra:t.jsx(ne,{href:"/",children:c("common.back")})})});const f=k.getAllComponents(s);return p.page?t.jsx(B,{mode:e,components:f,page:p.page,locale:g,defaultLocale:m}):null}function B({mode:e,components:s,page:o,locale:r,defaultLocale:c,headerAddons:n}){var _,M,q,L,U,D,$,V,z;const i=ce.useColorConvert(),l=((_=o.locales)==null?void 0:_[r])??((M=o.locales)==null?void 0:M[c])??{},m=l.title||((q=window.blocklet)==null?void 0:q.appName),j=l.description||((L=window.blocklet)==null?void 0:L.appDescription),d=k.autoResizeImage(k.getImageAbsoluteUrl(l.image),540),{logo:a,brand:g,description:p,...u}=ie.useHeaderState(),f=x.useMemo(()=>S=>{var R;let b=(n==null?void 0:n(S))??S;return b=((R=u.addons)==null?void 0:R.call(u,b))??b,b},[u.addons,n]),h=(U=l.header)!=null&&U.translucent?oe:te;return t.jsxs(P.PageProvider,{page:o,defaultLocale:c,currentLocale:r,children:[!!l.backgroundColor&&t.jsx(T.Global,{styles:T.css`
|
|
30
|
-
body {
|
|
31
|
-
background-color: ${i(l.backgroundColor)} !important;
|
|
32
|
-
}
|
|
33
|
-
`}),t.jsx(h,{hideNavMenu:!!((D=l.header)!=null&&D.hideNavMenus),translucentTextColor:($=l.header)==null?void 0:$.translucentTextColor,...a?{logo:a}:{},...g?{brand:g}:{},...p?{description:p}:{},className:X.cx(((V=l.header)==null?void 0:V.sticky)&&"sticky","page-header"),maxWidth:!1,addons:f}),t.jsx(w.ScrollRestoration,{}),t.jsxs(pe.Helmet,{children:[t.jsx("title",{children:m}),t.jsx("meta",{name:"og:title",content:m}),t.jsx("meta",{name:"og:description",content:j}),t.jsx("meta",{name:"og:image",content:d}),t.jsx("meta",{name:"twitter:image:src",content:d}),t.jsx("meta",{name:"twitter:image",content:d}),t.jsx("meta",{property:"twitter:description",content:j}),t.jsx("meta",{property:"twitter:title",content:m}),t.jsx("meta",{name:"description",content:j})]}),t.jsx(y.Stack,{flexGrow:1,className:"PageView-root",sx:{"& .BlockBase-root:first-child":{pt:"0 !important"}},children:o.sectionIds.map(S=>{var G,W;const b=o.sections[S];if(!b||b.visibility==="hidden")return null;const R=(G=b.locales)==null?void 0:G[r],se=((W=b.locales)==null?void 0:W[c])??{};return t.jsx(P.BlockRenderer,{id:S,type:b.component,mode:e,section:b,config:{...ve.default(R)?se:R,locale:r,dev:e==="draft"?{mode:e,components:s,defaultLocale:c}:{mode:e}}},S)})}),!((z=l.footer)!=null&&z.hidden)&&t.jsx(qe,{})]})}const Le=x.lazy(()=>Promise.resolve().then(()=>require("./publish-button-aUYadvYo.js"))),te=Z.default(be.default)`
|
|
34
|
-
&.sticky {
|
|
35
|
-
position: sticky;
|
|
36
|
-
top: 0;
|
|
37
|
-
}
|
|
38
|
-
`;function Ue({logo:e}){const[s,o]=x.useState(),r=y.useMediaQuery(n=>n.breakpoints.down("sm")),{value:c}=H.useAsync(()=>{var l,m;const n=new URL(r?((l=window==null?void 0:window.blocklet)==null?void 0:l.appLogo)||"/.well-known/service/blocklet/logo":((m=window==null?void 0:window.blocklet)==null?void 0:m.appLogoRect)||"/.well-known/service/blocklet/logo-rect",window.location.origin);n.searchParams.delete("imageFilter"),n.searchParams.delete("f");const i=n.toString();return new Promise(j=>{fetch(i).then(d=>{const a=d.headers.get("content-type");a!=null&&a.includes("svg")&&d.text().then(g=>{o(g),j(null)}),j(d.url)})})},[r]);if(e)return e;if(s)return t.jsx(y.Box,{sx:{filter:"initial !important"},dangerouslySetInnerHTML:{__html:ye.default.sanitize(s)}});if(c){const n=new URL(c);n.searchParams.set("imageFilter","convert"),n.searchParams.set("f","png"),n.searchParams.set("h","80");const i=n.toString();return t.jsx("img",{src:i,alt:"logo"})}return null}function oe({logo:e,translucentTextColor:s,...o}){const{y:r}=H.useWindowScroll();let c=Math.min(r/800,1),n="";if(c>.1){c=Math.max(c,.6);const i=Math.round(255*Math.min(1-c,.2));n=`rgb(${i}, ${i}, ${i})`}else n=s||"#EEEEEE";return t.jsx(te,{logo:t.jsx(Ue,{logo:e}),...o,className:X.cx(c<=.7&&"reverse-color"),style:{backgroundColor:`rgba(255,255,255,${c})`,"--logo-invert":c<=.7?1-c/6:1-c},sx:{backdropFilter:c>=.6?"blur(10px)":"blur(0px)",transition:"all 0.3s ease",position:"fixed !important",left:0,top:0,right:0,bgcolor:"transparent","&.reverse-color":{".navmenu-root>.navmenu-sub>span,\n .navmenu-root>.navmenu-item,\n .header-addons>button,\n .header-addons>a,\n .header-addons>div>button":{color:`${n} !important`}},".header-logo > div":{filter:"invert(var(--logo-invert))"},".header-logo":{color:n}}})}const ne=Z.default(y.Button)``;exports.Home=Oe;exports.HomeView=ee;exports.Loading=K;exports.PageRoutes=I;exports.PageView=B;exports.PageViewByPath=Ae;exports.TranslucentHeader=oe;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),v=require("./state-DDwYX2mu.js"),D=require("@arcblock/ux/lib/Locale/context"),O=require("@arcblock/ux/lib/Toast"),S=require("@mui/icons-material"),q=require("@mui/lab"),s=require("@mui/material"),W=require("immer"),z=require("lodash/difference"),c=require("react"),_=require("react-use"),N=require("./home-B4-4gx2w.js"),E=require("./array-C2Xw0f0u.js"),M=t=>t&&t.__esModule?t:{default:t},A=M(O),C=M(z);function R(t){const[d,b]=c.useState(!1);return e.jsx(q.LoadingButton,{...t,loading:t.loading||d,onClick:i=>{var h;const m=(h=t.onClick)==null?void 0:h.call(t,i);m instanceof Promise&&(b(!0),m.finally(()=>{b(!1)}))}})}const F=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 H(){const[t,d]=c.useState(),b=c.useMemo(()=>t?e.jsx(s.Dialog,{...t}):null,[t]),i=c.useCallback(()=>{d(void 0)},[]),m=c.useCallback(({title:h,content:g,cancelText:T="Cancel",okText:p="Ok",onOk:f,onClose:k,okIcon:L,okColor:n="primary",cancelColor:y="primary",DialogContentProps:u,form:x,...I})=>{d({...I,open:!0,children:e.jsxs("form",{onSubmit:P=>P.preventDefault(),children:[h&&e.jsxs(s.DialogTitle,{className:"between",zIndex:"appBar",bgcolor:"background.paper",sx:{borderBottom:"1px solid #E5E7EB"},children:[e.jsx(s.Box,{children:h}),e.jsx(s.IconButton,{size:"small",onClick:async()=>{i(),k==null||k()},children:e.jsx(F,{})})]}),g&&e.jsx(s.DialogContent,{...u,sx:{mt:-3,...u==null?void 0:u.sx},children:e.jsx(s.Box,{pt:3,children:g})}),e.jsxs(s.DialogActions,{children:[e.jsx(s.Button,{variant:"outlined",color:y||"primary",onClick:k??i,children:T}),e.jsx(R,{variant:"contained",color:n||"primary",startIcon:L,loadingPosition:L?"start":"center",onClick:async()=>{await(f==null?void 0:f()),i()},type:"submit",children:p})]})]}),onClose:k??i})},[i]);return{dialog:b,showDialog:m,closeDialog:i}}const J=c.forwardRef(({mode:t,state:d},b)=>{const{t:i}=D.useLocaleContext(),[m,h]=c.useState(!1),{dialog:g,showDialog:T}=H(),p=v.useProjectId(),f=c.useCallback(L=>{let n=[];T({title:i("maker.publishToProduction"),content:e.jsxs(s.Box,{sx:{minWidth:300},children:[e.jsx(s.Alert,{color:"warning",icon:e.jsx(S.Warning,{}),children:i("maker.publishToProductionTip")}),e.jsx(s.Box,{maxHeight:"50vh",overflow:"auto",mt:2,children:e.jsx(V,{state:d,toMode:t,onChange:y=>n=y,defaultPageIds:L})})]}),okText:i("maker.publish"),cancelText:i("common.cancel"),onOk:async()=>{var y,u;if((n==null?void 0:n.length)===0){const x=i("maker.publishSelectPagesMessage");throw A.default.error(x),new Error(x)}for(const x of n??d.pageIds){const I=d.pages[x];if(I){const P=(u=(y=v.checkPage(i,I,d))==null?void 0:y[0])==null?void 0:u.message;if(P)throw A.default.error(P),new Error(P)}}localStorage.setItem(v.getProjectPageVersionKey(p??""),String(new Date().getTime())),h(!0);try{await E.publishPages({mode:t,pages:n}),A.default.success(i("maker.publishSuccessMessage"))}catch(x){throw A.default.error(x.message),x}finally{h(!1)}}})},[t,d,i,p,T]);c.useImperativeHandle(b,()=>({openPublishDialog:f}));const k=c.useCallback(()=>{f()},[f]);return e.jsxs(e.Fragment,{children:[e.jsx(q.LoadingButton,{color:"primary",variant:"contained",size:"small",sx:{mr:1},onClick:k,loading:m,disabled:m,children:i("maker.publishToProduction")}),g]})});function V({state:t,toMode:d,onChange:b,defaultPageIds:i}){const{t:m,locale:h}=D.useLocaleContext(),[g,T]=c.useState(!1),[p,f]=c.useState(()=>i?Object.fromEntries(i.map(r=>[r,!0])):{}),{loading:k,error:L,value:n}=_.useAsync(()=>E.getPages({mode:d}),[d]);if(L)throw L;const y=c.useMemo(()=>JSON.parse(JSON.stringify(t.pageIds)).sort((a,j)=>{const o=t.pages[a],l=t.pages[j];return o!=null&&o.publishedAt&&new Date(o.publishedAt).getTime()<new Date(o.updatedAt).getTime()?-1:l!=null&&l.publishedAt&&new Date(l.publishedAt).getTime()<new Date(l.updatedAt).getTime()?1:new Date((o==null?void 0:o.updatedAt)??"").getTime()-new Date((l==null?void 0:l.updatedAt)??"").getTime()}),[t]),u=c.useMemo(()=>n?C.default(n.pageIds,t.pageIds):[],[t,n]),x=c.useMemo(()=>[...t.pageIds].concat(u),[t,u]),I=c.useCallback(r=>{f(a=>{const j=W.produce(a,o=>{g?(Object.assign(o,Object.fromEntries(x.map(l=>[l,!0]))),delete o[r]):o[r]?(delete o[r],u.includes(r)&&t.pageIds.filter(l=>{var w,B;return((w=t.pages[l])==null?void 0:w.slug)===((B=n==null?void 0:n.pages[r])==null?void 0:B.slug)}).forEach(l=>{delete o[l]})):(o[r]=!0,t.pageIds.includes(r)&&u.filter(l=>{var w,B;return((w=n==null?void 0:n.pages[l])==null?void 0:w.slug)===((B=t.pages[r])==null?void 0:B.slug)}).forEach(l=>{o[l]=!0}))});return T(C.default(x,Object.keys(j)).length===0),j})},[g,x,u,t,n]),P=c.useCallback(()=>{T(r=>(r&&f({}),!r))},[p]);return c.useEffect(()=>{b(g?null:Object.keys(p))},[g,p,b]),k?e.jsx(N.Loading,{sx:{my:4}}):e.jsxs(s.List,{disablePadding:!0,sx:{maxWidth:500},children:[e.jsx(s.ListItem,{sx:{position:"sticky",top:0,bgcolor:"background.paper",zIndex:1},disablePadding:!0,children:e.jsxs(s.ListItemButton,{onClick:P,dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:g,tabIndex:-1})}),e.jsx(s.ListItemText,{primary:m("common.all")})]})}),y.map(r=>{var l,w;const a=t.pages[r];if(!a)return null;const j=v.checkPage(m,a,t),o=!a.publishedAt||a.updatedAt&&new Date(a.updatedAt).getTime()>new Date(a.publishedAt).getTime();return e.jsx(s.ListItem,{disablePadding:!0,secondaryAction:e.jsxs(e.Fragment,{children:[o&&e.jsx(s.Tooltip,{title:m("maker.pages.needPublish"),children:e.jsx(S.Sync,{fontSize:"small",sx:{color:"warning.main",fontSize:16,mr:.35}})}),!a.isPublic&&e.jsx(s.Tooltip,{title:m("maker.pages.notPublic"),children:e.jsx(S.VisibilityOff,{fontSize:"small",sx:{color:"warning.main",fontSize:16,mr:.35}})}),j&&e.jsx(v.PageErrorTip,{errors:j,children:e.jsx(S.Warning,{sx:{color:"error.dark",mr:.35}})})]}),children:e.jsxs(s.ListItemButton,{onClick:()=>I(r),dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:g||!!p[r],tabIndex:-1})}),e.jsx(s.ListItemText,{primary:a.slug,secondary:(w=(l=a.locales)==null?void 0:l[h])==null?void 0:w.title,primaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"},secondaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"}})]})},r)}),u.map(r=>{var j,o;const a=n==null?void 0:n.pages[r];return a?e.jsx(s.ListItem,{disablePadding:!0,secondaryAction:e.jsx(s.Chip,{color:"warning",label:"deleted",size:"small"}),children:e.jsxs(s.ListItemButton,{onClick:()=>I(r),dense:!0,children:[e.jsx(s.ListItemIcon,{children:e.jsx(s.Checkbox,{edge:"start",checked:g||!!p[r],tabIndex:-1})}),e.jsx(s.ListItemText,{primary:a.slug,secondary:(o=(j=a.locales)==null?void 0:j[h])==null?void 0:o.title,primaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"},secondaryTypographyProps:{noWrap:!0,textOverflow:"ellipsis"}})]})},r):null})]})}exports.default=J;
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
"use strict";var ft=Object.defineProperty;var mt=(t,n,e)=>n in t?ft(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var A=(t,n,e)=>mt(t,typeof n!="symbol"?n+"":n,e);const gt=require("@blocklet/pages-kit/builtin/utils"),ue=require("@blocklet/pages-kit/types"),se=require("@blocklet/pages-kit/utils/property"),K=require("@blocklet/quickjs"),ht=require("@blocklet/sdk/lib/config"),ve=require("lru-cache"),Je=require("node-fetch"),R=require("ufo"),me=require("crypto"),yt=require("@blocklet/logger"),St=require("@blocklet/pages-kit/utils/builtin"),Ke=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),De=require("@blocklet/sdk/lib/component"),wt=require("autoprefixer"),Et=require("esbuild"),h=require("fs"),bt=require("postcss"),Tt=require("tailwindcss"),It=require("typescript"),Ct=require("@reactivedata/reactive"),ce=require("@syncedstore/core"),Ie=require("glob"),Ot=require("lib0/decoding"),Pt=require("lib0/encoding"),_t=require("lodash/cloneDeep"),jt=require("lodash/debounce"),At=require("lodash/get"),vt=require("lodash/isEmpty"),Dt=require("lodash/pick"),xt=require("lodash/set"),kt=require("lodash/union"),Rt=require("nanoid"),Nt=require("p-limit"),f=require("path"),Lt=require("stream/promises"),Ut=require("tar"),Mt=require("wait-on"),W=require("y-protocols/awareness"),we=require("y-protocols/sync"),Ft=require("yaml"),qt=require("yjs"),$t=require("lodash/isNil"),O=require("sequelize");require("sqlite3");require("@blocklet/pages-kit/types/state");const D=t=>t&&t.__esModule?t:{default:t};function re(t){if(t&&t.__esModule)return t;const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const e in t)if(e!=="default"){const s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(n,e,s.get?s:{enumerable:!0,get:()=>t[e]})}}return n.default=t,Object.freeze(n)}const y=D(ht),Bt=D(Je),Ht=D(yt),Vt=D(wt),Gt=re(Et),zt=D(bt),Jt=D(Tt),k=D(It),Ee=re(Ot),v=re(Pt),Kt=D(_t),Ye=D(jt),xe=D(At),Yt=D(vt),Qt=D(Dt),qe=D(xt),Wt=D(kt),Xt=D(Nt),Zt=D(f),es=D(Mt),Z=re(Ft),J=re(qt),ts=D($t);y.default.env.mode;y.default.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY;y.default.env.OPENAI_BASE_URL||process.env.OPENAI_BASE_URL;const ss="image-bin";y.default.env.INIT_TEMPLATE_PATH;const ns=process.env.DATABASE_URL||Zt.default.join(y.default.env.dataDir,"db/pages-kit.db"),$e=y.default,os=()=>y.default.env.tenantMode==="multiple",rs=()=>{var t;return(ts.default($e.env.preferences.multiTenantAllProjectAccessPassports)?[]:(t=$e.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:t.split(","))||[]},T=Ht.default("pages-kit"),as=O.DataTypes.sqlite.DATE.parse;O.DataTypes.sqlite.DATE.parse=(t,n)=>typeof t=="number"?new Date(t):as(t,n);const ae=new O.Sequelize({dialect:"sqlite",storage:ns,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});ae.query("pragma journal_mode = WAL;");ae.query("pragma synchronous = normal;");ae.query("pragma journal_size_limit = 67108864;");class ge extends O.Model{}ge.init({id:{type:O.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:O.DataTypes.UUIDV4},projectId:{type:O.DataTypes.UUID,allowNull:!1},componentId:{type:O.DataTypes.STRING,allowNull:!1}},{sequelize:ae,tableName:"ProjectComponents",timestamps:!1});class H extends O.Model{static async getProjectByIdOrSlug(n){return H.findOne({where:{[O.Op.or]:[{id:n},{slug:n}]}})}}H.init({id:{type:O.DataTypes.UUID,defaultValue:O.DataTypes.UUIDV4,primaryKey:!0},name:{type:O.DataTypes.STRING,allowNull:!1},description:O.DataTypes.TEXT,createdAt:O.DataTypes.DATE,updatedAt:O.DataTypes.DATE,createdBy:{type:O.DataTypes.STRING,allowNull:!1},updatedBy:{type:O.DataTypes.STRING,allowNull:!1},slug:O.DataTypes.STRING,icon:O.DataTypes.STRING,pinnedAt:O.DataTypes.DATE,useAllResources:O.DataTypes.BOOLEAN,npmSecret:O.DataTypes.STRING,relatedBlocklets:{type:O.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(t){this.setDataValue("relatedBlocklets",JSON.stringify(t||{}))}}},{sequelize:ae,paranoid:!0});H.hasMany(ge,{foreignKey:"projectId",as:"components"});const is=async(t,{componentId:n})=>{const e=`@tailwind components;
|
|
2
|
-
@tailwind utilities;
|
|
3
|
-
`,s=`.CustomComponent_${n}`;return(await zt.default([Jt.default({content:[{raw:t,extension:"tsx"}]}),Vt.default({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),r=>{r.walkRules(u=>{u.selectors=u.selectors.map(a=>a.replace(/\.(.+)/g,`${s}.$1,${s} .$1`))})}]).process(e)).css},cs=async(t,{componentId:n})=>{const e=await is(t,{componentId:n});return`export const __PagesKit_CSS__ = ${JSON.stringify(e)};
|
|
4
|
-
|
|
5
|
-
${t}
|
|
6
|
-
`},Be=K.memoize(async(t,n)=>{let e=k.default.transpileModule(t,{compilerOptions:{jsx:k.default.JsxEmit.React,target:k.default.ScriptTarget.ES2016,module:k.default.ModuleKind.ESNext},transformers:{before:[Ke.createBuiltinModuleTransformer(k.default)]}}).outputText;if(n.tailwind&&(e=await cs(e,{componentId:n.componentId})),n.module===ue.PreloadComponentScriptModule.ESM)return e;const s=k.default.transpileModule(e,{compilerOptions:{jsx:k.default.JsxEmit.React,target:k.default.ScriptTarget.ES2016,module:k.default.ModuleKind.CommonJS,moduleResolution:k.default.ModuleResolutionKind.Node16}}).outputText;return n.module===ue.PreloadComponentScriptModule.CJS?s:us(n.moduleName,s)},{keyGenerator:(t,n)=>{const e=me.createHash("md5").update(t).digest("hex"),s={...n,componentId:n.componentId,module:n.module,...n.module!==ue.PreloadComponentScriptModule.ESM?{moduleName:n.moduleName}:{},tailwind:n.tailwind};return JSON.stringify(["transpileModule",e,s])},lruOptions:{max:100,ttl:1e3*60*60}}),ls=async(t,n)=>{var u,a;const s=(a=(u=(await Gt.build({entryPoints:["index.tsx"],external:Object.keys(St.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(i){let c=null;i.onResolve({filter:/.*/},l=>l.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:l.path==="./component"?{path:"component.tsx",namespace:"vfs"}:null),i.onLoad({filter:/.*/,namespace:"vfs"},async l=>{var p;if(l.path==="index.tsx")return{contents:`export { ${n} } from './component'`,loader:"tsx"};if(l.path==="component.tsx")return{contents:t,loader:"tsx"};if(Ke.isRelativeModule(l.path)){const d=l.path.split("/").pop();if(c||(c=await he({ensureLoaded:!1})),(p=c==null?void 0:c.chunks)!=null&&p[d])try{const g=h.readFileSync(c.chunks[d],"utf-8");return T.info("get chunk from local file system",d),{contents:g,loader:"tsx"}}catch{}}return null})}}]})).outputFiles)==null?void 0:u[0])==null?void 0:a.contents;if(!s)throw new Error("Failed to build server code");const o=Buffer.from(s).toString();return k.default.transpileModule(o,{compilerOptions:{module:k.default.ModuleKind.ESNext,target:k.default.ScriptTarget.ES2020}}).outputText},Qe=K.memoize(async(t,n)=>{const e=await ls(t,n);return new RegExp(`export\\s+\\{\\s+${n}\\s+\\}`,"m").test(e)?e:void 0},{keyGenerator:(t,n)=>{const e=me.createHash("md5").update(t).digest("hex");return JSON.stringify(["extractExportValueSchema",e,n])},lruOptions:{max:100,ttl:1e3*60*60}}),us=(t,n)=>{const e=/\bawait\b/.test(n);return`// GENERATED FILE. DO NOT EDIT.
|
|
7
|
-
var ${t} = ${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
|
-
`},ee=new ve.LRUCache({max:100}),We=60*60,Ce=60;function Xe(t){T.info("clear preload components cache",{cacheKey:t}),ee.delete(t)}function Ze(t){for(const n of ee.keys())n.includes(t)&&(T.info("clear preload components cache",{cacheKey:n}),Xe(n))}function et({mode:t,instanceId:n,componentId:e,locale:s}){return["getPreloadComponents",t,n,e,s].join("-")}async function ps({mode:t,req:n,state:e,locale:s,instances:o,module:r}){const{supportedLocales:u,config:{defaultLocale:a}}=e;if(!a)return null;const i=(await Promise.all(o.map(async g=>{try{const w=et({mode:t,instanceId:g.id,componentId:g.componentId,locale:s});if(t!=="draft"&&g.useCache&&ee.has(w))return T.info(`get preload component from cache: ${w}`),ee.get(w);const j=ne({state:e,componentId:g.componentId});if(!j)return null;const x=await tt({req:n,state:e,componentId:j.id,locale:s,defaultLocale:a,properties:g.properties});if(!x)return null;const F={instanceId:g.id,preload:x};if(t!=="draft"&&g.useCache){let N=We;g.cacheDuration&&(N=g.cacheDuration),T.info(`set preload component to cache(${N}s): ${w}`),ee.set(w,F,{ttl:N*1e3})}return F}catch(w){return T.error("get preload component error",{instanceId:g.id,componentId:g.componentId},{error:w}),null}}))).filter(g=>!!g),c=Object.values(i.reduce((g,w)=>({...g,...w.preload.components}),{}));async function l(){const g=await Promise.all(c.map(async w=>{const j=se.componentUMDName({componentId:w.component.id}),x=r===ue.PreloadComponentScriptModule.ESM?{module:r,script:await Be(w.script,{componentId:w.component.id,module:r,tailwind:t!=="draft"})}:{module:r,script:await Be(w.script,{componentId:w.component.id,module:r,moduleName:j,tailwind:t!=="draft"}),moduleName:j};return[w.component.id,{component:w.component,script:x}]}));return Object.fromEntries(g)}const p=await l();return{config:{defaultLocale:a,supportedLocales:u},components:p,instances:i.map(g=>({id:g.instanceId,componentId:g.preload.component.id,locales:{[g.preload.locale]:{props:g.preload.props}}}))}}async function tt({req:t,state:n,componentId:e,locale:s,defaultLocale:o,properties:r}){const{supportedLocales:u}=n,a=ne({state:n,componentId:e});if(!a)return null;const i=u.some(l=>l.locale===s)?s:o;if(!i)return null;const c=await st({req:t,state:n,componentId:e,locale:i,defaultLocale:o,properties:r});return c?{component:a,...c}:null}const ds=20;async function st({req:t,depth:n=0,state:e,componentId:s,locale:o,defaultLocale:r,properties:u}){if(n>ds)throw new RangeError("max component depth exceeded");const a=fs({state:e,componentId:s,properties:u,locale:o});if(!a)return null;const{props:i}=a,c={locale:o||r,components:{[a.component.id]:{component:a.component,script:a.script}},props:{...i}};try{const l=await gs({...a,req:t});l!=null&&l.props&&Object.assign(c.props,l.props)}catch(l){T.error("preload data at server side error",{componentId:s,name:a.component.name},{error:l})}return await Promise.all(Object.entries(i).map(async([l,p])=>{if((p==null?void 0:p.type)===se.RenderNestedComponent){const d=await st({req:t,depth:n+1,state:e,componentId:p.componentId,locale:o,defaultLocale:r,properties:p.properties});d&&(Object.assign(c.components,d.components),Object.assign(c.props,{[l]:{type:se.RenderNestedComponent,componentId:p.componentId,props:d.props}}))}})),c}function fs({state:t,componentId:n,locale:e,properties:s}){const o=ne({state:t,componentId:n});if(!o)return null;const r=se.mergeComponent({componentId:n,getComponent:u=>ne({state:t,componentId:u}),locale:e,defaultLocale:t.config.defaultLocale,properties:s});return r?{component:o,script:r.script,props:{locale:e,...r.props}}:null}function ne({state:t,componentId:n}){var e,s,o;return((e=t.components[n])==null?void 0:e.data)??((o=(s=t.resources.components)==null?void 0:s[n])==null?void 0:o.component)}function ms({state:t,name:n}){var s,o;const e=n.toLowerCase();return((s=Object.values(t.components).find(r=>{var u;return((u=r.data.name)==null?void 0:u.toLowerCase())===e}))==null?void 0:s.data)??((o=t.resources.components&&Object.values(t.resources.components).find(r=>{var u;return((u=r.component.name)==null?void 0:u.toLowerCase())===e}))==null?void 0:o.component)}async function gs({component:t,script:n,props:e,req:s}){if(!(n!=null&&n.includes("getServerSideProps")))return null;const o=await Qe(n,"getServerSideProps");if(!o)return null;const r=new Promise(a=>{setTimeout(()=>{a({})},Ce*1e3)});return await Promise.race([r,K.Sandbox.callFunction({code:`${o}
|
|
33
|
-
|
|
34
|
-
export async function getServerSidePropsWrapper(props) {
|
|
35
|
-
const { location, fetch, props: componentProps } = props;
|
|
36
|
-
// 使用局部变量而不是全局变量
|
|
37
|
-
const originalLocation = typeof window !== 'undefined' ? window.location : undefined;
|
|
38
|
-
const originalFetch = globalThis.fetch;
|
|
39
|
-
|
|
40
|
-
try {
|
|
41
|
-
globalThis.location = location;
|
|
42
|
-
globalThis.fetch = fetch;
|
|
43
|
-
return await getServerSideProps(componentProps);
|
|
44
|
-
} finally {
|
|
45
|
-
// 清理全局状态
|
|
46
|
-
if (originalLocation) globalThis.location = originalLocation;
|
|
47
|
-
if (originalFetch) globalThis.fetch = originalFetch;
|
|
48
|
-
}
|
|
49
|
-
}`,filename:`${t.name||t.id}.js`,moduleLoader:a=>{if(a==="@blocklet/pages-kit/builtin/utils")return`const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
|
|
50
|
-
export { joinURL, withQuery, getQuery, getComponentMountPoint }
|
|
51
|
-
`;if(a==="@blocklet/pages-kit/builtin/dayjs")return K.BuiltinModules.dayjs},global:{console:{log:(...a)=>{T.info(...a)},warn:(...a)=>{T.warn(...a)},error:(...a)=>{T.error(...a)}},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:(a,{...i}={})=>{const c=typeof a=="string"&&a.startsWith("/")?R.joinURL(y.default.env.appUrl,a):a;if(typeof c=="string"&&R.parseURL(c).host===R.parseURL(y.default.env.appUrl).host){const l=s.get("cookie");if(l){const p=new Je.Headers(i.headers);p.set("cookie",l),i.headers=p}}return Bt.default(c,{...i,timeout:Ce*1e3}).then(l=>({ok:l.ok,status:l.status,statusText:l.statusText,headers:Object.fromEntries(l.headers.entries()),json:()=>l.json()}))},props:e}]})])}const nt=K.memoize(async(t,n,e)=>{if(!(t!=null&&t.includes(n)))return null;const s=await Qe(t,n);if(s)try{return await K.Sandbox.callFunction({code:`
|
|
52
|
-
${s}
|
|
53
|
-
|
|
54
|
-
export function get${n}SchemaWrapper() {
|
|
55
|
-
return ${n};
|
|
56
|
-
}
|
|
57
|
-
`,filename:`${e}.js`,functionName:`get${n}SchemaWrapper`})}catch(o){return T.error(`获取 ${n} 失败`,{componentId:e,error:o}),null}return null},{keyGenerator:(t,n,e)=>{const s=me.createHash("md5").update(t).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",s,n,e])},lruOptions:{max:100,ttl:1e3*60*60}}),hs="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",Oe="page",Pe="trigger-reload-project-resource",ke=hs,ys="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM",{uploadToMediaKit:Ss}=require("@blocklet/uploader-server"),_e=Rt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),Re=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,te=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,He=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,ws=1e4,Es=3e4,le=0,be=1,bs=0,Ts=1,je=y.default,X=f.join(process.env.BLOCKLET_DATA_DIR,"site-state"),Is=["production","draft"],Cs=["production"];function ot(t){return(t==null?void 0:t.replace(/\//g,"|"))||""}function Os(){var e;const t=je.env.languages.map(s=>({locale:s.code,name:s.name})),n=(e=t[0])==null?void 0:e.locale;return{pageIds:[],pages:{},components:{},supportedLocales:t,config:{defaultLocale:n},resources:{}}}const B=class B extends J.Doc{constructor(e){super();A(this,"states",{});A(this,"syncedStore");A(this,"conns",new Map);A(this,"awareness");A(this,"awarenessChangeHandler",({added:e,updated:s,removed:o},r)=>{const u=e.concat(s,o);if(r!==null){const c=this.conns.get(r);c&&(e.forEach(l=>{c.add(l)}),o.forEach(l=>{c.delete(l)}))}const a=v.createEncoder();v.writeVarUint(a,be),v.writeVarUint8Array(a,W.encodeAwarenessUpdate(this.awareness,u));const i=v.toUint8Array(a);this.conns.forEach((c,l)=>this.send(l,i))});A(this,"updateHandler",e=>{const s=v.createEncoder();v.writeVarUint(s,le),we.writeUpdate(s,e);const o=v.toUint8Array(s);this.conns.forEach((r,u)=>this.send(u,o))});A(this,"ensureDataStructure",()=>{var u;const{supportedLocales:e,pages:s,pageIds:o,config:r}=this.syncedStore;{const a=new Set(Object.keys(s));let i=0;for(;i<o.length;){const c=o[i];a.has(c)?(a.delete(c),i++):o.splice(i,1)}}e.splice(0,e.length),e.push(...je.env.languages.map(a=>({locale:a.code,name:a.name}))),r.defaultLocale=(u=e[0])==null?void 0:u.locale;{let a=0;const i=new Set;for(;a<e.length;){const{locale:c}=e[a];i.has(c)?e.splice(a,1):(a++,i.add(c))}}});A(this,"send",(e,s)=>{e.readyState!==bs&&e.readyState!==Ts&&this.closeConn(e);try{e.send(s,o=>{o&&this.closeConn(e)})}catch{this.closeConn(e)}});A(this,"closeConn",e=>{if(e.removeAllListeners(),this.conns.has(e)){const s=this.conns.get(e);this.conns.delete(e),s&&W.removeAwarenessStates(this.awareness,Array.from(s),null)}e.close()});A(this,"autoSave",Ye.default(()=>{h.mkdirSync(f.dirname(this.draftYjsFilePath),{recursive:!0}),h.writeFileSync(this.draftYjsFilePath,J.encodeStateAsUpdate(this))},ws));A(this,"save",({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()});A(this,"publish",async({mode:e,pages:s})=>{const o=await this.getState("draft"),r=await this.getState("production");await Ae(o,r,{pages:s,pageMergeMode:"replace",deletePages:!0,publishMode:e}),r.config.publishedAt=new Date().getTime();for(const u of s||Object.keys(this.syncedStore.pages))this.syncedStore.pages[u]&&(this.syncedStore.pages[u].publishedAt=new Date().toISOString());await this.setState(e,r)});A(this,"mergeState",async(e,s)=>{var a,i,c;const o=JSON.parse(JSON.stringify(s));(a=e.config).fontFamily??(a.fontFamily={});const r=(i=o.config)==null?void 0:i.fontFamily,u=(c=e.config)==null?void 0:c.fontFamily;e.config.fontFamily.title=(r==null?void 0:r.title)||(u==null?void 0:u.title),e.config.fontFamily.description=(r==null?void 0:r.description)||(u==null?void 0:u.description),await new Promise((l,p)=>{this.transact(async()=>{try{const d=await Ae(e,s);l(d)}catch(d){p(d)}})})});A(this,"addConnection",e=>{if(this.conns.has(e))return;e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",r=>this.messageListener(e,new Uint8Array(r)));let s=!0;const o=setInterval(()=>{if(!s)this.conns.has(e)&&this.closeConn(e),clearInterval(o);else if(this.conns.has(e)){s=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(o)}}},Es);e.on("close",()=>{this.closeConn(e),clearInterval(o)}),e.on("pong",()=>{s=!0});{const r=v.createEncoder();v.writeVarUint(r,le),we.writeSyncStep1(r,this),this.send(e,v.toUint8Array(r));const u=this.awareness.getStates();if(u.size>0){const a=v.createEncoder();v.writeVarUint(a,be),v.writeVarUint8Array(a,W.encodeAwarenessUpdate(this.awareness,Array.from(u.keys()))),this.send(e,v.toUint8Array(a))}}});A(this,"messageListener",(e,s)=>{try{const o=v.createEncoder(),r=Ee.createDecoder(s),u=Ee.readVarUint(r);switch(u){case le:v.writeVarUint(o,le),we.readSyncMessage(r,o,this,null),v.length(o)>1&&(this.ensureDataStructure(),this.send(e,v.toUint8Array(o)));break;case be:{W.applyAwarenessUpdate(this.awareness,Ee.readVarUint8Array(r),e);break}default:T.warn(`Unsupported messageType ${u}`)}}catch(o){T.error(o)}this.save()});this.options=e,h.existsSync(this.draftYjsFilePath)&&J.applyUpdate(this,h.readFileSync(this.draftYjsFilePath)),this.syncedStore=Ct.reactive(ce.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new W.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const s=f.join(X,e),o=f.join(X,`@del-${e}`);h.renameSync(s,o)}catch(s){T.error("Failed to safe delete project state dir:",s)}}static get projectIds(){return Ie.globSync("*/",{cwd:X,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(e=>B.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let s=this.sharedInstances.get(e);return s||(s=new B({path:f.join(X,e)}),this.sharedInstances.set(e,s),s)}destroy(){this.conns.forEach((e,s)=>this.closeConn(s)),this.awareness.destroy(),super.destroy()}initObserver(){const e=o=>{o.observeDeep(r=>{r.some(u=>u.changes.keys.has("updatedAt")||u.changes.keys.has("publishedAt"))||o.set("updatedAt",new Date().toISOString())})};this.syncedStore.pages&&Object.keys(this.syncedStore.pages).forEach(o=>{const r=ce.getYjsValue(this.syncedStore.pages[o]);r&&r instanceof J.Map&&e(r)});const s=ce.getYjsValue(this.syncedStore.pages);s&&s instanceof J.Map&&s.observe(o=>{o.changes.keys.forEach((r,u)=>{if(r.action==="add"){const a=ce.getYjsValue(this.syncedStore.pages[u]);a&&a instanceof J.Map&&e(a)}})})}get draftYjsFilePath(){return f.join(this.options.path,"draft.yjs")}async getState(e){var s,o,r,u;if(e==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[e]&&(this.states[e]=await Ne(this.getPublishDir(e),{includeResources:!0})??Os(),!((o=(s=this.states[e])==null?void 0:s.config)!=null&&o.defaultLocale))){(r=this.states[e]).config??(r.config={});const a=je.env.languages.map(i=>({locale:i.code,name:i.name}));this.states[e].config.defaultLocale=(u=a[0])==null?void 0:u.locale}return{...this.states[e],resources:await he().then(async a=>{var g,w,j,x;const{pages:i,components:c}=Qt.default(a,"pages","components");let l=c;const p=f.basename(this.options.path),d=await H.findByPk(p);if(d!=null&&d.useAllResources)l=c;else{const N=(await ge.findAll({where:{projectId:p}})).map(E=>E.componentId);l=Object.fromEntries(Object.entries(c||{}).filter(([E])=>N.includes(E)))}return Object.keys(((w=(g=this.states[e])==null?void 0:g.resources)==null?void 0:w.components)||{}).length>0&&(l={...l,...(x=(j=this.states[e])==null?void 0:j.resources)==null?void 0:x.components}),{pages:i,components:l}}).catch(()=>({}))}}async setState(e,s){const o=await it(s,{exportAssets:!1,includeResources:!0}),r=this.getPublishDir(e);h.mkdirSync(f.dirname(r),{recursive:!0}),h.rmSync(r,{force:!0,recursive:!0}),h.renameSync(o,r),this.states[e]=s}getPublishDir(e){return f.join(this.options.path,e)}static async pageUrlMap(e){const{projectIds:s}=this,o={};for(const r of s){const u=await H.findByPk(r);if(!u)continue;const a=await B.shared(r).getState(e),i=Wt.default(y.default.env.languages.map(c=>c.code),a.supportedLocales.map(c=>c.locale));for(const c of a.pageIds){const l=a.pages[c];if(!l||e==="production"&&!l.isPublic)continue;const p=l.slug,d=u.slug||r,g={projectId:r,projectSlug:d,pageSlug:p,pageId:c,defaultLocale:i==null?void 0:i[0],locales:i,publishedAt:a.config.publishedAt,isPublic:l.isPublic,templateConfig:l.templateConfig};d&&(o[R.joinURL("/",d,p)]={...g,shouldRedirect:!0,mainPage:!0}),o[R.joinURL("/",r,p)]={...g,shouldRedirect:!0,mainPage:!0};for(const w of i){const j={...g,locale:w};o[R.joinURL("/",w,r,p)]=j,d&&(o[R.joinURL("/",w,d,p)]=j)}}}return o}getDocumentSize(){return J.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const e=[];for(const[s,o]of this.sharedInstances.entries()){const r=o.getDocumentSize();e.push({projectId:s,sizeInBytes:r,sizeInMB:`${(r/(1024*1024)).toFixed(2)} MB`,activeConnections:o.conns.size})}return e}};A(B,"INSTANCE_TTL",30*60*1e3),A(B,"sharedInstances",new ve.LRUCache({max:100,ttl:B.INSTANCE_TTL,dispose:e=>{e.destroy()}}));let oe=B;function rt(){return h.mkdtempSync(f.join(y.default.env.dataDir,"tmp-"))}function de(t,n,e=[]){return Array.isArray(t)?t.flatMap((s,o)=>de(s,n,[...e,o])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([s,o])=>de(o,n,[...e,s])):n(t)?[e]:[]}function M(t){return t.filter(n=>n!=null)}async function Ps(t,n,e){if(!t||!h.existsSync(t)||!h.lstatSync(t).isFile())return null;let s=e[t];return s||(s=(async()=>{var o;try{const r=(o=await Ss({filePath:t,fileName:n}))==null?void 0:o.data;return r==null?void 0:r.filename}catch(r){return T.error(`Failed to upload asset ${t}:`,r),null}})(),e[t]=s),s}const _s=async(t,n)=>{const e=f.basename(t),s=await De.call({name:ke,path:R.joinURL("/uploads",e),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const o=h.createWriteStream(n);await Lt.pipeline(s.data,o)}else throw new Error(`download asset failed ${s.status}`)},js=async(t,n)=>{await Promise.all(t.map(async e=>{try{await _s(e,f.join(n,f.basename(e)))}catch(s){T.error(`Failed to export assets: ${e}, ${s}`)}}))};function at(t){return Re.test(t)?[t]:te.test(t)?(He.lastIndex=0,Array.from(t.matchAll(He)).map(e=>e[1]).filter(e=>!!e)):[]}async function Te(t,n,e){const{getFilename:s,exportAssets:o}=e,r=f.join(n,s(t));if(h.mkdirSync(f.dirname(r),{recursive:!0}),h.writeFileSync(r,Z.stringify(t)),o){const a=de(t,i=>typeof i=="string"&&(Re.test(i)||te.test(i))).map(i=>{const c=xe.default(t,i);return at(c)}).flat().filter(Boolean);await js(a,f.dirname(r))}}const Ve=new ve.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function Ge(t,n,e){var a;const s=de(t,i=>typeof i=="string"&&(Re.test(i)||te.test(i))),o=Xt.default(2),r=s.map(i=>o(async()=>{try{const c=xe.default(t,i),l=at(c);for(const p of l){const d=f.basename(p),g=e.getFilePath(p,i),w=g?`${g}:${d}`:d,j=Ve.get(w);if(j){te.test(c)||qe.default(t,i,j);return}const x=await Ps(g,d,n);x&&(te.test(c)||qe.default(t,i,x),Ve.set(w,x))}}catch(c){T.error(`Failed to process upload for path ${i.join(".")}:`,c.message||c.reason)}})),u=await Promise.allSettled(r);(a=e.onFinish)==null||a.call(e,u)}async function it(t,{exportAssets:n,pageIds:e="all",componentIds:s="all",rawConfig:o,includeResources:r=!1}={}){var F,N,S,E,b,I,V,C,L,G,ie,Q;const u=e==="all"?t.pageIds:e,a=se.getComponentDependencies({state:t,pageIds:u,componentIds:s==="all"?Object.keys(t.components):s}),i=(m,P)=>{var _;return{id:m.id,name:m.name,isTemplateSection:m.isTemplateSection??!1,templateDescription:m.templateDescription,llmConfig:m.llmConfig,component:m.component,config:m.config,visibility:m.visibility,properties:((_=m.locales)==null?void 0:_[P])??{}}},c=(m,P)=>{var _;return{id:m.id,createdAt:m.createdAt,updatedAt:m.updatedAt,publishedAt:m.publishedAt,isPublic:m.isPublic??!0,templateConfig:m.templateConfig,meta:((_=m.locales)==null?void 0:_[P])??{},sections:M(m.sectionIds.map($=>{const q=m.sections[$];return q&&i(q,P)}))}},l=M(t.supportedLocales.map(m=>m.locale).flatMap(m=>u.map(P=>{const _=t.pages[P];return _&&{locale:m,slug:_.slug,page:c(_,m)}}))),p=rt(),d=f.join(p,"pages");h.mkdirSync(d,{recursive:!0});const g=f.join(p,"components");h.mkdirSync(g,{recursive:!0});for(const{locale:m,slug:P,page:_}of l)await Te(_,d,{getFilename:()=>`${ot(P)||"index"}.${m}.yml`,exportAssets:n});for(const m of a){const P=(F=t.components[m])==null?void 0:F.data;P&&await Te(P,g,{getFilename:_=>`${_.name||"unnamed"}.${_.id}.yml`,exportAssets:n})}const w=f.join(p,".blocklet/pages/pages.config.yml");h.mkdirSync(f.dirname(w),{recursive:!0});const j={pages:M(u.map(m=>{const P=t.pages[m];return P&&{id:m,slug:P.slug}})),components:M(a.map(m=>{var _;const P=(_=t.components[m])==null?void 0:_.data;return P&&{id:m,name:P.name}})),...r?{resources:{components:M(Object.keys(((N=t.resources)==null?void 0:N.components)||{}).filter(m=>a.includes(m)).map(m=>{var P,_,$,q;return{id:m,name:(q=($=(_=(P=t.resources)==null?void 0:P.components)==null?void 0:_[m])==null?void 0:$.component)==null?void 0:q.name}}))}}:{},supportedLocales:t.supportedLocales,config:t.config};h.writeFileSync(w,Z.stringify(j));const x=f.join(p,"config.source.json");if(o&&h.writeFileSync(x,JSON.stringify(o)),r){const m=f.join(p,"resources"),P=f.join(m,"components");h.mkdirSync(P,{recursive:!0});for(const q of Object.keys(((S=t==null?void 0:t.resources)==null?void 0:S.components)??{}).filter(U=>a.includes(U))){const U=(I=(b=(E=t.resources)==null?void 0:E.components)==null?void 0:b[q])==null?void 0:I.component;U&&await Te(U,P,{getFilename:z=>`${z.name||"unnamed"}.${z.id}.yml`,exportAssets:n})}const _=f.join(p,"chunks");h.mkdirSync(_,{recursive:!0});const{chunks:$}=await he();for(const q of Object.keys(((V=t==null?void 0:t.resources)==null?void 0:V.components)??{}).filter(U=>a.includes(U))){const U=(G=(L=(C=t.resources)==null?void 0:C.components)==null?void 0:L[q])==null?void 0:G.component;if(U&&((ie=U.renderer)==null?void 0:ie.type)==="react-component"){const z=((Q=U.renderer)==null?void 0:Q.chunks)??[];if((z==null?void 0:z.length)>0)for(const ye of z){const Fe=f.join(_,ye),Se=$==null?void 0:$[ye];try{Se&&h.existsSync(Se)&&!h.existsSync(Fe)&&h.copyFileSync(Se,Fe)}catch(dt){T.error(`copy chunk ${ye} error`,dt.message)}}}}}return p}async function Ne(t,{importAssets:n,includeResources:e}={}){var r,u,a;if(!h.existsSync(t))return null;let s,o=!1;try{h.lstatSync(t).isDirectory()?s=t:/\.(tgz|gz|tar)$/.test(t)&&(o=!0,s=rt(),await Ut.x({file:t,C:s}));const i=Ie.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}).at(0),c=i&&f.join(f.dirname(i),"../../pages"),l=i&&f.join(f.dirname(i),"../../components"),p=i&&f.join(f.dirname(i),"../../chunks");if(!i)return null;const d=Z.parse(h.readFileSync(i).toString()),g=(S,E,b)=>{let I=f.join(S,`${E}${b?`.${b}`:""}.yml`);return(!h.existsSync(I)||!h.lstatSync(I).isFile())&&(I=f.join(S,E,`index${b?`.${b}`:""}.yml`),!h.existsSync(I)||!h.lstatSync(I))?null:Z.parse(h.readFileSync(I).toString())},w=(S,E)=>{try{const b=Ie.globSync(`*.${E}.yml`,{cwd:S,absolute:!0})[0];return b?Z.parse(h.readFileSync(b).toString()):null}catch(b){T.error("parse component error",b)}return null},j=M(d.pages.map(({slug:S})=>{var V;const E=M(d.supportedLocales.map(({locale:C})=>{const L=c?g(c,ot(S),C):void 0;if(L)return{locale:C,page:L};const G=c?g(c,S,C):void 0;return G&&{locale:C,page:G}})),b=(V=E[0])==null?void 0:V.page;if(!b)return null;const I=b.sections.map(C=>{const L=C.id||_e();return{id:L,component:C.component,config:C.config,name:C.name,isTemplateSection:C.isTemplateSection??!1,templateDescription:C.templateDescription,llmConfig:C.llmConfig,visibility:C.visibility,locales:Object.fromEntries(M(E.map(({locale:G,page:ie})=>{const Q=ie.sections.find(m=>m.id===L);return Q&&[G,Q.properties]})))}});return{id:b.id||_e(),createdAt:b.createdAt,updatedAt:b.updatedAt,publishedAt:b.publishedAt,isPublic:b.isPublic??!0,templateConfig:b.templateConfig,slug:S,sections:Object.fromEntries(I.map(C=>[C.id,C])),sectionIds:I.map(C=>C.id),locales:Object.fromEntries(E.map(({locale:C,page:L})=>[C,L.meta]))}})),x=l?M(((r=d.components)==null?void 0:r.map(({id:S})=>w(l,S)))??[]):[];if(n){const S=(...E)=>{T.info(`[${o?f.basename(t):f.basename(f.join(t,"../../../../"))}] importAssets:`,...E)};try{S("wait image-bin api ready"),await es.default({resources:[`${De.getComponentWebEndpoint(ss)}/api/sdk/uploads`],validateStatus:I=>I>=200&&I<=500}),S("image-bin api is ready");const E={},b={};S("start to upload assets"),await Promise.allSettled([Ge(x,E,{getFilePath:I=>l&&f.join(l,I),onFinish:I=>{S(`upload ${I.length} component assets`)}}),Ge(j,b,{getFilePath:(I,V)=>{const C=xe.default(j,V.slice(0,1));return c&&f.join(c,f.dirname(C.slug),I)},onFinish:I=>{S(`upload ${I.length} page assets`)}})]),S("upload assets done"),global.gc&&global.gc()}catch(E){S("Error during asset import:",E)}}const F={};if(e){const S=i&&f.join(f.dirname(i),"../../resources/components"),E=M(((a=(u=d.resources)==null?void 0:u.components)==null?void 0:a.map(({id:b})=>w(S,b)))??[]);E.length>0&&(F.components=Object.fromEntries(E.map((b,I)=>[b.id,{index:I,component:b}])))}const N={};if(p&&h.existsSync(p)){const S=h.readdirSync(p);for(const E of S)N[E]=f.join(p,E)}return{supportedLocales:d.supportedLocales,pageIds:j.map(S=>S.id),components:Object.fromEntries(x.map((S,E)=>[S.id,{index:E,data:S}])),pages:Object.fromEntries(j.map(S=>[S.id,S])),config:d.config||{},resources:F,chunks:N}}finally{o&&s&&h.rmSync(s,{force:!0,recursive:!0})}}async function Ae(t,n,{pages:e,pageMergeMode:s="byUpdateTime",deletePages:o=!1,publishMode:r=void 0}={}){try{r&&Ze(r)}catch(l){T.error("clear preload page cache error",{error:l})}const{pageIds:u,pages:a,supportedLocales:i}=t;for(const l of e??u){const p=a[l];if(!p){const d=n.pageIds.indexOf(l);d!==-1&&o&&(n.pageIds.splice(d,1),delete n.pages[l]);continue}if(n.pageIds.includes(p.id)){if(s==="replace")n.pages[p.id]=p;else if(s==="byUpdateTime"){const d=n.pages[p.id];(!d||p.updatedAt&&p.updatedAt>d.updatedAt)&&(n.pages[p.id]=p)}}else n.pageIds.push(p.id),n.pages[p.id]=p}if(o&&!e)for(const l of n.pageIds)t.pageIds.includes(l)||delete n.pages[l],n.pageIds=[...n.pageIds].filter(p=>t.pageIds.includes(p));if(n.supportedLocales.splice(0,n.supportedLocales.length),n.supportedLocales.push(...Kt.default(i)),o)for(const l of Object.keys(n.components))delete n.components[l];let c=JSON.parse(JSON.stringify(t.components));c=Object.fromEntries(await Promise.all(Object.entries(c).map(async([l,p])=>{const d=await ct(p==null?void 0:p.data);return[l,{...p,data:d}]}))),Object.assign(n.components,c),Object.assign(n.config,JSON.parse(JSON.stringify(t.config))),n.resources.components=JSON.parse(JSON.stringify(t.resources.components||{}))}const ct=K.memoize(async t=>{var n;if(!Yt.default(t==null?void 0:t.properties))return t;if(((n=t==null?void 0:t.renderer)==null?void 0:n.type)==="react-component"){const{script:e}=(t==null?void 0:t.renderer)||{};if(e&&e.includes("PROPERTIES_SCHEMA"))try{const s=await nt(e,"PROPERTIES_SCHEMA",t.id);s&&s.length>0&&t&&(t.properties={},s.forEach((o,r)=>{t!=null&&t.properties&&(t.properties[o.id]={index:r,data:o})}))}catch(s){T.error("checkPropertiesFromCode error",{componentId:t.id,name:t.name},{error:s})}}return t},{keyGenerator:t=>{var u;const n=(t==null?void 0:t.id)||"",e=(t==null?void 0:t.name)||"",s=((u=t==null?void 0:t.renderer)==null?void 0:u.type)||"",o=(t==null?void 0:t.properties)||{},r=me.createHash("md5").update(JSON.stringify(o)).digest("hex");return JSON.stringify(["checkPropertiesFromCode",n,e,s,r])},lruOptions:{max:100,ttl:1e3*60*60}});let fe,Y,Le,Ue,Me;function lt(){return fe=(async()=>{const t=De.getResources({types:[{did:ke,type:Oe},{did:ys,type:Oe}]});Y=(await Promise.all(t.map(async e=>{const s=e.path?await Ne(e.path,{importAssets:!1}):void 0;return s?{blockletId:e.did,state:s,blockletTitle:e.title}:void 0}))).filter(e=>!!e),Le=Y.reduce((e,s)=>Object.assign(e,Object.fromEntries(Object.values(s.state.pages).map(o=>o?[o==null?void 0:o.id,{page:o,blockletId:s.blockletId}]:[]))),{});const n=Y.reduce((e,s)=>Object.assign(e,Object.fromEntries(Object.values(s.state.components).map(o=>[o.data.id,{blockletId:s.blockletId,component:o.data}]))),{});Ue=Object.fromEntries(await Promise.all(Object.entries(n).map(async([e,s])=>{const o=await ct(s.component);return[e,{...s,component:o}]}))),Me=Y.reduce((e,s)=>Object.assign(e,s.state.chunks),{})})(),fe}function ut(t){const n=Ye.default(async()=>{await lt().catch(e=>{T.error("load resource states error",{error:e})}),await(t==null?void 0:t({states:Y,pages:Le,components:Ue,chunks:Me}))},3e3,{leading:!1,trailing:!0});return n(),y.default.events.on(y.default.Events.componentAdded,n),y.default.events.on(y.default.Events.componentRemoved,n),y.default.events.on(y.default.Events.componentStarted,n),y.default.events.on(y.default.Events.componentStopped,n),y.default.events.on(y.default.Events.componentUpdated,n),y.default.events.on(Pe,n),()=>{y.default.events.off(y.default.Events.componentAdded,n),y.default.events.off(y.default.Events.componentRemoved,n),y.default.events.off(y.default.Events.componentStarted,n),y.default.events.off(y.default.Events.componentStopped,n),y.default.events.off(y.default.Events.componentUpdated,n),y.default.events.off(Pe,n)}}const pt=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),pe=globalThis;var ze;(ze=pe[pt])==null||ze.call(pe);pe[pt]=ut(async({pages:t,components:n})=>{const{projectIds:e}=oe;T.info(`start update resource states projects(${e.length})`,e),await Promise.race([new Promise(s=>{setTimeout(()=>{s({})},30*1e3)}),Promise.all(e.map(async s=>{const o=oe.shared(s);o.syncedStore.resources.pages=t;const r=await H.findByPk(s);if(r!=null&&r.useAllResources)o.syncedStore.resources.components=n;else{const a=(await ge.findAll({where:{projectId:s}})).map(c=>c.componentId),i=Object.fromEntries(Object.entries(n||{}).filter(([c])=>a.includes(c)));o.syncedStore.resources.components=i}T.info(`update [${s}] resource states:`,{pages:Object.keys(o.syncedStore.resources.pages||{}).length,components:Object.keys(o.syncedStore.resources.components||{}).length})}))]).catch(s=>{T.error("update resource states failed:",s)})});async function As(){T.info("trigger reload all project resource"),y.default.events.emit(Pe)}async function he({ensureLoaded:t=!0}={}){return t&&(fe??(fe=lt()),await fe),{states:Y,pages:Le,components:Ue,chunks:Me}}exports.COMPONENT_DID=ke;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=We;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=Ce;exports.PUBLISH_MODES=Cs;exports.Project=H;exports.RESOURCE_TYPE=Oe;exports.SITE_STATE_PATH=X;exports.STATE_MODES=Is;exports.SiteState=oe;exports.clearPreloadComponentsCache=Xe;exports.clearPreloadComponentsCacheByMode=Ze;exports.fromPackage=Ne;exports.getComponentFromState=ne;exports.getComponentFromStateByName=ms;exports.getExportSchemaValueFromCode=nt;exports.getMultiTenantAllProjectAccessPassports=rs;exports.getPreloadComponent=tt;exports.getPreloadComponents=ps;exports.getPreloadComponentsCacheKey=et;exports.getResourceStates=he;exports.initPackResourceStates=ut;exports.isMultiTenant=os;exports.logger=T;exports.mergeState=Ae;exports.nextId=_e;exports.toPackage=it;exports.triggerReloadAllProjectResource=As;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const C=require("react/jsx-runtime"),v=require("@mui/material"),y=require("ufo"),Z=require("@blocklet/js-sdk"),H=require("lodash/isEmpty"),ee=require("yaml"),te=require("@arcblock/ux/lib/Locale/context"),F=require("@syncedstore/core"),oe=require("@syncedstore/react"),ne=require("ahooks"),b=require("immer"),re=require("js-cookie"),se=require("lodash/debounce"),ce=require("nanoid"),l=require("react"),V=require("react-router-dom"),ie=require("y-indexeddb"),ae=require("y-websocket"),ue=require("yjs");require("@blocklet/pages-kit/types");const E=e=>e&&e.__esModule?e:{default:e};function le(e){if(e&&e.__esModule)return e;const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const c in e)if(c!=="default"){const a=Object.getOwnPropertyDescriptor(e,c);Object.defineProperty(o,c,a.get?a:{enumerable:!0,get:()=>e[c]})}}return o.default=e,Object.freeze(o)}const de=E(H),fe=le(ee),me=E(F),pe=E(re),z=E(se),Se=e=>{const o=blocklet==null?void 0:blocklet.componentMountPoints.find(c=>c.name===e);return o?o.mountPoint:"/"};function B(){const{pathname:e}=window.location,o=e.match(/\/admin\/(maker|previewer)\/([^/]+)/),c=o==null?void 0:o[2],a=window.__PROJECT_ID__;if(!c&&!a)throw new Error("Unable to get projectId from pathname");return c||a}function we(e){return`${e}:pages:version`}function Pe(e,o){return o==="yaml"?de.default(e)?"":fe.stringify(e,{indent:2}):o==="json"?JSON.parse(JSON.stringify(e||{})):o==="array"?JSON.parse(JSON.stringify(e||[])):e}function he({error:e}){return C.jsx(v.Box,{children:C.jsx(v.Alert,{severity:"error",children:e.message})})}var W;const O=((W=window.blocklet)==null?void 0:W.prefix)||"/",L=Z.createAxios({timeout:200*1e3}),ge=window.location.protocol==="https:"?"wss":"ws",je=e=>y.joinURL(`${ge}://${window.location.hostname}`,O,`api/${e}/ws/pages`),Ce="z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";var N;(N=blocklet==null?void 0:blocklet.componentMountPoints.find(e=>e.did===Ce))!=null&&N.mountPoint||y.joinURL(O,"/image-bin");function ye(e){return e&&!/^(https?:\/\/|\/)/.test(e)?window.location.origin+y.joinURL(O,"uploads",e):e}const Ie=window.innerWidth<=750;function ke(e,o,c){if(!e||/\.gif/.test(e))return e;const a=(Ie?o/1.5:o)*(c==="quality"?1.5:1);return ve(e,{imageFilter:"resize",w:a,f:"webp"})}function ve(e,o){return!e||!o?e:y.withQuery(e,o)}async function xe(e){return L.get(`/api/projects/${e}`).then(o=>o.data)}async function Ee(e){return L.post(`/api/projects/${e.id}/update`,e).then(o=>o.data)}const be=500,_=ce.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),J=l.createContext(null);function _e({url:e,name:o,children:c,waitingSynced:a}){const[f,d]=l.useState(!1),{locale:j}=te.useLocaleContext(),P=A(),t=`${P}:MakerLocalState`,s=`${P}:${o}`,[r,n]=ne.useLocalStorageState(t,{defaultValue:{},listenStorageChange:!0}),i=l.useRef(r);i.current=r;const u=l.useMemo(()=>me.default({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{}}),[]),m=l.useMemo(()=>F.getYjsDoc(u),[u]);l.useMemo(()=>new ie.IndexeddbPersistence(s,m),[s,m]);const h=l.useMemo(()=>new ae.WebsocketProvider(e,s,m,{params:{token:pe.default.get("login_token")},resyncInterval:5*60*1e3}),[e,s,m]),q=l.useCallback(()=>{h&&(h.disconnect(),h.connect())},[h]),I=l.useMemo(()=>new ue.UndoManager([m.getArray("pageIds"),m.getMap("pages"),m.getArray("supportedLocales"),m.getMap("config")],{doc:m}),[m]),[k,x]=l.useState(null),[M,R]=l.useState(!1),[T,U]=l.useState(void 0),$=l.useCallback(async()=>{if(P){R(!0);try{const p=await xe(P);x(p)}catch(p){console.error("Failed to fetch project:",p)}finally{R(!1)}}},[P]),D=l.useCallback(async(p,S)=>{var g;if(U(void 0),!!P){S!=null&&S.optimisticUpdate&&k&&x(w=>({...w,...p}));try{const w=await Ee({...p});x(w)}catch(w){console.error("Failed to update project:",w),S!=null&&S.optimisticUpdate&&x(k),U((g=w==null?void 0:w.response)==null?void 0:g.data)}}},[P,k]);l.useEffect(()=>{P&&$()},[P,$]);const Y=l.useMemo(()=>({doc:m,state:u,localState:{...r,currentLocale:j},setLocalState:p=>n(typeof p=="function"?S=>p(S??{}):p),undoManager:I,projectState:{project:k,isLoadingProject:M,error:T},updateProject:D,forceSync:q}),[m,u,JSON.stringify(r),n,I,k,M,D,T,j,q]);return l.useEffect(()=>{I.on("stack-item-added",({stackItem:p})=>{const{currentPageId:S,currentLocale:g,pages:w}=i.current;p.meta.set("localState",{currentPageId:S,currentLocale:g,pages:w})}),I.on("stack-item-popped",({stackItem:p})=>{const S=p.meta.get("localState");S&&n(g=>({...g,...S}))})},[I,n]),l.useEffect(()=>{h.awareness.setLocalState(r)},[h,r]),l.useEffect(()=>{h.once("synced",()=>d(!0));const p=()=>{n(w=>({...w,networkStatus:void 0}))},S=()=>{n(w=>({...w,networkStatus:"offline"}))},g=z.default(({status:w})=>{w==="connected"?p():w==="disconnected"&&S()},be);return h.on("status",g),window.addEventListener("online",p),window.addEventListener("offline",S),()=>{h.off("status",g),window.removeEventListener("online",p),window.removeEventListener("offline",S)}},[h,n]),a&&!f?null:C.jsx(J.Provider,{value:Y,children:c})}const G=()=>{const e=l.useContext(J);if(!e)throw new Error("Context is null");const o=oe.useSyncedStore(e.state),{setLocalState:c,localState:a}=e,f=V.useNavigate(),d=A(),j=l.useMemo(()=>({setCurrentSectionId:(t,s)=>{var r,n;t===a.currentPageId&&s===((n=(r=a.pages)==null?void 0:r[t])==null?void 0:n.currentSectionId)||(f(y.joinURL("/admin/maker",d??"","pages",t)),c(i=>b.produce(i,u=>{var m;u.currentPageId=t,u.currentComponentId=void 0,u.customComponentPreviewerProperties={},s!==void 0&&(u.pages??(u.pages={}),(m=u.pages)[t]??(m[t]={}),u.pages[t].currentSectionId=s??void 0),s?window.sessionStorage.setItem("iframe_show_id",`"${s}"`):window.sessionStorage.removeItem("iframe_show_id")})))},setCurrentComponentId:t=>{t!==a.currentComponentId&&(f(y.joinURL("/admin/maker",d??"","components",t)),c(s=>b.produce(s,r=>{r.currentComponentId=t,r.customComponentPreviewerProperties={}})))},setCustomComponentPreviewerProperties:(()=>{const t={},s=z.default(()=>{c(r=>b.produce(r,n=>{n.customComponentPreviewerProperties={...n==null?void 0:n.customComponentPreviewerProperties,...t},Object.keys(t).forEach(i=>delete t[i])}))},5);return r=>{Object.assign(t,r),s()}})()}),[c,f,d]),P=l.useMemo(()=>({addPage:(t,s)=>{var i,u,m,h;const r=(t==null?void 0:t.id)??_(),n={...t,id:r,createdAt:(t==null?void 0:t.createdAt)??new Date().toISOString(),updatedAt:(t==null?void 0:t.updatedAt)??new Date().toISOString(),publishedAt:new Date(0).toISOString(),slug:(t==null?void 0:t.slug)??`/${r}`,sections:(t==null?void 0:t.sections)??{},sectionIds:(t==null?void 0:t.sectionIds)??[],isPublic:(t==null?void 0:t.isPublic)??!0,templateConfig:(t==null?void 0:t.templateConfig)??{isTemplate:((i=t==null?void 0:t.templateConfig)==null?void 0:i.isTemplate)??!0,displayTemplateId:((u=t==null?void 0:t.templateConfig)==null?void 0:u.displayTemplateId)??void 0,dataSourceId:((m=t==null?void 0:t.templateConfig)==null?void 0:m.dataSourceId)??void 0,dataSourceParameters:((h=t==null?void 0:t.templateConfig)==null?void 0:h.dataSourceParameters)??{}}};return e.doc.transact(()=>{o.pages[n.id]=n,o.pageIds.splice(s??o.pageIds.length,0,n.id)}),n},deletePage:t=>{const s=o.pageIds.indexOf(t);s!==-1&&e.doc.transact(()=>{o.pageIds.splice(s,1),delete o.pages[t]})},movePage:(t,s)=>{const{pageIds:r}=o,n=r.indexOf(t);n>=0&&r.splice(s,0,...r.splice(n,1))},addSection:(t,s,r)=>{const n=o.pages[t];if(!n)throw new Error(`Page ${t} is not exists`);const i={...s,id:s.id??_(),isTemplateSection:s.isTemplateSection??!0,llmConfig:s.llmConfig??{}};return e.doc.transact(()=>{n.sections[i.id]=i,n.sectionIds.splice(r??n.sectionIds.length,0,i.id)}),i},deleteSection:(t,s)=>{const r=o.pages[t];if(!r)throw new Error(`Page ${t} is not exists`);const n=r.sectionIds.indexOf(s);n!==-1&&e.doc.transact(()=>{r.sectionIds.splice(n,1),delete r.sections[s]})},toggleSectionVisibility:(t,s,r)=>{const n=o.pages[t];if(!n)throw new Error(`Page ${t} is not exists`);const i=n.sections[s];i&&(i.visibility=r)},moveSection:(t,s,r)=>{const n=o.pages[t];if(!n)throw new Error(`Page ${t} is not exists`);const{sectionIds:i}=n,u=i.indexOf(s);u>=0&&i.splice(r,0,...i.splice(u,1))}}),[o,e.doc]);return{...e,state:o,actions:P,localActions:j,get currentPage(){const{localState:{currentPageId:t}}=e;return t?o.pages[t]:void 0},get currentSection(){var n,i,u;const{localState:{currentPageId:t,...s}}=e;if(!t)return;const r=(i=(n=s.pages)==null?void 0:n[t])==null?void 0:i.currentSectionId;if(r)return(u=o.pages[t])==null?void 0:u.sections[r]}}},A=()=>{const{projectId:e}=V.useParams();return e??B()??""};function K(e){var a,f;const{resources:o}=e;if(!o.components)return{};const c={};return(f=(a=window==null?void 0:window.blocklet)==null?void 0:a.componentMountPoints)==null||f.forEach(d=>{c[d.did]=d}),Object.fromEntries(Object.entries(o.components).map(([d,{blockletId:j,component:P}])=>{var t;return[d,{data:P,blockletId:j,blockletTitle:((t=c[j])==null?void 0:t.title)||j}]}))}function Q(e){const{components:o}=e;return o||{}}function X(e){return{...K(e),...Q(e)}}const Oe=()=>X(G().state),Le=[/\.\./,/<[^>]*>/,/%[0-9a-f]{2}/i,/[<>'"%;{}()\\]/,/\x00/,/\n|\r|\t|\v|\f/,/[^a-zA-Z0-9-_@/]/];function Ae(e,o,c){const a=[];{let f;o.slug?o.slug.startsWith("/")?o.slug!=="/"&&o.slug.endsWith("/")?f=e("maker.properties.pathCheckEndWithoutSlash"):/\/{2,}/.test(o.slug)?f=e("maker.properties.pathCheckConsecutiveSlash"):/\s/.test(o.slug)?f=e("maker.properties.pathCheckWhitespace"):Le.some(d=>d.test(o.slug))?f=e("maker.properties.pathCheckInvalid"):Object.values(c.pages).some(d=>(d==null?void 0:d.id)!==o.id&&(d==null?void 0:d.slug)===o.slug)&&(f=e("maker.properties.pathCheckAlreadyExist")):f=e("maker.properties.pathCheckStartWithSlash"):f=e("maker.properties.pathCheckRequired"),f&&a.push({path:["path"],message:f})}return a.length>0?a:null}function qe({errors:e,...o}){return e!=null&&e.length?C.jsx(v.Tooltip,{...o,title:C.jsx(v.Box,{children:e.map((c,a)=>C.jsx(v.Box,{children:c.message},a))})}):null}exports.ErrorView=he;exports.PageErrorTip=qe;exports.StoreProvider=_e;exports.api=L;exports.autoResizeImage=ke;exports.checkPage=Ae;exports.getAllComponents=X;exports.getCustomComponents=Q;exports.getImageAbsoluteUrl=ye;exports.getMountPoint=Se;exports.getProjectIdFromPathnameOrWindow=B;exports.getProjectPageVersionKey=we;exports.getResourceComponents=K;exports.getWssURL=je;exports.nextId=_;exports.transformValue=Pe;exports.useAllComponents=Oe;exports.useProjectId=A;exports.useStore=G;
|