@blocklet/pages-kit-inner-components 0.6.83 → 0.6.85

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.
@@ -1,1572 +0,0 @@
1
- import { d as Ue, l as f, I as Qe, c as Xe, m as Ze, b as et } from "./components-DLwSTd_N.js";
2
- import { getYjsValue as V, syncedStore as tt } from "@syncedstore/core";
3
- import * as N from "yjs";
4
- import { setPageDataSource as st } from "@blocklet/pages-kit/utils/data-source";
5
- import { getRouteMetaDataByOptionIds as at, generateParamCombinations as Se } from "@blocklet/pages-kit/utils/route";
6
- import $e from "lodash/cloneDeep";
7
- import E from "@blocklet/sdk/lib/config";
8
- import { mkdtempSync as ot, existsSync as $, readFileSync as q, renameSync as Ce, mkdirSync as _, rmSync as Me, writeFileSync as ee, copyFileSync as rt, lstatSync as B, readdirSync as nt, createWriteStream as it } from "fs";
9
- import { join as b, basename as R, dirname as L } from "path";
10
- import { nextId as Oe } from "@blocklet/pages-kit/utils/common";
11
- import { unzipSection as ct } from "@blocklet/pages-kit/utils/page-model";
12
- import { getComponentDependencies as pt } from "@blocklet/pages-kit/utils/property";
13
- import { getComponentWebEndpoint as lt, getResources as ut, call as dt } from "@blocklet/sdk/lib/component";
14
- import { reactive as ft } from "@reactivedata/reactive";
15
- import { globSync as te } from "glob";
16
- import * as ue from "lib0/decoding";
17
- import * as k from "lib0/encoding";
18
- import Ne from "lodash/debounce";
19
- import Ie from "lodash/get";
20
- import Ee from "lodash/isEmpty";
21
- import ve from "lodash/set";
22
- import mt from "lodash/union";
23
- import { LRUCache as be } from "lru-cache";
24
- import gt from "p-limit";
25
- import { DataTypes as j, Sequelize as ht, Model as Fe, Op as _e } from "sequelize";
26
- import { pipeline as yt } from "stream/promises";
27
- import { x as St } from "tar";
28
- import { withoutTrailingSlash as It, joinURL as H } from "ufo";
29
- import Et from "wait-on";
30
- import { Awareness as bt, encodeAwarenessUpdate as Te, removeAwarenessStates as wt, applyAwarenessUpdate as At } from "y-protocols/awareness";
31
- import { writeUpdate as Pt, writeSyncStep1 as Ct, readSyncMessage as Ot } from "y-protocols/sync";
32
- import * as G from "yaml";
33
- import { m as je } from "./html-DOgzvdOd.js";
34
- import "sqlite3";
35
- import "@blocklet/pages-kit/types/state";
36
- const vt = j.sqlite.DATE.parse;
37
- j.sqlite.DATE.parse = (t, e) => typeof t == "number" ? new Date(t) : vt(t, e);
38
- const F = new ht({
39
- dialect: "sqlite",
40
- storage: Ue,
41
- benchmark: process.env.ENABLE_SEQUELIZE_BENCHMARK === "true",
42
- retry: {
43
- match: [/SQLITE_BUSY/],
44
- name: "query",
45
- max: 10
46
- },
47
- // eslint-disable-next-line no-console
48
- logging: process.env.ENABLE_SEQUELIZE_LOGGING === "true" ? console.log : !1
49
- // logQueryParameters: true,
50
- });
51
- F.query("pragma journal_mode = WAL;");
52
- F.query("pragma synchronous = normal;");
53
- F.query("pragma journal_size_limit = 33554432;");
54
- F.query("pragma cache_size = -2000;");
55
- F.query("pragma mmap_size = 33554432;");
56
- process.on("SIGINT", async () => {
57
- await F.close(), process.exit(0);
58
- });
59
- process.on("SIGTERM", async () => {
60
- await F.close(), process.exit(0);
61
- });
62
- async function Tt(t, e) {
63
- try {
64
- if (t.getDialect() !== "sqlite")
65
- return;
66
- const [s] = await t.query("SELECT 1");
67
- if (!s || s.length === 0)
68
- return;
69
- await t.query("PRAGMA shrink_memory;");
70
- } catch (s) {
71
- if (s.name === "SequelizeConnectionError" || s?.message && /closed!/.test(s.message))
72
- return;
73
- console.error("Failed to cleanup SQLite memory", e, s);
74
- }
75
- }
76
- let me = null;
77
- me && clearInterval(me);
78
- me = setInterval(
79
- async () => {
80
- f.info("Start cleanupSqliteMemory"), await Tt(F, Ue), f.info("End cleanupSqliteMemory");
81
- },
82
- 60 * 1e3 * 10
83
- // 10 minutes
84
- );
85
- class we extends Fe {
86
- // Foreign key to Component
87
- }
88
- we.init(
89
- {
90
- id: {
91
- type: j.UUID,
92
- allowNull: !1,
93
- primaryKey: !0,
94
- defaultValue: j.UUIDV4
95
- },
96
- projectId: {
97
- type: j.UUID,
98
- allowNull: !1
99
- },
100
- componentId: {
101
- type: j.STRING,
102
- allowNull: !1
103
- }
104
- },
105
- { sequelize: F, tableName: "ProjectComponents", timestamps: !1 }
106
- );
107
- class M extends Fe {
108
- static async getProjectByIdOrSlug(e) {
109
- return M.findOne({
110
- where: {
111
- [_e.or]: [{ id: e }, { slug: e }]
112
- }
113
- });
114
- }
115
- }
116
- M.init(
117
- {
118
- id: {
119
- type: j.UUID,
120
- defaultValue: j.UUIDV4,
121
- primaryKey: !0
122
- },
123
- name: {
124
- type: j.STRING,
125
- allowNull: !1
126
- },
127
- description: j.TEXT,
128
- createdAt: j.DATE,
129
- updatedAt: j.DATE,
130
- createdBy: {
131
- type: j.STRING,
132
- allowNull: !1
133
- },
134
- updatedBy: {
135
- type: j.STRING,
136
- allowNull: !1
137
- },
138
- slug: j.STRING,
139
- icon: j.STRING,
140
- pinnedAt: j.DATE,
141
- useAllResources: j.BOOLEAN,
142
- npmSecret: j.STRING,
143
- relatedBlocklets: {
144
- type: j.JSON,
145
- allowNull: !1,
146
- defaultValue: {},
147
- get() {
148
- const t = this.getDataValue("relatedBlocklets");
149
- if (typeof t == "object")
150
- return t ?? {};
151
- try {
152
- return t ? JSON.parse(t) : {};
153
- } catch (e) {
154
- return f.error("Failed to parse relatedBlocklets", { error: e, rawValue: t }), {};
155
- }
156
- },
157
- set(t) {
158
- try {
159
- this.setDataValue("relatedBlocklets", t ? JSON.stringify(t) : "{}");
160
- } catch (e) {
161
- f.error("Failed to set relatedBlocklets", { error: e, value: t }), this.setDataValue("relatedBlocklets", "{}");
162
- }
163
- }
164
- },
165
- productionState: {
166
- type: j.JSON,
167
- allowNull: !1,
168
- defaultValue: {},
169
- get() {
170
- const t = this.getDataValue("productionState");
171
- if (typeof t == "object")
172
- return t ?? {};
173
- try {
174
- return t ? JSON.parse(t) : {};
175
- } catch (e) {
176
- return f.error("Failed to parse productionState", { error: e, rawValue: t }), {};
177
- }
178
- },
179
- set(t) {
180
- try {
181
- this.setDataValue("productionState", t ? JSON.stringify(t) : "{}");
182
- } catch (e) {
183
- f.error("Failed to set productionState", { error: e, value: t }), this.setDataValue("productionState", "{}");
184
- }
185
- }
186
- }
187
- },
188
- { sequelize: F, paranoid: !0 }
189
- );
190
- M.hasMany(we, {
191
- foreignKey: "projectId",
192
- as: "components"
193
- });
194
- const jt = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o", ke = "page", ge = "trigger-reload-project-resource", xe = jt, kt = "z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM";
195
- function se(t) {
196
- t.observeDeep((e) => {
197
- e.some((s) => s.changes.keys.has("updatedAt") || s.changes.keys.has("publishedAt")) || t.set("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
198
- });
199
- }
200
- function Be() {
201
- return ot(b(E.env.dataDir, "tmp-"));
202
- }
203
- function ae(t, e, s = []) {
204
- return Array.isArray(t) ? t.flatMap((a, o) => ae(a, e, [...s, o])) : typeof t == "object" ? t === null ? [] : Object.entries(t).flatMap(([a, o]) => ae(o, e, [...s, a])) : e(t) ? [s] : [];
205
- }
206
- function D(t) {
207
- return t.filter((e) => e != null);
208
- }
209
- function Dt(t) {
210
- t.pages && Object.keys(t.pages).forEach((s) => {
211
- const a = V(t.pages[s]);
212
- a && a instanceof N.Map && se(a);
213
- });
214
- const e = V(t.pages);
215
- e && e instanceof N.Map && e.observe((s) => {
216
- s.changes.keys.forEach((a, o) => {
217
- if (a.action === "add") {
218
- const r = V(t.pages[o]);
219
- r && r instanceof N.Map && se(r);
220
- }
221
- });
222
- });
223
- }
224
- function Rt(t) {
225
- t.routes && Object.keys(t.routes).forEach((s) => {
226
- const a = V(t.routes?.[s]);
227
- a && a instanceof N.Map && se(a);
228
- });
229
- const e = V(t.routes);
230
- e && e instanceof N.Map && e.observe((s) => {
231
- s.changes.keys.forEach((a, o) => {
232
- if (a.action === "add") {
233
- const r = V(t.routes?.[o]);
234
- r && r instanceof N.Map && se(r);
235
- }
236
- });
237
- });
238
- }
239
- function Lt(t, e) {
240
- for (const s of e || Object.keys(t.routes || {})) {
241
- let a = s, o = [];
242
- if (s.includes("-")) {
243
- const [r, ...i] = s.split("-");
244
- a = r, o = i || [];
245
- }
246
- if (t.routes?.[a] !== void 0) {
247
- t.routes[a].publishedAt = (/* @__PURE__ */ new Date()).toISOString();
248
- const r = t.routes[a];
249
- if (!r || !r.params || r.params.length === 0)
250
- continue;
251
- if (s.includes("-") && o.length > 0) {
252
- const i = at(o, r);
253
- i && (i.publishedAt = (/* @__PURE__ */ new Date()).toISOString());
254
- }
255
- if (!e) {
256
- const i = Se({
257
- basePath: r.path,
258
- params: r.params,
259
- routeId: r.id,
260
- paramsOptions: r.paramsOptions,
261
- currentIndex: 0,
262
- currentParams: [],
263
- currentOptionIds: [],
264
- result: []
265
- });
266
- for (const p of i)
267
- p.routeMetaData ??= {}, p.routeMetaData.publishedAt = (/* @__PURE__ */ new Date()).toISOString();
268
- }
269
- }
270
- }
271
- }
272
- function de({
273
- page: t,
274
- route: e,
275
- state: s,
276
- routeId: a,
277
- routePathInfo: o
278
- }) {
279
- f.info(
280
- `Executing datasource data assembly, routeId: ${a}, routePathInfo: ${JSON.stringify(o)}`
281
- );
282
- const r = {
283
- ...$e(t),
284
- id: a,
285
- slug: o?.path ?? e.path,
286
- createdAt: e.createdAt,
287
- updatedAt: o?.routeMetaData?.updatedAt ?? e.updatedAt,
288
- publishedAt: o?.routeMetaData?.publishedAt ?? e.publishedAt,
289
- isPublic: (o?.routeMetaData?.isPublic ?? e.isPublic) && e.isPublic
290
- };
291
- for (const i of s.supportedLocales) {
292
- if (e.dataSource) {
293
- let p = e.id;
294
- o && (p = o.paramOptionIds.join("-"));
295
- const l = e.dataSource.pathDataMappings?.[p]?.dataCache?.[i.locale] ?? e.dataSource.pathDataMappings?.[p]?.dataCache?.[s.config.defaultLocale || "en"];
296
- if (!l)
297
- continue;
298
- st(r, s, i.locale, l);
299
- }
300
- o && o.routeMetaData && (o.routeMetaData.publishedAt = (/* @__PURE__ */ new Date()).toISOString());
301
- }
302
- return r;
303
- }
304
- ["true", "1", "yes", "y"].includes(process.env.USE_FS_CACHE_HTML ?? "");
305
- const Ut = 60 * 60 * 1e3, Y = new be({
306
- max: 100,
307
- ttl: Ut,
308
- ttlResolution: 10 * 1e3,
309
- // 10 seconds
310
- allowStale: !0
311
- });
312
- function $t(t, e = []) {
313
- let s = 0;
314
- const a = Array.from(Y.keys()), o = t.map((r) => It(r));
315
- for (const r of a)
316
- for (const i of o) {
317
- if (je(r, { currentPath: i })) {
318
- Y.delete(r), s++, f.info(`[Cache CLEAR] key: ${r}`);
319
- break;
320
- }
321
- for (const p of e)
322
- if (je(r, { currentPath: `/${p}${i}` })) {
323
- Y.delete(r), s++, f.info(`[Cache CLEAR] key: ${r}`);
324
- break;
325
- }
326
- }
327
- return f.info(`[Cache CLEAR] cleared ${s} entries for paths:`, o), s;
328
- }
329
- function Mt() {
330
- const t = Y.size;
331
- return Y.clear(), f.info(`[Cache CLEAR ALL] cleared ${t} entries`), t;
332
- }
333
- E.events.on(E.Events.envUpdate, Mt);
334
- const { uploadToMediaKit: Nt } = require("@blocklet/uploader-server"), Ae = /^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/, W = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i, De = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi, Ft = 1e4, _t = 3e4, X = 0, fe = 1, xt = 0, Bt = 1, he = E, K = b(process.env.BLOCKLET_DATA_DIR, "site-state"), Os = ["production", "draft"], vs = ["production"];
335
- function oe(t) {
336
- return t?.replace(/\//g, "|") || "";
337
- }
338
- function Gt() {
339
- const t = he.env.languages?.map((s) => ({ locale: s.code, name: s.name })) || [], e = t[0]?.locale || "en";
340
- return {
341
- pageIds: [],
342
- pages: {},
343
- routeIds: [],
344
- routes: {},
345
- dataSourceIds: [],
346
- dataSources: {},
347
- components: {},
348
- supportedLocales: t,
349
- config: { defaultLocale: e },
350
- resources: {}
351
- };
352
- }
353
- class O extends N.Doc {
354
- constructor(e) {
355
- super(), this.options = e, $(this.draftYjsFilePath) && N.applyUpdate(this, q(this.draftYjsFilePath)), this.syncedStore = ft(
356
- tt(
357
- {
358
- pages: {},
359
- pageIds: [],
360
- components: {},
361
- supportedLocales: [],
362
- config: {},
363
- resources: {},
364
- routeIds: [],
365
- routes: {},
366
- dataSourceIds: [],
367
- dataSources: {}
368
- },
369
- this
370
- )
371
- ), this.initObserver(), this.on("update", this.updateHandler), this.awareness = new bt(this), this.awareness.on("update", this.awarenessChangeHandler), this.ensureDataStructure();
372
- }
373
- // 延迟释放时间:5 分钟
374
- static RELEASE_DELAY = 5 * 60 * 1e3;
375
- // 定期检查间隔:2 小时
376
- static PERIODIC_CHECK_INTERVAL = 2 * 60 * 60 * 1e3;
377
- // 2 hours
378
- static sharedInstances = {};
379
- static pageUrlMapCache = new be({
380
- max: 100,
381
- ttl: 1e3 * 60 * 60 * 24
382
- // 1 day
383
- });
384
- // 定期检查定时器
385
- static periodicCheckTimer;
386
- // safe delete project state dir
387
- static safeDeleteProjectStateDir(e) {
388
- if (!e)
389
- throw new Error("Should provide project context");
390
- try {
391
- const s = b(K, e), a = b(K, `@del-${e}`);
392
- Ce(s, a);
393
- } catch (s) {
394
- f.error("Failed to safe delete project state dir:", s);
395
- }
396
- }
397
- static async getProjectIds() {
398
- return (await M.findAll({ attributes: ["id"], raw: !0 }))?.map((e) => e.id);
399
- }
400
- /** @deprecated 不再使用这个 getter 了,仅作为兼容性处理,请使用 getProjectIds 代替 */
401
- static get projectIds() {
402
- return te("*/", {
403
- cwd: K,
404
- ignore: ["@del-*", "@tmp-*", ".*", "staging", "production", "@backup-*", "undefined"]
405
- // Ignore temp directories and hidden files
406
- });
407
- }
408
- /** @deprecated 不再使用这个 getter 了,仅作为兼容性处理 */
409
- static get allShared() {
410
- return this.projectIds.map((e) => O.shared(e));
411
- }
412
- static shared(e) {
413
- if (!e)
414
- throw new Error("Should provide project context");
415
- let s = O.sharedInstances[e];
416
- return s || (s = new O({
417
- path: b(K, e)
418
- }), O.sharedInstances[e] = s, s);
419
- }
420
- // 轻量级 production 状态获取,不加载 draft 数据
421
- static async getProductionState(e) {
422
- const s = await M.findByPk(e, {
423
- attributes: ["productionState"]
424
- });
425
- if (Ee(s?.productionState)) {
426
- const a = b(K, e, "production"), o = await Ve(a, { includeResources: !0 }) ?? Gt();
427
- if (!o?.config?.defaultLocale) {
428
- o.config ??= {};
429
- const r = he.env.languages?.map((i) => ({ locale: i.code, name: i.name })) || [];
430
- o.config.defaultLocale = r[0]?.locale;
431
- }
432
- return o;
433
- }
434
- return s?.productionState;
435
- }
436
- destroy() {
437
- this.cancelRelease(), this.save({ flush: !0 }), this.conns.forEach((s, a) => this.closeConn(a)), this.awareness.destroy();
438
- const e = R(this.options.path);
439
- delete O.sharedInstances[e], super.destroy();
440
- }
441
- initObserver() {
442
- Dt(this.syncedStore), Rt(this.syncedStore);
443
- }
444
- get draftYjsFilePath() {
445
- return b(this.options.path, "draft.yjs");
446
- }
447
- static async getStateByProjectId(e, s) {
448
- if (s === "draft") {
449
- const a = O.shared(e);
450
- return JSON.parse(JSON.stringify(a.syncedStore));
451
- }
452
- return O.getProductionState(e);
453
- }
454
- async getState(e) {
455
- if (e === "draft")
456
- return JSON.parse(JSON.stringify(this.syncedStore));
457
- const s = R(this.options.path);
458
- return O.getProductionState(s);
459
- }
460
- async setState(e, s) {
461
- const a = await Kt(s, { exportAssets: !1, includeResources: !0 }), o = this.getPublishDir(e);
462
- if (_(L(o), { recursive: !0 }), Me(o, { force: !0, recursive: !0 }), Ce(a, o), e === "production") {
463
- const r = R(this.options.path);
464
- O.pageUrlMapCache.delete(r), await M.update({ productionState: { ...s } }, { where: { id: r } });
465
- }
466
- }
467
- getPublishDir(e) {
468
- return b(this.options.path, e);
469
- }
470
- syncedStore;
471
- conns = /* @__PURE__ */ new Map();
472
- awareness;
473
- // 延迟释放定时器
474
- releaseTimer;
475
- awarenessChangeHandler = ({ added: e, updated: s, removed: a }, o) => {
476
- const r = e.concat(s, a);
477
- if (o !== null) {
478
- const l = this.conns.get(o);
479
- l && (e.forEach((y) => {
480
- l.add(y);
481
- }), a.forEach((y) => {
482
- l.delete(y);
483
- }));
484
- }
485
- const i = k.createEncoder();
486
- k.writeVarUint(i, fe), k.writeVarUint8Array(i, Te(this.awareness, r));
487
- const p = k.toUint8Array(i);
488
- this.conns.forEach((l, y) => this.send(y, p));
489
- };
490
- updateHandler = (e) => {
491
- const s = k.createEncoder();
492
- k.writeVarUint(s, X), Pt(s, e);
493
- const a = k.toUint8Array(s);
494
- this.conns.forEach((o, r) => this.send(r, a));
495
- };
496
- ensureDataStructure = () => {
497
- const { supportedLocales: e, pages: s, pageIds: a, config: o, routes: r, routeIds: i } = this.syncedStore;
498
- {
499
- const p = new Set(Object.keys(s));
500
- let l = 0;
501
- for (; l < a.length; ) {
502
- const y = a[l];
503
- p.has(y) ? (p.delete(y), l++) : a.splice(l, 1);
504
- }
505
- }
506
- {
507
- const p = new Set(Object.keys(r));
508
- let l = 0;
509
- for (; l < i.length; ) {
510
- const y = i[l];
511
- p.has(y) ? (p.delete(y), l++) : i.splice(l, 1);
512
- }
513
- }
514
- e.splice(0, e.length), e.push(...he.env.languages.map((p) => ({ locale: p.code, name: p.name }))), o.defaultLocale = e[0]?.locale;
515
- {
516
- let p = 0;
517
- const l = /* @__PURE__ */ new Set();
518
- for (; p < e.length; ) {
519
- const { locale: y } = e[p];
520
- l.has(y) ? e.splice(p, 1) : (p++, l.add(y));
521
- }
522
- }
523
- };
524
- send = (e, s) => {
525
- e.readyState !== xt && e.readyState !== Bt && this.closeConn(e);
526
- try {
527
- e.send(s, (a) => {
528
- a && this.closeConn(e);
529
- });
530
- } catch {
531
- this.closeConn(e);
532
- }
533
- };
534
- closeConn = (e) => {
535
- if (e.removeAllListeners(), this.conns.has(e)) {
536
- const s = this.conns.get(e);
537
- this.conns.delete(e), s && wt(this.awareness, Array.from(s), null);
538
- }
539
- e.close(), this.checkAndScheduleRelease();
540
- };
541
- // 检查并调度延迟释放
542
- checkAndScheduleRelease() {
543
- this.conns.size === 0 && this.scheduleRelease();
544
- }
545
- // 调度延迟释放
546
- scheduleRelease() {
547
- this.cancelRelease();
548
- const e = R(this.options.path);
549
- this.releaseTimer = setTimeout(() => {
550
- f.info(`[SiteState] releasing instance due to no active connections: ${e}`), this.conns.size === 0 && (this.releaseTimer = void 0, this.destroy());
551
- }, O.RELEASE_DELAY), f.info(`[SiteState] scheduled release for project ${e} in ${O.RELEASE_DELAY / 1e3}s`);
552
- }
553
- // 取消延迟释放
554
- cancelRelease() {
555
- if (this.releaseTimer) {
556
- clearTimeout(this.releaseTimer), this.releaseTimer = void 0;
557
- const e = R(this.options.path);
558
- f.info(`[SiteState] cancelled scheduled release for project ${e}`);
559
- }
560
- }
561
- autoSave = Ne(() => {
562
- _(L(this.draftYjsFilePath), { recursive: !0 }), ee(this.draftYjsFilePath, N.encodeStateAsUpdate(this));
563
- }, Ft);
564
- save = ({ flush: e = !1 } = {}) => {
565
- this.autoSave(), e && this.autoSave.flush();
566
- };
567
- publish = async ({ mode: e, routes: s }) => {
568
- const a = await this.getState("draft"), o = await this.getState("production");
569
- await Le(a, o, { routes: s, mergeMode: "replace", deleteRoutes: !0, publishMode: e }), o.config.publishedAt = (/* @__PURE__ */ new Date()).getTime(), Lt(this.syncedStore, s), await this.setState(e, o), await this.clearPageCacheForRoutes(s, o);
570
- };
571
- mergeState = async (e, s) => {
572
- const a = JSON.parse(JSON.stringify(s));
573
- e.config.fontFamily ??= {};
574
- const o = a.config?.fontFamily, r = e.config?.fontFamily;
575
- e.config.fontFamily.title = o?.title || r?.title, e.config.fontFamily.description = o?.description || r?.description, await new Promise((i, p) => {
576
- this.transact(async () => {
577
- try {
578
- const l = await Le(e, s);
579
- i(l);
580
- } catch (l) {
581
- p(l);
582
- }
583
- });
584
- });
585
- };
586
- clearPageCacheForRoutes = async (e, s) => {
587
- const a = R(this.options.path), r = (await M.findByPk(a))?.slug || a;
588
- let i = e;
589
- (!i || i.length === 0) && (i = s.pageIds ?? []), f.info(`[SiteState] clearing page cache for project ${a}, routes:`, i || []);
590
- const p = s.supportedLocales.map((w) => w.locale), l = [], y = i.filter((w) => s.pageIds?.includes(w));
591
- for (const w of y) {
592
- const I = s.pages[w].slug;
593
- r && r !== a && (r === "/" ? l.push(I) : l.push(`/${r}${I}`)), l.push(`/${a}${I}`);
594
- }
595
- if (l.length > 0)
596
- try {
597
- const w = $t(l, p);
598
- f.info(`[SiteState] cleared ${w} page cache entries for project ${a}, routes:`, i);
599
- } catch {
600
- }
601
- };
602
- addConnection = (e) => {
603
- if (this.conns.has(e))
604
- return;
605
- this.cancelRelease(), e.binaryType = "arraybuffer", this.conns.set(e, /* @__PURE__ */ new Set()), e.on("message", (o) => this.messageListener(e, new Uint8Array(o)));
606
- let s = !0;
607
- const a = setInterval(() => {
608
- if (!s)
609
- this.conns.has(e) && this.closeConn(e), clearInterval(a);
610
- else if (this.conns.has(e)) {
611
- s = !1;
612
- try {
613
- e.ping();
614
- } catch {
615
- this.closeConn(e), clearInterval(a);
616
- }
617
- }
618
- }, _t);
619
- e.on("close", () => {
620
- this.closeConn(e), clearInterval(a);
621
- }), e.on("pong", () => {
622
- s = !0;
623
- });
624
- {
625
- const o = k.createEncoder();
626
- k.writeVarUint(o, X), Ct(o, this), this.send(e, k.toUint8Array(o));
627
- const r = this.awareness.getStates();
628
- if (r.size > 0) {
629
- const i = k.createEncoder();
630
- k.writeVarUint(i, fe), k.writeVarUint8Array(i, Te(this.awareness, Array.from(r.keys()))), this.send(e, k.toUint8Array(i));
631
- }
632
- }
633
- };
634
- messageListener = (e, s) => {
635
- try {
636
- const a = k.createEncoder(), o = ue.createDecoder(s), r = ue.readVarUint(o);
637
- switch (r) {
638
- case X:
639
- k.writeVarUint(a, X), Ot(o, a, this, null), k.length(a) > 1 && (this.ensureDataStructure(), this.send(e, k.toUint8Array(a)));
640
- break;
641
- case fe: {
642
- At(this.awareness, ue.readVarUint8Array(o), e);
643
- break;
644
- }
645
- default:
646
- f.warn(`Unsupported messageType ${r}`);
647
- }
648
- } catch (a) {
649
- f.error(a);
650
- }
651
- this.save();
652
- };
653
- // 这个方法还是需要动态的,因为可能会动态修改 projectSlug、语言之类的
654
- static async pageUrlMap(e, s) {
655
- let a = [];
656
- s ? a = [s] : a = await this.getProjectIds();
657
- let o = {};
658
- if (e === "production" && a?.length) {
659
- const r = new Map(a?.map((i) => [i, !0]) || []);
660
- for (const i of a) {
661
- const p = O.pageUrlMapCache.get(i);
662
- p && (o = { ...o, ...p }, r.delete(i));
663
- }
664
- a = Array.from(r.keys());
665
- }
666
- if (a?.length) {
667
- const r = await M.findAll({
668
- where: {
669
- id: {
670
- [_e.in]: a
671
- }
672
- }
673
- });
674
- await Promise.all(
675
- r?.map(async (i) => {
676
- const p = i.id, l = i.slug || p, y = {}, w = e === "production" && i?.productionState ? i.productionState : await O.getStateByProjectId(i.id, e), T = mt(
677
- E.env.languages?.map((u) => u.code) || [],
678
- w.supportedLocales?.map((u) => u.locale) || []
679
- ), I = (u, c) => {
680
- l && (y[H("/", l, u)] = {
681
- ...c,
682
- shouldRedirect: !0,
683
- mainPage: !0
684
- }), y[H("/", p, u)] = {
685
- ...c,
686
- shouldRedirect: !0,
687
- mainPage: !0
688
- };
689
- for (const g of T) {
690
- const C = { ...c, locale: g };
691
- y[H("/", g, p, u)] = C, l && (y[H("/", g, l, u)] = C);
692
- }
693
- };
694
- if (e === "draft")
695
- for (const u of w.routeIds || []) {
696
- const c = w?.routes?.[u];
697
- if (!c) continue;
698
- if (c.params && c.params.length > 0) {
699
- const m = Se({
700
- basePath: c.path,
701
- params: c.params,
702
- routeId: c.id,
703
- paramsOptions: c.paramsOptions,
704
- currentIndex: 0,
705
- currentParams: [],
706
- currentOptionIds: [],
707
- result: []
708
- });
709
- for (const d of m) {
710
- const h = d.path, A = {
711
- projectId: p,
712
- projectSlug: l,
713
- pageSlug: h,
714
- pageId: c.displayTemplateId || "",
715
- routeId: u,
716
- // default locale
717
- defaultLocale: T?.[0],
718
- locales: T,
719
- publishedAt: w.config.publishedAt,
720
- isPublic: c.isPublic && d?.routeMetaData?.isPublic
721
- };
722
- I(h, A);
723
- }
724
- }
725
- const g = c.path, C = {
726
- projectId: p,
727
- projectSlug: l,
728
- pageSlug: g,
729
- pageId: c.displayTemplateId || "",
730
- routeId: u,
731
- // default locale
732
- defaultLocale: T?.[0],
733
- locales: T,
734
- publishedAt: w.config.publishedAt,
735
- isPublic: c.isPublic
736
- };
737
- I(g, C);
738
- }
739
- for (const u of w.pageIds || []) {
740
- const c = w.pages[u];
741
- if (!c || e === "production" && !c.isPublic)
742
- continue;
743
- const g = c.slug, C = i.slug || p, m = {
744
- projectId: p,
745
- projectSlug: C,
746
- pageSlug: g,
747
- pageId: u,
748
- // default locale
749
- defaultLocale: T?.[0],
750
- locales: T,
751
- publishedAt: w.config.publishedAt,
752
- isPublic: c.isPublic,
753
- templateConfig: c.templateConfig
754
- };
755
- I(g, m);
756
- }
757
- e === "production" && O.pageUrlMapCache.set(p, y), o = { ...o, ...y };
758
- })
759
- );
760
- }
761
- return o;
762
- }
763
- getDocumentSize() {
764
- return N.encodeStateAsUpdate(this).byteLength;
765
- }
766
- static getInstancesSizeInfo() {
767
- const e = [];
768
- for (const [s, a] of Object.entries(O.sharedInstances)) {
769
- const o = a.getDocumentSize();
770
- e.push({
771
- projectId: s,
772
- sizeInBytes: o,
773
- sizeInMB: `${(o / (1024 * 1024)).toFixed(2)} MB`,
774
- activeConnections: a.conns.size
775
- });
776
- }
777
- return e;
778
- }
779
- // 启动定期检查
780
- static startPeriodicCheck() {
781
- this.periodicCheckTimer || (this.periodicCheckTimer = setInterval(() => {
782
- this.performPeriodicCheck();
783
- }, this.PERIODIC_CHECK_INTERVAL), f.info(
784
- `[SiteState] periodic check started, interval: ${this.PERIODIC_CHECK_INTERVAL / (60 * 60 * 1e3)} hours`
785
- ));
786
- }
787
- // 停止定期检查
788
- static stopPeriodicCheck() {
789
- this.periodicCheckTimer && (clearInterval(this.periodicCheckTimer), this.periodicCheckTimer = void 0, f.info("[SiteState] periodic check stopped"));
790
- }
791
- // 执行定期检查
792
- static performPeriodicCheck() {
793
- const e = Object.keys(O.sharedInstances).length, s = [], a = [];
794
- for (const [o, r] of Object.entries(O.sharedInstances))
795
- r.conns.size === 0 ? s.push({ projectId: o, instance: r }) : a.push({ projectId: o, connections: r.conns.size });
796
- if (f.info(
797
- `[SiteState] periodic check summary: total instances: ${e}, with connections: ${a.length}, without connections: ${s.length}`
798
- ), s.length > 0) {
799
- f.info(
800
- `[SiteState] releasing ${s.length} instances without connections:`,
801
- s.map((r) => r.projectId)
802
- );
803
- let o = 0;
804
- for (const { projectId: r, instance: i } of s)
805
- try {
806
- f.info(`[SiteState] releasing instance due to periodic check: ${r}`), i.destroy(), o++;
807
- } catch (p) {
808
- f.error(`[SiteState] failed to release instance ${r} during periodic check:`, p);
809
- }
810
- f.info(
811
- `[SiteState] periodic check completed: ${o}/${s.length} instances released successfully`
812
- );
813
- } else e > 0 ? f.debug("[SiteState] periodic check: all instances have active connections") : f.debug("[SiteState] periodic check: no instances exist");
814
- }
815
- }
816
- async function Vt(t, e, s) {
817
- if (!t || !$(t) || !B(t).isFile())
818
- return null;
819
- let a = s[t];
820
- return a || (a = (async () => {
821
- try {
822
- return (await Nt({
823
- filePath: t,
824
- fileName: e
825
- }))?.data?.filename;
826
- } catch (o) {
827
- return f.error(`Failed to upload asset ${t}:`, o), null;
828
- }
829
- })(), s[t] = a), a;
830
- }
831
- const zt = async (t, e) => {
832
- const s = R(t), a = await dt({
833
- name: xe,
834
- path: H("/uploads", s),
835
- responseType: "stream",
836
- method: "GET"
837
- });
838
- if (a.status >= 200 && a.status < 400) {
839
- const o = it(e);
840
- await yt(a.data, o);
841
- } else
842
- throw new Error(`download asset failed ${a.status}`);
843
- }, Jt = async (t, e) => {
844
- await Promise.all(
845
- t.map(async (s) => {
846
- try {
847
- await zt(s, b(e, R(s)));
848
- } catch (a) {
849
- f.error(`Failed to export assets: ${s}, ${a}`);
850
- }
851
- })
852
- );
853
- };
854
- function Ge(t) {
855
- return Ae.test(t) ? [t] : W.test(t) ? (De.lastIndex = 0, Array.from(t.matchAll(De)).map((s) => s[1]).filter((s) => !!s)) : [];
856
- }
857
- async function Z(t, e, s) {
858
- const { getFilename: a, exportAssets: o } = s, r = b(e, a(t));
859
- if (_(L(r), { recursive: !0 }), ee(r, G.stringify(t)), o) {
860
- const p = ae(
861
- t,
862
- (l) => typeof l == "string" && (Ae.test(l) || W.test(l))
863
- ).map((l) => {
864
- const y = Ie(t, l);
865
- return Ge(y);
866
- }).flat().filter(Boolean);
867
- await Jt(p, L(r));
868
- }
869
- }
870
- const ye = new be({
871
- max: 100,
872
- ttl: 1 * 60 * 1e3
873
- // 1 minute
874
- });
875
- async function Re(t, e, s) {
876
- const a = ae(
877
- t,
878
- (p) => typeof p == "string" && (Ae.test(p) || W.test(p))
879
- ), o = gt(2), r = a.map(
880
- (p) => o(async () => {
881
- try {
882
- const l = Ie(t, p), y = Ge(l);
883
- for (const w of y) {
884
- const T = R(w), I = s.getFilePath(w, p), u = I ? `${I}:${T}` : T, c = ye.get(u);
885
- if (c) {
886
- W.test(l) || ve(t, p, c);
887
- return;
888
- }
889
- const g = await Vt(I, T, e);
890
- g && (W.test(l) || ve(t, p, g), ye.set(u, g));
891
- }
892
- } catch (l) {
893
- f.error(`Failed to process upload for path ${p.join(".")}:`, l.message || l.reason);
894
- }
895
- })
896
- ), i = await Promise.allSettled(r);
897
- s.onFinish?.(i);
898
- }
899
- async function Kt(t, {
900
- exportAssets: e,
901
- pageIds: s = "all",
902
- componentIds: a = "all",
903
- rawConfig: o,
904
- includeResources: r = !1,
905
- routeIds: i = "all"
906
- } = {}) {
907
- const p = s === "all" ? t.pageIds : s, l = pt({
908
- state: t,
909
- pageIds: p,
910
- componentIds: a === "all" ? Object.keys(t.components) : a
911
- });
912
- Object.entries(t.components).forEach(([n, S]) => {
913
- S.data?.renderer?.type === "component-template" && l.push(n);
914
- });
915
- const y = i === "all" ? t.routeIds : i, w = (n) => ({
916
- id: n.id,
917
- name: n.name,
918
- isTemplateSection: n.isTemplateSection ?? !1,
919
- templateDescription: n.templateDescription,
920
- /** @deprecated 已经废弃,llmConfig 从 component / resources.component 中获取 */
921
- // llmConfig: section.llmConfig,
922
- component: n.component,
923
- config: n.config,
924
- visibility: n.visibility,
925
- sections: n?.sectionIds ? D(
926
- n?.sectionIds?.map((S) => {
927
- const v = n.sections?.[S];
928
- return v && w(v);
929
- })
930
- ) : void 0
931
- /** @deprecated 已经废弃,数据在 page.dataSource 中管理 */
932
- // properties: section.locales?.[locale] ?? {},
933
- }), T = (n, S) => ({
934
- id: n.id,
935
- createdAt: n.createdAt,
936
- updatedAt: n.updatedAt,
937
- publishedAt: n.publishedAt,
938
- isPublic: n.isPublic ?? !0,
939
- templateConfig: n.templateConfig,
940
- meta: n.locales?.[S] ?? {},
941
- sections: D(
942
- n.sectionIds.map((v) => {
943
- const x = n.sections[v];
944
- return x && w(x);
945
- })
946
- ),
947
- // 将 dataSource.sectionId.locale 转换为 dataSource.sectionId
948
- dataSource: Object.fromEntries(
949
- Object.entries(n.dataSource || {}).map(([v, x]) => [v, x?.[S] ?? {}])
950
- )
951
- }), I = (n) => ({
952
- id: n.id,
953
- createdAt: n.createdAt,
954
- updatedAt: n.updatedAt,
955
- publishedAt: n.publishedAt,
956
- path: n.path,
957
- handler: n.handler,
958
- isPublic: n.isPublic ?? !0,
959
- params: n.params ?? [],
960
- enabledGenerate: n.enabledGenerate ?? !1,
961
- displayTemplateId: n.displayTemplateId,
962
- dataSource: n.dataSource
963
- }), u = D(
964
- y.map((n) => {
965
- const S = t.routes[n];
966
- return S && I(S);
967
- })
968
- ), c = D(
969
- t.supportedLocales.map((n) => n.locale).flatMap(
970
- (n) => p.map((S) => {
971
- const v = t.pages[S];
972
- return v && {
973
- locale: n,
974
- slug: v.slug,
975
- page: T(v, n)
976
- };
977
- })
978
- )
979
- ), g = Be(), C = b(g, "pages");
980
- _(C, { recursive: !0 });
981
- const m = b(g, "components");
982
- _(m, { recursive: !0 });
983
- const d = b(g, "routes");
984
- _(d, { recursive: !0 });
985
- for (const { locale: n, slug: S, page: v } of c)
986
- await Z(v, C, {
987
- getFilename: () => `${oe(S) || "index"}.${n}.yml`,
988
- exportAssets: e
989
- });
990
- for (const n of u)
991
- await Z(n, d, {
992
- // getFilename: () => `${sanitizeSlug(route.path)}.yml`,
993
- getFilename: () => `${oe(n.path) || "index"}.yml`,
994
- exportAssets: e
995
- });
996
- for (const n of l) {
997
- const S = t.components[n]?.data;
998
- S && await Z(S, m, {
999
- getFilename: (v) => `${v.name || "unnamed"}.${v.id}.yml`,
1000
- exportAssets: e
1001
- });
1002
- }
1003
- const h = b(g, ".blocklet/pages/pages.config.yml");
1004
- _(L(h), { recursive: !0 });
1005
- const A = {
1006
- pages: D(
1007
- p.map((n) => {
1008
- const S = t.pages[n];
1009
- return S && { id: n, slug: S.slug };
1010
- })
1011
- ),
1012
- routes: D(
1013
- y.map((n) => {
1014
- const S = t.routes[n];
1015
- return S && { id: n, path: S.path };
1016
- })
1017
- ),
1018
- components: D(
1019
- l.map((n) => {
1020
- const S = t.components[n]?.data;
1021
- return S && {
1022
- id: n,
1023
- name: S.name
1024
- };
1025
- })
1026
- ),
1027
- ...r ? {
1028
- resources: {
1029
- components: D(
1030
- Object.keys(t.resources?.components || {}).filter((n) => l.includes(n)).map((n) => ({
1031
- id: n,
1032
- name: t.resources?.components?.[n]?.component?.name
1033
- }))
1034
- )
1035
- }
1036
- } : {},
1037
- supportedLocales: t.supportedLocales,
1038
- config: t.config
1039
- };
1040
- ee(h, G.stringify(A));
1041
- const P = b(g, "config.source.json");
1042
- if (o && ee(P, JSON.stringify(o)), r) {
1043
- const n = b(g, "resources"), S = b(n, "components");
1044
- _(S, { recursive: !0 });
1045
- for (const z of Object.keys(t?.resources?.components ?? {}).filter(
1046
- (U) => l.includes(U)
1047
- )) {
1048
- const U = t.resources?.components?.[z]?.component;
1049
- U && await Z(U, S, {
1050
- getFilename: (J) => `${J.name || "unnamed"}.${J.id}.yml`,
1051
- exportAssets: e
1052
- });
1053
- }
1054
- const v = b(g, "chunks");
1055
- _(v, { recursive: !0 });
1056
- const x = qt();
1057
- for (const z of Object.keys(t?.resources?.components ?? {}).filter(
1058
- (U) => l.includes(U)
1059
- )) {
1060
- const U = t.resources?.components?.[z]?.component;
1061
- if (U && U.renderer?.type === "react-component") {
1062
- const J = U.renderer?.chunks ?? [];
1063
- if (J?.length > 0)
1064
- for (const pe of J) {
1065
- const Pe = b(v, pe), le = x?.[pe];
1066
- try {
1067
- le && $(le) && !$(Pe) && rt(le, Pe);
1068
- } catch (We) {
1069
- f.error(`copy chunk ${pe} error`, We.message);
1070
- }
1071
- }
1072
- }
1073
- }
1074
- }
1075
- return g;
1076
- }
1077
- async function Ve(t, { importAssets: e, includeResources: s } = {}) {
1078
- if (!$(t))
1079
- return null;
1080
- let a, o = !1;
1081
- try {
1082
- B(t).isDirectory() ? a = t : /\.(tgz|gz|tar)$/.test(t) && (o = !0, a = Be(), await St({ file: t, C: a }));
1083
- const r = te("**/.blocklet/pages/pages.config.yml", { cwd: a, absolute: !0 }).at(0), i = r && b(L(r), "../../pages"), p = r && b(L(r), "../../components"), l = r && b(L(r), "../../routes");
1084
- if (!r)
1085
- return null;
1086
- const y = G.parse(q(r).toString()), w = (m, d, h) => {
1087
- let A = b(m, `${d}${h ? `.${h}` : ""}.yml`);
1088
- return (!$(A) || !B(A).isFile()) && (A = b(m, d, `index${h ? `.${h}` : ""}.yml`), !$(A) || !B(A)) ? null : G.parse(q(A).toString());
1089
- }, T = (m, d) => {
1090
- try {
1091
- const h = te(`*.${d}.yml`, { cwd: m, absolute: !0 })[0];
1092
- return h ? G.parse(q(h).toString()) : null;
1093
- } catch (h) {
1094
- f.error("parse component error", h);
1095
- }
1096
- return null;
1097
- }, I = (m, d) => {
1098
- let h = b(m, `${d}.yml`);
1099
- return (!$(h) || !B(h).isFile()) && (h = b(m, d, "index.yml"), !$(h) || !B(h)) ? null : G.parse(q(h).toString());
1100
- }, u = D(
1101
- y.pages.map(({ slug: m }) => {
1102
- const d = D(
1103
- y.supportedLocales.map(({ locale: P }) => {
1104
- const n = i ? w(i, oe(m), P) : void 0;
1105
- if (n)
1106
- return { locale: P, page: n };
1107
- const S = i ? w(i, m, P) : void 0;
1108
- return S && { locale: P, page: S };
1109
- })
1110
- ), h = d[0]?.page;
1111
- if (!h)
1112
- return null;
1113
- const A = h.sections.map(ct);
1114
- return {
1115
- id: h.id || Oe(),
1116
- createdAt: h.createdAt,
1117
- updatedAt: h.updatedAt,
1118
- publishedAt: h.publishedAt,
1119
- isPublic: h.isPublic ?? !0,
1120
- templateConfig: h.templateConfig,
1121
- slug: m,
1122
- sections: Object.fromEntries(A.map((P) => [P.id, P])),
1123
- sectionIds: A.map((P) => P.id),
1124
- locales: Object.fromEntries(d.map(({ locale: P, page: n }) => [P, n.meta])),
1125
- dataSource: h.dataSource ? Object.fromEntries(
1126
- // 获取 dataSource 中所有 section ID
1127
- [...new Set(d.flatMap(({ page: P }) => Object.keys(P.dataSource ?? {})))].map((P) => [
1128
- P,
1129
- Object.fromEntries(
1130
- d.map(({ locale: n, page: S }) => {
1131
- const v = S.dataSource?.[P];
1132
- return [n, v || {}];
1133
- })
1134
- )
1135
- ])
1136
- ) : Object.fromEntries(
1137
- // 获取所有 section ID
1138
- [...new Set(d.flatMap(({ page: P }) => P.sections.map((n) => n.id)))].map((P) => [
1139
- P,
1140
- Object.fromEntries(
1141
- d.map(({ locale: n, page: S }) => {
1142
- const v = S.dataSource?.[P];
1143
- if (v)
1144
- return [n, v];
1145
- const x = S.sections.find((z) => z.id === P);
1146
- return [n, x?.properties || {}];
1147
- })
1148
- )
1149
- ])
1150
- )
1151
- };
1152
- })
1153
- ), c = D(
1154
- y?.routes?.map(({ path: m }) => {
1155
- const d = l ? I(l, oe(m)) : void 0;
1156
- return {
1157
- ...d,
1158
- id: d?.id || Oe(),
1159
- createdAt: d?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1160
- updatedAt: d?.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1161
- publishedAt: (/* @__PURE__ */ new Date(0)).toISOString(),
1162
- path: d?.path ?? `/${d?.id}`,
1163
- params: d?.params,
1164
- handler: d?.handler ?? "Pages Kit",
1165
- isPublic: d?.isPublic ?? !0,
1166
- enabledGenerate: d?.enabledGenerate ?? !1,
1167
- displayTemplateId: d?.displayTemplateId ?? void 0,
1168
- dataSource: d?.dataSource ?? {}
1169
- };
1170
- }) ?? []
1171
- ), g = p ? D(y.components?.map(({ id: m }) => T(p, m)) ?? []) : [];
1172
- if (e) {
1173
- const m = (...d) => {
1174
- f.info(`[${o ? R(t) : R(b(t, "../../../../"))}] importAssets:`, ...d);
1175
- };
1176
- try {
1177
- m("wait image-bin api ready"), await Et({
1178
- resources: [`${lt(Qe)}/api/sdk/uploads`],
1179
- validateStatus: (A) => A >= 200 && A <= 500
1180
- }), m("image-bin api is ready");
1181
- const d = {}, h = {};
1182
- m("start to upload assets"), await Promise.allSettled([
1183
- Re(g, d, {
1184
- getFilePath: (A) => p && b(p, A),
1185
- onFinish: (A) => {
1186
- m(`upload ${A.length} component assets`);
1187
- }
1188
- }),
1189
- Re(u, h, {
1190
- getFilePath: (A, P) => {
1191
- const n = Ie(u, P.slice(0, 1));
1192
- return i && b(i, L(n.slug), A);
1193
- },
1194
- onFinish: (A) => {
1195
- m(`upload ${A.length} page assets`);
1196
- }
1197
- })
1198
- ]), m("upload assets done"), ye.clear(), global.gc && global.gc();
1199
- } catch (d) {
1200
- m("Error during asset import:", d);
1201
- }
1202
- }
1203
- const C = {};
1204
- if (s) {
1205
- const m = r && b(L(r), "../../resources/components"), d = D(
1206
- y.resources?.components?.map(({ id: h }) => T(m, h)) ?? []
1207
- );
1208
- d.length > 0 && (C.components = Object.fromEntries(
1209
- d.map((h, A) => [h.id, { index: A, component: h }])
1210
- ));
1211
- }
1212
- return {
1213
- supportedLocales: y.supportedLocales,
1214
- pageIds: u.map((m) => m.id),
1215
- components: Object.fromEntries(g.map((m, d) => [m.id, { index: d, data: m }])),
1216
- pages: Object.fromEntries(u.map((m) => [m.id, m])),
1217
- config: y.config || {},
1218
- resources: C,
1219
- routeIds: c.map((m) => m.id),
1220
- routes: Object.fromEntries(c.map((m) => [m.id, m])),
1221
- dataSourceIds: [],
1222
- dataSources: {}
1223
- };
1224
- } finally {
1225
- o && a && Me(a, { force: !0, recursive: !0 });
1226
- }
1227
- }
1228
- async function Le(t, e, {
1229
- routes: s,
1230
- mergeMode: a = "byUpdateTime",
1231
- deleteRoutes: o = !1,
1232
- publishMode: r = void 0
1233
- } = {}) {
1234
- try {
1235
- r && Xe(r);
1236
- } catch (I) {
1237
- f.error("clear preload page cache error", { error: I });
1238
- }
1239
- const { pages: i, pageIds: p, routeIds: l, routes: y, supportedLocales: w } = t;
1240
- if (r === "production") {
1241
- let I = s ?? [], u = null;
1242
- for (const c of l ?? []) {
1243
- const g = y?.[c];
1244
- if (g?.params && g?.params.length > 0 && g?.paramsOptions && g?.paramsOptions.length > 0) {
1245
- const C = Se({
1246
- basePath: g.path,
1247
- params: g.params,
1248
- routeId: g.id,
1249
- paramsOptions: g.paramsOptions,
1250
- currentIndex: 0,
1251
- currentParams: [],
1252
- currentOptionIds: [],
1253
- result: []
1254
- }), m = Object.fromEntries(C.map((d) => [`${c}-${d.paramOptionIds.join("-")}`, d]));
1255
- u = { ...u || {}, ...m }, s || (I = [...I, ...C.map((d) => `${c}-${d.paramOptionIds.join("-")}`)]);
1256
- } else s || I.push(c);
1257
- }
1258
- f.info("routeIds to be published: ", I);
1259
- for (const c of I) {
1260
- let g = c;
1261
- if (g.includes("-")) {
1262
- const [d] = g.split("-");
1263
- g = d;
1264
- }
1265
- const C = y?.[g];
1266
- if (!C) {
1267
- const d = e.pageIds.indexOf(g);
1268
- d !== -1 && o && (e.pageIds.splice(d, 1), delete e.pages[g]);
1269
- for (const h of e.pageIds)
1270
- h.includes(`${g}-`) && (e.pageIds.splice(e.pageIds.indexOf(h), 1), delete e.pages[h]);
1271
- f.info("delete main route page", g);
1272
- continue;
1273
- }
1274
- if (c.includes("-") && !u?.[c]) {
1275
- const d = e.pageIds.indexOf(c);
1276
- d !== -1 && o && (e.pageIds.splice(d, 1), delete e.pages[c]), f.info("delete page", c);
1277
- continue;
1278
- }
1279
- if (!C.displayTemplateId) {
1280
- f.info("no display template", c);
1281
- continue;
1282
- }
1283
- const m = i[C.displayTemplateId];
1284
- if (!m) {
1285
- f.info("no template page", c);
1286
- continue;
1287
- }
1288
- if (e.pageIds.includes(c)) {
1289
- if (f.info("has need update page", c), a === "replace")
1290
- e.pages[c] = de({
1291
- page: m,
1292
- route: C,
1293
- state: t,
1294
- routeId: c,
1295
- routePathInfo: u?.[c]
1296
- }), f.info("replace page", c);
1297
- else if (a === "byUpdateTime") {
1298
- const d = e.pages[C.id];
1299
- (!d || C.updatedAt && C.updatedAt > d.updatedAt) && (e.pages[c] = de({
1300
- page: m,
1301
- route: C,
1302
- state: t,
1303
- routeId: c,
1304
- routePathInfo: u?.[c]
1305
- }), f.info("replace page by update time", c));
1306
- }
1307
- } else
1308
- e.pageIds.push(c), e.pages[c] = de({
1309
- page: m,
1310
- route: C,
1311
- state: t,
1312
- routeId: c,
1313
- routePathInfo: u?.[c]
1314
- }), f.info("add page", c);
1315
- }
1316
- if (o && !s)
1317
- for (const c of e.pageIds)
1318
- I?.includes(c) || (delete e.pages[c], f.info("delete page", c)), e.pageIds = [...e.pageIds].filter((g) => I?.includes(g));
1319
- } else {
1320
- for (const I of p) {
1321
- const u = i[I];
1322
- if (u)
1323
- if (e.pageIds.includes(u.id)) {
1324
- if (a === "replace")
1325
- e.pages[u.id] = u;
1326
- else if (a === "byUpdateTime") {
1327
- const c = e.pages[u.id];
1328
- (!c || u.updatedAt && u.updatedAt > c.updatedAt) && (e.pages[u.id] = u);
1329
- }
1330
- } else
1331
- e.pageIds.push(u.id), e.pages[u.id] = u;
1332
- }
1333
- for (const I of l) {
1334
- const u = y[I];
1335
- if (u)
1336
- if (e.routeIds.includes(u.id)) {
1337
- if (a === "replace")
1338
- e.routes[u.id] = u;
1339
- else if (a === "byUpdateTime") {
1340
- const c = e.routes[u.id];
1341
- (!c || u.updatedAt && u.updatedAt > c.updatedAt) && (e.routes[u.id] = u);
1342
- }
1343
- } else
1344
- e.routeIds.push(u.id), e.routes[u.id] = u;
1345
- }
1346
- }
1347
- if (e.supportedLocales.splice(0, e.supportedLocales.length), e.supportedLocales.push(...$e(w)), o)
1348
- for (const I of Object.keys(e.components))
1349
- delete e.components[I];
1350
- let T = JSON.parse(JSON.stringify(t.components));
1351
- T = Object.fromEntries(
1352
- await Promise.all(
1353
- Object.entries(T).map(async ([I, u]) => {
1354
- const c = await ze(u?.data);
1355
- return [
1356
- I,
1357
- {
1358
- ...u,
1359
- data: c
1360
- }
1361
- ];
1362
- })
1363
- )
1364
- ), Object.assign(e.components, T), Object.assign(e.config, JSON.parse(JSON.stringify(t.config))), Ee(t.resources.components) || (e.resources.components = JSON.parse(JSON.stringify(t.resources.components || {})));
1365
- }
1366
- const ze = Ze(
1367
- async (t) => {
1368
- if (!Ee(t?.properties))
1369
- return t;
1370
- if (t?.renderer?.type === "react-component") {
1371
- const { script: e, PROPERTIES_SCHEMA: s } = t?.renderer || {};
1372
- if (s || e && e.includes("PROPERTIES_SCHEMA"))
1373
- try {
1374
- const a = await et(
1375
- e ?? "",
1376
- "PROPERTIES_SCHEMA",
1377
- t.id,
1378
- s
1379
- );
1380
- a && a.length > 0 && t && (t.properties = {}, a.forEach((o, r) => {
1381
- t?.properties && (t.properties[o.id] = {
1382
- index: r,
1383
- data: o
1384
- });
1385
- }));
1386
- } catch (a) {
1387
- f.error("getPropertiesFromCode error", { componentId: t.id, name: t.name }, { error: a });
1388
- }
1389
- }
1390
- return t;
1391
- },
1392
- {
1393
- subdir: "getPropertiesFromCode"
1394
- }
1395
- );
1396
- let re, Q, ne, ie;
1397
- const Je = () => ut({
1398
- types: [
1399
- { did: xe, type: ke },
1400
- { did: kt, type: ke }
1401
- ]
1402
- }), qt = () => {
1403
- const t = Je(), e = {};
1404
- return t.forEach((s) => {
1405
- const a = te("**/.blocklet/pages/pages.config.yml", { cwd: s.path, absolute: !0 }).at(0), o = a && b(L(a), "../../chunks");
1406
- if (o && $(o)) {
1407
- const r = nt(o);
1408
- for (const i of r)
1409
- e[i] = b(o, i);
1410
- }
1411
- }), e;
1412
- };
1413
- function Ke() {
1414
- return re = (async () => {
1415
- const t = Je();
1416
- Q = (await Promise.all(
1417
- t.map(async (s) => {
1418
- const a = s.path ? await Ve(s.path, { importAssets: !1 }) : void 0;
1419
- return a ? { blockletId: s.did, state: a, blockletTitle: s.title } : void 0;
1420
- })
1421
- )).filter((s) => !!s), ne = Q.reduce(
1422
- (s, a) => Object.assign(
1423
- s,
1424
- Object.fromEntries(
1425
- Object.values(a.state.pages).map((o) => o ? [o?.id, { page: o, blockletId: a.blockletId }] : [])
1426
- )
1427
- ),
1428
- {}
1429
- );
1430
- const e = Q.reduce(
1431
- (s, a) => Object.assign(
1432
- s,
1433
- Object.fromEntries(
1434
- Object.values(a.state.components).map((o) => [o.data.id, { blockletId: a.blockletId, component: o.data }])
1435
- )
1436
- ),
1437
- {}
1438
- );
1439
- ie = Object.fromEntries(
1440
- await Promise.all(
1441
- Object.entries(e).map(async ([s, a]) => {
1442
- const o = await ze(a.component);
1443
- return [
1444
- s,
1445
- {
1446
- ...a,
1447
- component: o
1448
- }
1449
- ];
1450
- })
1451
- )
1452
- );
1453
- })(), re;
1454
- }
1455
- function Ht(t) {
1456
- const e = Ne(
1457
- async () => {
1458
- await Ke().catch((s) => {
1459
- f.error("load resource states error", { error: s });
1460
- }), await t?.({
1461
- states: Q,
1462
- pages: ne,
1463
- components: ie
1464
- });
1465
- },
1466
- 3e3,
1467
- // 3s
1468
- { leading: !1, trailing: !0 }
1469
- );
1470
- return e(), E.events.on(E.Events.componentAdded, e), E.events.on(E.Events.componentRemoved, e), E.events.on(E.Events.componentStarted, e), E.events.on(E.Events.componentStopped, e), E.events.on(E.Events.componentUpdated, e), E.events.on(ge, e), () => {
1471
- E.events.off(E.Events.componentAdded, e), E.events.off(E.Events.componentRemoved, e), E.events.off(E.Events.componentStarted, e), E.events.off(E.Events.componentStopped, e), E.events.off(E.Events.componentUpdated, e), E.events.off(ge, e);
1472
- };
1473
- }
1474
- const qe = Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"), He = Symbol.for("GLOBAL_ENV_UPDATE_LISTENER_KEY"), ce = globalThis;
1475
- ce[qe]?.();
1476
- ce[qe] = Ht(async ({ pages: t, components: e }) => {
1477
- const s = await O.getProjectIds();
1478
- f.info(`start update resource states projects(${s.length})`, s), await Promise.race([
1479
- new Promise((a) => {
1480
- setTimeout(() => {
1481
- a({});
1482
- }, 30 * 1e3);
1483
- }),
1484
- Promise.all(
1485
- s.map(async (a) => {
1486
- Ye({
1487
- projectId: a,
1488
- pages: t,
1489
- components: e
1490
- });
1491
- })
1492
- )
1493
- ]).catch((a) => {
1494
- f.error("update resource states failed:", a);
1495
- });
1496
- });
1497
- ce[He]?.();
1498
- ce[He] = () => {
1499
- const t = () => {
1500
- O.pageUrlMapCache.clear(), f.info("[Cache CLEAR ALL] clear all page url map cache by env update");
1501
- };
1502
- return E.events.on(E.Events.envUpdate, t), () => {
1503
- E.events.off(E.Events.envUpdate, t);
1504
- };
1505
- };
1506
- O.startPeriodicCheck();
1507
- process.on("beforeExit", () => {
1508
- O.stopPeriodicCheck();
1509
- });
1510
- process.on("SIGINT", () => {
1511
- O.stopPeriodicCheck(), process.exit(0);
1512
- });
1513
- process.on("SIGTERM", () => {
1514
- O.stopPeriodicCheck(), process.exit(0);
1515
- });
1516
- async function Ye({
1517
- projectId: t,
1518
- pages: e,
1519
- components: s
1520
- }) {
1521
- const a = O.sharedInstances[t];
1522
- if (!a) {
1523
- f.info(`projectId: ${t} not found in sharedInstances`);
1524
- return;
1525
- }
1526
- if (a.syncedStore.resources.pages = e, (await M.findByPk(t))?.useAllResources)
1527
- a.syncedStore.resources.components = s;
1528
- else {
1529
- const i = (await we.findAll({ where: { projectId: t } })).map((l) => l.componentId), p = Object.fromEntries(
1530
- Object.entries(s || {}).filter(([l]) => i.includes(l))
1531
- );
1532
- a.syncedStore.resources.components = p;
1533
- }
1534
- f.info(`update [${t}] resource states:`, {
1535
- pages: Object.keys(a.syncedStore.resources.pages || {}).length,
1536
- components: Object.keys(a.syncedStore.resources.components || {}).length
1537
- });
1538
- }
1539
- async function Ts(t) {
1540
- return Ye({
1541
- projectId: t,
1542
- pages: ne,
1543
- components: ie
1544
- });
1545
- }
1546
- async function js() {
1547
- f.info("trigger reload all project resource"), E.events.emit(ge);
1548
- }
1549
- async function ks({
1550
- ensureLoaded: t = !0
1551
- } = {}) {
1552
- return t && (re ??= Ke(), await re), { states: Q, pages: ne, components: ie };
1553
- }
1554
- export {
1555
- xe as C,
1556
- M as P,
1557
- ke as R,
1558
- O as S,
1559
- K as a,
1560
- Os as b,
1561
- vs as c,
1562
- Gt as d,
1563
- zt as e,
1564
- Jt as f,
1565
- ks as g,
1566
- Ve as h,
1567
- Ht as i,
1568
- js as j,
1569
- Le as m,
1570
- Kt as t,
1571
- Ts as u
1572
- };