@blocklet/pages-kit-inner-components 0.5.28 → 0.5.30

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