@blocklet/pages-kit-inner-components 0.4.117 → 0.4.119

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