@blocklet/pages-kit-inner-components 0.4.23 → 0.4.24

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