@blocklet/pages-kit-inner-components 0.4.32 → 0.4.34
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.
- package/lib/cjs/_chunks/site-state-DdXLmutN.js +57 -0
- package/lib/cjs/components.js +1 -1
- package/lib/cjs/locales.js +1 -1
- package/lib/cjs/project-html.js +1 -1
- package/lib/cjs/resources.js +1 -1
- package/lib/cjs/setting.js +4 -4
- package/lib/cjs/site-state.js +1 -1
- package/lib/cjs/theme.js +2 -2
- package/lib/es/_chunks/site-state-BF64quiV.js +1507 -0
- package/lib/es/components.js +1 -1
- package/lib/es/locales.js +12 -0
- package/lib/es/project-html.js +1 -1
- package/lib/es/resources.js +1 -1
- package/lib/es/setting.js +1594 -937
- package/lib/es/site-state.js +1 -1
- package/lib/es/theme.js +14 -14
- package/package.json +4 -4
- package/lib/cjs/_chunks/site-state-DNRKik3e.js +0 -57
- package/lib/es/_chunks/site-state-B0nM69Rk.js +0 -1485
package/lib/es/site-state.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "vite-plugin-node-polyfills/shims/process";
|
|
2
2
|
import "vite-plugin-node-polyfills/shims/global";
|
|
3
|
-
import { q as H, o as M, p as O, S as j, r as q, a as v, u as B, s as L, n as U, t as b, v as h } from "./_chunks/site-state-
|
|
3
|
+
import { q as H, o as M, p as O, S as j, r as q, a as v, u as B, s as L, n as U, t as b, v as h } from "./_chunks/site-state-BF64quiV.js";
|
|
4
4
|
import "@blocklet/quickjs";
|
|
5
5
|
import "@blocklet/sdk/lib/component";
|
|
6
6
|
import "@blocklet/sdk/lib/config";
|
package/lib/es/theme.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { jsx as f } from "react/jsx-runtime";
|
|
2
2
|
import g from "@arcblock/ux/lib/Colors";
|
|
3
|
-
import { createTheme as
|
|
4
|
-
import { Icon as
|
|
3
|
+
import { createTheme as v } from "@arcblock/ux/lib/Theme";
|
|
4
|
+
import { Icon as w } from "@iconify-icon/react";
|
|
5
5
|
import x from "@iconify-icons/tabler/chevron-down";
|
|
6
6
|
import { loadingButtonClasses as E } from "@blocklet/pages-kit/builtin/mui/lab";
|
|
7
|
-
import { listItemIconClasses as k, switchClasses as y, svgIconClasses as a, sliderClasses as n, outlinedInputClasses as u, inputBaseClasses as e, filledInputClasses as b, inputLabelClasses as s, inputClasses as i, selectClasses as B, autocompleteClasses as d, getContrastRatio as D, darken as $, lighten as C, Box as
|
|
8
|
-
import { defu as
|
|
7
|
+
import { listItemIconClasses as k, switchClasses as y, svgIconClasses as a, sliderClasses as n, outlinedInputClasses as u, inputBaseClasses as e, filledInputClasses as b, inputLabelClasses as s, inputClasses as i, selectClasses as B, autocompleteClasses as d, getContrastRatio as D, darken as $, lighten as C, Box as z } from "@blocklet/pages-kit/builtin/mui/material";
|
|
8
|
+
import { defu as A } from "defu";
|
|
9
9
|
function h(t) {
|
|
10
10
|
const l = g.common.white, m = D(t, l) >= 2 ? l : "rgba(0, 0, 0, 0.87)";
|
|
11
11
|
return {
|
|
@@ -16,8 +16,8 @@ function h(t) {
|
|
|
16
16
|
};
|
|
17
17
|
}
|
|
18
18
|
function c(t = {}) {
|
|
19
|
-
return
|
|
20
|
-
|
|
19
|
+
return v(
|
|
20
|
+
A(t, {
|
|
21
21
|
palette: {
|
|
22
22
|
_did: h(g.did.primary),
|
|
23
23
|
black: h(g.grey[900])
|
|
@@ -35,7 +35,7 @@ function c(t = {}) {
|
|
|
35
35
|
})
|
|
36
36
|
);
|
|
37
37
|
}
|
|
38
|
-
const
|
|
38
|
+
const S = `
|
|
39
39
|
:root {
|
|
40
40
|
/* Light */
|
|
41
41
|
/* colors */
|
|
@@ -154,7 +154,7 @@ const A = `
|
|
|
154
154
|
--radius-m: 8px;
|
|
155
155
|
--radius-l: 12px;
|
|
156
156
|
--radius-round: 9999px;
|
|
157
|
-
}`,
|
|
157
|
+
}`, U = `
|
|
158
158
|
:root {
|
|
159
159
|
/* Dark */
|
|
160
160
|
/* colors */
|
|
@@ -306,7 +306,7 @@ const A = `
|
|
|
306
306
|
},
|
|
307
307
|
components: {
|
|
308
308
|
MuiCssBaseline: {
|
|
309
|
-
styleOverrides:
|
|
309
|
+
styleOverrides: S
|
|
310
310
|
},
|
|
311
311
|
MuiFormLabel: {
|
|
312
312
|
styleOverrides: {
|
|
@@ -702,7 +702,7 @@ const A = `
|
|
|
702
702
|
styleOverrides: {
|
|
703
703
|
contained: ({ ownerState: t }) => ({
|
|
704
704
|
// 只对默认按钮应用自定义样式,warning 和 error 按钮保持原样
|
|
705
|
-
...(t.color === "inherit" || t.color === "primary") && {
|
|
705
|
+
...(t.color === "inherit" || t.color === "primary") && t.className !== "ignore-style-override" && {
|
|
706
706
|
backgroundColor: "#030712",
|
|
707
707
|
color: "white",
|
|
708
708
|
"&:hover": {
|
|
@@ -715,7 +715,7 @@ const A = `
|
|
|
715
715
|
}),
|
|
716
716
|
outlined: ({ ownerState: t }) => ({
|
|
717
717
|
// 只对默认按钮应用自定义样式
|
|
718
|
-
...(t.color === "inherit" || t.color === "primary") && {
|
|
718
|
+
...(t.color === "inherit" || t.color === "primary") && t.className !== "ignore-style-override" && {
|
|
719
719
|
bgcolor: "#fff",
|
|
720
720
|
color: "#000",
|
|
721
721
|
border: "1px solid #E5E7EB",
|
|
@@ -755,13 +755,13 @@ const M = c({
|
|
|
755
755
|
});
|
|
756
756
|
M.typography.big = { ...F };
|
|
757
757
|
function p(t) {
|
|
758
|
-
return /* @__PURE__ */ f(
|
|
758
|
+
return /* @__PURE__ */ f(z, { ...t, component: w, icon: x });
|
|
759
759
|
}
|
|
760
760
|
export {
|
|
761
761
|
c as create,
|
|
762
|
-
|
|
762
|
+
U as darkThemeRoot,
|
|
763
763
|
h as genPaletteColor,
|
|
764
|
-
|
|
764
|
+
S as lightThemeRoot,
|
|
765
765
|
M as pagesTheme,
|
|
766
766
|
o as theme
|
|
767
767
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blocklet/pages-kit-inner-components",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.34",
|
|
4
4
|
"description": "Pages Kit inner components library",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -73,7 +73,7 @@
|
|
|
73
73
|
"@blocklet/ai-kit": "^0.1.71",
|
|
74
74
|
"@blocklet/ai-runtime": "^0.4.249",
|
|
75
75
|
"@blocklet/code-editor": "^0.4.249",
|
|
76
|
-
"@blocklet/crawler": "^2.1.
|
|
76
|
+
"@blocklet/crawler": "^2.1.199",
|
|
77
77
|
"@blocklet/embed": "^0.2.3",
|
|
78
78
|
"@blocklet/js-sdk": "^1.16.39",
|
|
79
79
|
"@blocklet/logger": "1.16.36",
|
|
@@ -202,8 +202,8 @@
|
|
|
202
202
|
"yaml": "^2.5.0",
|
|
203
203
|
"yjs": "^13.6.18",
|
|
204
204
|
"zustand": "^4.5.5",
|
|
205
|
-
"@blocklet/pages-kit
|
|
206
|
-
"@blocklet/pages-kit": "^0.4.
|
|
205
|
+
"@blocklet/pages-kit": "^0.4.34",
|
|
206
|
+
"@blocklet/pages-kit-block-studio": "^0.4.34"
|
|
207
207
|
},
|
|
208
208
|
"devDependencies": {
|
|
209
209
|
"@trivago/prettier-plugin-sort-imports": "^5.2.1",
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
"use strict";const st=require("vite-plugin-node-polyfills/shims/process"),nt=require("vite-plugin-node-polyfills/shims/global"),ot=require("@blocklet/pages-kit/builtin/utils"),te=require("@blocklet/pages-kit/types"),ne=require("@blocklet/pages-kit/utils/property"),$=require("@blocklet/quickjs"),rt=require("@blocklet/sdk/lib/config"),Te=require("lru-cache"),Me=require("node-fetch"),v=require("ufo"),ie=require("crypto"),at=require("@blocklet/logger"),it=require("vite-plugin-node-polyfills/shims/buffer"),ct=require("@blocklet/pages-kit/utils/builtin"),me=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),ce=require("@blocklet/sdk/lib/component"),lt=require("autoprefixer"),ut=require("esbuild"),E=require("fs"),pt=require("postcss"),dt=require("tailwindcss"),ft=require("typescript"),mt=require("@reactivedata/reactive"),Z=require("@syncedstore/core"),ge=require("glob"),gt=require("lib0/decoding"),ht=require("lib0/encoding"),R=require("lodash"),yt=require("nanoid"),St=require("p-limit"),m=require("path"),wt=require("stream/promises"),Et=require("tar"),bt=require("wait-on"),G=require("y-protocols/awareness"),ue=require("y-protocols/sync"),Tt=require("yaml"),Ot=require("yjs"),jt=require("lodash/isNil"),C=require("sequelize");require("sqlite3");const x=e=>e&&e.__esModule?e:{default:e};function Q(e){if(e&&e.__esModule)return e;const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const t in e)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(s,t,n.get?n:{enumerable:!0,get:()=>e[t]})}}return s.default=e,Object.freeze(s)}const oe=x(st),xe=x(nt),w=x(rt),Ct=x(Me),It=x(at),Pt=x(it),At=x(lt),_t=Q(ut),vt=x(pt),xt=x(dt),D=x(ft),pe=Q(gt),A=Q(ht),Dt=x(St),kt=x(m),Rt=x(bt),J=Q(Tt),B=Q(Ot),Nt=x(jt);w.default.env.mode;const Lt="image-bin";w.default.env.INIT_TEMPLATE_PATH;const Ut=oe.default.env.DATABASE_URL||kt.default.join(w.default.env.dataDir,"db/pages-kit.db"),De=w.default,Mt=()=>w.default.env.tenantMode==="multiple",Ft=()=>{var e;return(Nt.default(De.env.preferences.multiTenantAllProjectAccessPassports)?[]:(e=De.env.preferences.multiTenantAllProjectAccessPassports)==null?void 0:e.split(","))||[]},I=It.default("pages-kit"),qt=C.DataTypes.sqlite.DATE.parse;C.DataTypes.sqlite.DATE.parse=(e,s)=>typeof e=="number"?new Date(e):qt(e,s);const X=new C.Sequelize({dialect:"sqlite",storage:Ut,benchmark:oe.default.env.ENABLE_SEQUELIZE_BENCHMARK==="true",retry:{match:[/SQLITE_BUSY/],name:"query",max:10},logging:oe.default.env.ENABLE_SEQUELIZE_LOGGING==="true"?console.log:!1});X.query("pragma journal_mode = WAL;");X.query("pragma synchronous = normal;");X.query("pragma journal_size_limit = 67108864;");class le extends C.Model{}le.init({id:{type:C.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:C.DataTypes.UUIDV4},projectId:{type:C.DataTypes.UUID,allowNull:!1},componentId:{type:C.DataTypes.STRING,allowNull:!1}},{sequelize:X,tableName:"ProjectComponents",timestamps:!1});class q extends C.Model{static async getProjectByIdOrSlug(s){return q.findOne({where:{[C.Op.or]:[{id:s},{slug:s}]}})}}q.init({id:{type:C.DataTypes.UUID,defaultValue:C.DataTypes.UUIDV4,primaryKey:!0},name:{type:C.DataTypes.STRING,allowNull:!1},description:C.DataTypes.TEXT,createdAt:C.DataTypes.DATE,updatedAt:C.DataTypes.DATE,createdBy:{type:C.DataTypes.STRING,allowNull:!1},updatedBy:{type:C.DataTypes.STRING,allowNull:!1},slug:C.DataTypes.STRING,icon:C.DataTypes.STRING,pinnedAt:C.DataTypes.DATE,useAllResources:C.DataTypes.BOOLEAN,relatedBlocklets:{type:C.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){return this.getDataValue("relatedBlocklets")||{}},set(e){this.setDataValue("relatedBlocklets",JSON.stringify(e||{}))}}},{sequelize:X,paranoid:!0});q.hasMany(le,{foreignKey:"projectId",as:"components"});const $t=async(e,{componentId:s})=>{const t=`@tailwind components;
|
|
2
|
-
@tailwind utilities;
|
|
3
|
-
`,n=`.CustomComponent_${s}`;return(await vt.default([xt.default({content:[{raw:e,extension:"tsx"}]}),At.default({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),a=>{a.walkRules(l=>{l.selectors=l.selectors.map(r=>r.replace(/\.(.+)/g,`${n}.$1,${n} .$1`))})}]).process(t)).css},Bt=async(e,{componentId:s})=>{const t=await $t(e,{componentId:s});return`export const __PagesKit_CSS__ = ${JSON.stringify(t)};
|
|
4
|
-
|
|
5
|
-
${e}
|
|
6
|
-
`},ke=$.memoize(async(e,s)=>{let t=D.default.transpileModule(e,{compilerOptions:{jsx:D.default.JsxEmit.React,target:D.default.ScriptTarget.ES2016,module:D.default.ModuleKind.ESNext},transformers:{before:[me.createBuiltinModuleTransformer(D.default)]}}).outputText;if(s.tailwind&&(t=await Bt(t,{componentId:s.componentId})),s.module===te.PreloadComponentScriptModule.ESM)return t;const n=D.default.transpileModule(t,{compilerOptions:{jsx:D.default.JsxEmit.React,target:D.default.ScriptTarget.ES2016,module:D.default.ModuleKind.CommonJS,moduleResolution:D.default.ModuleResolutionKind.Node16}}).outputText;return s.module===te.PreloadComponentScriptModule.CJS?n:Gt(s.moduleName,n)},{keyGenerator:(e,s)=>{const t=ie.createHash("md5").update(e).digest("hex"),n={...s,componentId:s.componentId,module:s.module,...s.module!==te.PreloadComponentScriptModule.ESM?{moduleName:s.moduleName}:{},tailwind:s.tailwind};return JSON.stringify(["transpileModule",t,n])},lruOptions:{max:100,ttl:1e3*60*60}}),Vt=async(e,s)=>{var l,r;const n=(r=(l=(await _t.build({entryPoints:["index.tsx"],external:Object.keys(ct.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(i){let c=null;i.onResolve({filter:/.*/},u=>u.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:u.path==="./component"?{path:"component.tsx",namespace:"vfs"}:me.isRelativeModule(u.path)?{path:u.path,namespace:"vfs"}:null),i.onLoad({filter:/.*/,namespace:"vfs"},async u=>{var p;if(u.path==="index.tsx")return{contents:`export { ${s} } from './component'`,loader:"tsx"};if(u.path==="component.tsx")return{contents:e,loader:"tsx"};if(me.isRelativeModule(u.path)){c||(c=await _e({ensureLoaded:!1}));const g=u.path.split("/").pop();if((p=c==null?void 0:c.chunks)!=null&&p[g])return{contents:E.readFileSync(c.chunks[g],"utf-8"),loader:"js"};const h=v.joinURL("chunks",g),{data:S}=await ce.call({name:"pages-kit",method:"GET",path:h});return{contents:S,loader:"js"}}return null})}}]})).outputFiles)==null?void 0:l[0])==null?void 0:r.contents;if(!n)throw new Error("Failed to build server code");const o=Pt.default.from(n).toString();return D.default.transpileModule(o,{compilerOptions:{module:D.default.ModuleKind.ESNext,target:D.default.ScriptTarget.ES2020}}).outputText},Fe=$.memoize(async(e,s)=>{const t=await Vt(e,s);return new RegExp(`export\\s+\\{\\s+${s}\\s+\\}`,"m").test(t)?t:void 0},{keyGenerator:(e,s)=>{const t=ie.createHash("md5").update(e).digest("hex");return JSON.stringify(["extractExportValueSchema",t,s])},lruOptions:{max:100,ttl:1e3*60*60}}),Gt=(e,s)=>{const t=/\bawait\b/.test(s);return`// GENERATED FILE. DO NOT EDIT.
|
|
7
|
-
var ${e} = ${t?"async":""} function () {
|
|
8
|
-
|
|
9
|
-
const exports = {};
|
|
10
|
-
let moduleExports = null;
|
|
11
|
-
|
|
12
|
-
// add commonjs module compatibility layer
|
|
13
|
-
const module = { exports: moduleExports };
|
|
14
|
-
|
|
15
|
-
// execute component code
|
|
16
|
-
${s}
|
|
17
|
-
|
|
18
|
-
// handle possible module.exports
|
|
19
|
-
if (module.exports && module.exports !== moduleExports) {
|
|
20
|
-
// if module.exports is used, use it first
|
|
21
|
-
return typeof module.exports === 'object' ? module.exports : { default: module.exports };
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
// ensure a default export
|
|
25
|
-
if (!('default' in exports) && Object.keys(exports).length === 0) {
|
|
26
|
-
// module has no exports, return null to indicate invalid
|
|
27
|
-
return null;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
return exports;
|
|
31
|
-
};
|
|
32
|
-
`},K=new Te.LRUCache({max:100}),qe=60*60,he=60;function $e(e){I.info("clear preload components cache",{cacheKey:e}),K.delete(e)}function Be(e){for(const s of K.keys())s.includes(e)&&(I.info("clear preload components cache",{cacheKey:s}),$e(s))}function Ve({mode:e,instanceId:s,componentId:t,locale:n}){return["getPreloadComponents",e,s,t,n].join("-")}async function Ht({mode:e,req:s,state:t,locale:n,instances:o,module:a}){const{supportedLocales:l,config:{defaultLocale:r}}=t;if(!r)return null;const i=(await Promise.all(o.map(async h=>{try{const S=Ve({mode:e,instanceId:h.id,componentId:h.componentId,locale:n});if(e!=="draft"&&h.useCache&&K.has(S))return I.info(`get preload component from cache: ${S}`),K.get(S);const P=Y({state:t,componentId:h.componentId});if(!P)return null;const _=await Ge({req:s,state:t,componentId:P.id,locale:n,defaultLocale:r,properties:h.properties});if(!_)return null;const N={instanceId:h.id,preload:_};if(e!=="draft"&&h.useCache){let L=qe;h.cacheDuration&&(L=h.cacheDuration),I.info(`set preload component to cache(${L}s): ${S}`),K.set(S,N,{ttl:L*1e3})}return N}catch(S){return I.error("get preload component error",{instanceId:h.id,componentId:h.componentId},{error:S}),null}}))).filter(h=>!!h),c=Object.values(i.reduce((h,S)=>({...h,...S.preload.components}),{}));async function u(){const h=await Promise.all(c.map(async S=>{const P=ne.componentUMDName({componentId:S.component.id}),_=a===te.PreloadComponentScriptModule.ESM?{module:a,script:await ke(S.script,{componentId:S.component.id,module:a,tailwind:e!=="draft"})}:{module:a,script:await ke(S.script,{componentId:S.component.id,module:a,moduleName:P,tailwind:e!=="draft"}),moduleName:P};return[S.component.id,{component:S.component,script:_}]}));return Object.fromEntries(h)}const p=await u();return{config:{defaultLocale:r,supportedLocales:l},components:p,instances:i.map(h=>({id:h.instanceId,componentId:h.preload.component.id,locales:{[h.preload.locale]:{props:h.preload.props}}}))}}async function Ge({req:e,state:s,componentId:t,locale:n,defaultLocale:o,properties:a}){const{supportedLocales:l}=s,r=Y({state:s,componentId:t});if(!r)return null;const i=l.some(u=>u.locale===n)?n:o;if(!i)return null;const c=await He({req:e,state:s,componentId:t,locale:i,defaultLocale:o,properties:a});return c?{component:r,...c}:null}const Jt=20;async function He({req:e,depth:s=0,state:t,componentId:n,locale:o,defaultLocale:a,properties:l}){if(s>Jt)throw new RangeError("max component depth exceeded");const r=Kt({state:t,componentId:n,properties:l,locale:o});if(!r)return null;const{props:i}=r,c={locale:o||a,components:{[r.component.id]:{component:r.component,script:r.script}},props:{...i}};try{const u=await Yt({...r,req:e});u!=null&&u.props&&Object.assign(c.props,u.props)}catch(u){I.error("preload data at server side error",{componentId:n,name:r.component.name},{error:u})}return await Promise.all(Object.entries(i).map(async([u,p])=>{if((p==null?void 0:p.type)===ne.RenderNestedComponent){const g=await He({req:e,depth:s+1,state:t,componentId:p.componentId,locale:o,defaultLocale:a,properties:p.properties});g&&(Object.assign(c.components,g.components),Object.assign(c.props,{[u]:{type:ne.RenderNestedComponent,componentId:p.componentId,props:g.props}}))}})),c}function Kt({state:e,componentId:s,locale:t,properties:n}){const o=Y({state:e,componentId:s});if(!o)return null;const a=ne.mergeComponent({componentId:s,getComponent:l=>Y({state:e,componentId:l}),locale:t,defaultLocale:e.config.defaultLocale,properties:n});return a?{component:o,script:a.script,props:{locale:t,...a.properties}}:null}function Y({state:e,componentId:s}){var t,n,o;return((t=e.components[s])==null?void 0:t.data)??((o=(n=e.resources.components)==null?void 0:n[s])==null?void 0:o.component)}function zt({state:e,name:s}){var n,o;const t=s.toLowerCase();return((n=Object.values(e.components).find(a=>{var l;return((l=a.data.name)==null?void 0:l.toLowerCase())===t}))==null?void 0:n.data)??((o=e.resources.components&&Object.values(e.resources.components).find(a=>{var l;return((l=a.component.name)==null?void 0:l.toLowerCase())===t}))==null?void 0:o.component)}async function Yt({component:e,script:s,props:t,req:n}){const o=await Fe(s,"getServerSideProps");if(!o)return null;const a=new Promise((r,i)=>{setTimeout(()=>{i(new Error("getServerSideProps timeout in promise race"))},he*1e3)});return await Promise.race([a,$.Sandbox.callFunction({code:`${o}
|
|
33
|
-
|
|
34
|
-
export async function getServerSidePropsWrapper(props) {
|
|
35
|
-
const { location, fetch } = props;
|
|
36
|
-
// 使用局部变量而不是全局变量
|
|
37
|
-
const originalLocation = typeof window !== 'undefined' ? window.location : undefined;
|
|
38
|
-
const originalFetch = globalThis.fetch;
|
|
39
|
-
|
|
40
|
-
try {
|
|
41
|
-
globalThis.location = location;
|
|
42
|
-
globalThis.fetch = fetch;
|
|
43
|
-
return await getServerSideProps(props);
|
|
44
|
-
} finally {
|
|
45
|
-
// 清理全局状态
|
|
46
|
-
if (originalLocation) globalThis.location = originalLocation;
|
|
47
|
-
if (originalFetch) globalThis.fetch = originalFetch;
|
|
48
|
-
}
|
|
49
|
-
}`,filename:`${e.name||e.id}.js`,moduleLoader:r=>{if(r==="@blocklet/pages-kit/builtin/utils")return`const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
|
|
50
|
-
export { joinURL, withQuery, getQuery, getComponentMountPoint }
|
|
51
|
-
`;if(r==="@blocklet/pages-kit/builtin/dayjs")return $.BuiltinModules.dayjs},global:{console:{log:(...r)=>{I.info(...r)},warn:(...r)=>{I.warn(...r)},error:(...r)=>{I.error(...r)}},getComponentMountPoint:ot.getComponentMountPoint,joinURL:v.joinURL,withQuery:v.withQuery,getQuery:v.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:v.joinURL(v.withHttps(n.hostname),n.originalUrl)},fetch:(r,{...i}={})=>{const c=typeof r=="string"&&r.startsWith("/")?v.joinURL(w.default.env.appUrl,r):r;if(typeof c=="string"&&v.parseURL(c).host===v.parseURL(w.default.env.appUrl).host){const u=n.get("cookie");if(u){const p=new Me.Headers(i.headers);p.set("cookie",u),i.headers=p}}return Ct.default(c,{...i,timeout:he*1e3}).then(u=>({ok:u.ok,status:u.status,statusText:u.statusText,headers:Object.fromEntries(u.headers.entries()),json:()=>u.json()}))},props:t}]})])}const Je=$.memoize(async(e,s,t)=>{const n=await Fe(e,s);if(n)try{return await $.Sandbox.callFunction({code:`
|
|
52
|
-
${n}
|
|
53
|
-
|
|
54
|
-
export function get${s}SchemaWrapper() {
|
|
55
|
-
return ${s};
|
|
56
|
-
}
|
|
57
|
-
`,filename:`${t}.js`,functionName:`get${s}SchemaWrapper`})}catch(o){return I.error(`获取 ${s} 失败`,{componentId:t,error:o}),null}return null},{keyGenerator:(e,s,t)=>{const n=ie.createHash("md5").update(e).digest("hex");return JSON.stringify(["getExportSchemaValueFromCode",n,s,t])},lruOptions:{max:100,ttl:1e3*60*60}}),Wt="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",ye="page",Se="trigger-reload-project-resource",Oe=Wt,Qt="z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV",{uploadToMediaKit:Xt}=require("@blocklet/uploader-server"),we=yt.customAlphabet("abcdefghijklmnopqrstuvwxyz0123456789",16),je=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,z=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Re=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Zt=1e4,es=3e4,ee=0,de=1,ts=0,ss=1,Ee=w.default,H=m.join(oe.default.env.BLOCKLET_DATA_DIR,"site-state"),ns=["production","draft"],os=["production"];function Ke(e){return(e==null?void 0:e.replace(/\//g,"|"))||""}function rs(){var t;const e=Ee.env.languages.map(n=>({locale:n.code,name:n.name})),s=(t=e[0])==null?void 0:t.locale;return{pageIds:[],pages:{},components:{},supportedLocales:e,config:{defaultLocale:s},resources:{}}}const F=class F extends B.Doc{constructor(s){super(),this.options=s,this.states={},this.conns=new Map,this.awarenessChangeHandler=({added:t,updated:n,removed:o},a)=>{const l=t.concat(n,o);if(a!==null){const c=this.conns.get(a);c&&(t.forEach(u=>{c.add(u)}),o.forEach(u=>{c.delete(u)}))}const r=A.createEncoder();A.writeVarUint(r,de),A.writeVarUint8Array(r,G.encodeAwarenessUpdate(this.awareness,l));const i=A.toUint8Array(r);this.conns.forEach((c,u)=>this.send(u,i))},this.updateHandler=t=>{const n=A.createEncoder();A.writeVarUint(n,ee),ue.writeUpdate(n,t);const o=A.toUint8Array(n);this.conns.forEach((a,l)=>this.send(l,o))},this.ensureDataStructure=()=>{var l;const{supportedLocales:t,pages:n,pageIds:o,config:a}=this.syncedStore;{const r=new Set(Object.keys(n));let i=0;for(;i<o.length;){const c=o[i];r.has(c)?(r.delete(c),i++):o.splice(i,1)}}t.splice(0,t.length),t.push(...Ee.env.languages.map(r=>({locale:r.code,name:r.name}))),a.defaultLocale=(l=t[0])==null?void 0:l.locale;{let r=0;const i=new Set;for(;r<t.length;){const{locale:c}=t[r];i.has(c)?t.splice(r,1):(r++,i.add(c))}}},this.send=(t,n)=>{t.readyState!==ts&&t.readyState!==ss&&this.closeConn(t);try{t.send(n,o=>{o&&this.closeConn(t)})}catch{this.closeConn(t)}},this.closeConn=t=>{if(t.removeAllListeners(),this.conns.has(t)){const n=this.conns.get(t);this.conns.delete(t),n&&G.removeAwarenessStates(this.awareness,Array.from(n),null)}t.close()},this.autoSave=R.debounce(()=>{E.mkdirSync(m.dirname(this.draftYjsFilePath),{recursive:!0}),E.writeFileSync(this.draftYjsFilePath,B.encodeStateAsUpdate(this))},Zt),this.save=({flush:t=!1}={})=>{this.autoSave(),t&&this.autoSave.flush()},this.publish=async({mode:t,pages:n})=>{const o=await this.getState("draft"),a=await this.getState("production");await be(o,a,{pages:n,pageMergeMode:"replace",deletePages:!0,publishMode:t}),a.config.publishedAt=new Date().getTime();for(const l of n||Object.keys(this.syncedStore.pages))this.syncedStore.pages[l]&&(this.syncedStore.pages[l].publishedAt=new Date().toISOString());await this.setState(t,a)},this.mergeState=async(t,n)=>{var r,i,c;const o=JSON.parse(JSON.stringify(n));(r=t.config).fontFamily??(r.fontFamily={});const a=(i=o.config)==null?void 0:i.fontFamily,l=(c=t.config)==null?void 0:c.fontFamily;t.config.fontFamily.title=(a==null?void 0:a.title)||(l==null?void 0:l.title),t.config.fontFamily.description=(a==null?void 0:a.description)||(l==null?void 0:l.description),await new Promise((u,p)=>{this.transact(async()=>{try{const g=await be(t,n);u(g)}catch(g){p(g)}})})},this.addConnection=t=>{if(this.conns.has(t))return;t.binaryType="arraybuffer",this.conns.set(t,new Set),t.on("message",a=>this.messageListener(t,new Uint8Array(a)));let n=!0;const o=setInterval(()=>{if(!n)this.conns.has(t)&&this.closeConn(t),clearInterval(o);else if(this.conns.has(t)){n=!1;try{t.ping()}catch{this.closeConn(t),clearInterval(o)}}},es);t.on("close",()=>{this.closeConn(t),clearInterval(o)}),t.on("pong",()=>{n=!0});{const a=A.createEncoder();A.writeVarUint(a,ee),ue.writeSyncStep1(a,this),this.send(t,A.toUint8Array(a));const l=this.awareness.getStates();if(l.size>0){const r=A.createEncoder();A.writeVarUint(r,de),A.writeVarUint8Array(r,G.encodeAwarenessUpdate(this.awareness,Array.from(l.keys()))),this.send(t,A.toUint8Array(r))}}},this.messageListener=(t,n)=>{try{const o=A.createEncoder(),a=pe.createDecoder(n),l=pe.readVarUint(a);switch(l){case ee:A.writeVarUint(o,ee),ue.readSyncMessage(a,o,this,null),A.length(o)>1&&(this.ensureDataStructure(),this.send(t,A.toUint8Array(o)));break;case de:{G.applyAwarenessUpdate(this.awareness,pe.readVarUint8Array(a),t);break}default:I.warn(`Unsupported messageType ${l}`)}}catch(o){I.error(o)}this.save()},E.existsSync(this.draftYjsFilePath)&&B.applyUpdate(this,E.readFileSync(this.draftYjsFilePath)),this.syncedStore=mt.reactive(Z.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new G.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static safeDeleteProjectStateDir(s){if(!s)throw new Error("Should provide project context");try{const t=m.join(H,s),n=m.join(H,`@del-${s}`);E.renameSync(t,n)}catch(t){I.error("Failed to safe delete project state dir:",t)}}static get projectIds(){return ge.globSync("*/",{cwd:H,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*"]})}static get allShared(){return this.projectIds.map(s=>F.shared(s))}static shared(s){if(!s)throw new Error("Should provide project context");let t=this.sharedInstances.get(s);return t||(t=new F({path:m.join(H,s)}),this.sharedInstances.set(s,t),t)}destroy(){this.conns.forEach((s,t)=>this.closeConn(t)),this.awareness.destroy(),super.destroy()}initObserver(){const s=n=>{n.observeDeep(o=>{o.some(a=>a.changes.keys.has("updatedAt")||a.changes.keys.has("publishedAt"))||n.set("updatedAt",new Date().toISOString())})};this.syncedStore.pages&&Object.keys(this.syncedStore.pages).forEach(n=>{const o=Z.getYjsValue(this.syncedStore.pages[n]);o&&o instanceof B.Map&&s(o)});const t=Z.getYjsValue(this.syncedStore.pages);t&&t instanceof B.Map&&t.observe(n=>{n.changes.keys.forEach((o,a)=>{if(o.action==="add"){const l=Z.getYjsValue(this.syncedStore.pages[a]);l&&l instanceof B.Map&&s(l)}})})}get draftYjsFilePath(){return m.join(this.options.path,"draft.yjs")}async getState(s){var t,n,o,a;if(s==="draft")return JSON.parse(JSON.stringify(this.syncedStore));if(!this.states[s]&&(this.states[s]=await Ce(this.getPublishDir(s),{includeResources:!0})??rs(),!((n=(t=this.states[s])==null?void 0:t.config)!=null&&n.defaultLocale))){(o=this.states[s]).config??(o.config={});const l=Ee.env.languages.map(r=>({locale:r.code,name:r.name}));this.states[s].config.defaultLocale=(a=l[0])==null?void 0:a.locale}return{...this.states[s],resources:await _e().then(async l=>{var u,p,g,h;const{pages:r,components:i}=R.pick(l,"pages","components");let c=i;if((p=(u=this.states[s])==null?void 0:u.resources)!=null&&p.components)c={...(h=(g=this.states[s])==null?void 0:g.resources)==null?void 0:h.components};else{const S=m.basename(this.options.path),P=await q.findByPk(S);if(P!=null&&P.useAllResources)c=i;else{const N=(await le.findAll({where:{projectId:S}})).map(y=>y.componentId);c=Object.fromEntries(Object.entries(i||{}).filter(([y])=>N.includes(y)))}}return{pages:r,components:c}}).catch(()=>({}))}}async setState(s,t){const n=await We(t,{exportAssets:!1,includeResources:!0}),o=this.getPublishDir(s);E.mkdirSync(m.dirname(o),{recursive:!0}),E.rmSync(o,{force:!0,recursive:!0}),E.renameSync(n,o),this.states[s]=t}getPublishDir(s){return m.join(this.options.path,s)}static async pageUrlMap(s){const{projectIds:t}=this,n={};for(const o of t){const a=await q.findByPk(o);if(!a)continue;const l=await F.shared(o).getState(s),r=R.union(w.default.env.languages.map(i=>i.code),l.supportedLocales.map(i=>i.locale));for(const i of l.pageIds){const c=l.pages[i];if(!c||s==="production"&&!c.isPublic)continue;const u=c.slug,p=a.slug||o,g={projectId:o,projectSlug:p,pageSlug:u,pageId:i,defaultLocale:r==null?void 0:r[0],locales:r,publishedAt:l.config.publishedAt,isPublic:c.isPublic,isTemplate:c.isTemplate};p&&(n[v.joinURL("/",p,u)]={...g,shouldRedirect:!0,mainPage:!0}),n[v.joinURL("/",o,u)]={...g,shouldRedirect:!0,mainPage:!0};for(const h of r){const S={...g,locale:h};n[v.joinURL("/",h,o,u)]=S,p&&(n[v.joinURL("/",h,p,u)]=S)}}}return n}};F.INSTANCE_TTL=30*60*1e3,F.sharedInstances=new Te.LRUCache({max:100,ttl:F.INSTANCE_TTL,dispose:s=>{s.destroy()}});let W=F;function ze(){return E.mkdtempSync(m.join(w.default.env.dataDir,"tmp-"))}function re(e,s,t=[]){return Array.isArray(e)?e.flatMap((n,o)=>re(n,s,[...t,o])):typeof e=="object"?e===null?[]:Object.entries(e).flatMap(([n,o])=>re(o,s,[...t,n])):s(e)?[t]:[]}function M(e){return e.filter(s=>s!=null)}async function as(e,s,t){if(!e||!E.existsSync(e)||!E.lstatSync(e).isFile())return null;let n=t[e];return n||(n=(async()=>(await Xt({filePath:e,fileName:s})).data.filename)(),t[e]=n),n}const is=async(e,s)=>{const t=m.basename(e),n=await ce.call({name:Oe,path:v.joinURL("/uploads",t),responseType:"stream",method:"GET"});if(n.status>=200&&n.status<400){const o=E.createWriteStream(s);await wt.pipeline(n.data,o)}else throw new Error(`download asset failed ${n.status}`)},cs=async(e,s)=>{await Promise.all(e.map(async t=>{try{await is(t,m.join(s,m.basename(t)))}catch(n){I.error(`Failed to export assets: ${t}, ${n}`)}}))};function Ye(e){return je.test(e)?[e]:z.test(e)?(Re.lastIndex=0,Array.from(e.matchAll(Re)).map(t=>t[1]).filter(t=>!!t)):[]}async function fe(e,s,t){const{getFilename:n,exportAssets:o}=t,a=m.join(s,n(e));if(E.mkdirSync(m.dirname(a),{recursive:!0}),E.writeFileSync(a,J.stringify(e)),o){const r=re(e,i=>typeof i=="string"&&(je.test(i)||z.test(i))).map(i=>{const c=R.get(e,i);return Ye(c)}).flat().filter(Boolean);await cs(r,m.dirname(a))}}const Ne=new Te.LRUCache({max:1e3,ttl:30*24*60*60*1e3});async function Le(e,s,t){var r;const n=re(e,i=>typeof i=="string"&&(je.test(i)||z.test(i))),o=Dt.default(2),a=n.map(i=>o(async()=>{try{const c=R.get(e,i),u=Ye(c);for(const p of u){const g=m.basename(p),h=t.getFilePath(p,i),S=h?`${h}:${g}`:g,P=Ne.get(S);if(P){z.test(c)||R.set(e,i,P);return}const _=await as(h,g,s);_&&(z.test(c)||R.set(e,i,_),Ne.set(S,_))}}catch(c){I.error(`Failed to process upload for path ${i.join(".")}:`,c.message||c.reason)}})),l=await Promise.allSettled(a);(r=t.onFinish)==null||r.call(t,l)}async function We(e,{exportAssets:s,pageIds:t="all",componentIds:n="all",rawConfig:o,includeResources:a=!1}={}){var N,L,y,O,T,j;const l=t==="all"?e.pageIds:t,r=ls({state:e,pageIds:l,componentIds:n==="all"?Object.keys(e.components):n}),i=(f,d)=>{var b;return{id:f.id,name:f.name,isTemplateSection:f.isTemplateSection??!1,component:f.component,config:f.config,visibility:f.visibility,properties:((b=f.locales)==null?void 0:b[d])??{}}},c=(f,d)=>{var b;return{id:f.id,createdAt:f.createdAt,updatedAt:f.updatedAt,publishedAt:f.publishedAt,isPublic:f.isPublic??!0,isTemplate:f.isTemplate??!1,meta:((b=f.locales)==null?void 0:b[d])??{},sections:M(f.sectionIds.map(k=>{const U=f.sections[k];return U&&i(U,d)}))}},u=M(e.supportedLocales.map(f=>f.locale).flatMap(f=>l.map(d=>{const b=e.pages[d];return b&&{locale:f,slug:b.slug,page:c(b,f)}}))),p=ze(),g=m.join(p,"pages");E.mkdirSync(g,{recursive:!0});const h=m.join(p,"components");E.mkdirSync(h,{recursive:!0});for(const{locale:f,slug:d,page:b}of u)await fe(b,g,{getFilename:()=>`${Ke(d)||"index"}.${f}.yml`,exportAssets:s});for(const f of r){const d=(N=e.components[f])==null?void 0:N.data;d&&await fe(d,h,{getFilename:b=>`${b.name||"unnamed"}.${b.id}.yml`,exportAssets:s})}const S=m.join(p,".blocklet/pages/pages.config.yml");E.mkdirSync(m.dirname(S),{recursive:!0});const P={pages:M(l.map(f=>{const d=e.pages[f];return d&&{id:f,slug:d.slug}})),components:M(r.map(f=>{var b;const d=(b=e.components[f])==null?void 0:b.data;return d&&{id:f,name:d.name}})),...a?{resources:{components:M(Object.keys(((L=e.resources)==null?void 0:L.components)||{}).map(f=>{var d,b,k,U;return{id:f,name:(U=(k=(b=(d=e.resources)==null?void 0:d.components)==null?void 0:b[f])==null?void 0:k.component)==null?void 0:U.name}}))}}:{},supportedLocales:e.supportedLocales,config:e.config};E.writeFileSync(S,J.stringify(P));const _=m.join(p,"config.source.json");if(o&&E.writeFileSync(_,JSON.stringify(o)),a){const f=m.join(p,"resources"),d=m.join(f,"components");E.mkdirSync(d,{recursive:!0});for(const b of Object.keys(((y=e==null?void 0:e.resources)==null?void 0:y.components)??{})){const k=(j=(T=(O=e.resources)==null?void 0:O.components)==null?void 0:T[b])==null?void 0:j.component;k&&await fe(k,d,{getFilename:U=>`${U.name||"unnamed"}.${U.id}.yml`,exportAssets:s})}}return p}async function Ce(e,{importAssets:s,includeResources:t}={}){var a,l,r;if(!E.existsSync(e))return null;let n,o=!1;try{E.lstatSync(e).isDirectory()?n=e:/\.(tgz|gz|tar)$/.test(e)&&(o=!0,n=ze(),await Et.x({file:e,C:n}));const i=ge.globSync("**/.blocklet/pages/pages.config.yml",{cwd:n,absolute:!0}).at(0),c=i&&m.join(m.dirname(i),"../../pages"),u=i&&m.join(m.dirname(i),"../../components"),p=i&&m.join(m.dirname(i),"../../chunks");if(!i)return null;const g=J.parse(E.readFileSync(i).toString()),h=(y,O,T)=>{let j=m.join(y,`${O}${T?`.${T}`:""}.yml`);return(!E.existsSync(j)||!E.lstatSync(j).isFile())&&(j=m.join(y,O,`index${T?`.${T}`:""}.yml`),!E.existsSync(j)||!E.lstatSync(j))?null:J.parse(E.readFileSync(j).toString())},S=(y,O)=>{try{const T=ge.globSync(`*.${O}.yml`,{cwd:y,absolute:!0})[0];return T?J.parse(E.readFileSync(T).toString()):null}catch(T){I.error("parse component error",T)}return null},P=M(g.pages.map(({slug:y})=>{var f;const O=M(g.supportedLocales.map(({locale:d})=>{const b=c?h(c,Ke(y),d):void 0;if(b)return{locale:d,page:b};const k=c?h(c,y,d):void 0;return k&&{locale:d,page:k}})),T=(f=O[0])==null?void 0:f.page;if(!T)return null;const j=T.sections.map(d=>{const b=d.id||we();return{id:b,component:d.component,config:d.config,name:d.name,isTemplateSection:d.isTemplateSection??!1,visibility:d.visibility,locales:Object.fromEntries(M(O.map(({locale:k,page:U})=>{const ve=U.sections.find(tt=>tt.id===b);return ve&&[k,ve.properties]})))}});return{id:T.id||we(),createdAt:T.createdAt,updatedAt:T.updatedAt,publishedAt:T.publishedAt,isPublic:T.isPublic??!0,isTemplate:T.isTemplate??!1,slug:y,sections:Object.fromEntries(j.map(d=>[d.id,d])),sectionIds:j.map(d=>d.id),locales:Object.fromEntries(O.map(({locale:d,page:b})=>[d,b.meta]))}})),_=u?M(((a=g.components)==null?void 0:a.map(({id:y})=>S(u,y)))??[]):[];if(s){const y=(...O)=>{I.info(`[${o?m.basename(e):m.basename(m.join(e,"../../../../"))}] importAssets:`,...O)};try{y("wait image-bin api ready"),await Rt.default({resources:[`${ce.getComponentWebEndpoint(Lt)}/api/sdk/uploads`],validateStatus:j=>j>=200&&j<=500}),y("image-bin api is ready");const O={},T={};y("start to upload assets"),await Promise.allSettled([Le(_,O,{getFilePath:j=>u&&m.join(u,j),onFinish:j=>{y(`upload ${j.length} component assets`)}}),Le(P,T,{getFilePath:(j,f)=>{const d=R.get(P,f.slice(0,1));return c&&m.join(c,m.dirname(d.slug),j)},onFinish:j=>{y(`upload ${j.length} page assets`)}})]),y("upload assets done"),xe.default.gc&&xe.default.gc()}catch(O){y("Error during asset import:",O)}}const N={};if(t){const y=i&&m.join(m.dirname(i),"../../resources/components"),O=M(((r=(l=g.resources)==null?void 0:l.components)==null?void 0:r.map(({id:T})=>S(y,T)))??[]);O.length>0&&(N.components=Object.fromEntries(O.map((T,j)=>[T.id,{index:j,component:T}])))}const L={};if(p&&E.existsSync(p)){const y=E.readdirSync(p);for(const O of y)L[O]=m.join(p,O)}return{supportedLocales:g.supportedLocales,pageIds:P.map(y=>y.id),components:Object.fromEntries(_.map((y,O)=>[y.id,{index:O,data:y}])),pages:Object.fromEntries(P.map(y=>[y.id,y])),config:g.config||{},resources:N,chunks:L}}finally{o&&n&&E.rmSync(n,{force:!0,recursive:!0})}}async function be(e,s,{pages:t,pageMergeMode:n="byUpdateTime",deletePages:o=!1,publishMode:a=void 0}={}){try{a&&Be(a)}catch(u){I.error("clear preload page cache error",{error:u})}const{pageIds:l,pages:r,supportedLocales:i}=e;for(const u of t??l){const p=r[u];if(!p){const g=s.pageIds.indexOf(u);g!==-1&&o&&(s.pageIds.splice(g,1),delete s.pages[u]);continue}if(s.pageIds.includes(p.id)){if(n==="replace")s.pages[p.id]=p;else if(n==="byUpdateTime"){const g=s.pages[p.id];(!g||p.updatedAt&&p.updatedAt>g.updatedAt)&&(s.pages[p.id]=p)}}else s.pageIds.push(p.id),s.pages[p.id]=p}if(o&&!t)for(const u of s.pageIds)e.pageIds.includes(u)||delete s.pages[u],s.pageIds=[...s.pageIds].filter(p=>e.pageIds.includes(p));if(s.supportedLocales.splice(0,s.supportedLocales.length),s.supportedLocales.push(...R.cloneDeep(i)),o)for(const u of Object.keys(s.components))delete s.components[u];let c=JSON.parse(JSON.stringify(e.components));c=Object.fromEntries(await Promise.all(Object.entries(c).map(async([u,p])=>{const g=await Qe(p==null?void 0:p.data);return[u,{...p,data:g}]}))),Object.assign(s.components,c),Object.assign(s.config,JSON.parse(JSON.stringify(e.config))),s.resources.components=JSON.parse(JSON.stringify(e.resources.components||{}))}const Qe=$.memoize(async e=>{var s;if(!R.isEmpty(e==null?void 0:e.properties))return e;if(((s=e==null?void 0:e.renderer)==null?void 0:s.type)==="react-component"){const{script:t}=(e==null?void 0:e.renderer)||{};if(t)try{const n=await Je(t,"PROPERTIES_SCHEMA",e.id);n&&n.length>0&&e&&(e.properties={},n.forEach((o,a)=>{e!=null&&e.properties&&(e.properties[o.id]={index:a,data:o})}))}catch(n){I.error("checkPropertiesFromCode error",{componentId:e.id,name:e.name},{error:n})}}return e},{keyGenerator:e=>{var l;const s=(e==null?void 0:e.id)||"",t=(e==null?void 0:e.name)||"",n=((l=e==null?void 0:e.renderer)==null?void 0:l.type)||"",o=(e==null?void 0:e.properties)||{},a=ie.createHash("md5").update(JSON.stringify(o)).digest("hex");return JSON.stringify(["checkPropertiesFromCode",s,t,n,a])},lruOptions:{max:100,ttl:1e3*60*60}});function ls({state:e,pageIds:s=[],componentIds:t=[]}){var l;const n=(r,i=new Set)=>(Array.isArray(r)&&r.forEach(c=>n(c,i)),r&&typeof r=="object"&&(typeof r.componentId=="string"&&i.add(r.componentId),Object.values(r).forEach(c=>n(c,i))),i),o=new Set(t);for(const r of s){const i=e.pages[r];n(i,o)}const a=[...o];for(;a.length;){const r=a.shift();o.has(r)||o.add(r);const i=(l=e.components[r])==null?void 0:l.data;if(i)for(const c of n(i))o.has(c)||a.push(c)}return[...o]}let ae,V,Ie,Pe,Ae;function Xe(){return ae=(async()=>{const e=ce.getResources({types:[{did:Oe,type:ye},{did:Qt,type:ye}]});V=(await Promise.all(e.map(async t=>{const n=t.path?await Ce(t.path,{importAssets:!1}):void 0;return n?{blockletId:t.did,state:n,blockletTitle:t.title}:void 0}))).filter(t=>!!t),Ie=V.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.pages).map(o=>o?[o==null?void 0:o.id,{page:o,blockletId:n.blockletId}]:[]))),{});const s=V.reduce((t,n)=>Object.assign(t,Object.fromEntries(Object.values(n.state.components).map(o=>[o.data.id,{blockletId:n.blockletId,component:o.data}]))),{});Pe=Object.fromEntries(await Promise.all(Object.entries(s).map(async([t,n])=>{const o=await Qe(n.component);return[t,{...n,component:o}]}))),Ae=V.reduce((t,n)=>Object.assign(t,n.state.chunks),{})})(),ae}function Ze(e){const s=R.debounce(async()=>{await Xe().catch(t=>{I.error("load resource states error",{error:t})}),await(e==null?void 0:e({states:V,pages:Ie,components:Pe,chunks:Ae}))},3e3,{leading:!1,trailing:!0});return s(),w.default.events.on(w.default.Events.componentAdded,s),w.default.events.on(w.default.Events.componentRemoved,s),w.default.events.on(w.default.Events.componentStarted,s),w.default.events.on(w.default.Events.componentStopped,s),w.default.events.on(w.default.Events.componentUpdated,s),w.default.events.on(Se,s),()=>{w.default.events.off(w.default.Events.componentAdded,s),w.default.events.off(w.default.Events.componentRemoved,s),w.default.events.off(w.default.Events.componentStarted,s),w.default.events.off(w.default.Events.componentStopped,s),w.default.events.off(w.default.Events.componentUpdated,s),w.default.events.off(Se,s)}}const et=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),se=globalThis;var Ue;(Ue=se[et])==null||Ue.call(se);se[et]=Ze(async({pages:e,components:s})=>{const{projectIds:t}=W;await Promise.all(t.map(async n=>{const o=W.shared(n);o.syncedStore.resources.pages=e;const a=await q.findByPk(n);if(a!=null&&a.useAllResources)o.syncedStore.resources.components=s;else{const r=(await le.findAll({where:{projectId:n}})).map(c=>c.componentId),i=Object.fromEntries(Object.entries(s||{}).filter(([c])=>r.includes(c)));o.syncedStore.resources.components=i}I.info(`update [${n}] resource states:`,{pages:Object.keys(o.syncedStore.resources.pages||{}).length,components:Object.keys(o.syncedStore.resources.components||{}).length})}))});async function us(){I.info("trigger reload all project resource"),w.default.events.emit(Se)}async function _e({ensureLoaded:e=!0}={}){return e&&(ae??(ae=Xe()),await ae),{states:V,pages:Ie,components:Pe,chunks:Ae}}exports.COMPONENT_DID=Oe;exports.CUSTOM_COMPONENT_CACHE_DURATION_IN_SECONDS=qe;exports.GET_SERVER_SIDE_PROPS_TIMEOUT_IN_SECONDS=he;exports.PUBLISH_MODES=os;exports.Project=q;exports.RESOURCE_TYPE=ye;exports.SITE_STATE_PATH=H;exports.STATE_MODES=ns;exports.SiteState=W;exports.clearPreloadComponentsCache=$e;exports.clearPreloadComponentsCacheByMode=Be;exports.fromPackage=Ce;exports.getComponentFromState=Y;exports.getComponentFromStateByName=zt;exports.getExportSchemaValueFromCode=Je;exports.getMultiTenantAllProjectAccessPassports=Ft;exports.getPreloadComponent=Ge;exports.getPreloadComponents=Ht;exports.getPreloadComponentsCacheKey=Ve;exports.getResourceStates=_e;exports.initPackResourceStates=Ze;exports.isMultiTenant=Mt;exports.logger=I;exports.mergeState=be;exports.nextId=we;exports.toPackage=We;exports.triggerReloadAllProjectResource=us;
|