@blocklet/pages-kit-inner-components 0.1.4 → 0.1.6

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,959 +0,0 @@
1
- import { l as P, c as Fe, g as _e } from "./components-Bo3_pN-Y.js";
2
- import { memoize as Me } from "@blocklet/quickjs";
3
- import { getComponentWebEndpoint as $e, getResources as Be, call as xe } from "@blocklet/sdk/lib/component";
4
- import g from "@blocklet/sdk/lib/config";
5
- import { reactive as Ve } from "@reactivedata/reactive";
6
- import { syncedStore as Ge, getYjsValue as se } from "@syncedstore/core";
7
- import { mkdirSync as F, writeFileSync as X, existsSync as x, readFileSync as H, renameSync as fe, rmSync as Ie, lstatSync as Y, mkdtempSync as Je, createWriteStream as qe } from "fs";
8
- import { globSync as ae } from "glob";
9
- import * as ne from "lib0/decoding";
10
- import * as I from "lib0/encoding";
11
- import { debounce as Te, pick as ze, union as Ke, get as le, cloneDeep as He, isEmpty as Ye, set as me } from "lodash";
12
- import { LRUCache as Oe } from "lru-cache";
13
- import { customAlphabet as We } from "nanoid";
14
- import Xe from "p-limit";
15
- import Qe, { join as b, dirname as k, basename as $ } from "path";
16
- import { pipeline as Ze } from "stream/promises";
17
- import { x as et } from "tar";
18
- import { joinURL as B } from "ufo";
19
- import tt from "wait-on";
20
- import { encodeAwarenessUpdate as ge, removeAwarenessStates as st, applyAwarenessUpdate as nt, Awareness as rt } from "y-protocols/awareness";
21
- import { writeUpdate as ot, writeSyncStep1 as at, readSyncMessage as it } from "y-protocols/sync";
22
- import * as V from "yaml";
23
- import * as M from "yjs";
24
- import ct from "lodash/isNil";
25
- import { DataTypes as v, Sequelize as lt, Model as Pe, Op as pt } from "sequelize";
26
- import "sqlite3";
27
- g.env.mode;
28
- const dt = "image-bin";
29
- g.env.INIT_TEMPLATE_PATH;
30
- const ut = process.env.DATABASE_URL || Qe.join(g.env.dataDir, "db/pages-kit.db"), he = g, Xt = () => g.env.tenantMode === "multiple", Qt = () => {
31
- var t;
32
- return (ct(he.env.preferences.multiTenantAllProjectAccessPassports) ? [] : (t = he.env.preferences.multiTenantAllProjectAccessPassports) == null ? void 0 : t.split(",")) || [];
33
- }, ft = v.sqlite.DATE.parse;
34
- v.sqlite.DATE.parse = (t, s) => typeof t == "number" ? new Date(t) : ft(t, s);
35
- const q = new lt({
36
- dialect: "sqlite",
37
- storage: ut,
38
- benchmark: process.env.ENABLE_SEQUELIZE_BENCHMARK === "true",
39
- retry: {
40
- match: [/SQLITE_BUSY/],
41
- name: "query",
42
- max: 10
43
- },
44
- // eslint-disable-next-line no-console
45
- logging: process.env.ENABLE_SEQUELIZE_LOGGING === "true" ? console.log : !1
46
- // logQueryParameters: true,
47
- });
48
- q.query("pragma journal_mode = WAL;");
49
- q.query("pragma synchronous = normal;");
50
- q.query("pragma journal_size_limit = 67108864;");
51
- class te extends Pe {
52
- // Foreign key to Component
53
- }
54
- te.init(
55
- {
56
- id: {
57
- type: v.UUID,
58
- allowNull: !1,
59
- primaryKey: !0,
60
- defaultValue: v.UUIDV4
61
- },
62
- projectId: {
63
- type: v.UUID,
64
- allowNull: !1
65
- },
66
- componentId: {
67
- type: v.STRING,
68
- allowNull: !1
69
- }
70
- },
71
- { sequelize: q, tableName: "ProjectComponents", timestamps: !1 }
72
- );
73
- class _ extends Pe {
74
- static async getProjectByIdOrSlug(s) {
75
- return _.findOne({
76
- where: {
77
- [pt.or]: [{ id: s }, { slug: s }]
78
- }
79
- });
80
- }
81
- }
82
- _.init(
83
- {
84
- id: {
85
- type: v.UUID,
86
- defaultValue: v.UUIDV4,
87
- primaryKey: !0
88
- },
89
- name: {
90
- type: v.STRING,
91
- allowNull: !1
92
- },
93
- description: v.TEXT,
94
- createdAt: v.DATE,
95
- updatedAt: v.DATE,
96
- createdBy: {
97
- type: v.STRING,
98
- allowNull: !1
99
- },
100
- updatedBy: {
101
- type: v.STRING,
102
- allowNull: !1
103
- },
104
- slug: v.STRING,
105
- icon: v.STRING,
106
- pinnedAt: v.DATE,
107
- useAllResources: v.BOOLEAN,
108
- relatedBlocklets: {
109
- type: v.JSON,
110
- allowNull: !1,
111
- defaultValue: {},
112
- get() {
113
- return this.getDataValue("relatedBlocklets") || {};
114
- },
115
- set(t) {
116
- this.setDataValue("relatedBlocklets", JSON.stringify(t || {}));
117
- }
118
- }
119
- },
120
- { sequelize: q, paranoid: !0 }
121
- );
122
- _.hasMany(te, {
123
- foreignKey: "projectId",
124
- as: "components"
125
- });
126
- const mt = "z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o", ye = "page", ie = "trigger-reload-project-resource", De = mt, gt = "z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV", { uploadToMediaKit: ht } = require("@blocklet/uploader-server"), Se = We("abcdefghijklmnopqrstuvwxyz0123456789", 16), pe = /^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/, G = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i, we = /mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi, yt = 1e4, St = 3e4, z = 0, re = 1, wt = 0, Et = 1, ce = g, K = b(process.env.BLOCKLET_DATA_DIR, "site-state"), Zt = ["production", "draft"], es = ["production"];
127
- function je(t) {
128
- return (t == null ? void 0 : t.replace(/\//g, "|")) || "";
129
- }
130
- function At() {
131
- var e;
132
- const t = ce.env.languages.map((n) => ({ locale: n.code, name: n.name })), s = (e = t[0]) == null ? void 0 : e.locale;
133
- return {
134
- pageIds: [],
135
- pages: {},
136
- components: {},
137
- supportedLocales: t,
138
- config: { defaultLocale: s },
139
- resources: {}
140
- };
141
- }
142
- const R = class R extends M.Doc {
143
- constructor(s) {
144
- super(), this.options = s, this.states = {}, this.conns = /* @__PURE__ */ new Map(), this.awarenessChangeHandler = ({ added: e, updated: n, removed: r }, a) => {
145
- const l = e.concat(n, r);
146
- if (a !== null) {
147
- const c = this.conns.get(a);
148
- c && (e.forEach((u) => {
149
- c.add(u);
150
- }), r.forEach((u) => {
151
- c.delete(u);
152
- }));
153
- }
154
- const i = I.createEncoder();
155
- I.writeVarUint(i, re), I.writeVarUint8Array(i, ge(this.awareness, l));
156
- const o = I.toUint8Array(i);
157
- this.conns.forEach((c, u) => this.send(u, o));
158
- }, this.updateHandler = (e) => {
159
- const n = I.createEncoder();
160
- I.writeVarUint(n, z), ot(n, e);
161
- const r = I.toUint8Array(n);
162
- this.conns.forEach((a, l) => this.send(l, r));
163
- }, this.ensureDataStructure = () => {
164
- var l;
165
- const { supportedLocales: e, pages: n, pageIds: r, config: a } = this.syncedStore;
166
- {
167
- const i = new Set(Object.keys(n));
168
- let o = 0;
169
- for (; o < r.length; ) {
170
- const c = r[o];
171
- i.has(c) ? (i.delete(c), o++) : r.splice(o, 1);
172
- }
173
- }
174
- e.splice(0, e.length), e.push(...ce.env.languages.map((i) => ({ locale: i.code, name: i.name }))), a.defaultLocale = (l = e[0]) == null ? void 0 : l.locale;
175
- {
176
- let i = 0;
177
- const o = /* @__PURE__ */ new Set();
178
- for (; i < e.length; ) {
179
- const { locale: c } = e[i];
180
- o.has(c) ? e.splice(i, 1) : (i++, o.add(c));
181
- }
182
- }
183
- }, this.send = (e, n) => {
184
- e.readyState !== wt && e.readyState !== Et && this.closeConn(e);
185
- try {
186
- e.send(n, (r) => {
187
- r && this.closeConn(e);
188
- });
189
- } catch {
190
- this.closeConn(e);
191
- }
192
- }, this.closeConn = (e) => {
193
- if (e.removeAllListeners(), this.conns.has(e)) {
194
- const n = this.conns.get(e);
195
- this.conns.delete(e), n && st(this.awareness, Array.from(n), null);
196
- }
197
- e.close();
198
- }, this.autoSave = Te(() => {
199
- F(k(this.draftYjsFilePath), { recursive: !0 }), X(this.draftYjsFilePath, M.encodeStateAsUpdate(this));
200
- }, yt), this.save = ({ flush: e = !1 } = {}) => {
201
- this.autoSave(), e && this.autoSave.flush();
202
- }, this.publish = async ({ mode: e, pages: n }) => {
203
- const r = await this.getState("draft"), a = await this.getState("production");
204
- await be(r, a, { pages: n, pageMergeMode: "replace", deletePages: !0, publishMode: e }), a.config.publishedAt = (/* @__PURE__ */ new Date()).getTime();
205
- for (const l of n || Object.keys(this.syncedStore.pages))
206
- this.syncedStore.pages[l] && (this.syncedStore.pages[l].publishedAt = (/* @__PURE__ */ new Date()).toISOString());
207
- await this.setState(e, a);
208
- }, this.mergeState = async (e, n) => {
209
- var i, o, c;
210
- const r = JSON.parse(JSON.stringify(n));
211
- (i = e.config).fontFamily ?? (i.fontFamily = {});
212
- const a = (o = r.config) == null ? void 0 : o.fontFamily, l = (c = e.config) == null ? void 0 : c.fontFamily;
213
- e.config.fontFamily.title = (a == null ? void 0 : a.title) || (l == null ? void 0 : l.title), e.config.fontFamily.description = (a == null ? void 0 : a.description) || (l == null ? void 0 : l.description), await new Promise((u, p) => {
214
- this.transact(async () => {
215
- try {
216
- const h = await be(e, n);
217
- u(h);
218
- } catch (h) {
219
- p(h);
220
- }
221
- });
222
- });
223
- }, this.addConnection = (e) => {
224
- if (this.conns.has(e))
225
- return;
226
- e.binaryType = "arraybuffer", this.conns.set(e, /* @__PURE__ */ new Set()), e.on("message", (a) => this.messageListener(e, new Uint8Array(a)));
227
- let n = !0;
228
- const r = setInterval(() => {
229
- if (!n)
230
- this.conns.has(e) && this.closeConn(e), clearInterval(r);
231
- else if (this.conns.has(e)) {
232
- n = !1;
233
- try {
234
- e.ping();
235
- } catch {
236
- this.closeConn(e), clearInterval(r);
237
- }
238
- }
239
- }, St);
240
- e.on("close", () => {
241
- this.closeConn(e), clearInterval(r);
242
- }), e.on("pong", () => {
243
- n = !0;
244
- });
245
- {
246
- const a = I.createEncoder();
247
- I.writeVarUint(a, z), at(a, this), this.send(e, I.toUint8Array(a));
248
- const l = this.awareness.getStates();
249
- if (l.size > 0) {
250
- const i = I.createEncoder();
251
- I.writeVarUint(i, re), I.writeVarUint8Array(i, ge(this.awareness, Array.from(l.keys()))), this.send(e, I.toUint8Array(i));
252
- }
253
- }
254
- }, this.messageListener = (e, n) => {
255
- try {
256
- const r = I.createEncoder(), a = ne.createDecoder(n), l = ne.readVarUint(a);
257
- switch (l) {
258
- case z:
259
- I.writeVarUint(r, z), it(a, r, this, null), I.length(r) > 1 && (this.ensureDataStructure(), this.send(e, I.toUint8Array(r)));
260
- break;
261
- case re: {
262
- nt(this.awareness, ne.readVarUint8Array(a), e);
263
- break;
264
- }
265
- default:
266
- P.warn(`Unsupported messageType ${l}`);
267
- }
268
- } catch (r) {
269
- P.error(r);
270
- }
271
- this.save();
272
- }, x(this.draftYjsFilePath) && M.applyUpdate(this, H(this.draftYjsFilePath)), this.syncedStore = Ve(
273
- Ge(
274
- { pages: {}, pageIds: [], components: {}, supportedLocales: [], config: {}, resources: {} },
275
- this
276
- )
277
- ), this.initObserver(), this.on("update", this.updateHandler), this.awareness = new rt(this), this.awareness.on("update", this.awarenessChangeHandler), this.ensureDataStructure();
278
- }
279
- // safe delete project state dir
280
- static safeDeleteProjectStateDir(s) {
281
- if (!s)
282
- throw new Error("Should provide project context");
283
- try {
284
- const e = b(K, s), n = b(K, `@del-${s}`);
285
- fe(e, n);
286
- } catch (e) {
287
- P.error("Failed to safe delete project state dir:", e);
288
- }
289
- }
290
- static get projectIds() {
291
- return ae("*/", {
292
- cwd: K,
293
- ignore: ["@del-*", "@tmp-*", ".*", "staging", "production", "@backup-*"]
294
- // Ignore temp directories and hidden files
295
- });
296
- }
297
- static get allShared() {
298
- return this.projectIds.map((s) => R.shared(s));
299
- }
300
- static shared(s) {
301
- if (!s)
302
- throw new Error("Should provide project context");
303
- let e = this.sharedInstances.get(s);
304
- return e || (e = new R({
305
- path: b(K, s)
306
- }), this.sharedInstances.set(s, e), e);
307
- }
308
- destroy() {
309
- this.conns.forEach((s, e) => this.closeConn(e)), this.awareness.destroy(), super.destroy();
310
- }
311
- initObserver() {
312
- const s = (n) => {
313
- n.observeDeep((r) => {
314
- r.some((a) => a.changes.keys.has("updatedAt") || a.changes.keys.has("publishedAt")) || n.set("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
315
- });
316
- };
317
- this.syncedStore.pages && Object.keys(this.syncedStore.pages).forEach((n) => {
318
- const r = se(this.syncedStore.pages[n]);
319
- r && r instanceof M.Map && s(r);
320
- });
321
- const e = se(this.syncedStore.pages);
322
- e && e instanceof M.Map && e.observe((n) => {
323
- n.changes.keys.forEach((r, a) => {
324
- if (r.action === "add") {
325
- const l = se(this.syncedStore.pages[a]);
326
- l && l instanceof M.Map && s(l);
327
- }
328
- });
329
- });
330
- }
331
- get draftYjsFilePath() {
332
- return b(this.options.path, "draft.yjs");
333
- }
334
- async getState(s) {
335
- var e, n, r, a;
336
- if (s === "draft")
337
- return JSON.parse(JSON.stringify(this.syncedStore));
338
- if (!this.states[s] && (this.states[s] = await Ue(this.getPublishDir(s), { includeResources: !0 }) ?? At(), !((n = (e = this.states[s]) == null ? void 0 : e.config) != null && n.defaultLocale))) {
339
- (r = this.states[s]).config ?? (r.config = {});
340
- const l = ce.env.languages.map((i) => ({ locale: i.code, name: i.name }));
341
- this.states[s].config.defaultLocale = (a = l[0]) == null ? void 0 : a.locale;
342
- }
343
- return {
344
- ...this.states[s],
345
- resources: await Dt().then(async (l) => {
346
- var u, p, h, T;
347
- const { pages: i, components: o } = ze(l, "pages", "components");
348
- let c = o;
349
- if ((p = (u = this.states[s]) == null ? void 0 : u.resources) != null && p.components)
350
- c = {
351
- ...(T = (h = this.states[s]) == null ? void 0 : h.resources) == null ? void 0 : T.components
352
- };
353
- else {
354
- const O = $(this.options.path), D = await _.findByPk(O);
355
- if (D != null && D.useAllResources)
356
- c = o;
357
- else {
358
- const f = (await te.findAll({ where: { projectId: O } })).map((m) => m.componentId);
359
- c = Object.fromEntries(
360
- Object.entries(o || {}).filter(([m]) => f.includes(m))
361
- );
362
- }
363
- }
364
- return { pages: i, components: c };
365
- }).catch(() => ({}))
366
- };
367
- }
368
- async setState(s, e) {
369
- const n = await Tt(e, { exportAssets: !1, includeResources: !0 }), r = this.getPublishDir(s);
370
- F(k(r), { recursive: !0 }), Ie(r, { force: !0, recursive: !0 }), fe(n, r), this.states[s] = e;
371
- }
372
- getPublishDir(s) {
373
- return b(this.options.path, s);
374
- }
375
- static async pageUrlMap(s) {
376
- const { projectIds: e } = this, n = {};
377
- for (const r of e) {
378
- const a = await _.findByPk(r);
379
- if (!a) continue;
380
- const l = await R.shared(r).getState(s), i = Ke(
381
- g.env.languages.map((o) => o.code),
382
- l.supportedLocales.map((o) => o.locale)
383
- );
384
- for (const o of l.pageIds) {
385
- const c = l.pages[o];
386
- if (!c || s === "production" && !c.isPublic)
387
- continue;
388
- const u = c.slug, p = a.slug || r, h = {
389
- projectId: r,
390
- projectSlug: p,
391
- pageSlug: u,
392
- pageId: o,
393
- // default locale
394
- defaultLocale: i == null ? void 0 : i[0],
395
- locales: i,
396
- publishedAt: l.config.publishedAt,
397
- isPublic: c.isPublic,
398
- isTemplate: c.isTemplate
399
- };
400
- p && (n[B("/", p, u)] = {
401
- ...h,
402
- shouldRedirect: !0,
403
- mainPage: !0
404
- }), n[B("/", r, u)] = {
405
- ...h,
406
- shouldRedirect: !0,
407
- mainPage: !0
408
- };
409
- for (const T of i) {
410
- const O = { ...h, locale: T };
411
- n[B("/", T, r, u)] = O, p && (n[B("/", T, p, u)] = O);
412
- }
413
- }
414
- }
415
- return n;
416
- }
417
- };
418
- R.INSTANCE_TTL = 30 * 60 * 1e3, R.sharedInstances = new Oe({
419
- max: 100,
420
- // Maximum number of instances to store
421
- ttl: R.INSTANCE_TTL,
422
- dispose: (s) => {
423
- s.destroy();
424
- }
425
- });
426
- let Q = R;
427
- function Ce() {
428
- return Je(b(g.env.dataDir, "tmp-"));
429
- }
430
- function Z(t, s, e = []) {
431
- return Array.isArray(t) ? t.flatMap((n, r) => Z(n, s, [...e, r])) : typeof t == "object" ? t === null ? [] : Object.entries(t).flatMap(([n, r]) => Z(r, s, [...e, n])) : s(t) ? [e] : [];
432
- }
433
- function L(t) {
434
- return t.filter((s) => s != null);
435
- }
436
- async function bt(t, s, e) {
437
- if (!t || !x(t) || !Y(t).isFile())
438
- return null;
439
- let n = e[t];
440
- return n || (n = (async () => (await ht({
441
- filePath: t,
442
- fileName: s
443
- })).data.filename)(), e[t] = n), n;
444
- }
445
- const vt = async (t, s) => {
446
- const e = $(t), n = await xe({
447
- name: De,
448
- path: B("/uploads", e),
449
- responseType: "stream",
450
- method: "GET"
451
- });
452
- if (n.status >= 200 && n.status < 400) {
453
- const r = qe(s);
454
- await Ze(n.data, r);
455
- } else
456
- throw new Error(`download asset failed ${n.status}`);
457
- }, It = async (t, s) => {
458
- await Promise.all(
459
- t.map(async (e) => {
460
- try {
461
- await vt(e, b(s, $(e)));
462
- } catch (n) {
463
- P.error(`Failed to export assets: ${e}, ${n}`);
464
- }
465
- })
466
- );
467
- };
468
- function Le(t) {
469
- return pe.test(t) ? [t] : G.test(t) ? (we.lastIndex = 0, Array.from(t.matchAll(we)).map((e) => e[1]).filter((e) => !!e)) : [];
470
- }
471
- async function oe(t, s, e) {
472
- const { getFilename: n, exportAssets: r } = e, a = b(s, n(t));
473
- if (F(k(a), { recursive: !0 }), X(a, V.stringify(t)), r) {
474
- const i = Z(
475
- t,
476
- (o) => typeof o == "string" && (pe.test(o) || G.test(o))
477
- ).map((o) => {
478
- const c = le(t, o);
479
- return Le(c);
480
- }).flat().filter(Boolean);
481
- await It(i, k(a));
482
- }
483
- }
484
- const Ee = new Oe({
485
- max: 1e3,
486
- ttl: 30 * 24 * 60 * 60 * 1e3
487
- });
488
- async function Ae(t, s, e) {
489
- var i;
490
- const n = Z(
491
- t,
492
- (o) => typeof o == "string" && (pe.test(o) || G.test(o))
493
- ), r = Xe(2), a = n.map(
494
- (o) => r(async () => {
495
- try {
496
- const c = le(t, o), u = Le(c);
497
- for (const p of u) {
498
- const h = $(p), T = e.getFilePath(p, o), O = T ? `${T}:${h}` : h, D = Ee.get(O);
499
- if (D) {
500
- G.test(c) || me(t, o, D);
501
- return;
502
- }
503
- const U = await bt(T, h, s);
504
- U && (G.test(c) || me(t, o, U), Ee.set(O, U));
505
- }
506
- } catch (c) {
507
- P.error(`Failed to process upload for path ${o.join(".")}:`, c.message || c.reason);
508
- }
509
- })
510
- ), l = await Promise.allSettled(a);
511
- (i = e.onFinish) == null || i.call(e, l);
512
- }
513
- async function Tt(t, {
514
- exportAssets: s,
515
- pageIds: e = "all",
516
- componentIds: n = "all",
517
- rawConfig: r,
518
- includeResources: a = !1
519
- } = {}) {
520
- var f, E, m, S, N, A;
521
- const l = e === "all" ? t.pageIds : e, i = Ot({
522
- state: t,
523
- pageIds: l,
524
- componentIds: n === "all" ? Object.keys(t.components) : n
525
- }), o = (d, y) => {
526
- var w;
527
- return {
528
- id: d.id,
529
- name: d.name,
530
- isTemplateSection: d.isTemplateSection ?? !1,
531
- component: d.component,
532
- config: d.config,
533
- visibility: d.visibility,
534
- properties: ((w = d.locales) == null ? void 0 : w[y]) ?? {}
535
- };
536
- }, c = (d, y) => {
537
- var w;
538
- return {
539
- id: d.id,
540
- createdAt: d.createdAt,
541
- updatedAt: d.updatedAt,
542
- publishedAt: d.publishedAt,
543
- isPublic: d.isPublic ?? !0,
544
- isTemplate: d.isTemplate ?? !1,
545
- meta: ((w = d.locales) == null ? void 0 : w[y]) ?? {},
546
- sections: L(
547
- d.sectionIds.map((j) => {
548
- const C = d.sections[j];
549
- return C && o(C, y);
550
- })
551
- )
552
- };
553
- }, u = L(
554
- t.supportedLocales.map((d) => d.locale).flatMap(
555
- (d) => l.map((y) => {
556
- const w = t.pages[y];
557
- return w && {
558
- locale: d,
559
- slug: w.slug,
560
- page: c(w, d)
561
- };
562
- })
563
- )
564
- ), p = Ce(), h = b(p, "pages");
565
- F(h, { recursive: !0 });
566
- const T = b(p, "components");
567
- F(T, { recursive: !0 });
568
- for (const { locale: d, slug: y, page: w } of u)
569
- await oe(w, h, {
570
- getFilename: () => `${je(y) || "index"}.${d}.yml`,
571
- exportAssets: s
572
- });
573
- for (const d of i) {
574
- const y = (f = t.components[d]) == null ? void 0 : f.data;
575
- y && await oe(y, T, {
576
- getFilename: (w) => `${w.name || "unnamed"}.${w.id}.yml`,
577
- exportAssets: s
578
- });
579
- }
580
- const O = b(p, ".blocklet/pages/pages.config.yml");
581
- F(k(O), { recursive: !0 });
582
- const D = {
583
- pages: L(
584
- l.map((d) => {
585
- const y = t.pages[d];
586
- return y && { id: d, slug: y.slug };
587
- })
588
- ),
589
- components: L(
590
- i.map((d) => {
591
- var w;
592
- const y = (w = t.components[d]) == null ? void 0 : w.data;
593
- return y && {
594
- id: d,
595
- name: y.name
596
- };
597
- })
598
- ),
599
- ...a ? {
600
- resources: {
601
- components: L(
602
- Object.keys(((E = t.resources) == null ? void 0 : E.components) || {}).map((d) => {
603
- var y, w, j, C;
604
- return {
605
- id: d,
606
- name: (C = (j = (w = (y = t.resources) == null ? void 0 : y.components) == null ? void 0 : w[d]) == null ? void 0 : j.component) == null ? void 0 : C.name
607
- };
608
- })
609
- )
610
- }
611
- } : {},
612
- supportedLocales: t.supportedLocales,
613
- config: t.config
614
- };
615
- X(O, V.stringify(D));
616
- const U = b(p, "config.source.json");
617
- if (r && X(U, JSON.stringify(r)), a) {
618
- const d = b(p, "resources"), y = b(d, "components");
619
- F(y, { recursive: !0 });
620
- for (const w of Object.keys(((m = t == null ? void 0 : t.resources) == null ? void 0 : m.components) ?? {})) {
621
- const j = (A = (N = (S = t.resources) == null ? void 0 : S.components) == null ? void 0 : N[w]) == null ? void 0 : A.component;
622
- j && await oe(j, y, {
623
- getFilename: (C) => `${C.name || "unnamed"}.${C.id}.yml`,
624
- exportAssets: s
625
- });
626
- }
627
- }
628
- return p;
629
- }
630
- async function Ue(t, { importAssets: s, includeResources: e } = {}) {
631
- var a, l, i;
632
- if (!x(t))
633
- return null;
634
- let n, r = !1;
635
- try {
636
- Y(t).isDirectory() ? n = t : /\.(tgz|gz|tar)$/.test(t) && (r = !0, n = Ce(), await et({ file: t, C: n }));
637
- const o = ae("**/.blocklet/pages/pages.config.yml", { cwd: n, absolute: !0 }).at(0), c = o && b(k(o), "../../pages"), u = o && b(k(o), "../../components");
638
- if (!o)
639
- return null;
640
- const p = V.parse(H(o).toString()), h = (f, E, m) => {
641
- let S = b(f, `${E}${m ? `.${m}` : ""}.yml`);
642
- return (!x(S) || !Y(S).isFile()) && (S = b(f, E, `index${m ? `.${m}` : ""}.yml`), !x(S) || !Y(S)) ? null : V.parse(H(S).toString());
643
- }, T = (f, E) => {
644
- try {
645
- const m = ae(`*.${E}.yml`, { cwd: f, absolute: !0 })[0];
646
- return m ? V.parse(H(m).toString()) : null;
647
- } catch (m) {
648
- P.error("parse component error", m);
649
- }
650
- return null;
651
- }, O = L(
652
- p.pages.map(({ slug: f }) => {
653
- var N;
654
- const E = L(
655
- p.supportedLocales.map(({ locale: A }) => {
656
- const d = c ? h(c, je(f), A) : void 0;
657
- if (d)
658
- return { locale: A, page: d };
659
- const y = c ? h(c, f, A) : void 0;
660
- return y && { locale: A, page: y };
661
- })
662
- ), m = (N = E[0]) == null ? void 0 : N.page;
663
- if (!m)
664
- return null;
665
- const S = m.sections.map((A) => {
666
- const d = A.id || Se();
667
- return {
668
- id: d,
669
- component: A.component,
670
- config: A.config,
671
- name: A.name,
672
- isTemplateSection: A.isTemplateSection ?? !1,
673
- visibility: A.visibility,
674
- locales: Object.fromEntries(
675
- L(
676
- E.map(({ locale: y, page: w }) => {
677
- const j = w.sections.find((C) => C.id === d);
678
- return j && [y, j.properties];
679
- })
680
- )
681
- )
682
- };
683
- });
684
- return {
685
- id: m.id || Se(),
686
- createdAt: m.createdAt,
687
- updatedAt: m.updatedAt,
688
- publishedAt: m.publishedAt,
689
- isPublic: m.isPublic ?? !0,
690
- isTemplate: m.isTemplate ?? !1,
691
- slug: f,
692
- sections: Object.fromEntries(S.map((A) => [A.id, A])),
693
- sectionIds: S.map((A) => A.id),
694
- locales: Object.fromEntries(E.map(({ locale: A, page: d }) => [A, d.meta]))
695
- };
696
- })
697
- ), D = u ? L(((a = p.components) == null ? void 0 : a.map(({ id: f }) => T(u, f))) ?? []) : [];
698
- if (s) {
699
- const f = (...E) => {
700
- P.info(`[${r ? $(t) : $(b(t, "../../../../"))}] importAssets:`, ...E);
701
- };
702
- try {
703
- f("wait image-bin api ready"), await tt({
704
- resources: [`${$e(dt)}/api/sdk/uploads`],
705
- validateStatus: (S) => S >= 200 && S <= 500
706
- }), f("image-bin api is ready");
707
- const E = {}, m = {};
708
- f("start to upload assets"), await Promise.allSettled([
709
- Ae(D, E, {
710
- getFilePath: (S) => u && b(u, S),
711
- onFinish: (S) => {
712
- f(`upload ${S.length} component assets`);
713
- }
714
- }),
715
- Ae(O, m, {
716
- getFilePath: (S, N) => {
717
- const A = le(O, N.slice(0, 1));
718
- return c && b(c, k(A.slug), S);
719
- },
720
- onFinish: (S) => {
721
- f(`upload ${S.length} page assets`);
722
- }
723
- })
724
- ]), f("upload assets done"), global.gc && global.gc();
725
- } catch (E) {
726
- f("Error during asset import:", E);
727
- }
728
- }
729
- const U = {};
730
- if (e) {
731
- const f = o && b(k(o), "../../resources/components"), E = L(
732
- ((i = (l = p.resources) == null ? void 0 : l.components) == null ? void 0 : i.map(({ id: m }) => T(f, m))) ?? []
733
- );
734
- E.length > 0 && (U.components = Object.fromEntries(
735
- E.map((m, S) => [m.id, { index: S, component: m }])
736
- ));
737
- }
738
- return {
739
- supportedLocales: p.supportedLocales,
740
- pageIds: O.map((f) => f.id),
741
- components: Object.fromEntries(D.map((f, E) => [f.id, { index: E, data: f }])),
742
- pages: Object.fromEntries(O.map((f) => [f.id, f])),
743
- config: p.config || {},
744
- resources: U
745
- };
746
- } finally {
747
- r && n && Ie(n, { force: !0, recursive: !0 });
748
- }
749
- }
750
- async function be(t, s, {
751
- pages: e,
752
- pageMergeMode: n = "byUpdateTime",
753
- deletePages: r = !1,
754
- publishMode: a = void 0
755
- } = {}) {
756
- try {
757
- a && Fe(a);
758
- } catch (u) {
759
- P.error("clear preload page cache error", { error: u });
760
- }
761
- const { pageIds: l, pages: i, supportedLocales: o } = t;
762
- for (const u of e ?? l) {
763
- const p = i[u];
764
- if (!p) {
765
- const h = s.pageIds.indexOf(u);
766
- h !== -1 && r && (s.pageIds.splice(h, 1), delete s.pages[u]);
767
- continue;
768
- }
769
- if (s.pageIds.includes(p.id)) {
770
- if (n === "replace")
771
- s.pages[p.id] = p;
772
- else if (n === "byUpdateTime") {
773
- const h = s.pages[p.id];
774
- (!h || p.updatedAt && p.updatedAt > h.updatedAt) && (s.pages[p.id] = p);
775
- }
776
- } else
777
- s.pageIds.push(p.id), s.pages[p.id] = p;
778
- }
779
- if (r && !e)
780
- for (const u of s.pageIds)
781
- t.pageIds.includes(u) || delete s.pages[u], s.pageIds = [...s.pageIds].filter((p) => t.pageIds.includes(p));
782
- if (s.supportedLocales.splice(0, s.supportedLocales.length), s.supportedLocales.push(...He(o)), r)
783
- for (const u of Object.keys(s.components))
784
- delete s.components[u];
785
- let c = JSON.parse(JSON.stringify(t.components));
786
- c = Object.fromEntries(
787
- await Promise.all(
788
- Object.entries(c).map(async ([u, p]) => {
789
- const h = await ke(p == null ? void 0 : p.data);
790
- return [
791
- u,
792
- {
793
- ...p,
794
- data: h
795
- }
796
- ];
797
- })
798
- )
799
- ), Object.assign(s.components, c), Object.assign(s.config, JSON.parse(JSON.stringify(t.config))), s.resources.components = JSON.parse(JSON.stringify(t.resources.components || {}));
800
- }
801
- const ke = Me(
802
- async (t) => {
803
- var s;
804
- if (!Ye(t == null ? void 0 : t.properties))
805
- return t;
806
- if (((s = t == null ? void 0 : t.renderer) == null ? void 0 : s.type) === "react-component") {
807
- const { script: e } = (t == null ? void 0 : t.renderer) || {};
808
- if (e)
809
- try {
810
- const n = await _e(e, "PROPERTIES_SCHEMA", t.id);
811
- n && n.length > 0 && t && (t.properties = {}, n.forEach((r, a) => {
812
- t != null && t.properties && (t.properties[r.id] = {
813
- index: a,
814
- data: r
815
- });
816
- }));
817
- } catch (n) {
818
- P.error("checkPropertiesFromCode error", { componentId: t.id, name: t.name }, { error: n });
819
- }
820
- }
821
- return t;
822
- },
823
- {
824
- keyGenerator: (t) => JSON.stringify(["checkPropertiesFromCode", t])
825
- }
826
- );
827
- function Ot({
828
- state: t,
829
- pageIds: s = [],
830
- componentIds: e = []
831
- }) {
832
- var l;
833
- const n = (i, o = /* @__PURE__ */ new Set()) => (Array.isArray(i) && i.forEach((c) => n(c, o)), i && typeof i == "object" && (typeof i.componentId == "string" && o.add(i.componentId), Object.values(i).forEach((c) => n(c, o))), o), r = new Set(e);
834
- for (const i of s) {
835
- const o = t.pages[i];
836
- n(o, r);
837
- }
838
- const a = [...r];
839
- for (; a.length; ) {
840
- const i = a.shift();
841
- r.has(i) || r.add(i);
842
- const o = (l = t.components[i]) == null ? void 0 : l.data;
843
- if (o)
844
- for (const c of n(o))
845
- r.has(c) || a.push(c);
846
- }
847
- return [...r];
848
- }
849
- let ee, J, de, ue;
850
- function Re() {
851
- return ee = (async () => {
852
- const t = Be({
853
- types: [
854
- { did: De, type: ye },
855
- { did: gt, type: ye }
856
- ]
857
- });
858
- J = (await Promise.all(
859
- t.map(async (e) => {
860
- const n = e.path ? await Ue(e.path, { importAssets: !1 }) : void 0;
861
- return n ? { blockletId: e.did, state: n, blockletTitle: e.title } : void 0;
862
- })
863
- )).filter((e) => !!e), de = J.reduce(
864
- (e, n) => Object.assign(
865
- e,
866
- Object.fromEntries(
867
- Object.values(n.state.pages).map((r) => r ? [r == null ? void 0 : r.id, { page: r, blockletId: n.blockletId }] : [])
868
- )
869
- ),
870
- {}
871
- );
872
- const s = J.reduce(
873
- (e, n) => Object.assign(
874
- e,
875
- Object.fromEntries(
876
- Object.values(n.state.components).map((r) => [r.data.id, { blockletId: n.blockletId, component: r.data }])
877
- )
878
- ),
879
- {}
880
- );
881
- ue = Object.fromEntries(
882
- await Promise.all(
883
- Object.entries(s).map(async ([e, n]) => {
884
- const r = await ke(n.component);
885
- return [
886
- e,
887
- {
888
- ...n,
889
- component: r
890
- }
891
- ];
892
- })
893
- )
894
- );
895
- })(), ee;
896
- }
897
- function Pt(t) {
898
- const s = Te(
899
- async () => {
900
- await Re().catch((e) => {
901
- P.error("load resource states error", { error: e });
902
- }), await (t == null ? void 0 : t({ states: J, pages: de, components: ue }));
903
- },
904
- 3e3,
905
- { leading: !1, trailing: !0 }
906
- );
907
- return s(), g.events.on(g.Events.componentAdded, s), g.events.on(g.Events.componentRemoved, s), g.events.on(g.Events.componentStarted, s), g.events.on(g.Events.componentStopped, s), g.events.on(g.Events.componentUpdated, s), g.events.on(ie, s), () => {
908
- g.events.off(g.Events.componentAdded, s), g.events.off(g.Events.componentRemoved, s), g.events.off(g.Events.componentStarted, s), g.events.off(g.Events.componentStopped, s), g.events.off(g.Events.componentUpdated, s), g.events.off(ie, s);
909
- };
910
- }
911
- const Ne = Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"), W = globalThis;
912
- var ve;
913
- (ve = W[Ne]) == null || ve.call(W);
914
- W[Ne] = Pt(async ({ pages: t, components: s }) => {
915
- const { projectIds: e } = Q;
916
- await Promise.all(
917
- e.map(async (n) => {
918
- const r = Q.shared(n);
919
- r.syncedStore.resources.pages = t;
920
- const a = await _.findByPk(n);
921
- if (a != null && a.useAllResources)
922
- r.syncedStore.resources.components = s;
923
- else {
924
- const i = (await te.findAll({ where: { projectId: n } })).map((c) => c.componentId), o = Object.fromEntries(
925
- Object.entries(s || {}).filter(([c]) => i.includes(c))
926
- );
927
- r.syncedStore.resources.components = o;
928
- }
929
- P.info(`update [${n}] resource states:`, {
930
- pages: Object.keys(r.syncedStore.resources.pages || {}).length,
931
- components: Object.keys(r.syncedStore.resources.components || {}).length
932
- });
933
- })
934
- );
935
- });
936
- async function ts() {
937
- P.info("trigger reload all project resource"), g.events.emit(ie);
938
- }
939
- async function Dt() {
940
- return ee ?? (ee = Re()), await ee, { states: J, pages: de, components: ue };
941
- }
942
- export {
943
- De as C,
944
- _ as P,
945
- ye as R,
946
- Q as S,
947
- Dt as a,
948
- K as b,
949
- Zt as c,
950
- es as d,
951
- Pt as e,
952
- Ue as f,
953
- Qt as g,
954
- ts as h,
955
- Xt as i,
956
- be as m,
957
- Se as n,
958
- Tt as t
959
- };