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

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