@blocklet/pages-kit-inner-components 0.5.29 → 0.5.31

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 (38) hide show
  1. package/lib/cjs/add-component.js +47 -23
  2. package/lib/cjs/chunks/array-BH41o7C6.js +475 -0
  3. package/lib/cjs/chunks/{config-string-C4Q0hgG0.js → config-string-B3JoYJVu.js} +1 -1
  4. package/lib/cjs/chunks/{draft-data-Cu9gua-P.js → draft-data-hZaTeHgL.js} +1 -1
  5. package/lib/cjs/chunks/home-B6E0yAU3.js +38 -0
  6. package/lib/cjs/chunks/{publish-button-DvwoFH1F.js → publish-button-CO_WU_f5.js} +1 -1
  7. package/lib/cjs/chunks/site-state-D5jk8eJT.js +57 -0
  8. package/lib/cjs/chunks/state-DxOb57hO.js +1 -0
  9. package/lib/cjs/components.js +1 -1
  10. package/lib/cjs/home.js +1 -1
  11. package/lib/cjs/locales.js +3 -1
  12. package/lib/cjs/project-html.js +2 -2
  13. package/lib/cjs/resources.js +1 -1
  14. package/lib/cjs/setting.js +1 -1
  15. package/lib/cjs/site-state.js +1 -1
  16. package/lib/es/add-component.js +795 -749
  17. package/lib/es/chunks/array-NLDZzhVt.js +2224 -0
  18. package/lib/es/chunks/{config-string-CNLg1EYu.js → config-string-DutyRoOh.js} +1 -1
  19. package/lib/es/chunks/{draft-data-hSHLdxKp.js → draft-data-DjX0kpDC.js} +1 -1
  20. package/lib/es/chunks/{home-CNk6U8FU.js → home-CxRa0eKd.js} +112 -96
  21. package/lib/es/chunks/{publish-button-BftBlabj.js → publish-button-1bl_Nuva.js} +3 -3
  22. package/lib/es/chunks/site-state-DEduMTrY.js +2073 -0
  23. package/lib/es/chunks/state-C02ZI8vz.js +605 -0
  24. package/lib/es/components.js +1 -1
  25. package/lib/es/home.js +3 -3
  26. package/lib/es/locales.js +44 -6
  27. package/lib/es/project-html.js +43 -42
  28. package/lib/es/resources.js +51 -51
  29. package/lib/es/setting.js +2 -2
  30. package/lib/es/site-state.js +1 -1
  31. package/package.json +10 -10
  32. package/lib/cjs/chunks/array-CJC7ex3i.js +0 -467
  33. package/lib/cjs/chunks/home-CimGvyT9.js +0 -38
  34. package/lib/cjs/chunks/site-state-JgP3yURe.js +0 -57
  35. package/lib/cjs/chunks/state-jCG5gSUJ.js +0 -1
  36. package/lib/es/chunks/array-9j8tOSbO.js +0 -1993
  37. package/lib/es/chunks/site-state-BB9-Tm4i.js +0 -1930
  38. package/lib/es/chunks/state-D5BnGunt.js +0 -483
@@ -0,0 +1,2073 @@
1
+ var Ct = Object.defineProperty;
2
+ var Tt = (e, n, t) => n in e ? Ct(e, n, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[n] = t;
3
+ var k = (e, n, t) => Tt(e, typeof n != "symbol" ? n + "" : n, t);
4
+ import { getComponentMountPoint as Pt } from "@blocklet/pages-kit/builtin/utils";
5
+ import { PreloadComponentScriptModule as ye } from "@blocklet/pages-kit/types";
6
+ import { componentUMDName as vt, RenderNestedComponent as ze, mergeComponent as Dt, getComponentDependencies as kt } from "@blocklet/pages-kit/utils/property";
7
+ import { memoize as at, Sandbox as it, BuiltinModules as jt } from "@blocklet/quickjs";
8
+ import I from "@blocklet/sdk/lib/config";
9
+ import { LRUCache as $e } from "lru-cache";
10
+ import xt, { Headers as Rt } from "node-fetch";
11
+ import { joinURL as W, getQuery as Nt, withQuery as Lt, parseURL as Ke, withHttps as _t } from "ufo";
12
+ import { createHash as te } from "crypto";
13
+ import Mt from "@blocklet/logger";
14
+ import { promises as V, readFileSync as re, mkdtempSync as $t, existsSync as H, lstatSync as oe, readdirSync as Ut, rmSync as ct, renameSync as Ye, mkdirSync as Y, writeFileSync as we, copyFileSync as Ft, createWriteStream as Bt } from "fs";
15
+ import lt, { join as O, dirname as U, basename as J } from "path";
16
+ import Gt from "lodash/isNil";
17
+ import { BuiltinModules as Ht } from "@blocklet/pages-kit/utils/builtin";
18
+ import { isRelativeModule as Vt, createBuiltinModuleTransformer as Jt } from "@blocklet/pages-kit/utils/typescript/builtin-module-transformer";
19
+ import { getResources as zt, getComponentWebEndpoint as Kt, call as Yt } from "@blocklet/sdk/lib/component";
20
+ import Wt from "autoprefixer";
21
+ import * as qt from "esbuild";
22
+ import Qt from "postcss";
23
+ import Xt from "tailwindcss";
24
+ import M from "typescript";
25
+ import { getYjsValue as ce, syncedStore as Zt } from "@syncedstore/core";
26
+ import * as z from "yjs";
27
+ import { setPageDataSource as es } from "@blocklet/pages-kit/utils/data-source";
28
+ import { getRouteMetaDataByOptionIds as ts, generateParamCombinations as Ue } from "@blocklet/pages-kit/utils/route";
29
+ import { cloneDeep as ss } from "lodash";
30
+ import { reactive as ns } 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 os from "lodash/cloneDeep";
35
+ import pt from "lodash/debounce";
36
+ import Fe from "lodash/get";
37
+ import dt 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 ae from "yaml";
49
+ import { DataTypes as x, Sequelize as Ss, Model as ut, 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 (Gt(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 = Mt("pages-kit"), Os = x.sqlite.DATE.parse;
63
+ x.sqlite.DATE.parse = (e, n) => typeof e == "number" ? new Date(e) : Os(e, n);
64
+ const me = 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
+ me.query("pragma journal_mode = WAL;");
78
+ me.query("pragma synchronous = normal;");
79
+ me.query("pragma journal_size_limit = 67108864;");
80
+ class Ce extends ut {
81
+ // Foreign key to Component
82
+ }
83
+ Ce.init(
84
+ {
85
+ id: {
86
+ type: x.UUID,
87
+ allowNull: !1,
88
+ primaryKey: !0,
89
+ defaultValue: x.UUIDV4
90
+ },
91
+ projectId: {
92
+ type: x.UUID,
93
+ allowNull: !1
94
+ },
95
+ componentId: {
96
+ type: x.STRING,
97
+ allowNull: !1
98
+ }
99
+ },
100
+ { sequelize: me, tableName: "ProjectComponents", timestamps: !1 }
101
+ );
102
+ class se extends ut {
103
+ static async getProjectByIdOrSlug(n) {
104
+ return se.findOne({
105
+ where: {
106
+ [ws.or]: [{ id: n }, { slug: n }]
107
+ }
108
+ });
109
+ }
110
+ }
111
+ se.init(
112
+ {
113
+ id: {
114
+ type: x.UUID,
115
+ defaultValue: x.UUIDV4,
116
+ primaryKey: !0
117
+ },
118
+ name: {
119
+ type: x.STRING,
120
+ allowNull: !1
121
+ },
122
+ description: x.TEXT,
123
+ createdAt: x.DATE,
124
+ updatedAt: x.DATE,
125
+ createdBy: {
126
+ type: x.STRING,
127
+ allowNull: !1
128
+ },
129
+ updatedBy: {
130
+ type: x.STRING,
131
+ allowNull: !1
132
+ },
133
+ slug: x.STRING,
134
+ icon: x.STRING,
135
+ pinnedAt: x.DATE,
136
+ useAllResources: x.BOOLEAN,
137
+ npmSecret: x.STRING,
138
+ relatedBlocklets: {
139
+ type: x.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
+ se.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, ft = async (e = "") => {
157
+ const n = O(Cs, 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
+ }, vs = (e, n) => {
166
+ const t = te("md5").update(n).digest("hex");
167
+ return O(e, `${Ts}-${t}.json`);
168
+ }, Ds = async (e = "") => {
169
+ const n = await ft(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"), i = JSON.parse(a);
177
+ i.createdAt && t - i.createdAt > Le && await V.unlink(r);
178
+ } catch {
179
+ try {
180
+ const i = await V.stat(r);
181
+ t - i.mtimeMs > Le && 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
+ }, 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 ft(n.subdir || ""), r = n.keyGenerator ? n.keyGenerator(...s) : JSON.stringify(s), a = vs(o, r);
202
+ try {
203
+ const i = await V.readFile(a, "utf-8"), { value: p, createdAt: c } = JSON.parse(i);
204
+ if (c && Date.now() - c > Le)
205
+ throw await V.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 V.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 js = async (e, { componentId: n }) => {
222
+ const t = `@tailwind components;
223
+ @tailwind utilities;
224
+ `, s = `.CustomComponent_${n}`;
225
+ return (await Qt([
226
+ Xt({ content: [{ raw: e, extension: "tsx" }] }),
227
+ Wt({
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
+ }, xs = async (e, { componentId: n }) => {
240
+ const t = await js(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 = M.transpileModule(e, {
248
+ compilerOptions: {
249
+ jsx: M.JsxEmit.React,
250
+ target: M.ScriptTarget.ES2016,
251
+ module: M.ModuleKind.ESNext
252
+ },
253
+ transformers: {
254
+ before: [Jt(M)]
255
+ }
256
+ }).outputText;
257
+ if (n.tailwind && (t = await xs(t, { componentId: n.componentId })), n.module === ye.ESM) return t;
258
+ const s = M.transpileModule(t, {
259
+ compilerOptions: {
260
+ jsx: M.JsxEmit.React,
261
+ target: M.ScriptTarget.ES2016,
262
+ module: M.ModuleKind.CommonJS,
263
+ moduleResolution: M.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 = te("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 qt.build({
290
+ entryPoints: ["index.tsx"],
291
+ external: Object.keys(Ht),
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 (Vt(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 = re(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 M.transpileModule(o, {
325
+ compilerOptions: { module: M.ModuleKind.ESNext, target: M.ScriptTarget.ES2020 }
326
+ }).outputText;
327
+ }, mt = 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 = te("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
+ `, ue = new $e({
371
+ max: 100
372
+ }), Ls = 60 * 60, Ze = 60;
373
+ function _s(e) {
374
+ S.info("clear preload components cache", { cacheKey: e }), ue.delete(e);
375
+ }
376
+ function Ms(e) {
377
+ for (const n of ue.keys())
378
+ n.includes(e) && (S.info("clear preload components cache", { cacheKey: n }), _s(n));
379
+ }
380
+ function $s({
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 = $s({
405
+ mode: e,
406
+ instanceId: d.id,
407
+ componentId: d.componentId,
408
+ locale: s
409
+ });
410
+ if (e !== "draft" && d.useCache && ue.has(l))
411
+ return S.info(`get preload component from cache: ${l}`), ue.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 C = Ls;
426
+ d.cacheDuration && (C = d.cacheDuration), S.info(`set preload component to cache(${C}s): ${l}`), ue.set(l, D, {
427
+ ttl: C * 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 = vt({ 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 ht({ 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 ht({
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 ht({
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 = Dt({
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 mt(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 jt.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: Pt,
631
+ joinURL: W,
632
+ withQuery: Lt,
633
+ getQuery: Nt
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: W(_t(s.hostname), s.originalUrl) },
641
+ fetch: (i, { ...p } = {}) => {
642
+ const c = typeof i == "string" && i.startsWith("/") ? W(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 Rt(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 mt(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 = te("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", gt = 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 yt() {
707
+ return $t(O(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 = ce(e.pages[t]);
718
+ s && s instanceof z.Map && Ie(s);
719
+ });
720
+ const n = ce(e.pages);
721
+ n && n instanceof z.Map && n.observe((t) => {
722
+ t.changes.keys.forEach((s, o) => {
723
+ if (s.action === "add") {
724
+ const r = ce(e.pages[o]);
725
+ r && r instanceof z.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 = ce((o = e.routes) == null ? void 0 : o[t]);
734
+ s && s instanceof z.Map && Ie(s);
735
+ });
736
+ const n = ce(e.routes);
737
+ n && n instanceof z.Map && n.observe((t) => {
738
+ t.changes.keys.forEach((s, o) => {
739
+ var r;
740
+ if (s.action === "add") {
741
+ const a = ce((r = e.routes) == null ? void 0 : r[o]);
742
+ a && a instanceof z.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 = ts(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 je({
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
+ ...ss(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
+ es(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"), xe = is("abcdefghijklmnopqrstuvwxyz0123456789", 16), Ge = /^\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, 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, Me = I, de = O(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 = Me.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 P = class P extends z.Doc {
835
+ constructor(t) {
836
+ super();
837
+ k(this, "syncedStore");
838
+ k(this, "conns", /* @__PURE__ */ new Map());
839
+ k(this, "awareness");
840
+ // 延迟释放定时器
841
+ k(this, "releaseTimer");
842
+ k(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
+ k(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
+ k(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(...Me.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
+ k(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
+ k(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
+ k(this, "autoSave", pt(() => {
910
+ Y(U(this.draftYjsFilePath), { recursive: !0 }), we(this.draftYjsFilePath, z.encodeStateAsUpdate(this));
911
+ }, qs));
912
+ k(this, "save", ({ flush: t = !1 } = {}) => {
913
+ this.autoSave(), t && this.autoSave.flush();
914
+ });
915
+ k(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
+ k(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
+ k(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
+ k(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, H(this.draftYjsFilePath) && z.applyUpdate(this, re(this.draftYjsFilePath)), this.syncedStore = ns(
987
+ Zt(
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 = O(de, t), o = O(de, `@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: de,
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) => P.shared(t));
1024
+ }
1025
+ static shared(t) {
1026
+ if (!t)
1027
+ throw new Error("Should provide project context");
1028
+ let s = P.sharedInstances[t];
1029
+ return s || (s = new P({
1030
+ path: O(de, t)
1031
+ }), P.sharedInstances[t] = s, At({
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 = P.productionStates.get(t);
1041
+ if (!s) {
1042
+ const a = O(de, t, "production");
1043
+ if (s = await wt(a, { includeResources: !0 }) ?? en(), !((o = s == null ? void 0 : s.config) != null && o.defaultLocale)) {
1044
+ s.config ?? (s.config = {});
1045
+ const i = Me.env.languages.map((p) => ({ locale: p.code, name: p.name }));
1046
+ s.config.defaultLocale = (r = i[0]) == null ? void 0 : r.locale;
1047
+ }
1048
+ P.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 se.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 = J(this.options.path);
1075
+ delete P.sharedInstances[t], super.destroy();
1076
+ }
1077
+ initObserver() {
1078
+ zs(this.syncedStore), Ks(this.syncedStore);
1079
+ }
1080
+ get draftYjsFilePath() {
1081
+ return O(this.options.path, "draft.yjs");
1082
+ }
1083
+ static async getStateByProjectId(t, s) {
1084
+ if (s === "draft") {
1085
+ const o = P.shared(t);
1086
+ return JSON.parse(JSON.stringify(o.syncedStore));
1087
+ }
1088
+ return P.getProductionState(t);
1089
+ }
1090
+ async getState(t) {
1091
+ if (t === "draft")
1092
+ return JSON.parse(JSON.stringify(this.syncedStore));
1093
+ const s = J(this.options.path);
1094
+ return P.getProductionState(s);
1095
+ }
1096
+ async setState(t, s) {
1097
+ const o = await on(s, { exportAssets: !1, includeResources: !0 }), r = this.getPublishDir(t);
1098
+ if (Y(U(r), { recursive: !0 }), ct(r, { force: !0, recursive: !0 }), Ye(o, r), t === "production") {
1099
+ const a = J(this.options.path);
1100
+ P.productionStates.set(a, s);
1101
+ }
1102
+ }
1103
+ getPublishDir(t) {
1104
+ return O(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 = J(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
+ }, P.RELEASE_DELAY), S.info(`[SiteState] scheduled release for project ${t} in ${P.RELEASE_DELAY / 1e3}s`);
1117
+ }
1118
+ // 取消延迟释放
1119
+ cancelRelease() {
1120
+ if (this.releaseTimer) {
1121
+ clearTimeout(this.releaseTimer), this.releaseTimer = void 0;
1122
+ const t = J(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 se.findByPk(p);
1133
+ if (!c) continue;
1134
+ const u = await P.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[W("/", y, l)] = {
1139
+ ...f,
1140
+ shouldRedirect: !0,
1141
+ mainPage: !0
1142
+ }), r[W("/", 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[W("/", w, p, l)] = D, y && (r[W("/", 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 C = 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 L of C) {
1168
+ const Q = L.path, ne = {
1169
+ projectId: p,
1170
+ projectSlug: y,
1171
+ pageSlug: Q,
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 = L == null ? void 0 : L.routeMetaData) == null ? void 0 : i.isPublic)
1179
+ };
1180
+ d(Q, ne);
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, C = {
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, C);
1214
+ }
1215
+ }
1216
+ return r;
1217
+ }
1218
+ getDocumentSize() {
1219
+ return z.encodeStateAsUpdate(this).byteLength;
1220
+ }
1221
+ static getInstancesSizeInfo() {
1222
+ const t = [];
1223
+ for (const [s, o] of Object.entries(P.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(P.sharedInstances).length, s = [], o = [];
1249
+ for (const [r, a] of Object.entries(P.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
+ k(P, "PRODUCTION_CACHE_TTL", 7 * 24 * 60 * 60 * 1e3), // 7 days
1272
+ // 延迟释放时间:5分钟
1273
+ k(P, "RELEASE_DELAY", 5 * 60 * 1e3), // 定期检查间隔:2 小时
1274
+ k(P, "PERIODIC_CHECK_INTERVAL", 2 * 60 * 60 * 1e3), // 2 hours
1275
+ k(P, "sharedInstances", {}), k(P, "productionStates", new $e({
1276
+ max: 100,
1277
+ ttl: P.PRODUCTION_CACHE_TTL
1278
+ })), // 定期检查定时器
1279
+ k(P, "periodicCheckTimer");
1280
+ let q = P;
1281
+ async function tn(e, n, t) {
1282
+ if (!e || !H(e) || !oe(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 = J(e), s = await Yt({
1300
+ name: gt,
1301
+ path: W("/uploads", t),
1302
+ responseType: "stream",
1303
+ method: "GET"
1304
+ });
1305
+ if (s.status >= 200 && s.status < 400) {
1306
+ const o = Bt(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, O(n, J(t)));
1315
+ } catch (s) {
1316
+ S.error(`Failed to export assets: ${t}, ${s}`);
1317
+ }
1318
+ })
1319
+ );
1320
+ };
1321
+ function St(e) {
1322
+ return Ge.test(e) ? [e] : fe.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 = O(n, s(e));
1326
+ if (Y(U(r), { recursive: !0 }), we(r, ae.stringify(e)), o) {
1327
+ const i = be(
1328
+ e,
1329
+ (p) => typeof p == "string" && (Ge.test(p) || fe.test(p))
1330
+ ).map((p) => {
1331
+ const c = Fe(e, p);
1332
+ return St(c);
1333
+ }).flat().filter(Boolean);
1334
+ await nn(i, U(r));
1335
+ }
1336
+ }
1337
+ const st = new $e({
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) || fe.test(p))
1346
+ ), o = cs(2), r = s.map(
1347
+ (p) => o(async () => {
1348
+ try {
1349
+ const c = Fe(e, p), u = St(c);
1350
+ for (const y of u) {
1351
+ const m = J(y), d = t.getFilePath(y, p), l = d ? `${d}:${m}` : m, f = st.get(l);
1352
+ if (f) {
1353
+ fe.test(c) || We(e, p, f);
1354
+ return;
1355
+ }
1356
+ const w = await tn(d, m, n);
1357
+ w && (fe.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 le, E, h, A, v, X, b, N, F, Z, K, pe;
1375
+ const i = t === "all" ? e.pageIds : t, p = kt({
1376
+ state: e,
1377
+ pageIds: i,
1378
+ componentIds: s === "all" ? Object.keys(e.components) : s
1379
+ }), c = a === "all" ? e.routeIds : a, u = (g) => ({
1380
+ id: g.id,
1381
+ name: g.name,
1382
+ isTemplateSection: g.isTemplateSection ?? !1,
1383
+ templateDescription: g.templateDescription,
1384
+ llmConfig: g.llmConfig,
1385
+ component: g.component,
1386
+ config: g.config,
1387
+ visibility: g.visibility,
1388
+ sections: g.sections,
1389
+ sectionIds: g.sectionIds
1390
+ // 已经废弃,数据在 page.dataSource 中管理
1391
+ // properties: section.locales?.[locale] ?? {},
1392
+ }), y = (g, T) => {
1393
+ var j;
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: ((j = g.locales) == null ? void 0 : j[T]) ?? {},
1402
+ sections: $(
1403
+ g.sectionIds.map((B) => {
1404
+ const _ = g.sections[B];
1405
+ return _ && u(_);
1406
+ })
1407
+ ),
1408
+ // 将 dataSource.sectionId.locale 转换为 dataSource.sectionId
1409
+ dataSource: Object.fromEntries(
1410
+ Object.entries(g.dataSource || {}).map(([B, _]) => [B, (_ == null ? void 0 : _[T]) ?? {}])
1411
+ )
1412
+ };
1413
+ }, m = (g) => ({
1414
+ id: g.id,
1415
+ createdAt: g.createdAt,
1416
+ updatedAt: g.updatedAt,
1417
+ publishedAt: g.publishedAt,
1418
+ path: g.path,
1419
+ handler: g.handler,
1420
+ isPublic: g.isPublic ?? !0,
1421
+ params: g.params ?? [],
1422
+ enabledGenerate: g.enabledGenerate ?? !1,
1423
+ displayTemplateId: g.displayTemplateId,
1424
+ dataSource: g.dataSource
1425
+ }), d = $(
1426
+ c.map((g) => {
1427
+ const T = e.routes[g];
1428
+ return T && m(T);
1429
+ })
1430
+ ), l = $(
1431
+ e.supportedLocales.map((g) => g.locale).flatMap(
1432
+ (g) => i.map((T) => {
1433
+ const j = e.pages[T];
1434
+ return j && {
1435
+ locale: g,
1436
+ slug: j.slug,
1437
+ page: y(j, g)
1438
+ };
1439
+ })
1440
+ )
1441
+ ), f = yt(), w = O(f, "pages");
1442
+ Y(w, { recursive: !0 });
1443
+ const D = O(f, "components");
1444
+ Y(D, { recursive: !0 });
1445
+ const C = O(f, "routes");
1446
+ Y(C, { recursive: !0 });
1447
+ for (const { locale: g, slug: T, page: j } of l)
1448
+ await ge(j, w, {
1449
+ getFilename: () => `${Ae(T) || "index"}.${g}.yml`,
1450
+ exportAssets: n
1451
+ });
1452
+ for (const g of d)
1453
+ await ge(g, C, {
1454
+ // getFilename: () => `${sanitizeSlug(route.path)}.yml`,
1455
+ getFilename: () => `${Ae(g.path) || "index"}.yml`,
1456
+ exportAssets: n
1457
+ });
1458
+ for (const g of p) {
1459
+ const T = (le = e.components[g]) == null ? void 0 : le.data;
1460
+ T && await ge(T, D, {
1461
+ getFilename: (j) => `${j.name || "unnamed"}.${j.id}.yml`,
1462
+ exportAssets: n
1463
+ });
1464
+ }
1465
+ const L = O(f, ".blocklet/pages/pages.config.yml");
1466
+ Y(U(L), { recursive: !0 });
1467
+ const Q = {
1468
+ pages: $(
1469
+ i.map((g) => {
1470
+ const T = e.pages[g];
1471
+ return T && { id: g, slug: T.slug };
1472
+ })
1473
+ ),
1474
+ routes: $(
1475
+ c.map((g) => {
1476
+ const T = e.routes[g];
1477
+ return T && { id: g, path: T.path };
1478
+ })
1479
+ ),
1480
+ components: $(
1481
+ p.map((g) => {
1482
+ var j;
1483
+ const T = (j = e.components[g]) == null ? void 0 : j.data;
1484
+ return T && {
1485
+ id: g,
1486
+ name: T.name
1487
+ };
1488
+ })
1489
+ ),
1490
+ ...r ? {
1491
+ resources: {
1492
+ components: $(
1493
+ Object.keys(((E = e.resources) == null ? void 0 : E.components) || {}).filter((g) => p.includes(g)).map((g) => {
1494
+ var T, j, B, _;
1495
+ return {
1496
+ id: g,
1497
+ name: (_ = (B = (j = (T = e.resources) == null ? void 0 : T.components) == null ? void 0 : j[g]) == null ? void 0 : B.component) == null ? void 0 : _.name
1498
+ };
1499
+ })
1500
+ )
1501
+ }
1502
+ } : {},
1503
+ supportedLocales: e.supportedLocales,
1504
+ config: e.config
1505
+ };
1506
+ we(L, ae.stringify(Q));
1507
+ const ne = O(f, "config.source.json");
1508
+ if (o && we(ne, JSON.stringify(o)), r) {
1509
+ const g = O(f, "resources"), T = O(g, "components");
1510
+ Y(T, { recursive: !0 });
1511
+ for (const _ of Object.keys(((h = e == null ? void 0 : e.resources) == null ? void 0 : h.components) ?? {}).filter(
1512
+ (G) => p.includes(G)
1513
+ )) {
1514
+ const G = (X = (v = (A = e.resources) == null ? void 0 : A.components) == null ? void 0 : v[_]) == null ? void 0 : X.component;
1515
+ G && await ge(G, T, {
1516
+ getFilename: (ee) => `${ee.name || "unnamed"}.${ee.id}.yml`,
1517
+ exportAssets: n
1518
+ });
1519
+ }
1520
+ const j = O(f, "chunks");
1521
+ Y(j, { recursive: !0 });
1522
+ const { chunks: B } = await Ve();
1523
+ for (const _ of Object.keys(((b = e == null ? void 0 : e.resources) == null ? void 0 : b.components) ?? {}).filter(
1524
+ (G) => p.includes(G)
1525
+ )) {
1526
+ const G = (Z = (F = (N = e.resources) == null ? void 0 : N.components) == null ? void 0 : F[_]) == null ? void 0 : Z.component;
1527
+ if (G && ((K = G.renderer) == null ? void 0 : K.type) === "react-component") {
1528
+ const ee = ((pe = G.renderer) == null ? void 0 : pe.chunks) ?? [];
1529
+ if ((ee == null ? void 0 : ee.length) > 0)
1530
+ for (const ve of ee) {
1531
+ const Je = O(j, ve), De = B == null ? void 0 : B[ve];
1532
+ try {
1533
+ De && H(De) && !H(Je) && Ft(De, Je);
1534
+ } catch (Ot) {
1535
+ S.error(`copy chunk ${ve} error`, Ot.message);
1536
+ }
1537
+ }
1538
+ }
1539
+ }
1540
+ }
1541
+ return f;
1542
+ }
1543
+ async function wt(e, { importAssets: n, includeResources: t } = {}) {
1544
+ var r, a, i, p;
1545
+ if (!H(e))
1546
+ return null;
1547
+ let s, o = !1;
1548
+ try {
1549
+ oe(e).isDirectory() ? s = e : /\.(tgz|gz|tar)$/.test(e) && (o = !0, s = yt(), await ps({ file: e, C: s }));
1550
+ const c = Ne("**/.blocklet/pages/pages.config.yml", { cwd: s, absolute: !0 }).at(0), u = c && O(U(c), "../../pages"), y = c && O(U(c), "../../components"), m = c && O(U(c), "../../chunks"), d = c && O(U(c), "../../routes");
1551
+ if (!c)
1552
+ return null;
1553
+ const l = ae.parse(re(c).toString()), f = (E, h, A) => {
1554
+ let v = O(E, `${h}${A ? `.${A}` : ""}.yml`);
1555
+ return (!H(v) || !oe(v).isFile()) && (v = O(E, h, `index${A ? `.${A}` : ""}.yml`), !H(v) || !oe(v)) ? null : ae.parse(re(v).toString());
1556
+ }, w = (E, h) => {
1557
+ try {
1558
+ const A = Ne(`*.${h}.yml`, { cwd: E, absolute: !0 })[0];
1559
+ return A ? ae.parse(re(A).toString()) : null;
1560
+ } catch (A) {
1561
+ S.error("parse component error", A);
1562
+ }
1563
+ return null;
1564
+ }, D = (E, h) => {
1565
+ let A = O(E, `${h}.yml`);
1566
+ return (!H(A) || !oe(A).isFile()) && (A = O(E, h, "index.yml"), !H(A) || !oe(A)) ? null : ae.parse(re(A).toString());
1567
+ }, C = $(
1568
+ l.pages.map(({ slug: E }) => {
1569
+ var X;
1570
+ const h = $(
1571
+ l.supportedLocales.map(({ locale: b }) => {
1572
+ const N = u ? f(u, Ae(E), b) : void 0;
1573
+ if (N)
1574
+ return { locale: b, page: N };
1575
+ const F = u ? f(u, E, b) : void 0;
1576
+ return F && { locale: b, page: F };
1577
+ })
1578
+ ), A = (X = h[0]) == null ? void 0 : X.page;
1579
+ if (!A)
1580
+ return null;
1581
+ const v = A.sections.map((b) => ({
1582
+ id: b.id || xe(),
1583
+ component: b.component,
1584
+ config: b.config,
1585
+ name: b.name,
1586
+ isTemplateSection: b.isTemplateSection ?? !1,
1587
+ templateDescription: b.templateDescription,
1588
+ llmConfig: b.llmConfig,
1589
+ visibility: b.visibility,
1590
+ sections: b.sections,
1591
+ sectionIds: b.sectionIds
1592
+ // 不再需要 locales, 数据在 page.dataSource 中管理
1593
+ // locales: Object.fromEntries(
1594
+ // filterNone(
1595
+ // locales.map(({ locale, page }) => {
1596
+ // const section = page.sections.find((s) => s.id === sectionId);
1597
+ // return section && [locale, section.properties];
1598
+ // })
1599
+ // )
1600
+ // ),
1601
+ }));
1602
+ return {
1603
+ id: A.id || xe(),
1604
+ createdAt: A.createdAt,
1605
+ updatedAt: A.updatedAt,
1606
+ publishedAt: A.publishedAt,
1607
+ isPublic: A.isPublic ?? !0,
1608
+ templateConfig: A.templateConfig,
1609
+ slug: E,
1610
+ sections: Object.fromEntries(v.map((b) => [b.id, b])),
1611
+ sectionIds: v.map((b) => b.id),
1612
+ locales: Object.fromEntries(h.map(({ locale: b, page: N }) => [b, N.meta])),
1613
+ dataSource: A.dataSource ? Object.fromEntries(
1614
+ // 获取 dataSource 中所有 section ID
1615
+ [...new Set(h.flatMap(({ page: b }) => Object.keys(b.dataSource ?? {})))].map((b) => [
1616
+ b,
1617
+ Object.fromEntries(
1618
+ h.map(({ locale: N, page: F }) => {
1619
+ var K;
1620
+ const Z = (K = F.dataSource) == null ? void 0 : K[b];
1621
+ return [N, Z || {}];
1622
+ })
1623
+ )
1624
+ ])
1625
+ ) : Object.fromEntries(
1626
+ // 获取所有 section ID
1627
+ [...new Set(h.flatMap(({ page: b }) => b.sections.map((N) => N.id)))].map((b) => [
1628
+ b,
1629
+ Object.fromEntries(
1630
+ h.map(({ locale: N, page: F }) => {
1631
+ var pe;
1632
+ const Z = (pe = F.dataSource) == null ? void 0 : pe[b];
1633
+ if (Z)
1634
+ return [N, Z];
1635
+ const K = F.sections.find((g) => g.id === b);
1636
+ return [N, (K == null ? void 0 : K.properties) || {}];
1637
+ })
1638
+ )
1639
+ ])
1640
+ )
1641
+ };
1642
+ })
1643
+ ), L = $(
1644
+ ((r = l == null ? void 0 : l.routes) == null ? void 0 : r.map(({ path: E }) => {
1645
+ const h = d ? D(d, Ae(E)) : void 0;
1646
+ return {
1647
+ ...h,
1648
+ id: (h == null ? void 0 : h.id) || xe(),
1649
+ createdAt: (h == null ? void 0 : h.createdAt) ?? (/* @__PURE__ */ new Date()).toISOString(),
1650
+ updatedAt: (h == null ? void 0 : h.updatedAt) ?? (/* @__PURE__ */ new Date()).toISOString(),
1651
+ publishedAt: (/* @__PURE__ */ new Date(0)).toISOString(),
1652
+ path: (h == null ? void 0 : h.path) ?? `/${h == null ? void 0 : h.id}`,
1653
+ params: h == null ? void 0 : h.params,
1654
+ handler: (h == null ? void 0 : h.handler) ?? "Pages Kit",
1655
+ isPublic: (h == null ? void 0 : h.isPublic) ?? !0,
1656
+ enabledGenerate: (h == null ? void 0 : h.enabledGenerate) ?? !1,
1657
+ displayTemplateId: (h == null ? void 0 : h.displayTemplateId) ?? void 0,
1658
+ dataSource: (h == null ? void 0 : h.dataSource) ?? {}
1659
+ };
1660
+ })) ?? []
1661
+ ), Q = y ? $(((a = l.components) == null ? void 0 : a.map(({ id: E }) => w(y, E))) ?? []) : [];
1662
+ if (n) {
1663
+ const E = (...h) => {
1664
+ S.info(`[${o ? J(e) : J(O(e, "../../../../"))}] importAssets:`, ...h);
1665
+ };
1666
+ try {
1667
+ E("wait image-bin api ready"), await ds({
1668
+ resources: [`${Kt(Es)}/api/sdk/uploads`],
1669
+ validateStatus: (v) => v >= 200 && v <= 500
1670
+ }), E("image-bin api is ready");
1671
+ const h = {}, A = {};
1672
+ E("start to upload assets"), await Promise.allSettled([
1673
+ nt(Q, h, {
1674
+ getFilePath: (v) => y && O(y, v),
1675
+ onFinish: (v) => {
1676
+ E(`upload ${v.length} component assets`);
1677
+ }
1678
+ }),
1679
+ nt(C, A, {
1680
+ getFilePath: (v, X) => {
1681
+ const b = Fe(C, X.slice(0, 1));
1682
+ return u && O(u, U(b.slug), v);
1683
+ },
1684
+ onFinish: (v) => {
1685
+ E(`upload ${v.length} page assets`);
1686
+ }
1687
+ })
1688
+ ]), E("upload assets done"), global.gc && global.gc();
1689
+ } catch (h) {
1690
+ E("Error during asset import:", h);
1691
+ }
1692
+ }
1693
+ const ne = {};
1694
+ if (t) {
1695
+ const E = c && O(U(c), "../../resources/components"), h = $(
1696
+ ((p = (i = l.resources) == null ? void 0 : i.components) == null ? void 0 : p.map(({ id: A }) => w(E, A))) ?? []
1697
+ );
1698
+ h.length > 0 && (ne.components = Object.fromEntries(
1699
+ h.map((A, v) => [A.id, { index: v, component: A }])
1700
+ ));
1701
+ }
1702
+ const le = {};
1703
+ if (m && H(m)) {
1704
+ const E = Ut(m);
1705
+ for (const h of E)
1706
+ le[h] = O(m, h);
1707
+ }
1708
+ return {
1709
+ supportedLocales: l.supportedLocales,
1710
+ pageIds: C.map((E) => E.id),
1711
+ components: Object.fromEntries(Q.map((E, h) => [E.id, { index: h, data: E }])),
1712
+ pages: Object.fromEntries(C.map((E) => [E.id, E])),
1713
+ config: l.config || {},
1714
+ resources: ne,
1715
+ chunks: le,
1716
+ routeIds: L.map((E) => E.id),
1717
+ routes: Object.fromEntries(L.map((E) => [E.id, E])),
1718
+ dataSourceIds: [],
1719
+ dataSources: {}
1720
+ };
1721
+ } finally {
1722
+ o && s && ct(s, { force: !0, recursive: !0 });
1723
+ }
1724
+ }
1725
+ async function ot(e, n, {
1726
+ routes: t,
1727
+ mergeMode: s = "byUpdateTime",
1728
+ deleteRoutes: o = !1,
1729
+ publishMode: r = void 0
1730
+ } = {}) {
1731
+ try {
1732
+ r && Ms(r);
1733
+ } catch (m) {
1734
+ S.error("clear preload page cache error", { error: m });
1735
+ }
1736
+ const { pages: a, pageIds: i, routeIds: p, routes: c, supportedLocales: u } = e;
1737
+ if (r === "production") {
1738
+ let m = t ?? [], d = null;
1739
+ for (const l of p ?? []) {
1740
+ const f = c == null ? void 0 : c[l];
1741
+ 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) {
1742
+ const w = Ue({
1743
+ basePath: f.path,
1744
+ params: f.params,
1745
+ routeId: f.id,
1746
+ paramsOptions: f.paramsOptions,
1747
+ currentIndex: 0,
1748
+ currentParams: [],
1749
+ currentOptionIds: [],
1750
+ result: []
1751
+ }), D = Object.fromEntries(w.map((C) => [`${l}-${C.paramOptionIds.join("-")}`, C]));
1752
+ d = { ...d || {}, ...D }, t || (m = [...m, ...w.map((C) => `${l}-${C.paramOptionIds.join("-")}`)]);
1753
+ } else t || m.push(l);
1754
+ }
1755
+ S.info("routeIds to be published: ", m);
1756
+ for (const l of m) {
1757
+ let f = l;
1758
+ if (f.includes("-")) {
1759
+ const [C] = f.split("-");
1760
+ f = C;
1761
+ }
1762
+ const w = c == null ? void 0 : c[f];
1763
+ if (!w) {
1764
+ const C = n.pageIds.indexOf(f);
1765
+ C !== -1 && o && (n.pageIds.splice(C, 1), delete n.pages[f]);
1766
+ for (const L of n.pageIds)
1767
+ L.includes(`${f}-`) && (n.pageIds.splice(n.pageIds.indexOf(L), 1), delete n.pages[L]);
1768
+ S.info("delete main route page", f);
1769
+ continue;
1770
+ }
1771
+ if (l.includes("-") && !(d != null && d[l])) {
1772
+ const C = n.pageIds.indexOf(l);
1773
+ C !== -1 && o && (n.pageIds.splice(C, 1), delete n.pages[l]), S.info("delete page", l);
1774
+ continue;
1775
+ }
1776
+ if (!w.displayTemplateId) {
1777
+ S.info("no display template", l);
1778
+ continue;
1779
+ }
1780
+ const D = a[w.displayTemplateId];
1781
+ if (!D) {
1782
+ S.info("no template page", l);
1783
+ continue;
1784
+ }
1785
+ if (n.pageIds.includes(l)) {
1786
+ if (S.info("has need update page", l), s === "replace")
1787
+ n.pages[l] = je({
1788
+ page: D,
1789
+ route: w,
1790
+ state: e,
1791
+ routeId: l,
1792
+ routePathInfo: d == null ? void 0 : d[l]
1793
+ }), S.info("replace page", l);
1794
+ else if (s === "byUpdateTime") {
1795
+ const C = n.pages[w.id];
1796
+ (!C || w.updatedAt && w.updatedAt > C.updatedAt) && (n.pages[l] = je({
1797
+ page: D,
1798
+ route: w,
1799
+ state: e,
1800
+ routeId: l,
1801
+ routePathInfo: d == null ? void 0 : d[l]
1802
+ }), S.info("replace page by update time", l));
1803
+ }
1804
+ } else
1805
+ n.pageIds.push(l), n.pages[l] = je({
1806
+ page: D,
1807
+ route: w,
1808
+ state: e,
1809
+ routeId: l,
1810
+ routePathInfo: d == null ? void 0 : d[l]
1811
+ }), S.info("add page", l);
1812
+ }
1813
+ if (o && !t)
1814
+ for (const l of n.pageIds)
1815
+ 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));
1816
+ } else {
1817
+ for (const m of i) {
1818
+ const d = a[m];
1819
+ if (d)
1820
+ if (n.pageIds.includes(d.id)) {
1821
+ if (s === "replace")
1822
+ n.pages[d.id] = d;
1823
+ else if (s === "byUpdateTime") {
1824
+ const l = n.pages[d.id];
1825
+ (!l || d.updatedAt && d.updatedAt > l.updatedAt) && (n.pages[d.id] = d);
1826
+ }
1827
+ } else
1828
+ n.pageIds.push(d.id), n.pages[d.id] = d;
1829
+ }
1830
+ for (const m of p) {
1831
+ const d = c[m];
1832
+ if (d)
1833
+ if (n.routeIds.includes(d.id)) {
1834
+ if (s === "replace")
1835
+ n.routes[d.id] = d;
1836
+ else if (s === "byUpdateTime") {
1837
+ const l = n.routes[d.id];
1838
+ (!l || d.updatedAt && d.updatedAt > l.updatedAt) && (n.routes[d.id] = d);
1839
+ }
1840
+ } else
1841
+ n.routeIds.push(d.id), n.routes[d.id] = d;
1842
+ }
1843
+ }
1844
+ if (n.supportedLocales.splice(0, n.supportedLocales.length), n.supportedLocales.push(...os(u)), o)
1845
+ for (const m of Object.keys(n.components))
1846
+ delete n.components[m];
1847
+ let y = JSON.parse(JSON.stringify(e.components));
1848
+ y = Object.fromEntries(
1849
+ await Promise.all(
1850
+ Object.entries(y).map(async ([m, d]) => {
1851
+ const l = await Et(d == null ? void 0 : d.data);
1852
+ return [
1853
+ m,
1854
+ {
1855
+ ...d,
1856
+ data: l
1857
+ }
1858
+ ];
1859
+ })
1860
+ )
1861
+ ), Object.assign(n.components, y), Object.assign(n.config, JSON.parse(JSON.stringify(e.config))), dt(e.resources.components) || (n.resources.components = JSON.parse(JSON.stringify(e.resources.components || {})));
1862
+ }
1863
+ const Et = Be(
1864
+ async (e) => {
1865
+ var n;
1866
+ if (!dt(e == null ? void 0 : e.properties))
1867
+ return e;
1868
+ if (((n = e == null ? void 0 : e.renderer) == null ? void 0 : n.type) === "react-component") {
1869
+ const { script: t } = (e == null ? void 0 : e.renderer) || {};
1870
+ if (t && t.includes("PROPERTIES_SCHEMA"))
1871
+ try {
1872
+ const s = await Hs(t, "PROPERTIES_SCHEMA", e.id);
1873
+ s && s.length > 0 && e && (e.properties = {}, s.forEach((o, r) => {
1874
+ e != null && e.properties && (e.properties[o.id] = {
1875
+ index: r,
1876
+ data: o
1877
+ });
1878
+ }));
1879
+ } catch (s) {
1880
+ S.error("checkPropertiesFromCode error", { componentId: e.id, name: e.name }, { error: s });
1881
+ }
1882
+ }
1883
+ return e;
1884
+ },
1885
+ {
1886
+ keyGenerator: (e) => {
1887
+ var c, u, y, m;
1888
+ 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 = te("md5").update(JSON.stringify(o)).digest("hex");
1889
+ let i = "", p = "";
1890
+ return ((u = e == null ? void 0 : e.renderer) == null ? void 0 : u.type) === "react-component" && (i = te("md5").update(((y = e == null ? void 0 : e.renderer) == null ? void 0 : y.script) || "").digest("hex"), p = te("md5").update(((m = e == null ? void 0 : e.renderer) == null ? void 0 : m.editComponent) || "").digest("hex")), JSON.stringify([
1891
+ "checkPropertiesFromCode",
1892
+ n,
1893
+ t,
1894
+ s,
1895
+ a,
1896
+ r,
1897
+ i,
1898
+ p
1899
+ ]);
1900
+ },
1901
+ lruOptions: {
1902
+ max: 100,
1903
+ ttl: 1e3 * 60 * 60
1904
+ },
1905
+ subdir: "checkPropertiesFromCode"
1906
+ }
1907
+ );
1908
+ let Oe, ie, Te, Pe, He;
1909
+ function It() {
1910
+ return Oe = (async () => {
1911
+ const e = zt({
1912
+ types: [
1913
+ { did: gt, type: et },
1914
+ { did: Js, type: et }
1915
+ ]
1916
+ });
1917
+ ie = (await Promise.all(
1918
+ e.map(async (t) => {
1919
+ const s = t.path ? await wt(t.path, { importAssets: !1 }) : void 0;
1920
+ return s ? { blockletId: t.did, state: s, blockletTitle: t.title } : void 0;
1921
+ })
1922
+ )).filter((t) => !!t), Te = ie.reduce(
1923
+ (t, s) => Object.assign(
1924
+ t,
1925
+ Object.fromEntries(
1926
+ Object.values(s.state.pages).map((o) => o ? [o == null ? void 0 : o.id, { page: o, blockletId: s.blockletId }] : [])
1927
+ )
1928
+ ),
1929
+ {}
1930
+ );
1931
+ const n = ie.reduce(
1932
+ (t, s) => Object.assign(
1933
+ t,
1934
+ Object.fromEntries(
1935
+ Object.values(s.state.components).map((o) => [o.data.id, { blockletId: s.blockletId, component: o.data }])
1936
+ )
1937
+ ),
1938
+ {}
1939
+ );
1940
+ Pe = Object.fromEntries(
1941
+ await Promise.all(
1942
+ Object.entries(n).map(async ([t, s]) => {
1943
+ const o = await Et(s.component);
1944
+ return [
1945
+ t,
1946
+ {
1947
+ ...s,
1948
+ component: o
1949
+ }
1950
+ ];
1951
+ })
1952
+ )
1953
+ ), He = ie.reduce((t, s) => Object.assign(t, s.state.chunks), {});
1954
+ })(), Oe;
1955
+ }
1956
+ function rn(e) {
1957
+ const n = pt(
1958
+ async () => {
1959
+ await It().catch((t) => {
1960
+ S.error("load resource states error", { error: t });
1961
+ }), await (e == null ? void 0 : e({
1962
+ states: ie,
1963
+ pages: Te,
1964
+ components: Pe,
1965
+ chunks: He
1966
+ }));
1967
+ },
1968
+ 3e3,
1969
+ // 3s
1970
+ { leading: !1, trailing: !0 }
1971
+ );
1972
+ 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), () => {
1973
+ 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);
1974
+ };
1975
+ }
1976
+ const bt = Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"), Se = globalThis;
1977
+ var rt;
1978
+ (rt = Se[bt]) == null || rt.call(Se);
1979
+ Se[bt] = rn(async ({ pages: e, components: n }) => {
1980
+ const { projectIds: t } = q;
1981
+ S.info(`start update resource states projects(${t.length})`, t), await Promise.race([
1982
+ new Promise((s) => {
1983
+ setTimeout(() => {
1984
+ s({});
1985
+ }, 30 * 1e3);
1986
+ }),
1987
+ Promise.all(
1988
+ t.map(async (s) => {
1989
+ At({
1990
+ projectId: s,
1991
+ pages: e,
1992
+ components: n
1993
+ });
1994
+ })
1995
+ )
1996
+ ]).catch((s) => {
1997
+ S.error("update resource states failed:", s);
1998
+ });
1999
+ });
2000
+ q.startPeriodicCheck();
2001
+ process.on("beforeExit", () => {
2002
+ q.stopPeriodicCheck();
2003
+ });
2004
+ process.on("SIGINT", () => {
2005
+ q.stopPeriodicCheck(), process.exit(0);
2006
+ });
2007
+ process.on("SIGTERM", () => {
2008
+ q.stopPeriodicCheck(), process.exit(0);
2009
+ });
2010
+ async function At({
2011
+ projectId: e,
2012
+ pages: n,
2013
+ components: t
2014
+ }) {
2015
+ const s = q.sharedInstances[e];
2016
+ if (!s) {
2017
+ S.info(`projectId: ${e} not found in sharedInstances`);
2018
+ return;
2019
+ }
2020
+ s.syncedStore.resources.pages = n;
2021
+ const o = await se.findByPk(e);
2022
+ if (o != null && o.useAllResources)
2023
+ s.syncedStore.resources.components = t;
2024
+ else {
2025
+ const a = (await Ce.findAll({ where: { projectId: e } })).map((p) => p.componentId), i = Object.fromEntries(
2026
+ Object.entries(t || {}).filter(([p]) => a.includes(p))
2027
+ );
2028
+ s.syncedStore.resources.components = i;
2029
+ }
2030
+ S.info(`update [${e}] resource states:`, {
2031
+ pages: Object.keys(s.syncedStore.resources.pages || {}).length,
2032
+ components: Object.keys(s.syncedStore.resources.components || {}).length
2033
+ });
2034
+ }
2035
+ async function no() {
2036
+ S.info("trigger reload all project resource"), I.events.emit(_e);
2037
+ }
2038
+ async function Ve({
2039
+ ensureLoaded: e = !0
2040
+ } = {}) {
2041
+ return e && (Oe ?? (Oe = It()), await Oe), { states: ie, pages: Te, components: Pe, chunks: He };
2042
+ }
2043
+ export {
2044
+ gt as C,
2045
+ Ze as G,
2046
+ se as P,
2047
+ et as R,
2048
+ q as S,
2049
+ Xn as a,
2050
+ Ve as b,
2051
+ Ls as c,
2052
+ _s as d,
2053
+ Ms as e,
2054
+ $s as f,
2055
+ Zn as g,
2056
+ Us as h,
2057
+ Qn as i,
2058
+ Ee as j,
2059
+ eo as k,
2060
+ S as l,
2061
+ Hs as m,
2062
+ xe as n,
2063
+ de as o,
2064
+ to as p,
2065
+ so as q,
2066
+ sn as r,
2067
+ nn as s,
2068
+ on as t,
2069
+ wt as u,
2070
+ ot as v,
2071
+ rn as w,
2072
+ no as x
2073
+ };