@blocklet/pages-kit-inner-components 0.7.0 → 0.7.2
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/chunks/{components-BmFOXvb0.js → components-CnPdZJ2Z.js} +1 -1
- package/lib/cjs/chunks/html-dP5_4zu1.js +1 -0
- package/lib/cjs/chunks/site-state-DCRNxkS5.js +1 -0
- package/lib/cjs/components.js +1 -1
- package/lib/cjs/project-html.js +1 -1
- package/lib/cjs/resources.js +1 -1
- package/lib/cjs/site-state.js +1 -1
- package/lib/es/chunks/{components-DLjI_Xlm.js → components-CcZk17uO.js} +1 -1
- package/lib/es/chunks/html-CNFwwbdj.js +38 -0
- package/lib/es/chunks/site-state-21ffGEui.js +1743 -0
- package/lib/es/components.js +1 -1
- package/lib/es/project-html.js +2 -2
- package/lib/es/resources.js +62 -80
- package/lib/es/site-state.js +19 -18
- package/package.json +3 -3
- package/lib/cjs/chunks/html-xfTPTsl5.js +0 -1
- package/lib/cjs/chunks/site-state-BQySNTiP.js +0 -1
- package/lib/es/chunks/html-DOgzvdOd.js +0 -50
- package/lib/es/chunks/site-state-DS7eIMFg.js +0 -1684
package/lib/es/components.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as _, G as c, e as E, f as d, c as P, k as N, n as O, b as g, j as I, g as T, h, s as y } from "./chunks/components-
|
|
1
|
+
import { C as _, G as c, e as E, f as d, c as P, k as N, n as O, b as g, j as I, g as T, h, s as y } from "./chunks/components-CcZk17uO.js";
|
|
2
2
|
import "@blocklet/pages-kit/builtin/utils";
|
|
3
3
|
import "@blocklet/pages-kit/types";
|
|
4
4
|
import "@blocklet/pages-kit/utils/builtin";
|
package/lib/es/project-html.js
CHANGED
|
@@ -5,8 +5,8 @@ import { WalletAuthenticator as B } from "@blocklet/sdk/lib/wallet-authenticator
|
|
|
5
5
|
import { WalletHandlers as D } from "@blocklet/sdk/lib/wallet-handler";
|
|
6
6
|
import { BlockletService as K } from "@blocklet/sdk/service/auth";
|
|
7
7
|
import U, { resolve as C } from "path";
|
|
8
|
-
import { l as v, g as W } from "./chunks/components-
|
|
9
|
-
import { e as H, i as N } from "./chunks/html-
|
|
8
|
+
import { l as v, g as W } from "./chunks/components-CcZk17uO.js";
|
|
9
|
+
import { e as H, i as N } from "./chunks/html-CNFwwbdj.js";
|
|
10
10
|
import { createSnapshotMiddleware as O } from "@arcblock/crawler-middleware";
|
|
11
11
|
import { PreloadComponentScriptModule as R } from "@blocklet/pages-kit/types";
|
|
12
12
|
import { isMuiColorKey as F } from "@blocklet/pages-kit/utils/common";
|
package/lib/es/resources.js
CHANGED
|
@@ -1,65 +1,47 @@
|
|
|
1
|
-
import { i as A, a as
|
|
2
|
-
import { P as
|
|
3
|
-
import { Router as
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
import
|
|
8
|
-
import O, { join as $ } from "path";
|
|
1
|
+
import { i as A, a as T, l as D } from "./chunks/components-CcZk17uO.js";
|
|
2
|
+
import { P as E, C as L, R as M, S as b, t as F, c as J, g as X } from "./chunks/site-state-21ffGEui.js";
|
|
3
|
+
import { Router as G } from "express";
|
|
4
|
+
import { rm as C, mkdir as K } from "fs/promises";
|
|
5
|
+
import u from "joi";
|
|
6
|
+
import O from "lodash/groupBy";
|
|
7
|
+
import W from "lodash/sortBy";
|
|
9
8
|
import { authMiddleware as _ } from "@blocklet/sdk/lib/middlewares/auth";
|
|
10
|
-
import { getResourceExportDir as
|
|
11
|
-
|
|
9
|
+
import { getResourceExportDir as Y } from "@blocklet/sdk/lib/component";
|
|
10
|
+
import { join as $ } from "path";
|
|
11
|
+
const z = async (e, t, o) => {
|
|
12
12
|
try {
|
|
13
13
|
const { projectId: s } = e.params;
|
|
14
14
|
if (!s)
|
|
15
15
|
return o();
|
|
16
|
-
const n = await
|
|
16
|
+
const n = await E.findByPk(s);
|
|
17
17
|
if (!n)
|
|
18
18
|
return t?.status(404).json({ error: "Project not found" });
|
|
19
19
|
const r = e.user?.did, c = e.user?.role || "UNKNOWN_ROLE";
|
|
20
20
|
if (!r)
|
|
21
21
|
return t?.status(401).json({ error: "Authentication required" });
|
|
22
22
|
if (A()) {
|
|
23
|
-
const j = n.createdBy === r, I =
|
|
23
|
+
const j = n.createdBy === r, I = T()?.includes?.(c);
|
|
24
24
|
if (!j && !I)
|
|
25
25
|
return t?.status(403).json({ error: "No permission to access this project in multi-tenant mode" });
|
|
26
26
|
} else if (!["owner", "admin", "pagesEditor"].includes(c))
|
|
27
27
|
return t?.status(403).json({ error: "No permission to access this project in single-tenant mode" });
|
|
28
28
|
e.project = n, e.projectId = s, o();
|
|
29
29
|
} catch (s) {
|
|
30
|
-
|
|
30
|
+
D.error("Project middleware error:", s), t?.status(400).json({ error: "Internal server error" });
|
|
31
31
|
}
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
return
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
async function Q(e, t) {
|
|
48
|
-
(await a.promises.stat(e)).isDirectory() ? await U(e, t) : await N(e, t);
|
|
49
|
-
}
|
|
50
|
-
const E = (e, t, o) => A() ? _()(e, t, o) : _({ roles: ["owner", "admin", "pagesEditor"] })(e, t, o), V = (e, t) => {
|
|
51
|
-
const o = z({ projectId: e, releaseId: t });
|
|
52
|
-
return $(o, J, X);
|
|
53
|
-
}, S = K(), B = "@page", T = "@component", l = ":", P = "ALL", F = "@project", D = ({ pageId: e, projectId: t }) => [B, t, e].join(l), Z = (e) => {
|
|
54
|
-
const [t, o, s] = e.split(l);
|
|
55
|
-
if (t === B) return { pageId: s, projectId: o };
|
|
56
|
-
}, k = ({ componentId: e, projectId: t }) => [T, t, e].join(l), q = (e) => {
|
|
57
|
-
const [t, o, s] = e.split(l);
|
|
58
|
-
if (t === T) return { componentId: s, projectId: o };
|
|
59
|
-
}, ee = (e) => [F, e].join(l), te = (e) => {
|
|
60
|
-
const [t, o] = e.split(l);
|
|
61
|
-
if (t === F) return o;
|
|
62
|
-
}, oe = (e) => {
|
|
32
|
+
}, y = (e, t, o) => A() ? _()(e, t, o) : _({ roles: ["owner", "admin", "pagesEditor"] })(e, t, o), H = (e, t) => {
|
|
33
|
+
const o = Y({ projectId: e, releaseId: t });
|
|
34
|
+
return $(o, L, M);
|
|
35
|
+
}, w = G(), x = "@page", N = "@component", m = ":", g = "ALL", U = "@project", S = ({ pageId: e, projectId: t }) => [x, t, e].join(m), Q = (e) => {
|
|
36
|
+
const [t, o, s] = e.split(m);
|
|
37
|
+
if (t === x) return { pageId: s, projectId: o };
|
|
38
|
+
}, k = ({ componentId: e, projectId: t }) => [N, t, e].join(m), V = (e) => {
|
|
39
|
+
const [t, o, s] = e.split(m);
|
|
40
|
+
if (t === N) return { componentId: s, projectId: o };
|
|
41
|
+
}, Z = (e) => [U, e].join(m), q = (e) => {
|
|
42
|
+
const [t, o] = e.split(m);
|
|
43
|
+
if (t === U) return o;
|
|
44
|
+
}, ee = (e) => {
|
|
63
45
|
try {
|
|
64
46
|
return JSON.parse(e);
|
|
65
47
|
} catch {
|
|
@@ -67,37 +49,37 @@ const E = (e, t, o) => A() ? _()(e, t, o) : _({ roles: ["owner", "admin", "pages
|
|
|
67
49
|
return {};
|
|
68
50
|
};
|
|
69
51
|
async function v(e) {
|
|
70
|
-
const t = await
|
|
52
|
+
const t = await b.getStateByProjectId({ projectId: e, mode: "production" }), o = await E.findByPk(e), s = t.pageIds.map((r) => {
|
|
71
53
|
const c = t.pages[r];
|
|
72
54
|
if (c)
|
|
73
|
-
return { id:
|
|
74
|
-
}).filter(Boolean), n =
|
|
55
|
+
return { id: S({ pageId: r, projectId: e }), name: c.slug };
|
|
56
|
+
}).filter(Boolean), n = W(Object.values(t.components), (r) => r.index).map(({ data: r }) => ({
|
|
75
57
|
id: k({ componentId: r.id, projectId: e }),
|
|
76
58
|
name: r.name || r.id
|
|
77
59
|
}));
|
|
78
60
|
return {
|
|
79
|
-
id:
|
|
61
|
+
id: Z(e),
|
|
80
62
|
name: o?.name || "Unnamed Project",
|
|
81
63
|
children: [
|
|
82
|
-
{ id:
|
|
64
|
+
{ id: S({ pageId: g, projectId: e }), name: "Pages", children: s },
|
|
83
65
|
{
|
|
84
|
-
id: k({ componentId:
|
|
66
|
+
id: k({ componentId: g, projectId: e }),
|
|
85
67
|
name: "Components",
|
|
86
68
|
children: n
|
|
87
69
|
}
|
|
88
70
|
]
|
|
89
71
|
};
|
|
90
72
|
}
|
|
91
|
-
|
|
92
|
-
const { projectId: o } =
|
|
73
|
+
w.get("/resources", y, async (e, t) => {
|
|
74
|
+
const { projectId: o } = ee(e.query.resourcesParams);
|
|
93
75
|
if (o) {
|
|
94
|
-
e.params = { ...e.params, projectId: o }, await
|
|
76
|
+
e.params = { ...e.params, projectId: o }, await z(e, t, () => {
|
|
95
77
|
});
|
|
96
78
|
const r = await v(o);
|
|
97
79
|
t.json({ resources: [r] });
|
|
98
80
|
return;
|
|
99
81
|
}
|
|
100
|
-
const s = await
|
|
82
|
+
const s = await E.findAll({
|
|
101
83
|
where: {
|
|
102
84
|
// Add your permission check conditions here
|
|
103
85
|
// For example: userId: req.user.id
|
|
@@ -105,52 +87,52 @@ S.get("/resources", E, async (e, t) => {
|
|
|
105
87
|
}), n = await Promise.all(s.map((r) => v(r.id)));
|
|
106
88
|
t.json({ resources: n });
|
|
107
89
|
});
|
|
108
|
-
const
|
|
109
|
-
projectId:
|
|
110
|
-
releaseId:
|
|
111
|
-
resources:
|
|
112
|
-
locale:
|
|
90
|
+
const te = u.object({
|
|
91
|
+
projectId: u.string().required().min(1),
|
|
92
|
+
releaseId: u.string().allow(""),
|
|
93
|
+
resources: u.array().items(u.string()).required(),
|
|
94
|
+
locale: u.string().allow("")
|
|
113
95
|
});
|
|
114
|
-
|
|
115
|
-
const { resources: o, projectId: s, releaseId: n } = await
|
|
96
|
+
w.post("/resources", y, async (e, t) => {
|
|
97
|
+
const { resources: o, projectId: s, releaseId: n } = await te.validateAsync(e.body), r = "production", c = [], j = [];
|
|
116
98
|
for (const i of o) {
|
|
117
|
-
if (
|
|
99
|
+
if (q(i))
|
|
118
100
|
continue;
|
|
119
|
-
const { pageId:
|
|
120
|
-
if (
|
|
121
|
-
|
|
122
|
-
pageId:
|
|
123
|
-
projectId:
|
|
101
|
+
const { pageId: a, projectId: f } = Q(i) || {};
|
|
102
|
+
if (a)
|
|
103
|
+
a === g || a && f && c.push({
|
|
104
|
+
pageId: a,
|
|
105
|
+
projectId: f
|
|
124
106
|
});
|
|
125
107
|
else {
|
|
126
|
-
const { componentId:
|
|
127
|
-
|
|
128
|
-
componentId:
|
|
108
|
+
const { componentId: l, projectId: d } = V(i) || {};
|
|
109
|
+
l === g || l && d && j.push({
|
|
110
|
+
componentId: l,
|
|
129
111
|
projectId: d
|
|
130
112
|
});
|
|
131
113
|
}
|
|
132
114
|
}
|
|
133
|
-
const I =
|
|
134
|
-
|
|
135
|
-
for (const i of
|
|
136
|
-
const
|
|
115
|
+
const I = O(c, "projectId"), h = O(j, "projectId"), B = /* @__PURE__ */ new Set([...Object.keys(I), ...Object.keys(h)]), P = H(s, n);
|
|
116
|
+
await C(P, { recursive: !0, force: !0 }), await K(P, { recursive: !0 });
|
|
117
|
+
for (const i of B) {
|
|
118
|
+
const a = await b.getStateByProjectId({ projectId: i, mode: r }), f = I[i], l = h[i], d = f?.map((p) => p.pageId), R = l?.map((p) => p.componentId);
|
|
137
119
|
if (d?.length || R?.length) {
|
|
138
|
-
const
|
|
120
|
+
const p = await F(a, {
|
|
139
121
|
exportAssets: !0,
|
|
140
122
|
pageIds: d,
|
|
141
123
|
componentIds: R
|
|
142
124
|
});
|
|
143
|
-
await
|
|
125
|
+
await J(p, P), await C(p, { recursive: !0, force: !0 });
|
|
144
126
|
}
|
|
145
|
-
|
|
127
|
+
D.info(`Exported resources for project ${i}`, {
|
|
146
128
|
pageIds: d,
|
|
147
129
|
componentIds: R
|
|
148
130
|
});
|
|
149
131
|
}
|
|
150
132
|
t.json({});
|
|
151
133
|
});
|
|
152
|
-
|
|
153
|
-
const { states: o } = await
|
|
134
|
+
w.get("/all-resources", y, async (e, t) => {
|
|
135
|
+
const { states: o } = await X(), s = o?.map((n) => {
|
|
154
136
|
const r = {
|
|
155
137
|
blockletId: n.blockletId,
|
|
156
138
|
blockletTitle: n.blockletTitle,
|
|
@@ -162,5 +144,5 @@ S.get("/all-resources", E, async (e, t) => {
|
|
|
162
144
|
t.json(s);
|
|
163
145
|
});
|
|
164
146
|
export {
|
|
165
|
-
|
|
147
|
+
w as default
|
|
166
148
|
};
|
package/lib/es/site-state.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import "./chunks/components-
|
|
2
|
-
import {
|
|
3
|
-
import { nextId as
|
|
1
|
+
import "./chunks/components-CcZk17uO.js";
|
|
2
|
+
import { d as b, a as h, b as y, S as L, f as U, h as q, i as v, e as z, g as C, j as F, m as G, t as J, k as K, u as N } from "./chunks/site-state-21ffGEui.js";
|
|
3
|
+
import { nextId as V } from "@blocklet/pages-kit/utils/common";
|
|
4
4
|
import "@blocklet/pages-kit/utils/page-model";
|
|
5
5
|
import "@blocklet/pages-kit/utils/property";
|
|
6
6
|
import "@blocklet/pages-kit/utils/route";
|
|
@@ -9,6 +9,7 @@ import "@blocklet/sdk/lib/config";
|
|
|
9
9
|
import "@reactivedata/reactive";
|
|
10
10
|
import "@syncedstore/core";
|
|
11
11
|
import "fs";
|
|
12
|
+
import "fs/promises";
|
|
12
13
|
import "glob";
|
|
13
14
|
import "lib0/decoding";
|
|
14
15
|
import "lib0/encoding";
|
|
@@ -32,19 +33,19 @@ import "yaml";
|
|
|
32
33
|
import "yjs";
|
|
33
34
|
export * from "@blocklet/pages-kit/types/state";
|
|
34
35
|
export {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
36
|
+
b as PUBLISH_MODES,
|
|
37
|
+
h as SITE_STATE_PATH,
|
|
38
|
+
y as STATE_MODES,
|
|
39
|
+
L as default,
|
|
40
|
+
U as downloadAsset,
|
|
41
|
+
q as downloadAssets,
|
|
42
|
+
v as fromPackage,
|
|
43
|
+
z as getDefaultState,
|
|
44
|
+
C as getResourceStates,
|
|
45
|
+
F as initPackResourceStates,
|
|
46
|
+
G as mergeState,
|
|
47
|
+
V as nextId,
|
|
48
|
+
J as toPackage,
|
|
49
|
+
K as triggerReloadAllProjectResource,
|
|
50
|
+
N as updateResourceStatesByProjectId
|
|
50
51
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blocklet/pages-kit-inner-components",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.2",
|
|
4
4
|
"description": "Pages Kit inner components library",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -201,8 +201,8 @@
|
|
|
201
201
|
"yaml": "^2.5.0",
|
|
202
202
|
"yjs": "^13.6.18",
|
|
203
203
|
"zustand": "^4.5.5",
|
|
204
|
-
"@blocklet/pages-kit": "^0.7.
|
|
205
|
-
"@blocklet/pages-kit-block-studio": "^0.7.
|
|
204
|
+
"@blocklet/pages-kit": "^0.7.2",
|
|
205
|
+
"@blocklet/pages-kit-block-studio": "^0.7.2"
|
|
206
206
|
},
|
|
207
207
|
"devDependencies": {
|
|
208
208
|
"@trivago/prettier-plugin-sort-imports": "^5.2.1",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";var s=Object.create;var a=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var l=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty;var y=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of i(t))!h.call(e,c)&&c!==n&&a(e,c,{get:()=>t[c],enumerable:!(r=u(t,c))||r.enumerable});return e};var f=(e,t,n)=>(n=e!=null?s(l(e)):{},y(t||!e||!e.__esModule?a(n,"default",{value:e,enumerable:!0}):n,e));const d=require("crypto");require("ufo");const g=async()=>await import("cheerio"),o={};function p(e,t){const n=JSON.stringify([e,t]);return d.createHash("md5").update(n).digest("hex")}async function C(e,t){{let n=await g();try{const r=n.load(e);return t.forEach(c=>{r(c.selector.cheerio).replaceWith(c.value)}),r.html()}catch{}finally{n=null}}return T(e,t)}function T(e,t){let n=e;return t.forEach(r=>{const c=typeof r.selector.pattern=="string"?new RegExp(r.selector.pattern,"gis"):r.selector.pattern;n=n.replace(c,r.value)}),n}async function j(e,t){if(!t||t.length===0)return e;const n=p(e,t);return o[n]??=C(e,t).finally(()=>{setTimeout(()=>{delete o[n]},10*1e3)}),o[n]}function m(e){return e.match(/<body[^>]*>(.*?)<\/body>/s)?.[1]||""}function H(e,t){return!t||Object.keys(t).length===0?!0:Object.entries(t).every(([n,r])=>e.includes(`${n}=${r}`))}exports.extractBodyContent=m;exports.injectToHtml=j;exports.matchCacheKey=H;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";const d=require("./components-BmFOXvb0.js"),q=require("@syncedstore/core"),et=require("yjs"),tt=require("@blocklet/pages-kit/utils/data-source"),Q=require("@blocklet/pages-kit/utils/route"),st=require("lodash/cloneDeep"),at=require("@blocklet/sdk/lib/config"),S=require("fs"),g=require("path"),ke=require("@blocklet/pages-kit/utils/common"),nt=require("@blocklet/pages-kit/utils/page-model"),ot=require("@blocklet/pages-kit/utils/property"),Ee=require("@blocklet/sdk/lib/component"),rt=require("@reactivedata/reactive"),Z=require("glob"),it=require("lib0/decoding"),ct=require("lib0/encoding"),lt=require("lodash/debounce"),ut=require("lodash/get"),dt=require("lodash/isEmpty"),pt=require("lodash/set"),ft=require("lodash/union"),we=require("lru-cache"),gt=require("p-limit"),D=require("sequelize"),mt=require("stream/promises"),ht=require("tar"),U=require("ufo"),yt=require("wait-on"),z=require("y-protocols/awareness"),ue=require("y-protocols/sync"),St=require("yaml"),Le=require("./html-xfTPTsl5.js");require("sqlite3");require("@blocklet/pages-kit/types/state");const $=t=>t&&t.__esModule?t:{default:t};function ne(t){if(t&&t.__esModule)return t;const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const s in t)if(s!=="default"){const a=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(e,s,a.get?a:{enumerable:!0,get:()=>t[s]})}}return e.default=t,Object.freeze(e)}const M=ne(et),Ae=$(st),A=$(at),de=ne(it),v=ne(ct),Pe=$(lt),je=$(ut),Oe=$(dt),_e=$(pt),It=$(ft),Ne=$(gt),bt=$(yt),B=ne(St),Et=D.DataTypes.sqlite.DATE.parse;D.DataTypes.sqlite.DATE.parse=(t,e)=>typeof t=="number"?new Date(t):Et(t,e);const N=new D.Sequelize({dialect:"sqlite",storage:d.databaseUrl,benchmark:process.env.ENABLE_SEQUELIZE_BENCHMARK==="true",retry:{match:[/SQLITE_BUSY/],name:"query",max:10},logging:process.env.ENABLE_SEQUELIZE_LOGGING==="true"?console.log:!1});N.query("PRAGMA journal_mode = WAL;");N.query("PRAGMA synchronous = normal;");N.query("PRAGMA journal_size_limit = 67108864;");N.query("PRAGMA cache_size = 10000;");process.on("SIGINT",async()=>{await N.close(),process.exit(0)});process.on("SIGTERM",async()=>{await N.close(),process.exit(0)});async function wt(t,e){try{if(t.getDialect()!=="sqlite")return;const[s]=await t.query("SELECT 1");if(!s||s.length===0)return;await t.query("PRAGMA shrink_memory;")}catch(s){if(s.name==="SequelizeConnectionError"||s?.message&&/closed!/.test(s.message))return;console.error("Failed to cleanup SQLite memory",e,s)}}let me=null;me&&clearInterval(me);me=setInterval(async()=>{d.logger.info("Start cleanupSqliteMemory"),await wt(N,d.databaseUrl),d.logger.info("End cleanupSqliteMemory")},60*1e3*10);const At="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",he="page",ye="trigger-reload-project-resource",De=At,Pt="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM",jt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o";class Te extends D.Model{}Te.init({id:{type:D.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:D.DataTypes.UUIDV4},projectId:{type:D.DataTypes.UUID,allowNull:!1},componentId:{type:D.DataTypes.STRING,allowNull:!1}},{sequelize:N,tableName:"ProjectComponents",timestamps:!1});const Ot="SLUG_INVALID",Y=t=>({error:"slugInvalid",code:Ot,field:"slug",message:t}),Dt={error:"slugRequired",code:"SLUG_REQUIRED",field:"slug",message:()=>"Project slug is required"},Tt={error:"slugAlreadyExists",code:"SLUG_EXISTS",field:"slug",message:t=>`Project slug "${t}" already exists`},Ct=[/\.\./,/<[^>]*>/,/%[0-9a-f]{2}/i,/[<>'"%;{}()\\]/,/\x00/,/\n|\r|\t|\v|\f/,/[^a-zA-Z0-9-_@/\\:]/],Ue=t=>{if(!t)return"";if(t==="/")return"/";const e=U.withoutTrailingSlash(t);return U.withLeadingSlash(e)||"/"},Rt=t=>t.did===jt;class L extends D.Model{static async getProjectByIdOrSlug(e,s){return e?L.findOne({where:{[D.Op.or]:[{id:e},{slug:e}],...s?.createdBy?{createdBy:s.createdBy}:{}}}):null}static async validateProjectSlug({slug:e,projectId:s}){if(e==null)return null;if(e==="")return Dt;const a=e==="/"?"/":U.withoutTrailingSlash(U.withLeadingSlash(e)),n=Ue(a);if(a!=="/"&&a.endsWith("/"))return Y(i=>`Project slug "${i}" cannot end with /`);if(/\/{2,}/.test(a))return Y(i=>`Project slug "${i}" cannot contain consecutive /`);if(/\s/.test(a))return Y(i=>`Project slug "${i}" cannot contain whitespace`);if(Ct.some(i=>i.test(a)))return Y(i=>`Project slug "${i}" contains invalid characters`);if(A.default.components?.filter(i=>i.mountPoint&&!Rt(i)).some(i=>Ue(i.mountPoint)===n))return Y(i=>`Project slug "${i}" conflicts with existing blocklet`);const c=await L.findOne({where:{slug:a}});return c&&c?.id!==s?Tt:null}}L.init({id:{type:D.DataTypes.UUID,defaultValue:D.DataTypes.UUIDV4,primaryKey:!0},name:{type:D.DataTypes.STRING,allowNull:!1},description:D.DataTypes.TEXT,createdAt:D.DataTypes.DATE,updatedAt:D.DataTypes.DATE,createdBy:{type:D.DataTypes.STRING,allowNull:!1},updatedBy:{type:D.DataTypes.STRING,allowNull:!1},slug:D.DataTypes.STRING,icon:D.DataTypes.STRING,pinnedAt:D.DataTypes.DATE,useAllResources:D.DataTypes.BOOLEAN,npmSecret:D.DataTypes.STRING,relatedBlocklets:{type:D.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 d.logger.error("Failed to parse relatedBlocklets",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("relatedBlocklets",t?JSON.stringify(t):"{}")}catch(e){d.logger.error("Failed to set relatedBlocklets",{error:e,value:t}),this.setDataValue("relatedBlocklets","{}")}}},productionState:{type:D.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 d.logger.error("Failed to parse productionState",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("productionState",t?JSON.stringify(t):"{}")}catch(e){d.logger.error("Failed to set productionState",{error:e,value:t}),this.setDataValue("productionState","{}")}}},meta:{type:D.DataTypes.JSON,allowNull:!0}},{sequelize:N,paranoid:!0,indexes:[{name:"projects_slug_unique",unique:!0,fields:["slug"]},{name:"projects_created_by",fields:["createdBy"]},{name:"projects_pinned_updated_meta_not_null",fields:[{name:"pinnedAt",order:"DESC"},{name:"updatedAt",order:"DESC"}],where:{meta:{[D.Op.ne]:null}}}]});L.hasMany(Te,{foreignKey:"projectId",as:"components"});function ee(t){t.observeDeep(e=>{e.some(s=>s.changes.keys.has("updatedAt")||s.changes.keys.has("publishedAt"))||t.set("updatedAt",new Date().toISOString())})}function Fe(){return S.mkdtempSync(g.join(A.default.env.dataDir,"tmp-"))}function te(t,e,s=[]){return Array.isArray(t)?t.flatMap((a,n)=>te(a,e,[...s,n])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([a,n])=>te(n,e,[...s,a])):e(t)?[s]:[]}function k(t){return t.filter(e=>e!=null)}function vt(t){t.pages&&Object.keys(t.pages).forEach(s=>{const a=q.getYjsValue(t.pages[s]);a&&a instanceof M.Map&&ee(a)});const e=q.getYjsValue(t.pages);e&&e instanceof M.Map&&e.observe(s=>{s.changes.keys.forEach((a,n)=>{if(a.action==="add"){const o=q.getYjsValue(t.pages[n]);o&&o instanceof M.Map&&ee(o)}})})}function kt(t){t.routes&&Object.keys(t.routes).forEach(s=>{const a=q.getYjsValue(t.routes?.[s]);a&&a instanceof M.Map&&ee(a)});const e=q.getYjsValue(t.routes);e&&e instanceof M.Map&&e.observe(s=>{s.changes.keys.forEach((a,n)=>{if(a.action==="add"){const o=q.getYjsValue(t.routes?.[n]);o&&o instanceof M.Map&&ee(o)}})})}function Lt(t,e){for(const s of e||Object.keys(t.routes||{})){let a=s,n=[];if(s.includes("-")){const[o,...c]=s.split("-");a=o,n=c||[]}if(t.routes?.[a]!==void 0){t.routes[a].publishedAt=new Date().toISOString();const o=t.routes[a];if(!o||!o.params||o.params.length===0)continue;if(s.includes("-")&&n.length>0){const c=Q.getRouteMetaDataByOptionIds(n,o);c&&(c.publishedAt=new Date().toISOString())}if(!e){const c=Q.generateParamCombinations({basePath:o.path,params:o.params,routeId:o.id,paramsOptions:o.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const i of c)i.routeMetaData??={},i.routeMetaData.publishedAt=new Date().toISOString()}}}}function pe({page:t,route:e,state:s,routeId:a,routePathInfo:n}){d.logger.info(`Executing datasource data assembly, routeId: ${a}, routePathInfo: ${JSON.stringify(n)}`);const o={...Ae.default(t),id:a,slug:n?.path??e.path,createdAt:e.createdAt,updatedAt:n?.routeMetaData?.updatedAt??e.updatedAt,publishedAt:n?.routeMetaData?.publishedAt??e.publishedAt,isPublic:(n?.routeMetaData?.isPublic??e.isPublic)&&e.isPublic};for(const c of s.supportedLocales){if(e.dataSource){let i=e.id;n&&(i=n.paramOptionIds.join("-"));const p=e.dataSource.pathDataMappings?.[i]?.dataCache?.[c.locale]??e.dataSource.pathDataMappings?.[i]?.dataCache?.[s.config.defaultLocale||"en"];if(!p)continue;tt.setPageDataSource(o,s,c.locale,p)}n&&n.routeMetaData&&(n.routeMetaData.publishedAt=new Date().toISOString())}return o}["true","1","yes","y"].includes(process.env.USE_FS_CACHE_HTML??"");const _t=60*60*1e3,H=new we.LRUCache({max:300,ttl:_t,ttlResolution:10*1e3,allowStale:!0});function Ut(t,e=[]){let s=0;const a=Array.from(H.keys()),n=t.map(o=>U.withoutTrailingSlash(o));for(const o of a)for(const c of n){if(Le.matchCacheKey(o,{currentPath:c})){H.delete(o),s++,d.logger.info(`[Cache CLEAR] key: ${o}`);break}for(const i of e)if(Le.matchCacheKey(o,{currentPath:`/${i}${c}`})){H.delete(o),s++,d.logger.info(`[Cache CLEAR] key: ${o}`);break}}return d.logger.info(`[Cache CLEAR] cleared ${s} entries for paths:`,n),s}function Mt(){const t=H.size;return H.clear(),d.logger.info(`[Cache CLEAR ALL] cleared ${t} entries`),t}A.default.events.on(A.default.Events.envUpdate,Mt);const{uploadToMediaKit:$t}=require("@blocklet/uploader-server"),Ce=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,K=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Me=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Nt=1e4,Ft=3e4,W=0,fe=1,qt=0,xt=1,Se=A.default,x=g.join(process.env.BLOCKLET_DATA_DIR,"site-state"),Bt=["production","draft"],Gt=["production"];function se(t){return t?.replace(/\//g,"|")||""}function qe(){const t=Se.env.languages?.map(s=>({locale:s.code,name:s.name}))||[],e=t[0]?.locale||"en";return{pageIds:[],pages:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{},components:{},supportedLocales:t,config:{defaultLocale:e},resources:{}}}class T extends M.Doc{constructor(e){super(),this.options=e,S.existsSync(this.draftYjsFilePath)&&M.applyUpdate(this,S.readFileSync(this.draftYjsFilePath)),this.syncedStore=rt.reactive(q.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 we.LRUCache({max:300,ttl:1e3*60*60*24});static periodicCheckTimer;static safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const s=g.join(x,e),a=g.join(x,`@del-${e}`);S.renameSync(s,a)}catch(s){d.logger.error("Failed to safe delete project state dir:",s)}}static async getProjectIds(){return(await L.findAll({attributes:["id"],raw:!0}))?.map(e=>e.id)}static get projectIds(){return Z.globSync("*/",{cwd:x,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*","undefined"]})}static get allShared(){return this.projectIds.map(e=>T.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let s=T.sharedInstances[e];return s||(s=new T({path:g.join(x,e)}),T.sharedInstances[e]=s,s)}static async getProductionState(e){const s=await L.findByPk(e,{attributes:["productionState"]});if(Oe.default(s?.productionState)){const a=g.join(x,e,"production"),n=await Re(a,{includeResources:!0})??qe();if(!n?.config?.defaultLocale){n.config??={};const o=Se.env.languages?.map(c=>({locale:c.code,name:c.name}))||[];n.config.defaultLocale=o[0]?.locale}return n}return s?.productionState}destroy(){this.cancelRelease(),this.save({flush:!0}),this.conns.forEach((s,a)=>this.closeConn(a)),this.awareness.destroy();const e=g.basename(this.options.path);delete T.sharedInstances[e],super.destroy()}initObserver(){vt(this.syncedStore),kt(this.syncedStore)}get draftYjsFilePath(){return g.join(this.options.path,"draft.yjs")}static async getStateByProjectId(e,s){if(s==="draft"){const a=T.shared(e);return JSON.parse(JSON.stringify(a.syncedStore))}return T.getProductionState(e)}async getState(e){if(e==="draft")return JSON.parse(JSON.stringify(this.syncedStore));const s=g.basename(this.options.path);return T.getProductionState(s)}async setState(e,s){const a=await Ve(s,{exportAssets:!1,includeResources:!0}),n=this.getPublishDir(e);if(S.mkdirSync(g.dirname(n),{recursive:!0}),S.rmSync(n,{force:!0,recursive:!0}),S.renameSync(a,n),e==="production"){const o=g.basename(this.options.path);T.pageUrlMapCache.delete(o);const c=Ae.default(s);await L.update({productionState:c},{where:{id:o}})}}getPublishDir(e){return g.join(this.options.path,e)}syncedStore;conns=new Map;awareness;releaseTimer;awarenessChangeHandler=({added:e,updated:s,removed:a},n)=>{const o=e.concat(s,a);if(n!==null){const p=this.conns.get(n);p&&(e.forEach(y=>{p.add(y)}),a.forEach(y=>{p.delete(y)}))}const c=v.createEncoder();v.writeVarUint(c,fe),v.writeVarUint8Array(c,z.encodeAwarenessUpdate(this.awareness,o));const i=v.toUint8Array(c);this.conns.forEach((p,y)=>this.send(y,i))};updateHandler=e=>{const s=v.createEncoder();v.writeVarUint(s,W),ue.writeUpdate(s,e);const a=v.toUint8Array(s);this.conns.forEach((n,o)=>this.send(o,a))};ensureDataStructure=()=>{const{supportedLocales:e,pages:s,pageIds:a,config:n,routes:o,routeIds:c}=this.syncedStore;{const i=new Set(Object.keys(s));let p=0;for(;p<a.length;){const y=a[p];i.has(y)?(i.delete(y),p++):a.splice(p,1)}}{const i=new Set(Object.keys(o));let p=0;for(;p<c.length;){const y=c[p];i.has(y)?(i.delete(y),p++):c.splice(p,1)}}e.splice(0,e.length),e.push(...Se.env.languages.map(i=>({locale:i.code,name:i.name}))),n.defaultLocale=e[0]?.locale;{let i=0;const p=new Set;for(;i<e.length;){const{locale:y}=e[i];p.has(y)?e.splice(i,1):(i++,p.add(y))}}};send=(e,s)=>{e.readyState!==qt&&e.readyState!==xt&&this.closeConn(e);try{e.send(s,a=>{a&&this.closeConn(e)})}catch{this.closeConn(e)}};closeConn=e=>{if(e.removeAllListeners(),this.conns.has(e)){const s=this.conns.get(e);this.conns.delete(e),s&&z.removeAwarenessStates(this.awareness,Array.from(s),null)}e.close(),this.checkAndScheduleRelease()};checkAndScheduleRelease(){this.conns.size===0&&this.scheduleRelease()}scheduleRelease(){this.cancelRelease();const e=g.basename(this.options.path);this.releaseTimer=setTimeout(()=>{d.logger.info(`[SiteState] releasing instance due to no active connections: ${e}`),this.conns.size===0&&(this.releaseTimer=void 0,this.destroy())},T.RELEASE_DELAY),d.logger.info(`[SiteState] scheduled release for project ${e} in ${T.RELEASE_DELAY/1e3}s`)}cancelRelease(){if(this.releaseTimer){clearTimeout(this.releaseTimer),this.releaseTimer=void 0;const e=g.basename(this.options.path);d.logger.info(`[SiteState] cancelled scheduled release for project ${e}`)}}autoSave=Pe.default(()=>{S.mkdirSync(g.dirname(this.draftYjsFilePath),{recursive:!0}),S.writeFileSync(this.draftYjsFilePath,M.encodeStateAsUpdate(this))},Nt);save=({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()};publish=async({mode:e,routes:s})=>{const a=g.basename(this.options.path);await Qe(a);const n=await this.getState("draft"),o=await this.getState("production");await be(n,o,{routes:s,mergeMode:"replace",deleteRoutes:!0,publishMode:e}),o.config.publishedAt=new Date().getTime(),Lt(this.syncedStore,s),await this.setState(e,o),await this.clearPageCacheForRoutes(s,o)};mergeState=async(e,s)=>{const a=JSON.parse(JSON.stringify(s));e.config.fontFamily??={};const n=a.config?.fontFamily,o=e.config?.fontFamily;e.config.fontFamily.title=n?.title||o?.title,e.config.fontFamily.description=n?.description||o?.description,await new Promise((c,i)=>{this.transact(async()=>{try{const p=await be(e,s);c(p)}catch(p){i(p)}})})};clearPageCacheForRoutes=async(e,s)=>{const a=g.basename(this.options.path),o=(await L.findByPk(a))?.slug||a;let c=e;(!c||c.length===0)&&(c=s.pageIds??[]),d.logger.info(`[SiteState] clearing page cache for project ${a}, routes:`,c||[]);const i=s.supportedLocales.map(j=>j.locale),p=[],y=c.filter(j=>s.pageIds?.includes(j));for(const j of y){const E=s.pages[j].slug;o&&o!==a&&(o==="/"?p.push(E):p.push(`/${o}${E}`)),p.push(`/${a}${E}`)}if(p.length>0)try{const j=Ut(p,i);d.logger.info(`[SiteState] cleared ${j} page cache entries for project ${a}, routes:`,c)}catch{}T.pageUrlMapCache.delete(a)};addConnection=e=>{if(this.conns.has(e))return;this.cancelRelease(),e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",n=>this.messageListener(e,new Uint8Array(n)));let s=!0;const a=setInterval(()=>{if(!s)this.conns.has(e)&&this.closeConn(e),clearInterval(a);else if(this.conns.has(e)){s=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(a)}}},Ft);e.on("close",()=>{this.closeConn(e),clearInterval(a)}),e.on("pong",()=>{s=!0});{const n=v.createEncoder();v.writeVarUint(n,W),ue.writeSyncStep1(n,this),this.send(e,v.toUint8Array(n));const o=this.awareness.getStates();if(o.size>0){const c=v.createEncoder();v.writeVarUint(c,fe),v.writeVarUint8Array(c,z.encodeAwarenessUpdate(this.awareness,Array.from(o.keys()))),this.send(e,v.toUint8Array(c))}}};messageListener=(e,s)=>{try{const a=v.createEncoder(),n=de.createDecoder(s),o=de.readVarUint(n);switch(o){case W:v.writeVarUint(a,W),ue.readSyncMessage(n,a,this,null),v.length(a)>1&&(this.ensureDataStructure(),this.send(e,v.toUint8Array(a)));break;case fe:{z.applyAwarenessUpdate(this.awareness,de.readVarUint8Array(n),e);break}default:d.logger.warn(`Unsupported messageType ${o}`)}}catch(a){d.logger.error(a)}this.save()};static async pageUrlMap(e,s){d.logger.info(`[SiteState] get pageUrlMap, mode: ${e}, projectId: ${s}`);let a=[];s?a=[s]:a=await this.getProjectIds();let n={};if(e==="production"&&a?.length){const o=new Map(a?.map(c=>[c,!0])||[]);for(const c of a){const i=T.pageUrlMapCache.get(c);i&&(Object.assign(n,i),o.delete(c))}a=Array.from(o.keys())}if(a?.length){d.logger.info("[SiteState] find project infos from database, projectIds: ",a);const o=10;for(let c=0;c<a.length;c+=o){const i=a.slice(c,c+o);d.logger.info(`[SiteState] processing project batch ${c/o+1}, ids: `,i);const p=await L.findAll({where:{id:{[D.Op.in]:i}}});await Promise.all(p?.map(async y=>{const j=y.id,R=y.slug||j,E={},m=e==="production"&&y?.productionState?y.productionState:await T.getStateByProjectId(y.id,e),f=It.default(A.default.env.languages?.map(w=>w.code)||[],m.supportedLocales?.map(w=>w.locale)||[]),I=(w,l)=>{R&&(E[U.joinURL("/",R,w)]={...l,shouldRedirect:!0,mainPage:!0}),E[U.joinURL("/",j,w)]={...l,shouldRedirect:!0,mainPage:!0};for(const u of f){const h={...l,locale:u};E[U.joinURL("/",u,j,w)]=h,R&&(E[U.joinURL("/",u,R,w)]=h)}};if(e==="draft")for(const w of m.routeIds||[]){const l=m?.routes?.[w];if(!l)continue;if(l.params&&l.params.length>0){const O=Q.generateParamCombinations({basePath:l.path,params:l.params,routeId:l.id,paramsOptions:l.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const P of O){const r=P.path,b={projectId:j,projectSlug:R,pageSlug:r,pageId:l.displayTemplateId||"",routeId:w,defaultLocale:f?.[0],locales:f,publishedAt:m.config.publishedAt,isPublic:l.isPublic&&P?.routeMetaData?.isPublic};I(r,b)}}const u=l.path,h={projectId:j,projectSlug:R,pageSlug:u,pageId:l.displayTemplateId||"",routeId:w,defaultLocale:f?.[0],locales:f,publishedAt:m.config.publishedAt,isPublic:l.isPublic};I(u,h)}for(const w of m.pageIds||[]){const l=m.pages[w];if(!l||e==="production"&&!l.isPublic)continue;const u=l.slug,h=y.slug||j,O={projectId:j,projectSlug:h,pageSlug:u,pageId:w,defaultLocale:f?.[0],locales:f,publishedAt:m.config.publishedAt,isPublic:l.isPublic,templateConfig:l.templateConfig};I(u,O)}e==="production"&&T.pageUrlMapCache.set(j,E),n={...n,...E}}))}}return d.logger.info("[SiteState] success get pageUrlMap"),n}getDocumentSize(){return M.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const e=[];for(const[s,a]of Object.entries(T.sharedInstances)){const n=a.getDocumentSize();e.push({projectId:s,sizeInBytes:n,sizeInMB:`${(n/(1024*1024)).toFixed(2)} MB`,activeConnections:a.conns.size})}return e}static startPeriodicCheck(){this.periodicCheckTimer||(this.periodicCheckTimer=setInterval(()=>{this.performPeriodicCheck()},this.PERIODIC_CHECK_INTERVAL),d.logger.info(`[SiteState] periodic check started, interval: ${this.PERIODIC_CHECK_INTERVAL/(60*60*1e3)} hours`))}static stopPeriodicCheck(){this.periodicCheckTimer&&(clearInterval(this.periodicCheckTimer),this.periodicCheckTimer=void 0,d.logger.info("[SiteState] periodic check stopped"))}static performPeriodicCheck(){const e=Object.keys(T.sharedInstances).length,s=[],a=[];for(const[n,o]of Object.entries(T.sharedInstances))o.conns.size===0?s.push({projectId:n,instance:o}):a.push({projectId:n,connections:o.conns.size});if(d.logger.info(`[SiteState] periodic check summary: total instances: ${e}, with connections: ${a.length}, without connections: ${s.length}`),s.length>0){d.logger.info(`[SiteState] releasing ${s.length} instances without connections:`,s.map(o=>o.projectId));let n=0;for(const{projectId:o,instance:c}of s)try{d.logger.info(`[SiteState] releasing instance due to periodic check: ${o}`),c.destroy(),n++}catch(i){d.logger.error(`[SiteState] failed to release instance ${o} during periodic check:`,i)}d.logger.info(`[SiteState] periodic check completed: ${n}/${s.length} instances released successfully`)}else e>0?d.logger.debug("[SiteState] periodic check: all instances have active connections"):d.logger.debug("[SiteState] periodic check: no instances exist")}}async function Vt(t,e,s){if(!t||!S.existsSync(t)||!S.lstatSync(t).isFile())return null;let a=s[t];return a||(a=(async()=>{try{return(await $t({filePath:t,fileName:e}))?.data?.filename}catch(n){return d.logger.error(`Failed to upload asset ${t}:`,n),null}})(),s[t]=a),a}const xe=async(t,e)=>{const s=g.basename(t),a=await Ee.call({name:De,path:U.joinURL("/uploads",s),responseType:"stream",method:"GET"});if(a.status>=200&&a.status<400){const n=S.createWriteStream(e);await mt.pipeline(a.data,n)}else throw new Error(`download asset failed ${a.status}`)},Be=async(t,e)=>{await Promise.all(t.map(async s=>{try{await xe(s,g.join(e,g.basename(s)))}catch(a){d.logger.error(`Failed to export assets: ${s}, ${a}`)}}))};function Ge(t){return Ce.test(t)?[t]:K.test(t)?(Me.lastIndex=0,Array.from(t.matchAll(Me)).map(s=>s[1]).filter(s=>!!s)):[]}async function X(t,e,s){const{getFilename:a,exportAssets:n}=s,o=g.join(e,a(t));if(S.mkdirSync(g.dirname(o),{recursive:!0}),S.writeFileSync(o,B.stringify(t)),n){const i=te(t,p=>typeof p=="string"&&(Ce.test(p)||K.test(p))).map(p=>{const y=je.default(t,p);return Ge(y)}).flat().filter(Boolean);await Be(i,g.dirname(o))}}const Ie=new we.LRUCache({max:100,ttl:1*60*1e3});async function $e(t,e,s){const a=te(t,i=>typeof i=="string"&&(Ce.test(i)||K.test(i))),n=Ne.default(2),o=a.map(i=>n(async()=>{try{const p=je.default(t,i),y=Ge(p);for(const j of y){const R=g.basename(j),E=s.getFilePath(j,i),m=E?`${E}:${R}`:R,f=Ie.get(m);if(f){K.test(p)||_e.default(t,i,f);return}const I=await Vt(E,R,e);I&&(K.test(p)||_e.default(t,i,I),Ie.set(m,I))}}catch(p){d.logger.error(`Failed to process upload for path ${i.join(".")}:`,p.message||p.reason)}})),c=await Promise.allSettled(o);s.onFinish?.(c)}async function Ve(t,{exportAssets:e,pageIds:s="all",componentIds:a="all",rawConfig:n,includeResources:o=!1,routeIds:c="all"}={}){const i=s==="all"?t.pageIds:s,p=ot.getComponentDependencies({state:t,pageIds:i,componentIds:a==="all"?Object.keys(t.components):a});Object.entries(t.components).forEach(([r,b])=>{b.data?.renderer?.type==="component-template"&&p.push(r)});const y=c==="all"?t.routeIds:c,j=r=>({id:r.id,name:r.name,isTemplateSection:r.isTemplateSection??!1,templateDescription:r.templateDescription,component:r.component,config:r.config,visibility:r.visibility,sections:r?.sectionIds?k(r?.sectionIds?.map(b=>{const C=r.sections?.[b];return C&&j(C)})):void 0}),R=(r,b)=>({id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,publishedAt:r.publishedAt,isPublic:r.isPublic??!0,templateConfig:r.templateConfig,meta:r.locales?.[b]??{},sections:k(r.sectionIds.map(C=>{const F=r.sections[C];return F&&j(F)})),dataSource:Object.fromEntries(Object.entries(r.dataSource||{}).map(([C,F])=>[C,F?.[b]??{}]))}),E=r=>({id:r.id,createdAt:r.createdAt,updatedAt:r.updatedAt,publishedAt:r.publishedAt,path:r.path,handler:r.handler,isPublic:r.isPublic??!0,params:r.params??[],enabledGenerate:r.enabledGenerate??!1,displayTemplateId:r.displayTemplateId,dataSource:r.dataSource}),m=k(y.map(r=>{const b=t.routes[r];return b&&E(b)})),f=k(t.supportedLocales.map(r=>r.locale).flatMap(r=>i.map(b=>{const C=t.pages[b];return C&&{locale:r,slug:C.slug,page:R(C,r)}}))),I=Fe(),w=g.join(I,"pages");S.mkdirSync(w,{recursive:!0});const l=g.join(I,"components");S.mkdirSync(l,{recursive:!0});const u=g.join(I,"routes");S.mkdirSync(u,{recursive:!0});for(const{locale:r,slug:b,page:C}of f)await X(C,w,{getFilename:()=>`${se(b)||"index"}.${r}.yml`,exportAssets:e});for(const r of m)await X(r,u,{getFilename:()=>`${se(r.path)||"index"}.yml`,exportAssets:e});for(const r of p){const b=t.components[r]?.data;b&&await X(b,l,{getFilename:C=>`${C.name||"unnamed"}.${C.id}.yml`,exportAssets:e})}const h=g.join(I,".blocklet/pages/pages.config.yml");S.mkdirSync(g.dirname(h),{recursive:!0});const O={pages:k(i.map(r=>{const b=t.pages[r];return b&&{id:r,slug:b.slug}})),routes:k(y.map(r=>{const b=t.routes[r];return b&&{id:r,path:b.path}})),components:k(p.map(r=>{const b=t.components[r]?.data;return b&&{id:r,name:b.name}})),...o?{resources:{components:k(Object.keys(t.resources?.components||{}).filter(r=>p.includes(r)).map(r=>({id:r,name:t.resources?.components?.[r]?.component?.name})))}}:{},supportedLocales:t.supportedLocales,config:t.config};S.writeFileSync(h,B.stringify(O));const P=g.join(I,"config.source.json");if(n&&S.writeFileSync(P,JSON.stringify(n)),o){const r=g.join(I,"resources"),b=g.join(r,"components");S.mkdirSync(b,{recursive:!0});for(const G of Object.keys(t?.resources?.components??{}).filter(_=>p.includes(_))){const _=t.resources?.components?.[G]?.component;_&&await X(_,b,{getFilename:V=>`${V.name||"unnamed"}.${V.id}.yml`,exportAssets:e})}const C=g.join(I,"chunks");S.mkdirSync(C,{recursive:!0});const F=zt();for(const G of Object.keys(t?.resources?.components??{}).filter(_=>p.includes(_))){const _=t.resources?.components?.[G]?.component;if(_&&_.renderer?.type==="react-component"){const V=_.renderer?.chunks??[];if(V?.length>0)for(const ce of V){const ve=g.join(C,ce),le=F?.[ce];try{le&&S.existsSync(le)&&!S.existsSync(ve)&&S.copyFileSync(le,ve)}catch(Ze){d.logger.error(`copy chunk ${ce} error`,Ze.message)}}}}}return I}async function Re(t,{importAssets:e,includeResources:s}={}){if(!S.existsSync(t))return null;let a,n=!1;try{S.lstatSync(t).isDirectory()?a=t:/\.(tgz|gz|tar)$/.test(t)&&(n=!0,a=Fe(),await ht.x({file:t,C:a}));const o=Z.globSync("**/.blocklet/pages/pages.config.yml",{cwd:a,absolute:!0}).at(0),c=o&&g.join(g.dirname(o),"../../pages"),i=o&&g.join(g.dirname(o),"../../components"),p=o&&g.join(g.dirname(o),"../../routes");if(!o)return null;const y=B.parse(S.readFileSync(o).toString()),j=(l,u,h)=>{let O=g.join(l,`${u}${h?`.${h}`:""}.yml`);return(!S.existsSync(O)||!S.lstatSync(O).isFile())&&(O=g.join(l,u,`index${h?`.${h}`:""}.yml`),!S.existsSync(O)||!S.lstatSync(O))?null:B.parse(S.readFileSync(O).toString())},R=(l,u)=>{try{const h=Z.globSync(`*.${u}.yml`,{cwd:l,absolute:!0})[0];return h?B.parse(S.readFileSync(h).toString()):null}catch(h){d.logger.error("parse component error",h)}return null},E=(l,u)=>{let h=g.join(l,`${u}.yml`);return(!S.existsSync(h)||!S.lstatSync(h).isFile())&&(h=g.join(l,u,"index.yml"),!S.existsSync(h)||!S.lstatSync(h))?null:B.parse(S.readFileSync(h).toString())},m=k(y.pages.map(({slug:l})=>{const u=k(y.supportedLocales.map(({locale:P})=>{const r=c?j(c,se(l),P):void 0;if(r)return{locale:P,page:r};const b=c?j(c,l,P):void 0;return b&&{locale:P,page:b}})),h=u[0]?.page;if(!h)return null;const O=h.sections.map(nt.unzipSection);return{id:h.id||ke.nextId(),createdAt:h.createdAt,updatedAt:h.updatedAt,publishedAt:h.publishedAt,isPublic:h.isPublic??!0,templateConfig:h.templateConfig,slug:l,sections:Object.fromEntries(O.map(P=>[P.id,P])),sectionIds:O.map(P=>P.id),locales:Object.fromEntries(u.map(({locale:P,page:r})=>[P,r.meta])),dataSource:h.dataSource?Object.fromEntries([...new Set(u.flatMap(({page:P})=>Object.keys(P.dataSource??{})))].map(P=>[P,Object.fromEntries(u.map(({locale:r,page:b})=>{const C=b.dataSource?.[P];return[r,C||{}]}))])):Object.fromEntries([...new Set(u.flatMap(({page:P})=>P.sections.map(r=>r.id)))].map(P=>[P,Object.fromEntries(u.map(({locale:r,page:b})=>{const C=b.dataSource?.[P];if(C)return[r,C];const F=b.sections.find(G=>G.id===P);return[r,F?.properties||{}]}))]))}})),f=k(y?.routes?.map(({path:l})=>{const u=p?E(p,se(l)):void 0;return{...u,id:u?.id||ke.nextId(),createdAt:u?.createdAt??new Date().toISOString(),updatedAt:u?.updatedAt??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:u?.path??`/${u?.id}`,params:u?.params,handler:u?.handler??"Pages Kit",isPublic:u?.isPublic??!0,enabledGenerate:u?.enabledGenerate??!1,displayTemplateId:u?.displayTemplateId??void 0,dataSource:u?.dataSource??{}}})??[]),I=i?k(y.components?.map(({id:l})=>R(i,l))??[]):[];if(e){const l=(...u)=>{d.logger.info(`[${n?g.basename(t):g.basename(g.join(t,"../../../../"))}] importAssets:`,...u)};try{l("wait image-bin api ready"),await bt.default({resources:[`${Ee.getComponentWebEndpoint(d.IMAGE_BIN_NAME)}/api/sdk/uploads`],validateStatus:O=>O>=200&&O<=500}),l("image-bin api is ready");const u={},h={};l("start to upload assets"),await Promise.allSettled([$e(I,u,{getFilePath:O=>i&&g.join(i,O),onFinish:O=>{l(`upload ${O.length} component assets`)}}),$e(m,h,{getFilePath:(O,P)=>{const r=je.default(m,P.slice(0,1));return c&&g.join(c,g.dirname(r.slug),O)},onFinish:O=>{l(`upload ${O.length} page assets`)}})]),l("upload assets done"),Ie.clear(),global.gc&&global.gc()}catch(u){l("Error during asset import:",u)}}const w={};if(s){const l=o&&g.join(g.dirname(o),"../../resources/components"),u=k(y.resources?.components?.map(({id:h})=>R(l,h))??[]);u.length>0&&(w.components=Object.fromEntries(u.map((h,O)=>[h.id,{index:O,component:h}])))}return{supportedLocales:y.supportedLocales,pageIds:m.map(l=>l.id),components:Object.fromEntries(I.map((l,u)=>[l.id,{index:u,data:l}])),pages:Object.fromEntries(m.map(l=>[l.id,l])),config:y.config||{},resources:w,routeIds:f.map(l=>l.id),routes:Object.fromEntries(f.map(l=>[l.id,l])),dataSourceIds:[],dataSources:{}}}finally{n&&a&&S.rmSync(a,{force:!0,recursive:!0})}}async function be(t,e,{routes:s,mergeMode:a="byUpdateTime",deleteRoutes:n=!1,publishMode:o=void 0}={}){try{o&&d.clearPreloadComponentsCacheByMode(o)}catch(E){d.logger.error("clear preload page cache error",{error:E})}const{pages:c,pageIds:i,routeIds:p,routes:y,supportedLocales:j}=t;if(o==="production"){let E=s??[],m=null;for(const f of p??[]){const I=y?.[f];if(I?.params&&I?.params.length>0&&I?.paramsOptions&&I?.paramsOptions.length>0){const w=Q.generateParamCombinations({basePath:I.path,params:I.params,routeId:I.id,paramsOptions:I.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),l=Object.fromEntries(w.map(u=>[`${f}-${u.paramOptionIds.join("-")}`,u]));m={...m||{},...l},s||(E=[...E,...w.map(u=>`${f}-${u.paramOptionIds.join("-")}`)])}else s||E.push(f)}d.logger.info("routeIds to be published: ",E);for(const f of E){let I=f;if(I.includes("-")){const[u]=I.split("-");I=u}const w=y?.[I];if(!w){const u=e.pageIds.indexOf(I);u!==-1&&n&&(e.pageIds.splice(u,1),delete e.pages[I]);for(const h of e.pageIds)h.includes(`${I}-`)&&(e.pageIds.splice(e.pageIds.indexOf(h),1),delete e.pages[h]);d.logger.info("delete main route page",I);continue}if(f.includes("-")&&!m?.[f]){const u=e.pageIds.indexOf(f);u!==-1&&n&&(e.pageIds.splice(u,1),delete e.pages[f]),d.logger.info("delete page",f);continue}if(!w.displayTemplateId){d.logger.info("no display template",f);continue}const l=c[w.displayTemplateId];if(!l){d.logger.info("no template page",f);continue}if(e.pageIds.includes(f)){if(d.logger.info("has need update page",f),a==="replace")e.pages[f]=pe({page:l,route:w,state:t,routeId:f,routePathInfo:m?.[f]}),d.logger.info("replace page",f);else if(a==="byUpdateTime"){const u=e.pages[w.id];(!u||w.updatedAt&&w.updatedAt>u.updatedAt)&&(e.pages[f]=pe({page:l,route:w,state:t,routeId:f,routePathInfo:m?.[f]}),d.logger.info("replace page by update time",f))}}else e.pageIds.push(f),e.pages[f]=pe({page:l,route:w,state:t,routeId:f,routePathInfo:m?.[f]}),d.logger.info("add page",f)}if(n&&!s)for(const f of e.pageIds)E?.includes(f)||(delete e.pages[f],d.logger.info("delete page",f)),e.pageIds=[...e.pageIds].filter(I=>E?.includes(I))}else{for(const E of i){const m=c[E];if(m)if(e.pageIds.includes(m.id)){if(a==="replace")e.pages[m.id]=m;else if(a==="byUpdateTime"){const f=e.pages[m.id];(!f||m.updatedAt&&m.updatedAt>f.updatedAt)&&(e.pages[m.id]=m)}}else e.pageIds.push(m.id),e.pages[m.id]=m}for(const E of p){const m=y[E];if(m)if(e.routeIds.includes(m.id)){if(a==="replace")e.routes[m.id]=m;else if(a==="byUpdateTime"){const f=e.routes[m.id];(!f||m.updatedAt&&m.updatedAt>f.updatedAt)&&(e.routes[m.id]=m)}}else e.routeIds.push(m.id),e.routes[m.id]=m}}if(e.supportedLocales.splice(0,e.supportedLocales.length),e.supportedLocales.push(...Ae.default(j)),n)for(const E of Object.keys(e.components))delete e.components[E];let R=JSON.parse(JSON.stringify(t.components));R=Object.fromEntries(await Promise.all(Object.entries(R).map(async([E,m])=>{const f=await ze(m?.data);return[E,{...m,data:f}]}))),Object.assign(e.components,R),Object.assign(e.config,JSON.parse(JSON.stringify(t.config))),Oe.default(t.resources.components)||(e.resources.components=JSON.parse(JSON.stringify(t.resources.components||{})))}const ze=d.memoizeWithFs(async t=>{if(!Oe.default(t?.properties))return t;if(t?.renderer?.type==="react-component"){const{script:e,PROPERTIES_SCHEMA:s}=t?.renderer||{};if(s||e&&e.includes("PROPERTIES_SCHEMA"))try{const a=await d.getExportSchemaValueFromCode(e??"","PROPERTIES_SCHEMA",t.id,s);a&&a.length>0&&t&&(t.properties={},a.forEach((n,o)=>{t?.properties&&(t.properties[n.id]={index:o,data:n})}))}catch(a){d.logger.error("getPropertiesFromCode error",{componentId:t.id,name:t.name},{error:a})}}return t},{subdir:"getPropertiesFromCode"});let ae,J,oe,re;const Ye=()=>Ee.getResources({types:[{did:De,type:he},{did:Pt,type:he}]}),zt=()=>{const t=Ye(),e={};return t.forEach(s=>{const a=Z.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s.path,absolute:!0}).at(0),n=a&&g.join(g.dirname(a),"../../chunks");if(n&&S.existsSync(n)){const o=S.readdirSync(n);for(const c of o)e[c]=g.join(n,c)}}),e};function He(){return ae=(async()=>{const t=Ye();J=(await Promise.all(t.map(async s=>{const a=s.path?await Re(s.path,{importAssets:!1}):void 0;return a?{blockletId:s.did,state:a,blockletTitle:s.title}:void 0}))).filter(s=>!!s),oe=J.reduce((s,a)=>Object.assign(s,Object.fromEntries(Object.values(a.state.pages).map(n=>n?[n?.id,{page:n,blockletId:a.blockletId}]:[]))),{});const e=J.reduce((s,a)=>Object.assign(s,Object.fromEntries(Object.values(a.state.components).map(n=>[n.data.id,{blockletId:a.blockletId,component:n.data}]))),{});re=Object.fromEntries(await Promise.all(Object.entries(e).map(async([s,a])=>{const n=await ze(a.component);return[s,{...a,component:n}]})))})(),ae}function Ke(t){const e=Pe.default(async()=>{await He().catch(s=>{d.logger.error("load resource states error",{error:s})}),await t?.({states:J,pages:oe,components:re})},3e3,{leading:!1,trailing:!0});return e(),A.default.events.on(A.default.Events.componentAdded,e),A.default.events.on(A.default.Events.componentRemoved,e),A.default.events.on(A.default.Events.componentStarted,e),A.default.events.on(A.default.Events.componentStopped,e),A.default.events.on(A.default.Events.componentUpdated,e),A.default.events.on(ye,e),()=>{A.default.events.off(A.default.Events.componentAdded,e),A.default.events.off(A.default.Events.componentRemoved,e),A.default.events.off(A.default.Events.componentStarted,e),A.default.events.off(A.default.Events.componentStopped,e),A.default.events.off(A.default.Events.componentUpdated,e),A.default.events.off(ye,e)}}const Je=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),We=Symbol.for("GLOBAL_ENV_UPDATE_LISTENER_KEY"),ie=globalThis;ie[Je]?.();ie[Je]=Ke(async({pages:t,components:e})=>{const s=await T.getProjectIds();d.logger.info(`start update resource states projects(${s.length})`,s);const a=Ne.default(10);await Promise.race([new Promise(n=>{setTimeout(()=>{n({})},30*1e3)}),Promise.all(s.map(n=>a(async()=>{Xe({projectId:n,pages:t,components:e})})))]).catch(n=>{d.logger.error("update resource states failed:",n)})});ie[We]?.();ie[We]=()=>{const t=()=>{T.pageUrlMapCache.clear(),d.logger.info("[Cache CLEAR ALL] clear all page url map cache by env update")};return A.default.events.on(A.default.Events.envUpdate,t),()=>{A.default.events.off(A.default.Events.envUpdate,t)}};T.startPeriodicCheck();process.on("beforeExit",()=>{T.stopPeriodicCheck()});process.on("SIGINT",()=>{T.stopPeriodicCheck(),process.exit(0)});process.on("SIGTERM",()=>{T.stopPeriodicCheck(),process.exit(0)});async function Xe({projectId:t,pages:e,components:s}){const a=T.sharedInstances[t];if(!a){d.logger.info(`projectId: ${t} not found in sharedInstances`);return}if(a.syncedStore.resources.pages=e,(await L.findByPk(t))?.useAllResources)a.syncedStore.resources.components=s;else{const c=(await Te.findAll({where:{projectId:t}})).map(p=>p.componentId),i=Object.fromEntries(Object.entries(s||{}).filter(([p])=>c.includes(p)));a.syncedStore.resources.components=i}d.logger.info(`update [${t}] resource states:`,{pages:Object.keys(a.syncedStore.resources.pages||{}).length,components:Object.keys(a.syncedStore.resources.components||{}).length})}const ge=new Map;async function Qe(t){if(!ge.has(t)){const e=Pe.default(async s=>Xe({projectId:s,pages:oe,components:re}),3e3);ge.set(t,e)}return ge.get(t)(t)}async function Yt(){d.logger.info("trigger reload all project resource"),A.default.events.emit(ye)}async function Ht({ensureLoaded:t=!0}={}){return t&&(ae??=He(),await ae),{states:J,pages:oe,components:re}}exports.COMPONENT_DID=De;exports.PUBLISH_MODES=Gt;exports.Project=L;exports.RESOURCE_TYPE=he;exports.SITE_STATE_PATH=x;exports.STATE_MODES=Bt;exports.SiteState=T;exports.downloadAsset=xe;exports.downloadAssets=Be;exports.fromPackage=Re;exports.getDefaultState=qe;exports.getResourceStates=Ht;exports.initPackResourceStates=Ke;exports.mergeState=be;exports.toPackage=Ve;exports.triggerReloadAllProjectResource=Yt;exports.updateResourceStatesByProjectId=Qe;
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import { createHash as a } from "crypto";
|
|
2
|
-
import "ufo";
|
|
3
|
-
const s = async () => await import("cheerio"), o = {};
|
|
4
|
-
function u(t, e) {
|
|
5
|
-
const n = JSON.stringify([t, e]);
|
|
6
|
-
return a("md5").update(n).digest("hex");
|
|
7
|
-
}
|
|
8
|
-
async function i(t, e) {
|
|
9
|
-
{
|
|
10
|
-
let n = await s();
|
|
11
|
-
try {
|
|
12
|
-
const r = n.load(t);
|
|
13
|
-
return e.forEach((c) => {
|
|
14
|
-
r(c.selector.cheerio).replaceWith(c.value);
|
|
15
|
-
}), r.html();
|
|
16
|
-
} catch {
|
|
17
|
-
} finally {
|
|
18
|
-
n = null;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
return l(t, e);
|
|
22
|
-
}
|
|
23
|
-
function l(t, e) {
|
|
24
|
-
let n = t;
|
|
25
|
-
return e.forEach((r) => {
|
|
26
|
-
const c = typeof r.selector.pattern == "string" ? new RegExp(r.selector.pattern, "gis") : r.selector.pattern;
|
|
27
|
-
n = n.replace(c, r.value);
|
|
28
|
-
}), n;
|
|
29
|
-
}
|
|
30
|
-
async function f(t, e) {
|
|
31
|
-
if (!e || e.length === 0)
|
|
32
|
-
return t;
|
|
33
|
-
const n = u(t, e);
|
|
34
|
-
return o[n] ??= i(t, e).finally(() => {
|
|
35
|
-
setTimeout(() => {
|
|
36
|
-
delete o[n];
|
|
37
|
-
}, 10 * 1e3);
|
|
38
|
-
}), o[n];
|
|
39
|
-
}
|
|
40
|
-
function p(t) {
|
|
41
|
-
return t.match(/<body[^>]*>(.*?)<\/body>/s)?.[1] || "";
|
|
42
|
-
}
|
|
43
|
-
function g(t, e) {
|
|
44
|
-
return !e || Object.keys(e).length === 0 ? !0 : Object.entries(e).every(([n, r]) => t.includes(`${n}=${r}`));
|
|
45
|
-
}
|
|
46
|
-
export {
|
|
47
|
-
p as e,
|
|
48
|
-
f as i,
|
|
49
|
-
g as m
|
|
50
|
-
};
|