@blocklet/pages-kit-inner-components 0.5.35 → 0.5.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/lib/cjs/add-component.js +2 -2
  2. package/lib/cjs/chunks/{array-DxhrK2d5.js → array-Ck0L_JhL.js} +1 -1
  3. package/lib/cjs/chunks/{config-string-DqWgB7yO.js → config-string-CaLe_baf.js} +1 -1
  4. package/lib/cjs/chunks/{draft-data-DzN2u_NT.js → draft-data-CY1N7Ozn.js} +1 -1
  5. package/lib/cjs/chunks/{home-0fezWT4S.js → home-CjWVwLEf.js} +3 -3
  6. package/lib/cjs/chunks/{publish-button-D2jaaXXn.js → publish-button-BDrUGRX4.js} +1 -1
  7. package/lib/cjs/chunks/site-state-CIPfhJn5.js +57 -0
  8. package/lib/cjs/chunks/state-D4QeRw7n.js +1 -0
  9. package/lib/cjs/components.js +1 -1
  10. package/lib/cjs/home.js +1 -1
  11. package/lib/cjs/project-html.js +1 -1
  12. package/lib/cjs/resources.js +1 -1
  13. package/lib/cjs/setting.js +2 -2
  14. package/lib/cjs/site-state.js +1 -1
  15. package/lib/es/add-component.js +4 -4
  16. package/lib/es/chunks/{array-D6qyZucY.js → array-HCA75FfO.js} +1 -1
  17. package/lib/es/chunks/{config-string-Btybe5Rd.js → config-string-17RNX8vu.js} +1 -1
  18. package/lib/es/chunks/{draft-data-DQ7_JyJX.js → draft-data-CyeVe0kA.js} +1 -1
  19. package/lib/es/chunks/{home-Dox9JwvF.js → home-COrN_x32.js} +4 -4
  20. package/lib/es/chunks/{publish-button-T2YJBoty.js → publish-button-WmGjhj6q.js} +3 -3
  21. package/lib/es/chunks/site-state-CfrteYXm.js +2137 -0
  22. package/lib/es/chunks/{state-NhsHvaKm.js → state-Br2xp7Mf.js} +179 -175
  23. package/lib/es/components.js +1 -1
  24. package/lib/es/home.js +3 -3
  25. package/lib/es/project-html.js +1 -1
  26. package/lib/es/resources.js +1 -1
  27. package/lib/es/setting.js +541 -534
  28. package/lib/es/site-state.js +1 -1
  29. package/package.json +3 -3
  30. package/lib/cjs/chunks/site-state-D00xEf4T.js +0 -57
  31. package/lib/cjs/chunks/state-DoGBMTzI.js +0 -1
  32. package/lib/es/chunks/site-state-nXcBqjeR.js +0 -2076
@@ -0,0 +1,2137 @@
1
+ var Pt = Object.defineProperty;
2
+ var Tt = (e, n, t) => n in e ? Pt(e, n, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[n] = t;
3
+ var D = (e, n, t) => Tt(e, typeof n != "symbol" ? n + "" : n, t);
4
+ import { getComponentMountPoint as vt } from "@blocklet/pages-kit/builtin/utils";
5
+ import { PreloadComponentScriptModule as ye } from "@blocklet/pages-kit/types";
6
+ import { componentUMDName as kt, RenderNestedComponent as ze, mergeComponent as Dt, getComponentDependencies as xt } from "@blocklet/pages-kit/utils/property";
7
+ import { memoize as it, Sandbox as ct, BuiltinModules as Rt } from "@blocklet/quickjs";
8
+ import I from "@blocklet/sdk/lib/config";
9
+ import { LRUCache as Pe } from "lru-cache";
10
+ import jt, { Headers as $t } from "node-fetch";
11
+ import { joinURL as Y, getQuery as Lt, withQuery as Nt, parseURL as We, withHttps as _t } from "ufo";
12
+ import { createHash as se } from "crypto";
13
+ import Mt from "@blocklet/logger";
14
+ import { promises as V, readFileSync as re, mkdtempSync as Ut, existsSync as J, lstatSync as oe, readdirSync as Ft, rmSync as lt, renameSync as Ye, mkdirSync as W, writeFileSync as we, copyFileSync as Bt, createWriteStream as Gt } from "fs";
15
+ import pt, { join as O, dirname as U, basename as F } from "path";
16
+ import Ht from "lodash/isNil";
17
+ import { BuiltinModules as Jt } from "@blocklet/pages-kit/utils/builtin";
18
+ import { isRelativeModule as Vt, createBuiltinModuleTransformer as Kt } from "@blocklet/pages-kit/utils/typescript/builtin-module-transformer";
19
+ import { getResources as zt, getComponentWebEndpoint as Wt, call as Yt } from "@blocklet/sdk/lib/component";
20
+ import qt from "autoprefixer";
21
+ import * as Qt from "esbuild";
22
+ import Xt from "postcss";
23
+ import Zt from "tailwindcss";
24
+ import _ from "typescript";
25
+ import { getYjsValue as ce, syncedStore as es } from "@syncedstore/core";
26
+ import * as K from "yjs";
27
+ import { setPageDataSource as ts } from "@blocklet/pages-kit/utils/data-source";
28
+ import { getRouteMetaDataByOptionIds as ss, generateParamCombinations as Fe } from "@blocklet/pages-kit/utils/route";
29
+ import { cloneDeep as ns } from "lodash";
30
+ import { reactive as os } from "@reactivedata/reactive";
31
+ import { globSync as Ne } from "glob";
32
+ import * as Re from "lib0/decoding";
33
+ import * as j from "lib0/encoding";
34
+ import rs from "lodash/cloneDeep";
35
+ import dt from "lodash/debounce";
36
+ import Be from "lodash/get";
37
+ import ut from "lodash/isEmpty";
38
+ import as from "lodash/pick";
39
+ import qe from "lodash/set";
40
+ import is from "lodash/union";
41
+ import { customAlphabet as cs } from "nanoid";
42
+ import ls from "p-limit";
43
+ import { pipeline as ps } from "stream/promises";
44
+ import { x as ds } from "tar";
45
+ import us from "wait-on";
46
+ import { Awareness as fs, encodeAwarenessUpdate as Qe, removeAwarenessStates as ms, applyAwarenessUpdate as hs } from "y-protocols/awareness";
47
+ import { writeUpdate as gs, writeSyncStep1 as ys, readSyncMessage as Ss } from "y-protocols/sync";
48
+ import * as ae from "yaml";
49
+ import { DataTypes as R, Sequelize as ws, Model as ft, Op as Es } from "sequelize";
50
+ import "sqlite3";
51
+ import "@blocklet/pages-kit/types/state";
52
+ I.env.mode;
53
+ I.env.OPENAI_API_KEY || process.env.OPENAI_API_KEY;
54
+ I.env.OPENAI_BASE_URL || process.env.OPENAI_BASE_URL;
55
+ I.env.TRANSLATE_ADDITIONAL_PROMPT || process.env.TRANSLATE_ADDITIONAL_PROMPT;
56
+ I.env.PAGE_CONTENT_ADDITIONAL_PROMPT || process.env.PAGE_CONTENT_ADDITIONAL_PROMPT;
57
+ const Is = "image-bin";
58
+ I.env.INIT_TEMPLATE_PATH;
59
+ const bs = process.env.DATABASE_URL || pt.join(I.env.dataDir, "db/pages-kit.db"), Xe = I, eo = () => I.env.tenantMode === "multiple", to = () => {
60
+ var e;
61
+ return (Ht(Xe.env.preferences.multiTenantAllProjectAccessPassports) ? [] : (e = Xe.env.preferences.multiTenantAllProjectAccessPassports) == null ? void 0 : e.split(",")) || [];
62
+ }, As = pt.join(I.env.dataDir, "fs-memoize-cache"), Os = I.env.FS_MEMOIZE_CACHE_VERSION || "v1.0.0", y = Mt("pages-kit"), Cs = R.sqlite.DATE.parse;
63
+ R.sqlite.DATE.parse = (e, n) => typeof e == "number" ? new Date(e) : Cs(e, n);
64
+ const me = new ws({
65
+ dialect: "sqlite",
66
+ storage: bs,
67
+ benchmark: process.env.ENABLE_SEQUELIZE_BENCHMARK === "true",
68
+ retry: {
69
+ match: [/SQLITE_BUSY/],
70
+ name: "query",
71
+ max: 10
72
+ },
73
+ // eslint-disable-next-line no-console
74
+ logging: process.env.ENABLE_SEQUELIZE_LOGGING === "true" ? console.log : !1
75
+ // logQueryParameters: true,
76
+ });
77
+ me.query("pragma journal_mode = WAL;");
78
+ me.query("pragma synchronous = normal;");
79
+ me.query("pragma journal_size_limit = 67108864;");
80
+ class Te extends ft {
81
+ // Foreign key to Component
82
+ }
83
+ Te.init(
84
+ {
85
+ id: {
86
+ type: R.UUID,
87
+ allowNull: !1,
88
+ primaryKey: !0,
89
+ defaultValue: R.UUIDV4
90
+ },
91
+ projectId: {
92
+ type: R.UUID,
93
+ allowNull: !1
94
+ },
95
+ componentId: {
96
+ type: R.STRING,
97
+ allowNull: !1
98
+ }
99
+ },
100
+ { sequelize: me, tableName: "ProjectComponents", timestamps: !1 }
101
+ );
102
+ class q extends ft {
103
+ static async getProjectByIdOrSlug(n) {
104
+ return q.findOne({
105
+ where: {
106
+ [Es.or]: [{ id: n }, { slug: n }]
107
+ }
108
+ });
109
+ }
110
+ }
111
+ q.init(
112
+ {
113
+ id: {
114
+ type: R.UUID,
115
+ defaultValue: R.UUIDV4,
116
+ primaryKey: !0
117
+ },
118
+ name: {
119
+ type: R.STRING,
120
+ allowNull: !1
121
+ },
122
+ description: R.TEXT,
123
+ createdAt: R.DATE,
124
+ updatedAt: R.DATE,
125
+ createdBy: {
126
+ type: R.STRING,
127
+ allowNull: !1
128
+ },
129
+ updatedBy: {
130
+ type: R.STRING,
131
+ allowNull: !1
132
+ },
133
+ slug: R.STRING,
134
+ icon: R.STRING,
135
+ pinnedAt: R.DATE,
136
+ useAllResources: R.BOOLEAN,
137
+ npmSecret: R.STRING,
138
+ relatedBlocklets: {
139
+ type: R.JSON,
140
+ allowNull: !1,
141
+ defaultValue: {},
142
+ get() {
143
+ return this.getDataValue("relatedBlocklets") || {};
144
+ },
145
+ set(e) {
146
+ this.setDataValue("relatedBlocklets", JSON.stringify(e || {}));
147
+ }
148
+ }
149
+ },
150
+ { sequelize: me, paranoid: !0 }
151
+ );
152
+ q.hasMany(Te, {
153
+ foreignKey: "projectId",
154
+ as: "components"
155
+ });
156
+ const Ps = As, Ts = Os, _e = 7 * 24 * 60 * 60 * 1e3, vs = 24 * 60 * 60 * 1e3, mt = async (e = "") => {
157
+ const n = O(Ps, e);
158
+ try {
159
+ if (!(await V.stat(n)).isDirectory())
160
+ throw new Error(`${n} is not a directory`);
161
+ } catch {
162
+ await V.mkdir(n, { recursive: !0 });
163
+ }
164
+ return n;
165
+ }, ks = (e, n) => {
166
+ const t = se("md5").update(n).digest("hex");
167
+ return O(e, `${Ts}-${t}.json`);
168
+ }, Ds = async (e = "") => {
169
+ const n = await mt(e), t = Date.now();
170
+ try {
171
+ const s = await V.readdir(n);
172
+ await Promise.all(
173
+ s.filter((o) => o.endsWith(".json")).map(async (o) => {
174
+ const r = O(n, o);
175
+ try {
176
+ const a = await V.readFile(r, "utf-8"), u = JSON.parse(a);
177
+ u.createdAt && t - u.createdAt > _e && await V.unlink(r);
178
+ } catch {
179
+ try {
180
+ const u = await V.stat(r);
181
+ t - u.mtimeMs > _e && await V.unlink(r);
182
+ } catch {
183
+ }
184
+ }
185
+ })
186
+ );
187
+ } catch (s) {
188
+ console.error(`Failed to cleanup cache in ${n}:`, s);
189
+ }
190
+ }, xs = (() => {
191
+ const e = /* @__PURE__ */ new Set();
192
+ return setInterval(async () => {
193
+ await Promise.all(Array.from(e).map((s) => Ds(s)));
194
+ }, vs).unref(), (s) => {
195
+ e.add(s);
196
+ };
197
+ })();
198
+ function Ge(e, n) {
199
+ return n.subdir && xs(n.subdir), it(
200
+ async (...s) => {
201
+ const o = await mt(n.subdir || ""), r = n.keyGenerator ? n.keyGenerator(...s) : JSON.stringify(s), a = ks(o, r);
202
+ try {
203
+ const u = await V.readFile(a, "utf-8"), { value: c, createdAt: i } = JSON.parse(u);
204
+ if (i && Date.now() - i > _e)
205
+ throw await V.unlink(a).catch(() => {
206
+ }), new Error("Cache expired");
207
+ return c;
208
+ } catch {
209
+ const c = await e(...s), i = JSON.stringify({ value: c, createdAt: Date.now() });
210
+ return V.writeFile(a, i, "utf-8").catch((p) => {
211
+ console.error("Failed to write fs cache:", p);
212
+ }), c;
213
+ }
214
+ },
215
+ {
216
+ keyGenerator: n.keyGenerator,
217
+ lruOptions: n.lruOptions
218
+ }
219
+ );
220
+ }
221
+ const Rs = async (e, { componentId: n }) => {
222
+ const t = `@tailwind components;
223
+ @tailwind utilities;
224
+ `, s = `.CustomComponent_${n}`;
225
+ return (await Xt([
226
+ Zt({ content: [{ raw: e, extension: "tsx" }] }),
227
+ qt({
228
+ overrideBrowserslist: ["> 1%", "last 2 versions"],
229
+ stats: {}
230
+ }),
231
+ (r) => {
232
+ r.walkRules((a) => {
233
+ a.selectors = a.selectors.map((u) => u.replace(/\.(.+)/g, `${s}.$1,${s} .$1`));
234
+ });
235
+ }
236
+ // FIXME: cssnano use browserslist, it is not working with the fs isolation
237
+ // cssnano({ preset: 'default' }),
238
+ ]).process(t)).css;
239
+ }, js = async (e, { componentId: n }) => {
240
+ const t = await Rs(e, { componentId: n });
241
+ return `export const __PagesKit_CSS__ = ${JSON.stringify(t)};
242
+
243
+ ${e}
244
+ `;
245
+ }, Ze = Ge(
246
+ async (e, n) => {
247
+ let t = _.transpileModule(e, {
248
+ compilerOptions: {
249
+ jsx: _.JsxEmit.React,
250
+ target: _.ScriptTarget.ES2016,
251
+ module: _.ModuleKind.ESNext
252
+ },
253
+ transformers: {
254
+ before: [Kt(_)]
255
+ }
256
+ }).outputText;
257
+ if (n.tailwind && (t = await js(t, { componentId: n.componentId })), n.module === ye.ESM) return t;
258
+ const s = _.transpileModule(t, {
259
+ compilerOptions: {
260
+ jsx: _.JsxEmit.React,
261
+ target: _.ScriptTarget.ES2016,
262
+ module: _.ModuleKind.CommonJS,
263
+ moduleResolution: _.ModuleResolutionKind.Node16
264
+ }
265
+ }).outputText;
266
+ return n.module === ye.CJS ? s : Ls(n.moduleName, s);
267
+ },
268
+ {
269
+ keyGenerator: (e, n) => {
270
+ const t = se("md5").update(e).digest("hex"), s = {
271
+ ...n,
272
+ componentId: n.componentId,
273
+ module: n.module,
274
+ ...n.module !== ye.ESM ? { moduleName: n.moduleName } : {},
275
+ tailwind: n.tailwind
276
+ };
277
+ return JSON.stringify(["transpileModule", t, s]);
278
+ },
279
+ lruOptions: {
280
+ max: 100,
281
+ // 限制缓存项数量为100
282
+ ttl: 1e3 * 60 * 60 * 24 * 7
283
+ // 7天过期时间
284
+ },
285
+ subdir: "transpileModule"
286
+ }
287
+ ), $s = async (e, n) => {
288
+ var a, u;
289
+ const s = (u = (a = (await Qt.build({
290
+ entryPoints: ["index.tsx"],
291
+ external: Object.keys(Jt),
292
+ format: "esm",
293
+ target: "esnext",
294
+ bundle: !0,
295
+ write: !1,
296
+ plugins: [
297
+ {
298
+ name: "vfs",
299
+ setup(c) {
300
+ let i = null;
301
+ c.onResolve({ filter: /.*/ }, (p) => p.path === "index.tsx" ? { path: "index.tsx", namespace: "vfs" } : p.path === "./component" ? { path: "component.tsx", namespace: "vfs" } : null), c.onLoad({ filter: /.*/, namespace: "vfs" }, async (p) => {
302
+ var S;
303
+ if (p.path === "index.tsx")
304
+ return { contents: `export { ${n} } from './component'`, loader: "tsx" };
305
+ if (p.path === "component.tsx")
306
+ return { contents: e, loader: "tsx" };
307
+ if (Vt(p.path)) {
308
+ const f = p.path.split("/").pop();
309
+ if (i || (i = await Ve({ ensureLoaded: !1 })), (S = i == null ? void 0 : i.chunks) != null && S[f])
310
+ try {
311
+ const d = re(i.chunks[f], "utf-8");
312
+ return y.info("get chunk from local file system", f), { contents: d, loader: "tsx" };
313
+ } catch {
314
+ }
315
+ }
316
+ return null;
317
+ });
318
+ }
319
+ }
320
+ ]
321
+ })).outputFiles) == null ? void 0 : a[0]) == null ? void 0 : u.contents;
322
+ if (!s) throw new Error("Failed to build server code");
323
+ const o = Buffer.from(s).toString();
324
+ return _.transpileModule(o, {
325
+ compilerOptions: { module: _.ModuleKind.ESNext, target: _.ScriptTarget.ES2020 }
326
+ }).outputText;
327
+ }, ht = Ge(
328
+ async (e, n) => {
329
+ const t = await $s(e, n);
330
+ return new RegExp(
331
+ `export\\s+\\{[^}]*(?:\\w+\\s+as\\s+${n}\\b|\\b${n}\\b)[^}]*\\}`,
332
+ "m"
333
+ ).test(t) ? t : void 0;
334
+ },
335
+ {
336
+ keyGenerator: (e, n) => {
337
+ const t = se("md5").update(e).digest("hex");
338
+ return JSON.stringify(["extractExportValueSchema", t, n]);
339
+ },
340
+ lruOptions: {
341
+ max: 100,
342
+ ttl: 1e3 * 60 * 60 * 24 * 7
343
+ // 7天过期时间
344
+ },
345
+ subdir: "extractExportValueSchema"
346
+ }
347
+ ), Ls = (e, n) => `// GENERATED FILE. DO NOT EDIT.
348
+ var ${e} = async function () {
349
+
350
+ const exports = {};
351
+ let moduleExports = null;
352
+
353
+ // add commonjs module compatibility layer
354
+ const module = { exports: moduleExports };
355
+
356
+ // execute component code
357
+ ${n}
358
+
359
+ // handle possible module.exports
360
+ if (module.exports && module.exports !== moduleExports) {
361
+ // if module.exports is used, use it first
362
+ return typeof module.exports === 'object' ? module.exports : { default: module.exports };
363
+ }
364
+
365
+ // ensure a default export
366
+ if (!('default' in exports) && Object.keys(exports).length === 0) {
367
+ // module has no exports, return null to indicate invalid
368
+ return null;
369
+ }
370
+
371
+ return exports;
372
+ };
373
+ `, ue = new Pe({
374
+ max: 100
375
+ }), Ns = 60 * 60, et = 60;
376
+ function _s(e) {
377
+ y.info("clear preload components cache", { cacheKey: e }), ue.delete(e);
378
+ }
379
+ function Ms(e) {
380
+ for (const n of ue.keys())
381
+ n.includes(e) && (y.info("clear preload components cache", { cacheKey: n }), _s(n));
382
+ }
383
+ function Us({
384
+ mode: e,
385
+ instanceId: n,
386
+ componentId: t,
387
+ locale: s
388
+ }) {
389
+ return ["getPreloadComponents", e, n, t, s].join("-");
390
+ }
391
+ async function so({
392
+ mode: e,
393
+ req: n,
394
+ state: t,
395
+ locale: s,
396
+ instances: o,
397
+ module: r
398
+ }) {
399
+ const {
400
+ supportedLocales: a,
401
+ config: { defaultLocale: u }
402
+ } = t;
403
+ if (!u) return null;
404
+ const c = (await Promise.all(
405
+ o.map(async (d) => {
406
+ try {
407
+ const l = Us({
408
+ mode: e,
409
+ instanceId: d.id,
410
+ componentId: d.componentId,
411
+ locale: s
412
+ });
413
+ if (e !== "draft" && d.useCache && ue.has(l))
414
+ return y.info(`get preload component from cache: ${l}`), ue.get(l);
415
+ const m = Ee({ state: t, componentId: d.componentId });
416
+ if (!m) return null;
417
+ const w = await Fs({
418
+ req: n,
419
+ state: t,
420
+ componentId: m.id,
421
+ locale: s,
422
+ defaultLocale: u,
423
+ properties: d.properties
424
+ });
425
+ if (!w) return null;
426
+ const k = { instanceId: d.id, preload: w };
427
+ if (e !== "draft" && d.useCache) {
428
+ let C = Ns;
429
+ d.cacheDuration && (C = d.cacheDuration), y.info(`set preload component to cache(${C}s): ${l}`), ue.set(l, k, {
430
+ ttl: C * 1e3
431
+ });
432
+ }
433
+ return k;
434
+ } catch (l) {
435
+ return y.error("get preload component error", { instanceId: d.id, componentId: d.componentId }, { error: l }), null;
436
+ }
437
+ })
438
+ )).filter((d) => !!d), i = Object.values(
439
+ c.reduce((d, l) => ({ ...d, ...l.preload.components }), {})
440
+ );
441
+ async function p() {
442
+ const d = await Promise.all(
443
+ i.map(async (l) => {
444
+ const m = kt({ componentId: l.component.id }), w = r === ye.ESM ? {
445
+ module: r,
446
+ script: await Ze(l.script, {
447
+ componentId: l.component.id,
448
+ module: r,
449
+ tailwind: e !== "draft"
450
+ })
451
+ } : {
452
+ module: r,
453
+ script: await Ze(l.script, {
454
+ componentId: l.component.id,
455
+ module: r,
456
+ moduleName: m,
457
+ tailwind: e !== "draft"
458
+ }),
459
+ moduleName: m
460
+ };
461
+ return [l.component.id, { component: l.component, script: w }];
462
+ })
463
+ );
464
+ return Object.fromEntries(d);
465
+ }
466
+ const S = await p();
467
+ return {
468
+ config: { defaultLocale: u, supportedLocales: a },
469
+ components: S,
470
+ instances: c.map((d) => ({
471
+ id: d.instanceId,
472
+ componentId: d.preload.component.id,
473
+ locales: { [d.preload.locale]: { props: d.preload.props } }
474
+ }))
475
+ };
476
+ }
477
+ async function Fs({
478
+ req: e,
479
+ state: n,
480
+ componentId: t,
481
+ locale: s,
482
+ defaultLocale: o,
483
+ properties: r
484
+ }) {
485
+ const { supportedLocales: a } = n, u = Ee({ state: n, componentId: t });
486
+ if (!u) return null;
487
+ const c = a.some((p) => p.locale === s) ? s : o;
488
+ if (!c) return null;
489
+ const i = await gt({ req: e, state: n, componentId: t, locale: c, defaultLocale: o, properties: r });
490
+ return i ? {
491
+ component: u,
492
+ ...i
493
+ } : null;
494
+ }
495
+ const Bs = 20;
496
+ async function gt({
497
+ req: e,
498
+ depth: n = 0,
499
+ state: t,
500
+ componentId: s,
501
+ locale: o,
502
+ defaultLocale: r,
503
+ properties: a
504
+ }) {
505
+ if (n > Bs) throw new RangeError("max component depth exceeded");
506
+ const u = Gs({ state: t, componentId: s, properties: a, locale: o });
507
+ if (!u) return null;
508
+ const { props: c } = u, i = {
509
+ locale: o || r,
510
+ components: { [u.component.id]: { component: u.component, script: u.script } },
511
+ props: { ...c }
512
+ };
513
+ try {
514
+ const p = await Hs({ ...u, req: e });
515
+ p != null && p.props && Object.assign(i.props, p.props);
516
+ } catch (p) {
517
+ y.error("preload data at server side error", { componentId: s, name: u.component.name }, { error: p });
518
+ }
519
+ return await Promise.all(
520
+ Object.entries(c).map(async ([p, S]) => {
521
+ if ((S == null ? void 0 : S.type) === ze) {
522
+ const f = await gt({
523
+ req: e,
524
+ depth: n + 1,
525
+ state: t,
526
+ componentId: S.componentId,
527
+ locale: o,
528
+ defaultLocale: r,
529
+ properties: S.properties
530
+ });
531
+ f && (Object.assign(i.components, f.components), Object.assign(i.props, {
532
+ [p]: {
533
+ type: ze,
534
+ componentId: S.componentId,
535
+ props: f.props
536
+ }
537
+ }));
538
+ }
539
+ })
540
+ ), i;
541
+ }
542
+ function Gs({
543
+ state: e,
544
+ componentId: n,
545
+ locale: t,
546
+ properties: s
547
+ }) {
548
+ const o = Ee({ state: e, componentId: n });
549
+ if (!o) return null;
550
+ const r = Dt({
551
+ componentId: n,
552
+ getComponent: (a) => Ee({ state: e, componentId: a }),
553
+ locale: t,
554
+ defaultLocale: e.config.defaultLocale,
555
+ properties: s
556
+ });
557
+ return r ? { component: o, script: r.script, props: { locale: t, ...r.props } } : null;
558
+ }
559
+ function Ee({ state: e, componentId: n }) {
560
+ var t, s, o;
561
+ return ((t = e.components[n]) == null ? void 0 : t.data) ?? ((o = (s = e.resources.components) == null ? void 0 : s[n]) == null ? void 0 : o.component);
562
+ }
563
+ function no({ state: e, name: n }) {
564
+ var s, o;
565
+ const t = n.toLowerCase();
566
+ return ((s = Object.values(e.components).find((r) => {
567
+ var a;
568
+ return ((a = r.data.name) == null ? void 0 : a.toLowerCase()) === t;
569
+ })) == null ? void 0 : s.data) ?? ((o = e.resources.components && Object.values(e.resources.components).find((r) => {
570
+ var a;
571
+ return ((a = r.component.name) == null ? void 0 : a.toLowerCase()) === t;
572
+ })) == null ? void 0 : o.component);
573
+ }
574
+ async function Hs({
575
+ component: e,
576
+ script: n,
577
+ props: t,
578
+ req: s
579
+ }) {
580
+ if (!(n != null && n.includes("getServerSideProps")))
581
+ return null;
582
+ const o = await ht(n, "getServerSideProps");
583
+ if (!o) return null;
584
+ const r = o.match(/export\s*{\s*(\w+)\s+as\s+getServerSideProps\s*}/) || o.match(/export\s*{\s*getServerSideProps\s*}/), a = (r == null ? void 0 : r[1]) || "getServerSideProps", u = new Promise((i) => {
585
+ setTimeout(() => {
586
+ i({});
587
+ }, et * 1e3);
588
+ });
589
+ return await Promise.race([
590
+ u,
591
+ ct.callFunction({
592
+ code: `${o}
593
+
594
+ export async function getServerSidePropsWrapper(props) {
595
+ const { location, fetch, props: componentProps } = props;
596
+ // 使用局部变量而不是全局变量
597
+ const originalLocation = typeof window !== 'undefined' ? window.location : undefined;
598
+ const originalFetch = globalThis.fetch;
599
+
600
+ try {
601
+ globalThis.location = location;
602
+ globalThis.fetch = fetch;
603
+ return await ${a}(componentProps);
604
+ } finally {
605
+ // 清理全局状态
606
+ if (originalLocation) globalThis.location = originalLocation;
607
+ if (originalFetch) globalThis.fetch = originalFetch;
608
+ }
609
+ }`,
610
+ filename: `${e.name || e.id}.js`,
611
+ moduleLoader: (i) => {
612
+ if (i === "@blocklet/pages-kit/builtin/utils")
613
+ return `const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
614
+ export { joinURL, withQuery, getQuery, getComponentMountPoint }
615
+ `;
616
+ if (i === "@blocklet/pages-kit/builtin/dayjs")
617
+ return Rt.dayjs;
618
+ },
619
+ global: {
620
+ console: {
621
+ // NOTE: do not return logger.xxx result, it will cause memory leak
622
+ // eslint-disable-next-line prettier/prettier
623
+ log: (...i) => {
624
+ y.info(...i);
625
+ },
626
+ warn: (...i) => {
627
+ y.warn(...i);
628
+ },
629
+ error: (...i) => {
630
+ y.error(...i);
631
+ }
632
+ },
633
+ getComponentMountPoint: vt,
634
+ joinURL: Y,
635
+ withQuery: Nt,
636
+ getQuery: Lt
637
+ },
638
+ functionName: "getServerSidePropsWrapper",
639
+ args: [
640
+ {
641
+ // NOTE: IMPORTANT! place location and fetch (has side effect) at the args not global
642
+ // because the global is shared between all runtime and just init once
643
+ location: { href: Y(_t(s.hostname), s.originalUrl) },
644
+ fetch: (i, { ...p } = {}) => {
645
+ const S = typeof i == "string" && i.startsWith("/") ? Y(I.env.appUrl, i) : i;
646
+ if (typeof S == "string" && We(S).host === We(I.env.appUrl).host) {
647
+ const f = s.get("cookie");
648
+ if (f) {
649
+ const d = new $t(p.headers);
650
+ d.set("cookie", f), p.headers = d;
651
+ }
652
+ }
653
+ return jt(S, {
654
+ ...p,
655
+ timeout: et * 1e3
656
+ }).then((f) => ({
657
+ ok: f.ok,
658
+ status: f.status,
659
+ statusText: f.statusText,
660
+ headers: Object.fromEntries(f.headers.entries()),
661
+ json: () => f.json()
662
+ }));
663
+ },
664
+ props: t
665
+ }
666
+ ]
667
+ })
668
+ ]);
669
+ }
670
+ const Js = it(
671
+ async (e, n, t) => {
672
+ if (!(e != null && e.includes(n)))
673
+ return null;
674
+ const s = await ht(e, n);
675
+ if (s)
676
+ try {
677
+ return await ct.callFunction({
678
+ code: `
679
+ ${s}
680
+
681
+ export function get${n}SchemaWrapper() {
682
+ return ${n};
683
+ }
684
+ `,
685
+ filename: `${t}.js`,
686
+ functionName: `get${n}SchemaWrapper`
687
+ });
688
+ } catch (o) {
689
+ return y.error(`获取 ${n} 失败`, { componentId: t, error: o }), null;
690
+ }
691
+ return null;
692
+ },
693
+ {
694
+ keyGenerator: (e, n, t) => {
695
+ const s = se("md5").update(e).digest("hex");
696
+ return JSON.stringify(["getExportSchemaValueFromCode", s, n, t]);
697
+ },
698
+ lruOptions: {
699
+ max: 100,
700
+ ttl: 1e3 * 60 * 60
701
+ }
702
+ }
703
+ ), Vs = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o", tt = "page", Me = "trigger-reload-project-resource", yt = Vs, Ks = "z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM";
704
+ function Ie(e) {
705
+ e.observeDeep((n) => {
706
+ n.some((t) => t.changes.keys.has("updatedAt") || t.changes.keys.has("publishedAt")) || e.set("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
707
+ });
708
+ }
709
+ function St() {
710
+ return Ut(O(I.env.dataDir, "tmp-"));
711
+ }
712
+ function be(e, n, t = []) {
713
+ return Array.isArray(e) ? e.flatMap((s, o) => be(s, n, [...t, o])) : typeof e == "object" ? e === null ? [] : Object.entries(e).flatMap(([s, o]) => be(o, n, [...t, s])) : n(e) ? [t] : [];
714
+ }
715
+ function M(e) {
716
+ return e.filter((n) => n != null);
717
+ }
718
+ function zs(e) {
719
+ e.pages && Object.keys(e.pages).forEach((t) => {
720
+ const s = ce(e.pages[t]);
721
+ s && s instanceof K.Map && Ie(s);
722
+ });
723
+ const n = ce(e.pages);
724
+ n && n instanceof K.Map && n.observe((t) => {
725
+ t.changes.keys.forEach((s, o) => {
726
+ if (s.action === "add") {
727
+ const r = ce(e.pages[o]);
728
+ r && r instanceof K.Map && Ie(r);
729
+ }
730
+ });
731
+ });
732
+ }
733
+ function Ws(e) {
734
+ e.routes && Object.keys(e.routes).forEach((t) => {
735
+ var o;
736
+ const s = ce((o = e.routes) == null ? void 0 : o[t]);
737
+ s && s instanceof K.Map && Ie(s);
738
+ });
739
+ const n = ce(e.routes);
740
+ n && n instanceof K.Map && n.observe((t) => {
741
+ t.changes.keys.forEach((s, o) => {
742
+ var r;
743
+ if (s.action === "add") {
744
+ const a = ce((r = e.routes) == null ? void 0 : r[o]);
745
+ a && a instanceof K.Map && Ie(a);
746
+ }
747
+ });
748
+ });
749
+ }
750
+ function Ys(e, n) {
751
+ var t;
752
+ for (const s of n || Object.keys(e.routes || {})) {
753
+ let o = s, r = [];
754
+ if (s.includes("-")) {
755
+ const [a, ...u] = s.split("-");
756
+ o = a, r = u || [];
757
+ }
758
+ if (((t = e.routes) == null ? void 0 : t[o]) !== void 0) {
759
+ e.routes[o].publishedAt = (/* @__PURE__ */ new Date()).toISOString();
760
+ const a = e.routes[o];
761
+ if (!a || !a.params || a.params.length === 0)
762
+ continue;
763
+ if (s.includes("-") && r.length > 0) {
764
+ const u = ss(r, a);
765
+ u && (u.publishedAt = (/* @__PURE__ */ new Date()).toISOString());
766
+ }
767
+ if (!n) {
768
+ const u = Fe({
769
+ basePath: a.path,
770
+ params: a.params,
771
+ routeId: a.id,
772
+ paramsOptions: a.paramsOptions,
773
+ currentIndex: 0,
774
+ currentParams: [],
775
+ currentOptionIds: [],
776
+ result: []
777
+ });
778
+ for (const c of u)
779
+ c.routeMetaData ?? (c.routeMetaData = {}), c.routeMetaData.publishedAt = (/* @__PURE__ */ new Date()).toISOString();
780
+ }
781
+ }
782
+ }
783
+ }
784
+ function je({
785
+ page: e,
786
+ route: n,
787
+ state: t,
788
+ routeId: s,
789
+ routePathInfo: o
790
+ }) {
791
+ var a, u, c, i, p, S, f, d, l;
792
+ y.info(
793
+ `Executing datasource data assembly, routeId: ${s}, routePathInfo: ${JSON.stringify(o)}`
794
+ );
795
+ const r = {
796
+ ...ns(e),
797
+ id: s,
798
+ slug: (o == null ? void 0 : o.path) ?? n.path,
799
+ createdAt: n.createdAt,
800
+ updatedAt: ((a = o == null ? void 0 : o.routeMetaData) == null ? void 0 : a.updatedAt) ?? n.updatedAt,
801
+ publishedAt: ((u = o == null ? void 0 : o.routeMetaData) == null ? void 0 : u.publishedAt) ?? n.publishedAt,
802
+ isPublic: (((c = o == null ? void 0 : o.routeMetaData) == null ? void 0 : c.isPublic) ?? n.isPublic) && n.isPublic
803
+ };
804
+ for (const m of t.supportedLocales) {
805
+ if (n.dataSource) {
806
+ let w = n.id;
807
+ o && (w = o.paramOptionIds.join("-"));
808
+ const k = ((S = (p = (i = n.dataSource.pathDataMappings) == null ? void 0 : i[w]) == null ? void 0 : p.dataCache) == null ? void 0 : S[m.locale]) ?? ((l = (d = (f = n.dataSource.pathDataMappings) == null ? void 0 : f[w]) == null ? void 0 : d.dataCache) == null ? void 0 : l[t.config.defaultLocale || "en"]);
809
+ if (!k)
810
+ continue;
811
+ ts(r, t, m.locale, k);
812
+ }
813
+ o && o.routeMetaData && (o.routeMetaData.publishedAt = (/* @__PURE__ */ new Date()).toISOString());
814
+ }
815
+ return r;
816
+ }
817
+ const Ae = new Pe({
818
+ max: 20,
819
+ ttl: 10 * 60 * 1e3
820
+ // 10 minutes
821
+ });
822
+ function qs(e, n = []) {
823
+ let t = 0;
824
+ const s = Array.from(Ae.keys()), o = [];
825
+ for (const r of e) {
826
+ o.push(`page-html:prod:${r}:lang-path=none`);
827
+ for (const a of n)
828
+ o.push(`page-html:prod:/${a}${r}:lang-path=${a}`);
829
+ }
830
+ for (const r of s) {
831
+ const a = r.split(":lang-path=")[0] || "";
832
+ for (const u of o) {
833
+ const i = (u.split(":lang-path=")[0] || "").replace(/\/:[^/]+/g, "");
834
+ if (a.startsWith(i)) {
835
+ Ae.delete(r), t++, y.info(`[Cache CLEAR] key: ${r}`);
836
+ break;
837
+ }
838
+ }
839
+ }
840
+ return y.info(`[Cache CLEAR] cleared ${t} entries for patterns:`, o), t;
841
+ }
842
+ function Qs({
843
+ projectId: e,
844
+ projectSlug: n,
845
+ supportedLocales: t = []
846
+ }) {
847
+ let s = 0;
848
+ const o = Array.from(Ae.keys()), r = [];
849
+ r.push(`page-html:prod:/${e}/`), n && n !== e && r.push(`page-html:prod:/${n}/`);
850
+ for (const a of t)
851
+ r.push(`page-html:prod:/${a}/${e}/`), n && n !== e && r.push(`page-html:prod:/${a}/${n}/`);
852
+ for (const a of o)
853
+ for (const u of r)
854
+ if (a.startsWith(u)) {
855
+ Ae.delete(a), s++, y.info(`[Cache CLEAR PROJECT] key: ${a}`);
856
+ break;
857
+ }
858
+ return y.info(
859
+ `[Cache CLEAR PROJECT] cleared ${s} entries for project ${e}${n ? ` (slug: ${n})` : ""}`
860
+ ), s;
861
+ }
862
+ const { uploadToMediaKit: Xs } = require("@blocklet/uploader-server"), $e = cs("abcdefghijklmnopqrstuvwxyz0123456789", 16), He = /^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/, fe = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i, st = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi, Zs = 1e4, en = 3e4, he = 0, Le = 1, tn = 0, sn = 1, Ue = I, de = O(process.env.BLOCKLET_DATA_DIR, "site-state"), oo = ["production", "draft"], ro = ["production"];
863
+ function Oe(e) {
864
+ return (e == null ? void 0 : e.replace(/\//g, "|")) || "";
865
+ }
866
+ function nn() {
867
+ var t;
868
+ const e = Ue.env.languages.map((s) => ({ locale: s.code, name: s.name })), n = (t = e[0]) == null ? void 0 : t.locale;
869
+ return {
870
+ pageIds: [],
871
+ pages: {},
872
+ routeIds: [],
873
+ routes: {},
874
+ dataSourceIds: [],
875
+ dataSources: {},
876
+ components: {},
877
+ supportedLocales: e,
878
+ config: { defaultLocale: n },
879
+ resources: {}
880
+ };
881
+ }
882
+ const T = class T extends K.Doc {
883
+ constructor(t) {
884
+ super();
885
+ D(this, "syncedStore");
886
+ D(this, "conns", /* @__PURE__ */ new Map());
887
+ D(this, "awareness");
888
+ // 延迟释放定时器
889
+ D(this, "releaseTimer");
890
+ D(this, "awarenessChangeHandler", ({ added: t, updated: s, removed: o }, r) => {
891
+ const a = t.concat(s, o);
892
+ if (r !== null) {
893
+ const i = this.conns.get(r);
894
+ i && (t.forEach((p) => {
895
+ i.add(p);
896
+ }), o.forEach((p) => {
897
+ i.delete(p);
898
+ }));
899
+ }
900
+ const u = j.createEncoder();
901
+ j.writeVarUint(u, Le), j.writeVarUint8Array(u, Qe(this.awareness, a));
902
+ const c = j.toUint8Array(u);
903
+ this.conns.forEach((i, p) => this.send(p, c));
904
+ });
905
+ D(this, "updateHandler", (t) => {
906
+ const s = j.createEncoder();
907
+ j.writeVarUint(s, he), gs(s, t);
908
+ const o = j.toUint8Array(s);
909
+ this.conns.forEach((r, a) => this.send(a, o));
910
+ });
911
+ D(this, "ensureDataStructure", () => {
912
+ var c;
913
+ const { supportedLocales: t, pages: s, pageIds: o, config: r, routes: a, routeIds: u } = this.syncedStore;
914
+ {
915
+ const i = new Set(Object.keys(s));
916
+ let p = 0;
917
+ for (; p < o.length; ) {
918
+ const S = o[p];
919
+ i.has(S) ? (i.delete(S), p++) : o.splice(p, 1);
920
+ }
921
+ }
922
+ {
923
+ const i = new Set(Object.keys(a));
924
+ let p = 0;
925
+ for (; p < u.length; ) {
926
+ const S = u[p];
927
+ i.has(S) ? (i.delete(S), p++) : u.splice(p, 1);
928
+ }
929
+ }
930
+ t.splice(0, t.length), t.push(...Ue.env.languages.map((i) => ({ locale: i.code, name: i.name }))), r.defaultLocale = (c = t[0]) == null ? void 0 : c.locale;
931
+ {
932
+ let i = 0;
933
+ const p = /* @__PURE__ */ new Set();
934
+ for (; i < t.length; ) {
935
+ const { locale: S } = t[i];
936
+ p.has(S) ? t.splice(i, 1) : (i++, p.add(S));
937
+ }
938
+ }
939
+ });
940
+ D(this, "send", (t, s) => {
941
+ t.readyState !== tn && t.readyState !== sn && this.closeConn(t);
942
+ try {
943
+ t.send(s, (o) => {
944
+ o && this.closeConn(t);
945
+ });
946
+ } catch {
947
+ this.closeConn(t);
948
+ }
949
+ });
950
+ D(this, "closeConn", (t) => {
951
+ if (t.removeAllListeners(), this.conns.has(t)) {
952
+ const s = this.conns.get(t);
953
+ this.conns.delete(t), s && ms(this.awareness, Array.from(s), null);
954
+ }
955
+ t.close(), this.checkAndScheduleRelease();
956
+ });
957
+ D(this, "autoSave", dt(() => {
958
+ W(U(this.draftYjsFilePath), { recursive: !0 }), we(this.draftYjsFilePath, K.encodeStateAsUpdate(this));
959
+ }, Zs));
960
+ D(this, "save", ({ flush: t = !1 } = {}) => {
961
+ this.autoSave(), t && this.autoSave.flush();
962
+ });
963
+ D(this, "publish", async ({ mode: t, routes: s }) => {
964
+ const o = await this.getState("draft"), r = await this.getState("production");
965
+ await rt(o, r, { routes: s, mergeMode: "replace", deleteRoutes: !0, publishMode: t }), r.config.publishedAt = (/* @__PURE__ */ new Date()).getTime(), Ys(this.syncedStore, s), await this.setState(t, r), await this.clearPageCacheForRoutes(s, r);
966
+ });
967
+ D(this, "mergeState", async (t, s) => {
968
+ var u, c, i;
969
+ const o = JSON.parse(JSON.stringify(s));
970
+ (u = t.config).fontFamily ?? (u.fontFamily = {});
971
+ const r = (c = o.config) == null ? void 0 : c.fontFamily, a = (i = t.config) == null ? void 0 : i.fontFamily;
972
+ t.config.fontFamily.title = (r == null ? void 0 : r.title) || (a == null ? void 0 : a.title), t.config.fontFamily.description = (r == null ? void 0 : r.description) || (a == null ? void 0 : a.description), await new Promise((p, S) => {
973
+ this.transact(async () => {
974
+ try {
975
+ const f = await rt(t, s);
976
+ p(f);
977
+ } catch (f) {
978
+ S(f);
979
+ }
980
+ });
981
+ });
982
+ });
983
+ D(this, "clearPageCacheForRoutes", async (t, s) => {
984
+ const o = F(this.options.path), r = await q.findByPk(o), a = (r == null ? void 0 : r.slug) || o;
985
+ if (y.info(`[SiteState] clearing page cache for project ${o}, routes:`, t || []), !t || t.length === 0) {
986
+ Qs({ projectId: o, projectSlug: a, supportedLocales: s.supportedLocales.map((p) => p.locale) });
987
+ return;
988
+ }
989
+ const u = s.supportedLocales.map((p) => p.locale), c = [], i = t.filter((p) => s.pages[p]);
990
+ for (const p of i) {
991
+ const f = s.pages[p].slug;
992
+ a && c.push(`/${a}${f}`), c.push(`/${o}${f}`);
993
+ }
994
+ if (y.info(`[SiteState] clearing page cache for project ${o}, pathPatterns:`, c), c.length > 0) {
995
+ const p = qs(c, u);
996
+ y.info(`[SiteState] cleared ${p} page cache entries for project ${o}, routes:`, t);
997
+ }
998
+ });
999
+ D(this, "addConnection", (t) => {
1000
+ if (this.conns.has(t))
1001
+ return;
1002
+ this.cancelRelease(), t.binaryType = "arraybuffer", this.conns.set(t, /* @__PURE__ */ new Set()), t.on("message", (r) => this.messageListener(t, new Uint8Array(r)));
1003
+ let s = !0;
1004
+ const o = setInterval(() => {
1005
+ if (!s)
1006
+ this.conns.has(t) && this.closeConn(t), clearInterval(o);
1007
+ else if (this.conns.has(t)) {
1008
+ s = !1;
1009
+ try {
1010
+ t.ping();
1011
+ } catch {
1012
+ this.closeConn(t), clearInterval(o);
1013
+ }
1014
+ }
1015
+ }, en);
1016
+ t.on("close", () => {
1017
+ this.closeConn(t), clearInterval(o);
1018
+ }), t.on("pong", () => {
1019
+ s = !0;
1020
+ });
1021
+ {
1022
+ const r = j.createEncoder();
1023
+ j.writeVarUint(r, he), ys(r, this), this.send(t, j.toUint8Array(r));
1024
+ const a = this.awareness.getStates();
1025
+ if (a.size > 0) {
1026
+ const u = j.createEncoder();
1027
+ j.writeVarUint(u, Le), j.writeVarUint8Array(u, Qe(this.awareness, Array.from(a.keys()))), this.send(t, j.toUint8Array(u));
1028
+ }
1029
+ }
1030
+ });
1031
+ D(this, "messageListener", (t, s) => {
1032
+ try {
1033
+ const o = j.createEncoder(), r = Re.createDecoder(s), a = Re.readVarUint(r);
1034
+ switch (a) {
1035
+ case he:
1036
+ j.writeVarUint(o, he), Ss(r, o, this, null), j.length(o) > 1 && (this.ensureDataStructure(), this.send(t, j.toUint8Array(o)));
1037
+ break;
1038
+ case Le: {
1039
+ hs(this.awareness, Re.readVarUint8Array(r), t);
1040
+ break;
1041
+ }
1042
+ default:
1043
+ y.warn(`Unsupported messageType ${a}`);
1044
+ }
1045
+ } catch (o) {
1046
+ y.error(o);
1047
+ }
1048
+ this.save();
1049
+ });
1050
+ this.options = t, J(this.draftYjsFilePath) && K.applyUpdate(this, re(this.draftYjsFilePath)), this.syncedStore = os(
1051
+ es(
1052
+ {
1053
+ pages: {},
1054
+ pageIds: [],
1055
+ components: {},
1056
+ supportedLocales: [],
1057
+ config: {},
1058
+ resources: {},
1059
+ routeIds: [],
1060
+ routes: {},
1061
+ dataSourceIds: [],
1062
+ dataSources: {}
1063
+ },
1064
+ this
1065
+ )
1066
+ ), this.initObserver(), this.on("update", this.updateHandler), this.awareness = new fs(this), this.awareness.on("update", this.awarenessChangeHandler), this.ensureDataStructure();
1067
+ }
1068
+ // safe delete project state dir
1069
+ static safeDeleteProjectStateDir(t) {
1070
+ if (!t)
1071
+ throw new Error("Should provide project context");
1072
+ try {
1073
+ const s = O(de, t), o = O(de, `@del-${t}`);
1074
+ Ye(s, o);
1075
+ } catch (s) {
1076
+ y.error("Failed to safe delete project state dir:", s);
1077
+ }
1078
+ }
1079
+ static get projectIds() {
1080
+ return Ne("*/", {
1081
+ cwd: de,
1082
+ ignore: ["@del-*", "@tmp-*", ".*", "staging", "production", "@backup-*"]
1083
+ // Ignore temp directories and hidden files
1084
+ });
1085
+ }
1086
+ static get allShared() {
1087
+ return this.projectIds.map((t) => T.shared(t));
1088
+ }
1089
+ static shared(t) {
1090
+ if (!t)
1091
+ throw new Error("Should provide project context");
1092
+ let s = T.sharedInstances[t];
1093
+ return s || (s = new T({
1094
+ path: O(de, t)
1095
+ }), T.sharedInstances[t] = s, Ot({
1096
+ projectId: t,
1097
+ pages: ve,
1098
+ components: ke
1099
+ }), s);
1100
+ }
1101
+ // 轻量级 production 状态获取,不加载 draft 数据
1102
+ static async getProductionState(t) {
1103
+ var o, r;
1104
+ let s = T.productionStates.get(t);
1105
+ if (!s) {
1106
+ const a = O(de, t, "production");
1107
+ if (s = await Et(a, { includeResources: !0 }) ?? nn(), !((o = s == null ? void 0 : s.config) != null && o.defaultLocale)) {
1108
+ s.config ?? (s.config = {});
1109
+ const u = Ue.env.languages.map((c) => ({ locale: c.code, name: c.name }));
1110
+ s.config.defaultLocale = (r = u[0]) == null ? void 0 : r.locale;
1111
+ }
1112
+ T.productionStates.set(t, s);
1113
+ }
1114
+ return {
1115
+ ...s,
1116
+ resources: await Ve().then(async (a) => {
1117
+ var S, f;
1118
+ const { pages: u, components: c } = as(a, "pages", "components");
1119
+ let i = c;
1120
+ const p = await q.findByPk(t);
1121
+ if (p != null && p.useAllResources)
1122
+ i = c;
1123
+ else {
1124
+ const l = (await Te.findAll({ where: { projectId: t } })).map((w) => w.componentId);
1125
+ i = Object.fromEntries(
1126
+ Object.entries(c || {}).filter(([w]) => l.includes(w))
1127
+ );
1128
+ }
1129
+ return Object.keys(((S = s == null ? void 0 : s.resources) == null ? void 0 : S.components) || {}).length > 0 && (i = {
1130
+ ...i,
1131
+ ...(f = s == null ? void 0 : s.resources) == null ? void 0 : f.components
1132
+ }), { pages: u, components: i };
1133
+ }).catch(() => ({}))
1134
+ };
1135
+ }
1136
+ destroy() {
1137
+ this.cancelRelease(), this.save({ flush: !0 }), this.conns.forEach((s, o) => this.closeConn(o)), this.awareness.destroy();
1138
+ const t = F(this.options.path);
1139
+ delete T.sharedInstances[t], super.destroy();
1140
+ }
1141
+ initObserver() {
1142
+ zs(this.syncedStore), Ws(this.syncedStore);
1143
+ }
1144
+ get draftYjsFilePath() {
1145
+ return O(this.options.path, "draft.yjs");
1146
+ }
1147
+ static async getStateByProjectId(t, s) {
1148
+ if (s === "draft") {
1149
+ const o = T.shared(t);
1150
+ return JSON.parse(JSON.stringify(o.syncedStore));
1151
+ }
1152
+ return T.getProductionState(t);
1153
+ }
1154
+ async getState(t) {
1155
+ if (t === "draft")
1156
+ return JSON.parse(JSON.stringify(this.syncedStore));
1157
+ const s = F(this.options.path);
1158
+ return T.getProductionState(s);
1159
+ }
1160
+ async setState(t, s) {
1161
+ const o = await cn(s, { exportAssets: !1, includeResources: !0 }), r = this.getPublishDir(t);
1162
+ if (W(U(r), { recursive: !0 }), lt(r, { force: !0, recursive: !0 }), Ye(o, r), t === "production") {
1163
+ const a = F(this.options.path);
1164
+ T.productionStates.set(a, s);
1165
+ }
1166
+ }
1167
+ getPublishDir(t) {
1168
+ return O(this.options.path, t);
1169
+ }
1170
+ // 检查并调度延迟释放
1171
+ checkAndScheduleRelease() {
1172
+ this.conns.size === 0 && this.scheduleRelease();
1173
+ }
1174
+ // 调度延迟释放
1175
+ scheduleRelease() {
1176
+ this.cancelRelease();
1177
+ const t = F(this.options.path);
1178
+ this.releaseTimer = setTimeout(() => {
1179
+ y.info(`[SiteState] releasing instance due to no active connections: ${t}`), this.conns.size === 0 && (this.releaseTimer = void 0, this.destroy());
1180
+ }, T.RELEASE_DELAY), y.info(`[SiteState] scheduled release for project ${t} in ${T.RELEASE_DELAY / 1e3}s`);
1181
+ }
1182
+ // 取消延迟释放
1183
+ cancelRelease() {
1184
+ if (this.releaseTimer) {
1185
+ clearTimeout(this.releaseTimer), this.releaseTimer = void 0;
1186
+ const t = F(this.options.path);
1187
+ y.info(`[SiteState] cancelled scheduled release for project ${t}`);
1188
+ }
1189
+ }
1190
+ static async pageUrlMap(t, s) {
1191
+ var a, u;
1192
+ let { projectIds: o } = this;
1193
+ s && (o = [s]);
1194
+ const r = {};
1195
+ for (const c of o) {
1196
+ const i = await q.findByPk(c);
1197
+ if (!i) continue;
1198
+ const p = await T.getStateByProjectId(c, t), S = i.slug || c, f = is(
1199
+ I.env.languages.map((l) => l.code),
1200
+ p.supportedLocales.map((l) => l.locale)
1201
+ ), d = (l, m) => {
1202
+ S && (r[Y("/", S, l)] = {
1203
+ ...m,
1204
+ shouldRedirect: !0,
1205
+ mainPage: !0
1206
+ }), r[Y("/", c, l)] = {
1207
+ ...m,
1208
+ shouldRedirect: !0,
1209
+ mainPage: !0
1210
+ };
1211
+ for (const w of f) {
1212
+ const k = { ...m, locale: w };
1213
+ r[Y("/", w, c, l)] = k, S && (r[Y("/", w, S, l)] = k);
1214
+ }
1215
+ };
1216
+ if (t === "draft")
1217
+ for (const l of p.routeIds || []) {
1218
+ const m = (a = p == null ? void 0 : p.routes) == null ? void 0 : a[l];
1219
+ if (!m) continue;
1220
+ if (m.params && m.params.length > 0) {
1221
+ const C = Fe({
1222
+ basePath: m.path,
1223
+ params: m.params,
1224
+ routeId: m.id,
1225
+ paramsOptions: m.paramsOptions,
1226
+ currentIndex: 0,
1227
+ currentParams: [],
1228
+ currentOptionIds: [],
1229
+ result: []
1230
+ });
1231
+ for (const L of C) {
1232
+ const X = L.path, ne = {
1233
+ projectId: c,
1234
+ projectSlug: S,
1235
+ pageSlug: X,
1236
+ pageId: m.displayTemplateId || "",
1237
+ routeId: l,
1238
+ // default locale
1239
+ defaultLocale: f == null ? void 0 : f[0],
1240
+ locales: f,
1241
+ publishedAt: p.config.publishedAt,
1242
+ isPublic: m.isPublic && ((u = L == null ? void 0 : L.routeMetaData) == null ? void 0 : u.isPublic)
1243
+ };
1244
+ d(X, ne);
1245
+ }
1246
+ }
1247
+ const w = m.path, k = {
1248
+ projectId: c,
1249
+ projectSlug: S,
1250
+ pageSlug: w,
1251
+ pageId: m.displayTemplateId || "",
1252
+ routeId: l,
1253
+ // default locale
1254
+ defaultLocale: f == null ? void 0 : f[0],
1255
+ locales: f,
1256
+ publishedAt: p.config.publishedAt,
1257
+ isPublic: m.isPublic
1258
+ };
1259
+ d(w, k);
1260
+ }
1261
+ for (const l of p.pageIds) {
1262
+ const m = p.pages[l];
1263
+ if (!m || t === "production" && !m.isPublic)
1264
+ continue;
1265
+ const w = m.slug, k = i.slug || c, C = {
1266
+ projectId: c,
1267
+ projectSlug: k,
1268
+ pageSlug: w,
1269
+ pageId: l,
1270
+ // default locale
1271
+ defaultLocale: f == null ? void 0 : f[0],
1272
+ locales: f,
1273
+ publishedAt: p.config.publishedAt,
1274
+ isPublic: m.isPublic,
1275
+ templateConfig: m.templateConfig
1276
+ };
1277
+ d(w, C);
1278
+ }
1279
+ }
1280
+ return r;
1281
+ }
1282
+ getDocumentSize() {
1283
+ return K.encodeStateAsUpdate(this).byteLength;
1284
+ }
1285
+ static getInstancesSizeInfo() {
1286
+ const t = [];
1287
+ for (const [s, o] of Object.entries(T.sharedInstances)) {
1288
+ const r = o.getDocumentSize();
1289
+ t.push({
1290
+ projectId: s,
1291
+ sizeInBytes: r,
1292
+ sizeInMB: `${(r / (1024 * 1024)).toFixed(2)} MB`,
1293
+ activeConnections: o.conns.size
1294
+ });
1295
+ }
1296
+ return t;
1297
+ }
1298
+ // 启动定期检查
1299
+ static startPeriodicCheck() {
1300
+ this.periodicCheckTimer || (this.periodicCheckTimer = setInterval(() => {
1301
+ this.performPeriodicCheck();
1302
+ }, this.PERIODIC_CHECK_INTERVAL), y.info(
1303
+ `[SiteState] periodic check started, interval: ${this.PERIODIC_CHECK_INTERVAL / (60 * 60 * 1e3)} hours`
1304
+ ));
1305
+ }
1306
+ // 停止定期检查
1307
+ static stopPeriodicCheck() {
1308
+ this.periodicCheckTimer && (clearInterval(this.periodicCheckTimer), this.periodicCheckTimer = void 0, y.info("[SiteState] periodic check stopped"));
1309
+ }
1310
+ // 执行定期检查
1311
+ static performPeriodicCheck() {
1312
+ const t = Object.keys(T.sharedInstances).length, s = [], o = [];
1313
+ for (const [r, a] of Object.entries(T.sharedInstances))
1314
+ a.conns.size === 0 ? s.push({ projectId: r, instance: a }) : o.push({ projectId: r, connections: a.conns.size });
1315
+ if (y.info(
1316
+ `[SiteState] periodic check summary: total instances: ${t}, with connections: ${o.length}, without connections: ${s.length}`
1317
+ ), s.length > 0) {
1318
+ y.info(
1319
+ `[SiteState] releasing ${s.length} instances without connections:`,
1320
+ s.map((a) => a.projectId)
1321
+ );
1322
+ let r = 0;
1323
+ for (const { projectId: a, instance: u } of s)
1324
+ try {
1325
+ y.info(`[SiteState] releasing instance due to periodic check: ${a}`), u.destroy(), r++;
1326
+ } catch (c) {
1327
+ y.error(`[SiteState] failed to release instance ${a} during periodic check:`, c);
1328
+ }
1329
+ y.info(
1330
+ `[SiteState] periodic check completed: ${r}/${s.length} instances released successfully`
1331
+ );
1332
+ } else t > 0 ? y.debug("[SiteState] periodic check: all instances have active connections") : y.debug("[SiteState] periodic check: no instances exist");
1333
+ }
1334
+ };
1335
+ D(T, "PRODUCTION_CACHE_TTL", 7 * 24 * 60 * 60 * 1e3), // 7 days
1336
+ // 延迟释放时间:5分钟
1337
+ D(T, "RELEASE_DELAY", 5 * 60 * 1e3), // 定期检查间隔:2 小时
1338
+ D(T, "PERIODIC_CHECK_INTERVAL", 2 * 60 * 60 * 1e3), // 2 hours
1339
+ D(T, "sharedInstances", {}), D(T, "productionStates", new Pe({
1340
+ max: 100,
1341
+ ttl: T.PRODUCTION_CACHE_TTL
1342
+ })), // 定期检查定时器
1343
+ D(T, "periodicCheckTimer");
1344
+ let Q = T;
1345
+ async function on(e, n, t) {
1346
+ if (!e || !J(e) || !oe(e).isFile())
1347
+ return null;
1348
+ let s = t[e];
1349
+ return s || (s = (async () => {
1350
+ var o;
1351
+ try {
1352
+ const r = (o = await Xs({
1353
+ filePath: e,
1354
+ fileName: n
1355
+ })) == null ? void 0 : o.data;
1356
+ return r == null ? void 0 : r.filename;
1357
+ } catch (r) {
1358
+ return y.error(`Failed to upload asset ${e}:`, r), null;
1359
+ }
1360
+ })(), t[e] = s), s;
1361
+ }
1362
+ const rn = async (e, n) => {
1363
+ const t = F(e), s = await Yt({
1364
+ name: yt,
1365
+ path: Y("/uploads", t),
1366
+ responseType: "stream",
1367
+ method: "GET"
1368
+ });
1369
+ if (s.status >= 200 && s.status < 400) {
1370
+ const o = Gt(n);
1371
+ await ps(s.data, o);
1372
+ } else
1373
+ throw new Error(`download asset failed ${s.status}`);
1374
+ }, an = async (e, n) => {
1375
+ await Promise.all(
1376
+ e.map(async (t) => {
1377
+ try {
1378
+ await rn(t, O(n, F(t)));
1379
+ } catch (s) {
1380
+ y.error(`Failed to export assets: ${t}, ${s}`);
1381
+ }
1382
+ })
1383
+ );
1384
+ };
1385
+ function wt(e) {
1386
+ return He.test(e) ? [e] : fe.test(e) ? (st.lastIndex = 0, Array.from(e.matchAll(st)).map((t) => t[1]).filter((t) => !!t)) : [];
1387
+ }
1388
+ async function ge(e, n, t) {
1389
+ const { getFilename: s, exportAssets: o } = t, r = O(n, s(e));
1390
+ if (W(U(r), { recursive: !0 }), we(r, ae.stringify(e)), o) {
1391
+ const u = be(
1392
+ e,
1393
+ (c) => typeof c == "string" && (He.test(c) || fe.test(c))
1394
+ ).map((c) => {
1395
+ const i = Be(e, c);
1396
+ return wt(i);
1397
+ }).flat().filter(Boolean);
1398
+ await an(u, U(r));
1399
+ }
1400
+ }
1401
+ const nt = new Pe({
1402
+ max: 20,
1403
+ ttl: 30 * 24 * 60 * 60 * 1e3
1404
+ });
1405
+ async function ot(e, n, t) {
1406
+ var u;
1407
+ const s = be(
1408
+ e,
1409
+ (c) => typeof c == "string" && (He.test(c) || fe.test(c))
1410
+ ), o = ls(2), r = s.map(
1411
+ (c) => o(async () => {
1412
+ try {
1413
+ const i = Be(e, c), p = wt(i);
1414
+ for (const S of p) {
1415
+ const f = F(S), d = t.getFilePath(S, c), l = d ? `${d}:${f}` : f, m = nt.get(l);
1416
+ if (m) {
1417
+ fe.test(i) || qe(e, c, m);
1418
+ return;
1419
+ }
1420
+ const w = await on(d, f, n);
1421
+ w && (fe.test(i) || qe(e, c, w), nt.set(l, w));
1422
+ }
1423
+ } catch (i) {
1424
+ y.error(`Failed to process upload for path ${c.join(".")}:`, i.message || i.reason);
1425
+ }
1426
+ })
1427
+ ), a = await Promise.allSettled(r);
1428
+ (u = t.onFinish) == null || u.call(t, a);
1429
+ }
1430
+ async function cn(e, {
1431
+ exportAssets: n,
1432
+ pageIds: t = "all",
1433
+ componentIds: s = "all",
1434
+ rawConfig: o,
1435
+ includeResources: r = !1,
1436
+ routeIds: a = "all"
1437
+ } = {}) {
1438
+ var le, E, h, A, v, Z, b, $, B, ee, z, pe;
1439
+ const u = t === "all" ? e.pageIds : t, c = xt({
1440
+ state: e,
1441
+ pageIds: u,
1442
+ componentIds: s === "all" ? Object.keys(e.components) : s
1443
+ }), i = a === "all" ? e.routeIds : a, p = (g) => ({
1444
+ id: g.id,
1445
+ name: g.name,
1446
+ isTemplateSection: g.isTemplateSection ?? !1,
1447
+ templateDescription: g.templateDescription,
1448
+ llmConfig: g.llmConfig,
1449
+ component: g.component,
1450
+ config: g.config,
1451
+ visibility: g.visibility,
1452
+ sections: g.sections,
1453
+ sectionIds: g.sectionIds
1454
+ // 已经废弃,数据在 page.dataSource 中管理
1455
+ // properties: section.locales?.[locale] ?? {},
1456
+ }), S = (g, P) => {
1457
+ var x;
1458
+ return {
1459
+ id: g.id,
1460
+ createdAt: g.createdAt,
1461
+ updatedAt: g.updatedAt,
1462
+ publishedAt: g.publishedAt,
1463
+ isPublic: g.isPublic ?? !0,
1464
+ templateConfig: g.templateConfig,
1465
+ meta: ((x = g.locales) == null ? void 0 : x[P]) ?? {},
1466
+ sections: M(
1467
+ g.sectionIds.map((G) => {
1468
+ const N = g.sections[G];
1469
+ return N && p(N);
1470
+ })
1471
+ ),
1472
+ // 将 dataSource.sectionId.locale 转换为 dataSource.sectionId
1473
+ dataSource: Object.fromEntries(
1474
+ Object.entries(g.dataSource || {}).map(([G, N]) => [G, (N == null ? void 0 : N[P]) ?? {}])
1475
+ )
1476
+ };
1477
+ }, f = (g) => ({
1478
+ id: g.id,
1479
+ createdAt: g.createdAt,
1480
+ updatedAt: g.updatedAt,
1481
+ publishedAt: g.publishedAt,
1482
+ path: g.path,
1483
+ handler: g.handler,
1484
+ isPublic: g.isPublic ?? !0,
1485
+ params: g.params ?? [],
1486
+ enabledGenerate: g.enabledGenerate ?? !1,
1487
+ displayTemplateId: g.displayTemplateId,
1488
+ dataSource: g.dataSource
1489
+ }), d = M(
1490
+ i.map((g) => {
1491
+ const P = e.routes[g];
1492
+ return P && f(P);
1493
+ })
1494
+ ), l = M(
1495
+ e.supportedLocales.map((g) => g.locale).flatMap(
1496
+ (g) => u.map((P) => {
1497
+ const x = e.pages[P];
1498
+ return x && {
1499
+ locale: g,
1500
+ slug: x.slug,
1501
+ page: S(x, g)
1502
+ };
1503
+ })
1504
+ )
1505
+ ), m = St(), w = O(m, "pages");
1506
+ W(w, { recursive: !0 });
1507
+ const k = O(m, "components");
1508
+ W(k, { recursive: !0 });
1509
+ const C = O(m, "routes");
1510
+ W(C, { recursive: !0 });
1511
+ for (const { locale: g, slug: P, page: x } of l)
1512
+ await ge(x, w, {
1513
+ getFilename: () => `${Oe(P) || "index"}.${g}.yml`,
1514
+ exportAssets: n
1515
+ });
1516
+ for (const g of d)
1517
+ await ge(g, C, {
1518
+ // getFilename: () => `${sanitizeSlug(route.path)}.yml`,
1519
+ getFilename: () => `${Oe(g.path) || "index"}.yml`,
1520
+ exportAssets: n
1521
+ });
1522
+ for (const g of c) {
1523
+ const P = (le = e.components[g]) == null ? void 0 : le.data;
1524
+ P && await ge(P, k, {
1525
+ getFilename: (x) => `${x.name || "unnamed"}.${x.id}.yml`,
1526
+ exportAssets: n
1527
+ });
1528
+ }
1529
+ const L = O(m, ".blocklet/pages/pages.config.yml");
1530
+ W(U(L), { recursive: !0 });
1531
+ const X = {
1532
+ pages: M(
1533
+ u.map((g) => {
1534
+ const P = e.pages[g];
1535
+ return P && { id: g, slug: P.slug };
1536
+ })
1537
+ ),
1538
+ routes: M(
1539
+ i.map((g) => {
1540
+ const P = e.routes[g];
1541
+ return P && { id: g, path: P.path };
1542
+ })
1543
+ ),
1544
+ components: M(
1545
+ c.map((g) => {
1546
+ var x;
1547
+ const P = (x = e.components[g]) == null ? void 0 : x.data;
1548
+ return P && {
1549
+ id: g,
1550
+ name: P.name
1551
+ };
1552
+ })
1553
+ ),
1554
+ ...r ? {
1555
+ resources: {
1556
+ components: M(
1557
+ Object.keys(((E = e.resources) == null ? void 0 : E.components) || {}).filter((g) => c.includes(g)).map((g) => {
1558
+ var P, x, G, N;
1559
+ return {
1560
+ id: g,
1561
+ name: (N = (G = (x = (P = e.resources) == null ? void 0 : P.components) == null ? void 0 : x[g]) == null ? void 0 : G.component) == null ? void 0 : N.name
1562
+ };
1563
+ })
1564
+ )
1565
+ }
1566
+ } : {},
1567
+ supportedLocales: e.supportedLocales,
1568
+ config: e.config
1569
+ };
1570
+ we(L, ae.stringify(X));
1571
+ const ne = O(m, "config.source.json");
1572
+ if (o && we(ne, JSON.stringify(o)), r) {
1573
+ const g = O(m, "resources"), P = O(g, "components");
1574
+ W(P, { recursive: !0 });
1575
+ for (const N of Object.keys(((h = e == null ? void 0 : e.resources) == null ? void 0 : h.components) ?? {}).filter(
1576
+ (H) => c.includes(H)
1577
+ )) {
1578
+ const H = (Z = (v = (A = e.resources) == null ? void 0 : A.components) == null ? void 0 : v[N]) == null ? void 0 : Z.component;
1579
+ H && await ge(H, P, {
1580
+ getFilename: (te) => `${te.name || "unnamed"}.${te.id}.yml`,
1581
+ exportAssets: n
1582
+ });
1583
+ }
1584
+ const x = O(m, "chunks");
1585
+ W(x, { recursive: !0 });
1586
+ const { chunks: G } = await Ve();
1587
+ for (const N of Object.keys(((b = e == null ? void 0 : e.resources) == null ? void 0 : b.components) ?? {}).filter(
1588
+ (H) => c.includes(H)
1589
+ )) {
1590
+ const H = (ee = (B = ($ = e.resources) == null ? void 0 : $.components) == null ? void 0 : B[N]) == null ? void 0 : ee.component;
1591
+ if (H && ((z = H.renderer) == null ? void 0 : z.type) === "react-component") {
1592
+ const te = ((pe = H.renderer) == null ? void 0 : pe.chunks) ?? [];
1593
+ if ((te == null ? void 0 : te.length) > 0)
1594
+ for (const De of te) {
1595
+ const Ke = O(x, De), xe = G == null ? void 0 : G[De];
1596
+ try {
1597
+ xe && J(xe) && !J(Ke) && Bt(xe, Ke);
1598
+ } catch (Ct) {
1599
+ y.error(`copy chunk ${De} error`, Ct.message);
1600
+ }
1601
+ }
1602
+ }
1603
+ }
1604
+ }
1605
+ return m;
1606
+ }
1607
+ async function Et(e, { importAssets: n, includeResources: t } = {}) {
1608
+ var r, a, u, c;
1609
+ if (!J(e))
1610
+ return null;
1611
+ let s, o = !1;
1612
+ try {
1613
+ oe(e).isDirectory() ? s = e : /\.(tgz|gz|tar)$/.test(e) && (o = !0, s = St(), await ds({ file: e, C: s }));
1614
+ const i = Ne("**/.blocklet/pages/pages.config.yml", { cwd: s, absolute: !0 }).at(0), p = i && O(U(i), "../../pages"), S = i && O(U(i), "../../components"), f = i && O(U(i), "../../chunks"), d = i && O(U(i), "../../routes");
1615
+ if (!i)
1616
+ return null;
1617
+ const l = ae.parse(re(i).toString()), m = (E, h, A) => {
1618
+ let v = O(E, `${h}${A ? `.${A}` : ""}.yml`);
1619
+ return (!J(v) || !oe(v).isFile()) && (v = O(E, h, `index${A ? `.${A}` : ""}.yml`), !J(v) || !oe(v)) ? null : ae.parse(re(v).toString());
1620
+ }, w = (E, h) => {
1621
+ try {
1622
+ const A = Ne(`*.${h}.yml`, { cwd: E, absolute: !0 })[0];
1623
+ return A ? ae.parse(re(A).toString()) : null;
1624
+ } catch (A) {
1625
+ y.error("parse component error", A);
1626
+ }
1627
+ return null;
1628
+ }, k = (E, h) => {
1629
+ let A = O(E, `${h}.yml`);
1630
+ return (!J(A) || !oe(A).isFile()) && (A = O(E, h, "index.yml"), !J(A) || !oe(A)) ? null : ae.parse(re(A).toString());
1631
+ }, C = M(
1632
+ l.pages.map(({ slug: E }) => {
1633
+ var Z;
1634
+ const h = M(
1635
+ l.supportedLocales.map(({ locale: b }) => {
1636
+ const $ = p ? m(p, Oe(E), b) : void 0;
1637
+ if ($)
1638
+ return { locale: b, page: $ };
1639
+ const B = p ? m(p, E, b) : void 0;
1640
+ return B && { locale: b, page: B };
1641
+ })
1642
+ ), A = (Z = h[0]) == null ? void 0 : Z.page;
1643
+ if (!A)
1644
+ return null;
1645
+ const v = A.sections.map((b) => ({
1646
+ id: b.id || $e(),
1647
+ component: b.component,
1648
+ config: b.config,
1649
+ name: b.name,
1650
+ isTemplateSection: b.isTemplateSection ?? !1,
1651
+ templateDescription: b.templateDescription,
1652
+ llmConfig: b.llmConfig,
1653
+ visibility: b.visibility,
1654
+ sections: b.sections,
1655
+ sectionIds: b.sectionIds
1656
+ // 不再需要 locales, 数据在 page.dataSource 中管理
1657
+ // locales: Object.fromEntries(
1658
+ // filterNone(
1659
+ // locales.map(({ locale, page }) => {
1660
+ // const section = page.sections.find((s) => s.id === sectionId);
1661
+ // return section && [locale, section.properties];
1662
+ // })
1663
+ // )
1664
+ // ),
1665
+ }));
1666
+ return {
1667
+ id: A.id || $e(),
1668
+ createdAt: A.createdAt,
1669
+ updatedAt: A.updatedAt,
1670
+ publishedAt: A.publishedAt,
1671
+ isPublic: A.isPublic ?? !0,
1672
+ templateConfig: A.templateConfig,
1673
+ slug: E,
1674
+ sections: Object.fromEntries(v.map((b) => [b.id, b])),
1675
+ sectionIds: v.map((b) => b.id),
1676
+ locales: Object.fromEntries(h.map(({ locale: b, page: $ }) => [b, $.meta])),
1677
+ dataSource: A.dataSource ? Object.fromEntries(
1678
+ // 获取 dataSource 中所有 section ID
1679
+ [...new Set(h.flatMap(({ page: b }) => Object.keys(b.dataSource ?? {})))].map((b) => [
1680
+ b,
1681
+ Object.fromEntries(
1682
+ h.map(({ locale: $, page: B }) => {
1683
+ var z;
1684
+ const ee = (z = B.dataSource) == null ? void 0 : z[b];
1685
+ return [$, ee || {}];
1686
+ })
1687
+ )
1688
+ ])
1689
+ ) : Object.fromEntries(
1690
+ // 获取所有 section ID
1691
+ [...new Set(h.flatMap(({ page: b }) => b.sections.map(($) => $.id)))].map((b) => [
1692
+ b,
1693
+ Object.fromEntries(
1694
+ h.map(({ locale: $, page: B }) => {
1695
+ var pe;
1696
+ const ee = (pe = B.dataSource) == null ? void 0 : pe[b];
1697
+ if (ee)
1698
+ return [$, ee];
1699
+ const z = B.sections.find((g) => g.id === b);
1700
+ return [$, (z == null ? void 0 : z.properties) || {}];
1701
+ })
1702
+ )
1703
+ ])
1704
+ )
1705
+ };
1706
+ })
1707
+ ), L = M(
1708
+ ((r = l == null ? void 0 : l.routes) == null ? void 0 : r.map(({ path: E }) => {
1709
+ const h = d ? k(d, Oe(E)) : void 0;
1710
+ return {
1711
+ ...h,
1712
+ id: (h == null ? void 0 : h.id) || $e(),
1713
+ createdAt: (h == null ? void 0 : h.createdAt) ?? (/* @__PURE__ */ new Date()).toISOString(),
1714
+ updatedAt: (h == null ? void 0 : h.updatedAt) ?? (/* @__PURE__ */ new Date()).toISOString(),
1715
+ publishedAt: (/* @__PURE__ */ new Date(0)).toISOString(),
1716
+ path: (h == null ? void 0 : h.path) ?? `/${h == null ? void 0 : h.id}`,
1717
+ params: h == null ? void 0 : h.params,
1718
+ handler: (h == null ? void 0 : h.handler) ?? "Pages Kit",
1719
+ isPublic: (h == null ? void 0 : h.isPublic) ?? !0,
1720
+ enabledGenerate: (h == null ? void 0 : h.enabledGenerate) ?? !1,
1721
+ displayTemplateId: (h == null ? void 0 : h.displayTemplateId) ?? void 0,
1722
+ dataSource: (h == null ? void 0 : h.dataSource) ?? {}
1723
+ };
1724
+ })) ?? []
1725
+ ), X = S ? M(((a = l.components) == null ? void 0 : a.map(({ id: E }) => w(S, E))) ?? []) : [];
1726
+ if (n) {
1727
+ const E = (...h) => {
1728
+ y.info(`[${o ? F(e) : F(O(e, "../../../../"))}] importAssets:`, ...h);
1729
+ };
1730
+ try {
1731
+ E("wait image-bin api ready"), await us({
1732
+ resources: [`${Wt(Is)}/api/sdk/uploads`],
1733
+ validateStatus: (v) => v >= 200 && v <= 500
1734
+ }), E("image-bin api is ready");
1735
+ const h = {}, A = {};
1736
+ E("start to upload assets"), await Promise.allSettled([
1737
+ ot(X, h, {
1738
+ getFilePath: (v) => S && O(S, v),
1739
+ onFinish: (v) => {
1740
+ E(`upload ${v.length} component assets`);
1741
+ }
1742
+ }),
1743
+ ot(C, A, {
1744
+ getFilePath: (v, Z) => {
1745
+ const b = Be(C, Z.slice(0, 1));
1746
+ return p && O(p, U(b.slug), v);
1747
+ },
1748
+ onFinish: (v) => {
1749
+ E(`upload ${v.length} page assets`);
1750
+ }
1751
+ })
1752
+ ]), E("upload assets done"), global.gc && global.gc();
1753
+ } catch (h) {
1754
+ E("Error during asset import:", h);
1755
+ }
1756
+ }
1757
+ const ne = {};
1758
+ if (t) {
1759
+ const E = i && O(U(i), "../../resources/components"), h = M(
1760
+ ((c = (u = l.resources) == null ? void 0 : u.components) == null ? void 0 : c.map(({ id: A }) => w(E, A))) ?? []
1761
+ );
1762
+ h.length > 0 && (ne.components = Object.fromEntries(
1763
+ h.map((A, v) => [A.id, { index: v, component: A }])
1764
+ ));
1765
+ }
1766
+ const le = {};
1767
+ if (f && J(f)) {
1768
+ const E = Ft(f);
1769
+ for (const h of E)
1770
+ le[h] = O(f, h);
1771
+ }
1772
+ return {
1773
+ supportedLocales: l.supportedLocales,
1774
+ pageIds: C.map((E) => E.id),
1775
+ components: Object.fromEntries(X.map((E, h) => [E.id, { index: h, data: E }])),
1776
+ pages: Object.fromEntries(C.map((E) => [E.id, E])),
1777
+ config: l.config || {},
1778
+ resources: ne,
1779
+ chunks: le,
1780
+ routeIds: L.map((E) => E.id),
1781
+ routes: Object.fromEntries(L.map((E) => [E.id, E])),
1782
+ dataSourceIds: [],
1783
+ dataSources: {}
1784
+ };
1785
+ } finally {
1786
+ o && s && lt(s, { force: !0, recursive: !0 });
1787
+ }
1788
+ }
1789
+ async function rt(e, n, {
1790
+ routes: t,
1791
+ mergeMode: s = "byUpdateTime",
1792
+ deleteRoutes: o = !1,
1793
+ publishMode: r = void 0
1794
+ } = {}) {
1795
+ try {
1796
+ r && Ms(r);
1797
+ } catch (f) {
1798
+ y.error("clear preload page cache error", { error: f });
1799
+ }
1800
+ const { pages: a, pageIds: u, routeIds: c, routes: i, supportedLocales: p } = e;
1801
+ if (r === "production") {
1802
+ let f = t ?? [], d = null;
1803
+ for (const l of c ?? []) {
1804
+ const m = i == null ? void 0 : i[l];
1805
+ if (m != null && m.params && (m == null ? void 0 : m.params.length) > 0 && (m != null && m.paramsOptions) && (m == null ? void 0 : m.paramsOptions.length) > 0) {
1806
+ const w = Fe({
1807
+ basePath: m.path,
1808
+ params: m.params,
1809
+ routeId: m.id,
1810
+ paramsOptions: m.paramsOptions,
1811
+ currentIndex: 0,
1812
+ currentParams: [],
1813
+ currentOptionIds: [],
1814
+ result: []
1815
+ }), k = Object.fromEntries(w.map((C) => [`${l}-${C.paramOptionIds.join("-")}`, C]));
1816
+ d = { ...d || {}, ...k }, t || (f = [...f, ...w.map((C) => `${l}-${C.paramOptionIds.join("-")}`)]);
1817
+ } else t || f.push(l);
1818
+ }
1819
+ y.info("routeIds to be published: ", f);
1820
+ for (const l of f) {
1821
+ let m = l;
1822
+ if (m.includes("-")) {
1823
+ const [C] = m.split("-");
1824
+ m = C;
1825
+ }
1826
+ const w = i == null ? void 0 : i[m];
1827
+ if (!w) {
1828
+ const C = n.pageIds.indexOf(m);
1829
+ C !== -1 && o && (n.pageIds.splice(C, 1), delete n.pages[m]);
1830
+ for (const L of n.pageIds)
1831
+ L.includes(`${m}-`) && (n.pageIds.splice(n.pageIds.indexOf(L), 1), delete n.pages[L]);
1832
+ y.info("delete main route page", m);
1833
+ continue;
1834
+ }
1835
+ if (l.includes("-") && !(d != null && d[l])) {
1836
+ const C = n.pageIds.indexOf(l);
1837
+ C !== -1 && o && (n.pageIds.splice(C, 1), delete n.pages[l]), y.info("delete page", l);
1838
+ continue;
1839
+ }
1840
+ if (!w.displayTemplateId) {
1841
+ y.info("no display template", l);
1842
+ continue;
1843
+ }
1844
+ const k = a[w.displayTemplateId];
1845
+ if (!k) {
1846
+ y.info("no template page", l);
1847
+ continue;
1848
+ }
1849
+ if (n.pageIds.includes(l)) {
1850
+ if (y.info("has need update page", l), s === "replace")
1851
+ n.pages[l] = je({
1852
+ page: k,
1853
+ route: w,
1854
+ state: e,
1855
+ routeId: l,
1856
+ routePathInfo: d == null ? void 0 : d[l]
1857
+ }), y.info("replace page", l);
1858
+ else if (s === "byUpdateTime") {
1859
+ const C = n.pages[w.id];
1860
+ (!C || w.updatedAt && w.updatedAt > C.updatedAt) && (n.pages[l] = je({
1861
+ page: k,
1862
+ route: w,
1863
+ state: e,
1864
+ routeId: l,
1865
+ routePathInfo: d == null ? void 0 : d[l]
1866
+ }), y.info("replace page by update time", l));
1867
+ }
1868
+ } else
1869
+ n.pageIds.push(l), n.pages[l] = je({
1870
+ page: k,
1871
+ route: w,
1872
+ state: e,
1873
+ routeId: l,
1874
+ routePathInfo: d == null ? void 0 : d[l]
1875
+ }), y.info("add page", l);
1876
+ }
1877
+ if (o && !t)
1878
+ for (const l of n.pageIds)
1879
+ f != null && f.includes(l) || (delete n.pages[l], y.info("delete page", l)), n.pageIds = [...n.pageIds].filter((m) => f == null ? void 0 : f.includes(m));
1880
+ } else {
1881
+ for (const f of u) {
1882
+ const d = a[f];
1883
+ if (d)
1884
+ if (n.pageIds.includes(d.id)) {
1885
+ if (s === "replace")
1886
+ n.pages[d.id] = d;
1887
+ else if (s === "byUpdateTime") {
1888
+ const l = n.pages[d.id];
1889
+ (!l || d.updatedAt && d.updatedAt > l.updatedAt) && (n.pages[d.id] = d);
1890
+ }
1891
+ } else
1892
+ n.pageIds.push(d.id), n.pages[d.id] = d;
1893
+ }
1894
+ for (const f of c) {
1895
+ const d = i[f];
1896
+ if (d)
1897
+ if (n.routeIds.includes(d.id)) {
1898
+ if (s === "replace")
1899
+ n.routes[d.id] = d;
1900
+ else if (s === "byUpdateTime") {
1901
+ const l = n.routes[d.id];
1902
+ (!l || d.updatedAt && d.updatedAt > l.updatedAt) && (n.routes[d.id] = d);
1903
+ }
1904
+ } else
1905
+ n.routeIds.push(d.id), n.routes[d.id] = d;
1906
+ }
1907
+ }
1908
+ if (n.supportedLocales.splice(0, n.supportedLocales.length), n.supportedLocales.push(...rs(p)), o)
1909
+ for (const f of Object.keys(n.components))
1910
+ delete n.components[f];
1911
+ let S = JSON.parse(JSON.stringify(e.components));
1912
+ S = Object.fromEntries(
1913
+ await Promise.all(
1914
+ Object.entries(S).map(async ([f, d]) => {
1915
+ const l = await It(d == null ? void 0 : d.data);
1916
+ return [
1917
+ f,
1918
+ {
1919
+ ...d,
1920
+ data: l
1921
+ }
1922
+ ];
1923
+ })
1924
+ )
1925
+ ), Object.assign(n.components, S), Object.assign(n.config, JSON.parse(JSON.stringify(e.config))), ut(e.resources.components) || (n.resources.components = JSON.parse(JSON.stringify(e.resources.components || {})));
1926
+ }
1927
+ const It = Ge(
1928
+ async (e) => {
1929
+ var n;
1930
+ if (!ut(e == null ? void 0 : e.properties))
1931
+ return e;
1932
+ if (((n = e == null ? void 0 : e.renderer) == null ? void 0 : n.type) === "react-component") {
1933
+ const { script: t } = (e == null ? void 0 : e.renderer) || {};
1934
+ if (t && t.includes("PROPERTIES_SCHEMA"))
1935
+ try {
1936
+ const s = await Js(t, "PROPERTIES_SCHEMA", e.id);
1937
+ s && s.length > 0 && e && (e.properties = {}, s.forEach((o, r) => {
1938
+ e != null && e.properties && (e.properties[o.id] = {
1939
+ index: r,
1940
+ data: o
1941
+ });
1942
+ }));
1943
+ } catch (s) {
1944
+ y.error("checkPropertiesFromCode error", { componentId: e.id, name: e.name }, { error: s });
1945
+ }
1946
+ }
1947
+ return e;
1948
+ },
1949
+ {
1950
+ keyGenerator: (e) => {
1951
+ var i, p, S, f;
1952
+ const n = (e == null ? void 0 : e.id) || "", t = (e == null ? void 0 : e.name) || "", s = ((i = e == null ? void 0 : e.renderer) == null ? void 0 : i.type) || "", o = (e == null ? void 0 : e.properties) || {}, r = (e == null ? void 0 : e.updatedAt) || "", a = se("md5").update(JSON.stringify(o)).digest("hex");
1953
+ let u = "", c = "";
1954
+ return ((p = e == null ? void 0 : e.renderer) == null ? void 0 : p.type) === "react-component" && (u = se("md5").update(((S = e == null ? void 0 : e.renderer) == null ? void 0 : S.script) || "").digest("hex"), c = se("md5").update(((f = e == null ? void 0 : e.renderer) == null ? void 0 : f.editComponent) || "").digest("hex")), JSON.stringify([
1955
+ "checkPropertiesFromCode",
1956
+ n,
1957
+ t,
1958
+ s,
1959
+ a,
1960
+ r,
1961
+ u,
1962
+ c
1963
+ ]);
1964
+ },
1965
+ lruOptions: {
1966
+ max: 100,
1967
+ ttl: 1e3 * 60 * 60
1968
+ },
1969
+ subdir: "checkPropertiesFromCode"
1970
+ }
1971
+ );
1972
+ let Ce, ie, ve, ke, Je;
1973
+ function bt() {
1974
+ return Ce = (async () => {
1975
+ const e = zt({
1976
+ types: [
1977
+ { did: yt, type: tt },
1978
+ { did: Ks, type: tt }
1979
+ ]
1980
+ });
1981
+ ie = (await Promise.all(
1982
+ e.map(async (t) => {
1983
+ const s = t.path ? await Et(t.path, { importAssets: !1 }) : void 0;
1984
+ return s ? { blockletId: t.did, state: s, blockletTitle: t.title } : void 0;
1985
+ })
1986
+ )).filter((t) => !!t), ve = ie.reduce(
1987
+ (t, s) => Object.assign(
1988
+ t,
1989
+ Object.fromEntries(
1990
+ Object.values(s.state.pages).map((o) => o ? [o == null ? void 0 : o.id, { page: o, blockletId: s.blockletId }] : [])
1991
+ )
1992
+ ),
1993
+ {}
1994
+ );
1995
+ const n = ie.reduce(
1996
+ (t, s) => Object.assign(
1997
+ t,
1998
+ Object.fromEntries(
1999
+ Object.values(s.state.components).map((o) => [o.data.id, { blockletId: s.blockletId, component: o.data }])
2000
+ )
2001
+ ),
2002
+ {}
2003
+ );
2004
+ ke = Object.fromEntries(
2005
+ await Promise.all(
2006
+ Object.entries(n).map(async ([t, s]) => {
2007
+ const o = await It(s.component);
2008
+ return [
2009
+ t,
2010
+ {
2011
+ ...s,
2012
+ component: o
2013
+ }
2014
+ ];
2015
+ })
2016
+ )
2017
+ ), Je = ie.reduce((t, s) => Object.assign(t, s.state.chunks), {});
2018
+ })(), Ce;
2019
+ }
2020
+ function ln(e) {
2021
+ const n = dt(
2022
+ async () => {
2023
+ await bt().catch((t) => {
2024
+ y.error("load resource states error", { error: t });
2025
+ }), await (e == null ? void 0 : e({
2026
+ states: ie,
2027
+ pages: ve,
2028
+ components: ke,
2029
+ chunks: Je
2030
+ }));
2031
+ },
2032
+ 3e3,
2033
+ // 3s
2034
+ { leading: !1, trailing: !0 }
2035
+ );
2036
+ return n(), I.events.on(I.Events.componentAdded, n), I.events.on(I.Events.componentRemoved, n), I.events.on(I.Events.componentStarted, n), I.events.on(I.Events.componentStopped, n), I.events.on(I.Events.componentUpdated, n), I.events.on(Me, n), () => {
2037
+ I.events.off(I.Events.componentAdded, n), I.events.off(I.Events.componentRemoved, n), I.events.off(I.Events.componentStarted, n), I.events.off(I.Events.componentStopped, n), I.events.off(I.Events.componentUpdated, n), I.events.off(Me, n);
2038
+ };
2039
+ }
2040
+ const At = Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"), Se = globalThis;
2041
+ var at;
2042
+ (at = Se[At]) == null || at.call(Se);
2043
+ Se[At] = ln(async ({ pages: e, components: n }) => {
2044
+ const { projectIds: t } = Q;
2045
+ y.info(`start update resource states projects(${t.length})`, t), await Promise.race([
2046
+ new Promise((s) => {
2047
+ setTimeout(() => {
2048
+ s({});
2049
+ }, 30 * 1e3);
2050
+ }),
2051
+ Promise.all(
2052
+ t.map(async (s) => {
2053
+ Ot({
2054
+ projectId: s,
2055
+ pages: e,
2056
+ components: n
2057
+ });
2058
+ })
2059
+ )
2060
+ ]).catch((s) => {
2061
+ y.error("update resource states failed:", s);
2062
+ });
2063
+ });
2064
+ Q.startPeriodicCheck();
2065
+ process.on("beforeExit", () => {
2066
+ Q.stopPeriodicCheck();
2067
+ });
2068
+ process.on("SIGINT", () => {
2069
+ Q.stopPeriodicCheck(), process.exit(0);
2070
+ });
2071
+ process.on("SIGTERM", () => {
2072
+ Q.stopPeriodicCheck(), process.exit(0);
2073
+ });
2074
+ async function Ot({
2075
+ projectId: e,
2076
+ pages: n,
2077
+ components: t
2078
+ }) {
2079
+ const s = Q.sharedInstances[e];
2080
+ if (!s) {
2081
+ y.info(`projectId: ${e} not found in sharedInstances`);
2082
+ return;
2083
+ }
2084
+ s.syncedStore.resources.pages = n;
2085
+ const o = await q.findByPk(e);
2086
+ if (o != null && o.useAllResources)
2087
+ s.syncedStore.resources.components = t;
2088
+ else {
2089
+ const a = (await Te.findAll({ where: { projectId: e } })).map((c) => c.componentId), u = Object.fromEntries(
2090
+ Object.entries(t || {}).filter(([c]) => a.includes(c))
2091
+ );
2092
+ s.syncedStore.resources.components = u;
2093
+ }
2094
+ y.info(`update [${e}] resource states:`, {
2095
+ pages: Object.keys(s.syncedStore.resources.pages || {}).length,
2096
+ components: Object.keys(s.syncedStore.resources.components || {}).length
2097
+ });
2098
+ }
2099
+ async function ao() {
2100
+ y.info("trigger reload all project resource"), I.events.emit(Me);
2101
+ }
2102
+ async function Ve({
2103
+ ensureLoaded: e = !0
2104
+ } = {}) {
2105
+ return e && (Ce ?? (Ce = bt()), await Ce), { states: ie, pages: ve, components: ke, chunks: Je };
2106
+ }
2107
+ export {
2108
+ yt as C,
2109
+ et as G,
2110
+ q as P,
2111
+ tt as R,
2112
+ Q as S,
2113
+ to as a,
2114
+ Ve as b,
2115
+ Ns as c,
2116
+ _s as d,
2117
+ Ms as e,
2118
+ Us as f,
2119
+ so as g,
2120
+ Fs as h,
2121
+ eo as i,
2122
+ Ee as j,
2123
+ no as k,
2124
+ y as l,
2125
+ Js as m,
2126
+ $e as n,
2127
+ de as o,
2128
+ oo as p,
2129
+ ro as q,
2130
+ rn as r,
2131
+ an as s,
2132
+ cn as t,
2133
+ Et as u,
2134
+ rt as v,
2135
+ ln as w,
2136
+ ao as x
2137
+ };