@blocklet/pages-kit-inner-components 0.6.7 → 0.6.9

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