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

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