@blocklet/pages-kit-inner-components 0.6.2 → 0.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/lib/cjs/add-component.js +420 -1
  2. package/lib/cjs/chunks/draft-data-D44_IEV2.js +1 -0
  3. package/lib/cjs/chunks/home-BYk01EUy.js +39 -0
  4. package/lib/cjs/chunks/index-BRgYwvuv.js +475 -0
  5. package/lib/cjs/chunks/publish-button-C8XPA4g_.js +1 -0
  6. package/lib/cjs/chunks/session-BRtsDvA-.js +1 -0
  7. package/lib/cjs/chunks/site-state-BlQzwACl.js +57 -0
  8. package/lib/cjs/chunks/state-B6BF5wJ-.js +1 -0
  9. package/lib/cjs/components.js +1 -0
  10. package/lib/cjs/home.js +1 -1
  11. package/lib/cjs/locales.js +3 -0
  12. package/lib/cjs/project-html.js +4 -4
  13. package/lib/cjs/resources.js +1 -1
  14. package/lib/cjs/setting.js +11 -0
  15. package/lib/cjs/site-state.js +1 -0
  16. package/lib/cjs/theme.js +1 -0
  17. package/lib/cjs/uploader.js +1 -0
  18. package/lib/es/add-component.js +1089 -2
  19. package/lib/es/chunks/{draft-data-bRUHvvzp.js → draft-data-CafrGKeh.js} +4 -5
  20. package/lib/es/chunks/home-DW8SdyfO.js +594 -0
  21. package/lib/es/chunks/index-D5gXPe_7.js +2326 -0
  22. package/lib/es/chunks/{publish-button-Ceet-m88.js → publish-button-XSZrDaTQ.js} +140 -158
  23. package/lib/es/chunks/session-C72Dq8zg.js +19 -0
  24. package/lib/es/chunks/{site-state-Bh8guIeX.js → site-state-BdLTu3Od.js} +201 -170
  25. package/lib/es/chunks/state-0gvZF3k2.js +573 -0
  26. package/lib/es/components.js +24 -0
  27. package/lib/es/home.js +28 -3
  28. package/lib/es/locales.js +1032 -0
  29. package/lib/es/project-html.js +155 -79
  30. package/lib/es/resources.js +137 -93
  31. package/lib/es/setting.js +2294 -0
  32. package/lib/es/site-state.js +48 -0
  33. package/lib/es/theme.js +484 -0
  34. package/lib/es/uploader.js +8 -0
  35. package/package.json +3 -3
  36. package/lib/cjs/chunks/draft-data-CfIMszE7.js +0 -1
  37. package/lib/cjs/chunks/home-DUjl5PbP.js +0 -6
  38. package/lib/cjs/chunks/publish-button-C522nNv6.js +0 -1
  39. package/lib/cjs/chunks/site-state-DDXqWF74.js +0 -57
  40. package/lib/cjs/chunks/state-CtNs8GrN.js +0 -1
  41. package/lib/es/chunks/home-VWWdvIPQ.js +0 -69
  42. package/lib/es/chunks/state-BdNIIXJP.js +0 -502
@@ -1,57 +0,0 @@
1
- "use strict";var pt=Object.create;var ke=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,mt=Object.prototype.hasOwnProperty;var ht=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dt(e))!mt.call(t,o)&&o!==n&&ke(t,o,{get:()=>e[o],enumerable:!(s=ut(e,o))||s.enumerable});return t};var q=(t,e,n)=>(n=t!=null?pt(ft(t)):{},ht(e||!t||!t.__esModule?ke(n,"default",{value:t,enumerable:!0}):n,t));const gt=require("@blocklet/pages-kit/builtin/utils"),Ie=require("@blocklet/pages-kit/types"),W=require("@blocklet/pages-kit/utils/property"),ee=require("@blocklet/quickjs"),be=require("@blocklet/pages-kit/utils/builtin"),yt=require("@blocklet/sdk/lib/config"),le=require("lru-cache"),Be=require("node-fetch"),R=require("ufo"),St=require("lodash/isEmpty"),wt=require("crypto"),w=require("fs"),h=require("path"),It=require("lodash/isNil"),bt=require("@blocklet/logger"),Ve=require("@blocklet/pages-kit/utils/typescript/builtin-module-transformer"),Ce=require("@blocklet/sdk/lib/component"),F=require("@syncedstore/core"),Et=require("yjs"),Pt=require("@blocklet/pages-kit/utils/data-source"),te=require("@blocklet/pages-kit/utils/route"),Ct=require("lodash"),Re=require("@blocklet/pages-kit/utils/common"),At=require("@blocklet/pages-kit/utils/page-model"),Ot=require("@reactivedata/reactive"),ne=require("glob"),Tt=require("lib0/decoding"),jt=require("lib0/encoding"),vt=require("lodash/cloneDeep"),Dt=require("lodash/debounce"),kt=require("lodash/get"),Rt=require("lodash/set"),xt=require("lodash/union"),_t=require("p-limit"),v=require("sequelize"),Mt=require("stream/promises"),Lt=require("tar"),$t=require("wait-on"),z=require("y-protocols/awareness"),ge=require("y-protocols/sync"),Nt=require("yaml");require("sqlite3");require("@blocklet/pages-kit/types/state");const _=t=>t&&t.__esModule?t:{default:t};function pe(t){if(t&&t.__esModule)return t;const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,s.get?s:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const P=_(yt),Ut=_(Be),Ae=_(St),Ge=_(h),Ft=_(It),qt=_(bt),$=pe(Et),ye=pe(Tt),k=pe(jt),Bt=_(vt),Je=_(Dt),Oe=_(kt),xe=_(Rt),Vt=_(xt),Gt=_(_t),Jt=_($t),B=pe(Nt);P.default.env.mode;P.default.env.OPENAI_API_KEY||process.env.OPENAI_API_KEY;P.default.env.OPENAI_BASE_URL||process.env.OPENAI_BASE_URL;P.default.env.TRANSLATE_ADDITIONAL_PROMPT||process.env.TRANSLATE_ADDITIONAL_PROMPT;P.default.env.PAGE_CONTENT_ADDITIONAL_PROMPT||process.env.PAGE_CONTENT_ADDITIONAL_PROMPT;const zt="image-bin";P.default.env.INIT_TEMPLATE_PATH;const ze=process.env.DATABASE_URL||Ge.default.join(P.default.env.dataDir,"db/pages-kit.db"),_e=P.default,Kt=()=>P.default.env.tenantMode==="multiple",Ht=()=>(Ft.default(_e.env.preferences.multiTenantAllProjectAccessPassports)?[]:_e.env.preferences.multiTenantAllProjectAccessPassports?.split(","))||[],Yt=Ge.default.join(P.default.env.dataDir,"fs-memoize-cache"),Wt=P.default.env.FS_MEMOIZE_CACHE_VERSION||"v1.0.0",f=qt.default("pages-kit"),Qt=v.DataTypes.sqlite.DATE.parse;v.DataTypes.sqlite.DATE.parse=(t,e)=>typeof t=="number"?new Date(t):Qt(t,e);const N=new v.Sequelize({dialect:"sqlite",storage:ze,benchmark:process.env.ENABLE_SEQUELIZE_BENCHMARK==="true",retry:{match:[/SQLITE_BUSY/],name:"query",max:10},logging:process.env.ENABLE_SEQUELIZE_LOGGING==="true"?console.log:!1});N.query("pragma journal_mode = WAL;");N.query("pragma synchronous = normal;");N.query("pragma journal_size_limit = 33554432;");N.query("pragma cache_size = -2000;");N.query("pragma mmap_size = 33554432;");process.on("SIGINT",async()=>{await N.close(),process.exit(0)});process.on("SIGTERM",async()=>{await N.close(),process.exit(0)});async function Xt(t,e){try{if(t.getDialect()!=="sqlite")return;const[n]=await t.query("SELECT 1");if(!n||n.length===0)return;await t.query("PRAGMA shrink_memory;")}catch(n){if(n.name==="SequelizeConnectionError"||n?.message&&/closed!/.test(n.message))return;console.error("Failed to cleanup SQLite memory",e,n)}}setInterval(async()=>{f.info("Start cleanupSqliteMemory"),await Xt(N,ze),f.info("End cleanupSqliteMemory")},60*1e3*10);class Te extends v.Model{}Te.init({id:{type:v.DataTypes.UUID,allowNull:!1,primaryKey:!0,defaultValue:v.DataTypes.UUIDV4},projectId:{type:v.DataTypes.UUID,allowNull:!1},componentId:{type:v.DataTypes.STRING,allowNull:!1}},{sequelize:N,tableName:"ProjectComponents",timestamps:!1});class M extends v.Model{static async getProjectByIdOrSlug(e){return M.findOne({where:{[v.Op.or]:[{id:e},{slug:e}]}})}}M.init({id:{type:v.DataTypes.UUID,defaultValue:v.DataTypes.UUIDV4,primaryKey:!0},name:{type:v.DataTypes.STRING,allowNull:!1},description:v.DataTypes.TEXT,createdAt:v.DataTypes.DATE,updatedAt:v.DataTypes.DATE,createdBy:{type:v.DataTypes.STRING,allowNull:!1},updatedBy:{type:v.DataTypes.STRING,allowNull:!1},slug:v.DataTypes.STRING,icon:v.DataTypes.STRING,pinnedAt:v.DataTypes.DATE,useAllResources:v.DataTypes.BOOLEAN,npmSecret:v.DataTypes.STRING,relatedBlocklets:{type:v.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){const t=this.getDataValue("relatedBlocklets");try{return t?JSON.parse(t):{}}catch(e){return f.error("Failed to parse relatedBlocklets",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("relatedBlocklets",t?JSON.stringify(t):"{}")}catch(e){f.error("Failed to set relatedBlocklets",{error:e,value:t}),this.setDataValue("relatedBlocklets","{}")}}},productionState:{type:v.DataTypes.JSON,allowNull:!1,defaultValue:{},get(){const t=this.getDataValue("productionState");try{return t?JSON.parse(t):{}}catch(e){return f.error("Failed to parse productionState",{error:e,rawValue:t}),{}}},set(t){try{this.setDataValue("productionState",t?JSON.stringify(t):"{}")}catch(e){f.error("Failed to set productionState",{error:e,value:t}),this.setDataValue("productionState","{}")}}}},{sequelize:N,paranoid:!0});M.hasMany(Te,{foreignKey:"projectId",as:"components"});const Zt=Yt,en=Wt,se=30*24*60*60*1e3,tn=24*60*60*1e3,Ke=async(t="")=>{const e=h.join(Zt,t);try{if(!(await w.promises.stat(e)).isDirectory())throw new Error(`${e} is not a directory`)}catch{await w.promises.mkdir(e,{recursive:!0})}return e},Me=(t,...e)=>t.keyGenerator?t.keyGenerator(...e):JSON.stringify([t.subdir||"",...e]),nn=(t,e)=>{const n=wt.createHash("md5").update(e).digest("hex");return h.join(t,`${en}-${n}.json`)},sn=async(t="")=>{const e=await Ke(t),n=Date.now();try{const s=await w.promises.readdir(e);await Promise.all(s.filter(o=>o.endsWith(".json")).map(async o=>{const a=h.join(e,o);try{const c=await w.promises.readFile(a,"utf-8"),r=JSON.parse(c);r.createdAt&&n-r.createdAt>se&&await w.promises.unlink(a)}catch{try{const r=await w.promises.stat(a);n-r.mtimeMs>se&&await w.promises.unlink(a)}catch{}}}))}catch(s){console.error(`Failed to cleanup cache in ${e}:`,s)}},on=(()=>{const t=new Set;return setInterval(async()=>{await Promise.all(Array.from(t).map(s=>sn(s)))},tn).unref(),s=>{t.add(s)}})();function ue(t,e){return e.subdir&&on(e.subdir),ee.memoize(async(...s)=>{const o=await Ke(e.subdir||""),a=Me(e,...s),c=nn(o,a);try{const r=await w.promises.readFile(c,"utf-8"),{value:p,createdAt:d}=JSON.parse(r);if(d&&Date.now()-d>se)throw await w.promises.unlink(c).catch(()=>{}),new Error("Cache expired");return p}catch{const p=await t(...s),d=JSON.stringify({value:p,createdAt:Date.now()});return w.promises.writeFile(c,d,"utf-8").catch(E=>{console.error("Failed to write fs cache:",E)}),p}},{keyGenerator:(...s)=>Me(e,...s),lruOptions:e.lruOptions||{max:100,ttl:se}})}const He=async()=>await import("typescript"),an=async()=>await import("esbuild"),rn=async()=>(await import("postcss")).default,cn=async()=>(await import("tailwindcss")).default,ln=async()=>(await import("autoprefixer")).default,pn=async(t,{componentId:e})=>{const n=`@tailwind components;
2
- @tailwind utilities;
3
- `,s=`.CustomComponent_${e}`,o=await rn(),a=await cn(),c=await ln();return(await o([a({content:[{raw:t,extension:"tsx"}]}),c({overrideBrowserslist:["> 1%","last 2 versions"],stats:{}}),p=>{p.walkRules(d=>{d.selectors=d.selectors.map(E=>E.replace(/\.(.+)/g,`${s}.$1,${s} .$1`))})}]).process(n)).css},un=async(t,{componentId:e})=>{const n=await pn(t,{componentId:e});return`export const __PagesKit_CSS__ = ${JSON.stringify(n)};
4
-
5
- ${t}
6
- `},Le=ue(async(t,e)=>{const n=await He();let s=n.transpileModule(t,{compilerOptions:{jsx:n.JsxEmit.React,target:n.ScriptTarget.ES2016,module:n.ModuleKind.ESNext},transformers:{before:[Ve.createBuiltinModuleTransformer(n)]}}).outputText;if(e.tailwind&&(s=await un(s,{componentId:e.componentId})),e.module===Ie.PreloadComponentScriptModule.ESM)return s;const o=n.transpileModule(s,{compilerOptions:{jsx:n.JsxEmit.React,target:n.ScriptTarget.ES2016,module:n.ModuleKind.CommonJS,moduleResolution:n.ModuleResolutionKind.Node16}}).outputText;return e.module===Ie.PreloadComponentScriptModule.CJS?o:mn(e.moduleName,o)},{subdir:"transpileModule"}),dn=async(t,e)=>{const{build:n}=await an(),o=(await n({entryPoints:["index.tsx"],external:Object.keys(be.BuiltinModules),format:"esm",target:"esnext",bundle:!0,write:!1,plugins:[{name:"vfs",setup(p){let d=null;p.onResolve({filter:/.*/},E=>E.path==="index.tsx"?{path:"index.tsx",namespace:"vfs"}:E.path==="./component"?{path:"component.tsx",namespace:"vfs"}:null),p.onLoad({filter:/.*/,namespace:"vfs"},async E=>{if(E.path==="index.tsx")return{contents:`export { ${e} } from './component'`,loader:"tsx"};if(E.path==="component.tsx")return{contents:t,loader:"tsx"};if(Ve.isRelativeModule(E.path)){const g=E.path.split("/").pop();if(d||(d=await ct({ensureLoaded:!1})),d?.chunks?.[g])try{const I=w.readFileSync(d.chunks[g],"utf-8");return f.info("get chunk from local file system",g),{contents:I,loader:"tsx"}}catch{}}return null})}}]})).outputFiles?.[0]?.contents;if(!o)throw new Error("Failed to build server code");const a=Buffer.from(o).toString(),c=await He();return c.transpileModule(a,{compilerOptions:{module:c.ModuleKind.ESNext,target:c.ScriptTarget.ES2020}}).outputText},fn=(t,e)=>new RegExp(`export\\s+\\{[^}]*(?:\\w+\\s+as\\s+${e}\\b|\\b${e}\\b)[^}]*\\}`,"m").test(t)?t:void 0,Ye=ue(async(t,e)=>{const n=await dn(t,e);return fn(n,e)},{subdir:"extractExportValueSchema"}),mn=(t,e)=>`// GENERATED FILE. DO NOT EDIT.
7
- var ${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
- ${e}
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
- `,We=async()=>{const{Sandbox:t}=await import("@blocklet/quickjs");return t};function hn(t){return t?.type==="react-component"}const K=new le.LRUCache({max:100,ttl:1e3*60*60*24}),gn=60*60,$e=10;function yn(t){f.info("clear preload components cache",{cacheKey:t}),K.delete(t)}function Sn(t){for(const e of K.keys())e.includes(t)&&(f.info("clear preload components cache",{cacheKey:e}),yn(e))}function wn({mode:t,instanceId:e,componentId:n,locale:s}){return["getPreloadComponents",t,e,n,s].join("-")}async function In({mode:t,req:e,state:n,locale:s,instances:o,module:a}){const{supportedLocales:c,config:{defaultLocale:r}}=n;if(!r)return null;const p=(await Promise.all(o.map(async l=>{try{const i=wn({mode:t,instanceId:l.id,componentId:l.componentId,locale:s});if(t!=="draft"&&l.useCache&&K.has(i))return f.info(`get preload component from cache: ${i}`),K.get(i);const S=oe({state:n,componentId:l.componentId});if(!S)return null;const A=await bn({req:e,state:n,componentId:S.id,locale:s,defaultLocale:r,properties:l.properties});if(!A)return null;const y={instanceId:l.id,preload:A};if(t!=="draft"&&l.useCache){let m=gn;l.cacheDuration&&(m=l.cacheDuration),f.info(`set preload component to cache(${m}s): ${i}`),K.set(i,y,{ttl:m*1e3})}return y}catch(i){return f.error("get preload component error",{instanceId:l.id,componentId:l.componentId},{error:i}),null}}))).filter(l=>!!l),d=Object.values(p.reduce((l,i)=>({...l,...i.preload.components}),{}));async function E(){const l=await Promise.all(d.map(async i=>{const S=W.componentUMDName({componentId:i.component.id}),A=a===Ie.PreloadComponentScriptModule.ESM?{module:a,script:await Le(i.script,{componentId:i.component.id,module:a,tailwind:t!=="draft"})}:{module:a,script:await Le(i.script,{componentId:i.component.id,module:a,moduleName:S,tailwind:t!=="draft"}),moduleName:S};return[i.component.id,{component:i.component,script:A}]}));return Object.fromEntries(l)}const g=await E();return{config:{defaultLocale:r,supportedLocales:c},components:g,instances:p.map(l=>({id:l.instanceId,componentId:l.preload.component.id,locales:{[l.preload.locale]:{props:l.preload.props}}}))}}async function bn({req:t,state:e,componentId:n,locale:s,defaultLocale:o,properties:a}){const{supportedLocales:c}=e,r=oe({state:e,componentId:n});if(!r)return null;const p=c.some(E=>E.locale===s)?s:o;if(!p)return null;const d=await Qe({req:t,state:e,componentId:n,locale:p,defaultLocale:o,properties:a});return d?{component:r,...d}:null}const En=20;async function Qe({req:t,depth:e=0,state:n,componentId:s,locale:o,defaultLocale:a,properties:c}){if(e>En)throw new RangeError("max component depth exceeded");const r=Pn({state:n,componentId:s,properties:c,locale:o});if(!r)return null;const{props:p,component:d}=r,E={locale:o||a,components:{[r.component.id]:{component:r.component,script:r.script}},props:{...p}};try{const g=hn(d.renderer)?d.renderer.getServerSideProps:void 0,I=await Cn({...r,req:t,serverSideProps:g});I?.props&&Object.assign(E.props,I.props)}catch(g){f.error("preload data at server side error",{componentId:s,name:r.component.name},{error:g})}return await Promise.all(Object.entries(p).map(async([g,I])=>{if(I?.type===W.RenderNestedComponent){const l=await Qe({req:t,depth:e+1,state:n,componentId:I.componentId,locale:o,defaultLocale:a,properties:I.properties});l&&(Object.assign(E.components,l.components),Object.assign(E.props,{[g]:{type:W.RenderNestedComponent,componentId:I.componentId,props:l.props}}))}})),E}function Pn({state:t,componentId:e,locale:n,properties:s}){const o=oe({state:t,componentId:e});if(!o)return null;const a=W.mergeComponent({componentId:e,getComponent:c=>oe({state:t,componentId:c}),locale:n,defaultLocale:t.config.defaultLocale,properties:s});return a?{component:o,script:a.script,props:{locale:n,...a.props}}:null}function oe({state:t,componentId:e}){return t.components[e]?.data??t.resources.components?.[e]?.component}async function Cn({component:t,script:e,props:n,req:s,serverSideProps:o}){if(!o&&!e?.includes("getServerSideProps"))return null;const a=o??await Ye(e,"getServerSideProps");if(!a)return null;const r=(a.match(/export\s*{\s*(\w+)\s+as\s+getServerSideProps\s*}/)||a.match(/export\s*{\s*getServerSideProps\s*}/))?.[1]||"getServerSideProps",p=new Promise(g=>{setTimeout(()=>{g({})},$e*1e3)}),d=await We();return await Promise.race([p,d.callFunction({code:`${a}
33
-
34
- export async function getServerSidePropsWrapper(props) {
35
- const { location, fetch, props: componentProps } = 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 ${r}(componentProps);
44
- } finally {
45
- // 清理全局状态
46
- if (originalLocation) globalThis.location = originalLocation;
47
- if (originalFetch) globalThis.fetch = originalFetch;
48
- }
49
- }`,filename:`${t.name||t.id}.js`,moduleLoader:g=>{if(g==="@blocklet/pages-kit/builtin/utils")return` const { joinURL, withQuery, getQuery, getComponentMountPoint } = globalThis
50
- export { joinURL, withQuery, getQuery, getComponentMountPoint }
51
- `;if(g==="@blocklet/pages-kit/builtin/dayjs")return ee.BuiltinModules.dayjs;if(g in ee.BuiltinModules)return ee.BuiltinModules[g];if(g in be.BuiltinModules){const I=be.BuiltinModules[g];return Ae.default(I)?void 0:I}},global:{console:{log:(...g)=>{f.info(...g)},warn:(...g)=>{f.warn(...g)},error:(...g)=>{f.error(...g)}},getComponentMountPoint:gt.getComponentMountPoint,joinURL:R.joinURL,withQuery:R.withQuery,getQuery:R.getQuery},functionName:"getServerSidePropsWrapper",args:[{location:{href:R.joinURL(R.withHttps(s.hostname),s.originalUrl)},fetch:(g,{...I}={})=>{const l=typeof g=="string"&&g.startsWith("/")?R.joinURL(P.default.env.appUrl,g):g;if(typeof l=="string"&&R.parseURL(l).host===R.parseURL(P.default.env.appUrl).host){const i=s.get("cookie");if(i){const S=new Be.Headers(I.headers);S.set("cookie",i),I.headers=S}}return Ut.default(l,{...I,timeout:$e*1e3}).then(i=>({ok:i.ok,status:i.status,statusText:i.statusText,headers:Object.fromEntries(i.headers.entries()),json:()=>i.json()}))},props:n}]})])}const An=ue(async(t,e,n,s)=>{if(!t?.includes(e)&&!s)return null;const o=s??await Ye(t,e);if(o)try{return await(await We()).callFunction({code:`
52
- ${o}
53
-
54
- export function get${e}SchemaWrapper() {
55
- return ${e};
56
- }
57
- `,filename:`${n}.js`,functionName:`get${e}SchemaWrapper`})}catch(a){return f.error(`获取 ${e} 失败`,{componentId:n,error:a}),null}return null},{subdir:"getExportSchemaValueFromCode"}),On="z8iZiDFg3vkkrPwsiba1TLXy3H9XHzFERsP8o",Ee="page",Ne="trigger-reload-project-resource",je=On,Tn="z2qa7BQdkEb3TwYyEYC1psK6uvmGnHSUHt5RM";function ae(t){t.observeDeep(e=>{e.some(n=>n.changes.keys.has("updatedAt")||n.changes.keys.has("publishedAt"))||t.set("updatedAt",new Date().toISOString())})}function Xe(){return w.mkdtempSync(h.join(P.default.env.dataDir,"tmp-"))}function re(t,e,n=[]){return Array.isArray(t)?t.flatMap((s,o)=>re(s,e,[...n,o])):typeof t=="object"?t===null?[]:Object.entries(t).flatMap(([s,o])=>re(o,e,[...n,s])):e(t)?[n]:[]}function x(t){return t.filter(e=>e!=null)}function jn(t){t.pages&&Object.keys(t.pages).forEach(n=>{const s=F.getYjsValue(t.pages[n]);s&&s instanceof $.Map&&ae(s)});const e=F.getYjsValue(t.pages);e&&e instanceof $.Map&&e.observe(n=>{n.changes.keys.forEach((s,o)=>{if(s.action==="add"){const a=F.getYjsValue(t.pages[o]);a&&a instanceof $.Map&&ae(a)}})})}function vn(t){t.routes&&Object.keys(t.routes).forEach(n=>{const s=F.getYjsValue(t.routes?.[n]);s&&s instanceof $.Map&&ae(s)});const e=F.getYjsValue(t.routes);e&&e instanceof $.Map&&e.observe(n=>{n.changes.keys.forEach((s,o)=>{if(s.action==="add"){const a=F.getYjsValue(t.routes?.[o]);a&&a instanceof $.Map&&ae(a)}})})}function Dn(t,e){for(const n of e||Object.keys(t.routes||{})){let s=n,o=[];if(n.includes("-")){const[a,...c]=n.split("-");s=a,o=c||[]}if(t.routes?.[s]!==void 0){t.routes[s].publishedAt=new Date().toISOString();const a=t.routes[s];if(!a||!a.params||a.params.length===0)continue;if(n.includes("-")&&o.length>0){const c=te.getRouteMetaDataByOptionIds(o,a);c&&(c.publishedAt=new Date().toISOString())}if(!e){const c=te.generateParamCombinations({basePath:a.path,params:a.params,routeId:a.id,paramsOptions:a.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const r of c)r.routeMetaData??={},r.routeMetaData.publishedAt=new Date().toISOString()}}}}function Se({page:t,route:e,state:n,routeId:s,routePathInfo:o}){f.info(`Executing datasource data assembly, routeId: ${s}, routePathInfo: ${JSON.stringify(o)}`);const a={...Ct.cloneDeep(t),id:s,slug:o?.path??e.path,createdAt:e.createdAt,updatedAt:o?.routeMetaData?.updatedAt??e.updatedAt,publishedAt:o?.routeMetaData?.publishedAt??e.publishedAt,isPublic:(o?.routeMetaData?.isPublic??e.isPublic)&&e.isPublic};for(const c of n.supportedLocales){if(e.dataSource){let r=e.id;o&&(r=o.paramOptionIds.join("-"));const p=e.dataSource.pathDataMappings?.[r]?.dataCache?.[c.locale]??e.dataSource.pathDataMappings?.[r]?.dataCache?.[n.config.defaultLocale||"en"];if(!p)continue;Pt.setPageDataSource(a,n,c.locale,p)}o&&o.routeMetaData&&(o.routeMetaData.publishedAt=new Date().toISOString())}return a}const V=new le.LRUCache({max:100,ttl:10*60*1e3});function kn(t,e=[]){let n=0;const s=Array.from(V.keys()),o=[];for(const a of t){o.push(`page-html:prod:${a}:lang-path=none`);for(const c of e)o.push(`page-html:prod:/${c}${a}:lang-path=${c}`)}for(const a of s){const c=a.split(":lang-path=")[0]||"";for(const r of o){const d=(r.split(":lang-path=")[0]||"").replace(/\/:[^/]+/g,"");if(c.startsWith(d)){V.delete(a),n++,f.info(`[Cache CLEAR] key: ${a}`);break}}}return f.info(`[Cache CLEAR] cleared ${n} entries for patterns:`,o),n}function Rn({projectId:t,projectSlug:e,supportedLocales:n=[]}){let s=0;const o=Array.from(V.keys()),a=[];a.push(`page-html:prod:/${t}`),e&&e!==t&&a.push(`page-html:prod:/${e}`);for(const c of n)a.push(`page-html:prod:/${c}/${t}`),e&&e!==t&&(e!=="/"?a.push(`page-html:prod:/${c}/${e}`):a.push(`page-html:prod:/${c}`));for(const c of o)for(const r of a)if(c.startsWith(r)){V.delete(c),s++,f.info(`[Cache CLEAR PROJECT] key: ${c}`);break}return f.info(`[Cache CLEAR PROJECT] cleared ${s} entries for project ${t}${e?` (slug: ${e})`:""}`),s}function xn(){const t=V.size;return V.clear(),f.info(`[Cache CLEAR ALL] cleared ${t} entries`),t}P.default.events.on(P.default.Events.envUpdate,xn);const{uploadToMediaKit:_n}=require("@blocklet/uploader-server"),ve=/^\w+(\w|-|\.)+\w+\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm)$/,H=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/i,Ue=/mediakit:\/\/([a-f0-9]{32}\.(jpe?g|png|gif|svg|bmp|webp|mp4|m4v|webm))/gi,Mn=1e4,Ln=3e4,Q=0,we=1,$n=0,Nn=1,Ze=P.default,X=h.join(process.env.BLOCKLET_DATA_DIR,"site-state");function ie(t){return t?.replace(/\//g,"|")||""}function Un(){const t=Ze.env.languages.map(n=>({locale:n.code,name:n.name})),e=t[0]?.locale;return{pageIds:[],pages:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{},components:{},supportedLocales:t,config:{defaultLocale:e},resources:{}}}class j extends $.Doc{constructor(e){super(),this.options=e,w.existsSync(this.draftYjsFilePath)&&$.applyUpdate(this,w.readFileSync(this.draftYjsFilePath)),this.syncedStore=Ot.reactive(F.syncedStore({pages:{},pageIds:[],components:{},supportedLocales:[],config:{},resources:{},routeIds:[],routes:{},dataSourceIds:[],dataSources:{}},this)),this.initObserver(),this.on("update",this.updateHandler),this.awareness=new z.Awareness(this),this.awareness.on("update",this.awarenessChangeHandler),this.ensureDataStructure()}static RELEASE_DELAY=5*60*1e3;static PERIODIC_CHECK_INTERVAL=2*60*60*1e3;static sharedInstances={};static pageUrlMapCache=new le.LRUCache({max:100,ttl:1e3*60*60*24});static periodicCheckTimer;static safeDeleteProjectStateDir(e){if(!e)throw new Error("Should provide project context");try{const n=h.join(X,e),s=h.join(X,`@del-${e}`);w.renameSync(n,s)}catch(n){f.error("Failed to safe delete project state dir:",n)}}static async getProjectIds(){return(await M.findAll({attributes:["id"],raw:!0})).map(e=>e.id)}static get projectIds(){return ne.globSync("*/",{cwd:X,ignore:["@del-*","@tmp-*",".*","staging","production","@backup-*","undefined"]})}static get allShared(){return this.projectIds.map(e=>j.shared(e))}static shared(e){if(!e)throw new Error("Should provide project context");let n=j.sharedInstances[e];return n||(n=new j({path:h.join(X,e)}),j.sharedInstances[e]=n,it({projectId:e,pages:de,components:fe}),n)}static async getProductionState(e){return(await M.findByPk(e,{attributes:["productionState"]}))?.productionState??Un()}destroy(){this.cancelRelease(),this.save({flush:!0}),this.conns.forEach((n,s)=>this.closeConn(s)),this.awareness.destroy();const e=h.basename(this.options.path);delete j.sharedInstances[e],super.destroy()}initObserver(){jn(this.syncedStore),vn(this.syncedStore)}get draftYjsFilePath(){return h.join(this.options.path,"draft.yjs")}static async getStateByProjectId(e,n){if(n==="draft"){const s=j.shared(e);return JSON.parse(JSON.stringify(s.syncedStore))}return j.getProductionState(e)}async getState(e){if(e==="draft")return JSON.parse(JSON.stringify(this.syncedStore));const n=h.basename(this.options.path);return j.getProductionState(n)}async setState(e,n){const s=await tt(n,{exportAssets:!1,includeResources:!0}),o=this.getPublishDir(e);if(w.mkdirSync(h.dirname(o),{recursive:!0}),w.rmSync(o,{force:!0,recursive:!0}),w.renameSync(s,o),e==="production"){const a=h.basename(this.options.path);j.pageUrlMapCache.delete(a),await M.update({productionState:n},{where:{id:a}})}}getPublishDir(e){return h.join(this.options.path,e)}syncedStore;conns=new Map;awareness;releaseTimer;awarenessChangeHandler=({added:e,updated:n,removed:s},o)=>{const a=e.concat(n,s);if(o!==null){const p=this.conns.get(o);p&&(e.forEach(d=>{p.add(d)}),s.forEach(d=>{p.delete(d)}))}const c=k.createEncoder();k.writeVarUint(c,we),k.writeVarUint8Array(c,z.encodeAwarenessUpdate(this.awareness,a));const r=k.toUint8Array(c);this.conns.forEach((p,d)=>this.send(d,r))};updateHandler=e=>{const n=k.createEncoder();k.writeVarUint(n,Q),ge.writeUpdate(n,e);const s=k.toUint8Array(n);this.conns.forEach((o,a)=>this.send(a,s))};ensureDataStructure=()=>{const{supportedLocales:e,pages:n,pageIds:s,config:o,routes:a,routeIds:c}=this.syncedStore;{const r=new Set(Object.keys(n));let p=0;for(;p<s.length;){const d=s[p];r.has(d)?(r.delete(d),p++):s.splice(p,1)}}{const r=new Set(Object.keys(a));let p=0;for(;p<c.length;){const d=c[p];r.has(d)?(r.delete(d),p++):c.splice(p,1)}}e.splice(0,e.length),e.push(...Ze.env.languages.map(r=>({locale:r.code,name:r.name}))),o.defaultLocale=e[0]?.locale;{let r=0;const p=new Set;for(;r<e.length;){const{locale:d}=e[r];p.has(d)?e.splice(r,1):(r++,p.add(d))}}};send=(e,n)=>{e.readyState!==$n&&e.readyState!==Nn&&this.closeConn(e);try{e.send(n,s=>{s&&this.closeConn(e)})}catch{this.closeConn(e)}};closeConn=e=>{if(e.removeAllListeners(),this.conns.has(e)){const n=this.conns.get(e);this.conns.delete(e),n&&z.removeAwarenessStates(this.awareness,Array.from(n),null)}e.close(),this.checkAndScheduleRelease()};checkAndScheduleRelease(){this.conns.size===0&&this.scheduleRelease()}scheduleRelease(){this.cancelRelease();const e=h.basename(this.options.path);this.releaseTimer=setTimeout(()=>{f.info(`[SiteState] releasing instance due to no active connections: ${e}`),this.conns.size===0&&(this.releaseTimer=void 0,this.destroy())},j.RELEASE_DELAY),f.info(`[SiteState] scheduled release for project ${e} in ${j.RELEASE_DELAY/1e3}s`)}cancelRelease(){if(this.releaseTimer){clearTimeout(this.releaseTimer),this.releaseTimer=void 0;const e=h.basename(this.options.path);f.info(`[SiteState] cancelled scheduled release for project ${e}`)}}autoSave=Je.default(()=>{w.mkdirSync(h.dirname(this.draftYjsFilePath),{recursive:!0}),w.writeFileSync(this.draftYjsFilePath,$.encodeStateAsUpdate(this))},Mn);save=({flush:e=!1}={})=>{this.autoSave(),e&&this.autoSave.flush()};publish=async({mode:e,routes:n})=>{const s=await this.getState("draft"),o=await this.getState("production");await qe(s,o,{routes:n,mergeMode:"replace",deleteRoutes:!0,publishMode:e}),o.config.publishedAt=new Date().getTime(),Dn(this.syncedStore,n),await this.setState(e,o),await this.clearPageCacheForRoutes(n,o)};mergeState=async(e,n)=>{const s=JSON.parse(JSON.stringify(n));e.config.fontFamily??={};const o=s.config?.fontFamily,a=e.config?.fontFamily;e.config.fontFamily.title=o?.title||a?.title,e.config.fontFamily.description=o?.description||a?.description,await new Promise((c,r)=>{this.transact(async()=>{try{const p=await qe(e,n);c(p)}catch(p){r(p)}})})};clearPageCacheForRoutes=async(e,n)=>{const s=h.basename(this.options.path),a=(await M.findByPk(s))?.slug||s;if(f.info(`[SiteState] clearing page cache for project ${s}, routes:`,e||[]),!e||e.length===0){Rn({projectId:s,projectSlug:a,supportedLocales:n.supportedLocales.map(d=>d.locale)});return}const c=n.supportedLocales.map(d=>d.locale),r=[],p=e.filter(d=>n.pages[d]);for(const d of p){const g=n.pages[d].slug;a&&a!==s&&(a==="/"?r.push(g):r.push(`/${a}${g}`)),r.push(`/${s}${g}`)}if(f.info(`[SiteState] clearing page cache for project ${s}, pathPatterns:`,r),r.length>0){const d=kn(r,c);f.info(`[SiteState] cleared ${d} page cache entries for project ${s}, routes:`,e)}};addConnection=e=>{if(this.conns.has(e))return;this.cancelRelease(),e.binaryType="arraybuffer",this.conns.set(e,new Set),e.on("message",o=>this.messageListener(e,new Uint8Array(o)));let n=!0;const s=setInterval(()=>{if(!n)this.conns.has(e)&&this.closeConn(e),clearInterval(s);else if(this.conns.has(e)){n=!1;try{e.ping()}catch{this.closeConn(e),clearInterval(s)}}},Ln);e.on("close",()=>{this.closeConn(e),clearInterval(s)}),e.on("pong",()=>{n=!0});{const o=k.createEncoder();k.writeVarUint(o,Q),ge.writeSyncStep1(o,this),this.send(e,k.toUint8Array(o));const a=this.awareness.getStates();if(a.size>0){const c=k.createEncoder();k.writeVarUint(c,we),k.writeVarUint8Array(c,z.encodeAwarenessUpdate(this.awareness,Array.from(a.keys()))),this.send(e,k.toUint8Array(c))}}};messageListener=(e,n)=>{try{const s=k.createEncoder(),o=ye.createDecoder(n),a=ye.readVarUint(o);switch(a){case Q:k.writeVarUint(s,Q),ge.readSyncMessage(o,s,this,null),k.length(s)>1&&(this.ensureDataStructure(),this.send(e,k.toUint8Array(s)));break;case we:{z.applyAwarenessUpdate(this.awareness,ye.readVarUint8Array(o),e);break}default:f.warn(`Unsupported messageType ${a}`)}}catch(s){f.error(s)}this.save()};static async pageUrlMap(e,n){let s=[];n?s=[n]:s=await this.getProjectIds();let o={};if(e==="production"&&s?.length){const a=new Map(s.map(c=>[c,!0]));for(const c of s){const r=j.pageUrlMapCache.get(c);r&&(o={...o,...r},a.delete(c))}s=Array.from(a.keys())}if(s?.length){const a=await M.findAll({where:{id:{[v.Op.in]:s}}});await Promise.all(a.map(async c=>{const r=c.id,p=c.slug||r,d={},E=e==="production"&&c?.productionState?c.productionState:await j.getStateByProjectId(c.id,e),g=Vt.default(P.default.env.languages.map(l=>l.code),E.supportedLocales.map(l=>l.locale)),I=(l,i)=>{p&&(d[R.joinURL("/",p,l)]={...i,shouldRedirect:!0,mainPage:!0}),d[R.joinURL("/",r,l)]={...i,shouldRedirect:!0,mainPage:!0};for(const S of g){const A={...i,locale:S};d[R.joinURL("/",S,r,l)]=A,p&&(d[R.joinURL("/",S,p,l)]=A)}};if(e==="draft")for(const l of E.routeIds||[]){const i=E?.routes?.[l];if(!i)continue;if(i.params&&i.params.length>0){const y=te.generateParamCombinations({basePath:i.path,params:i.params,routeId:i.id,paramsOptions:i.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]});for(const m of y){const b=m.path,O={projectId:r,projectSlug:p,pageSlug:b,pageId:i.displayTemplateId||"",routeId:l,defaultLocale:g?.[0],locales:g,publishedAt:E.config.publishedAt,isPublic:i.isPublic&&m?.routeMetaData?.isPublic};I(b,O)}}const S=i.path,A={projectId:r,projectSlug:p,pageSlug:S,pageId:i.displayTemplateId||"",routeId:l,defaultLocale:g?.[0],locales:g,publishedAt:E.config.publishedAt,isPublic:i.isPublic};I(S,A)}for(const l of E.pageIds){const i=E.pages[l];if(!i||e==="production"&&!i.isPublic)continue;const S=i.slug,A=c.slug||r,y={projectId:r,projectSlug:A,pageSlug:S,pageId:l,defaultLocale:g?.[0],locales:g,publishedAt:E.config.publishedAt,isPublic:i.isPublic,templateConfig:i.templateConfig};I(S,y)}e==="production"&&j.pageUrlMapCache.set(r,d),o={...o,...d}}))}return o}getDocumentSize(){return $.encodeStateAsUpdate(this).byteLength}static getInstancesSizeInfo(){const e=[];for(const[n,s]of Object.entries(j.sharedInstances)){const o=s.getDocumentSize();e.push({projectId:n,sizeInBytes:o,sizeInMB:`${(o/(1024*1024)).toFixed(2)} MB`,activeConnections:s.conns.size})}return e}static startPeriodicCheck(){this.periodicCheckTimer||(this.periodicCheckTimer=setInterval(()=>{this.performPeriodicCheck()},this.PERIODIC_CHECK_INTERVAL),f.info(`[SiteState] periodic check started, interval: ${this.PERIODIC_CHECK_INTERVAL/(60*60*1e3)} hours`))}static stopPeriodicCheck(){this.periodicCheckTimer&&(clearInterval(this.periodicCheckTimer),this.periodicCheckTimer=void 0,f.info("[SiteState] periodic check stopped"))}static performPeriodicCheck(){const e=Object.keys(j.sharedInstances).length,n=[],s=[];for(const[o,a]of Object.entries(j.sharedInstances))a.conns.size===0?n.push({projectId:o,instance:a}):s.push({projectId:o,connections:a.conns.size});if(f.info(`[SiteState] periodic check summary: total instances: ${e}, with connections: ${s.length}, without connections: ${n.length}`),n.length>0){f.info(`[SiteState] releasing ${n.length} instances without connections:`,n.map(a=>a.projectId));let o=0;for(const{projectId:a,instance:c}of n)try{f.info(`[SiteState] releasing instance due to periodic check: ${a}`),c.destroy(),o++}catch(r){f.error(`[SiteState] failed to release instance ${a} during periodic check:`,r)}f.info(`[SiteState] periodic check completed: ${o}/${n.length} instances released successfully`)}else e>0?f.debug("[SiteState] periodic check: all instances have active connections"):f.debug("[SiteState] periodic check: no instances exist")}}async function Fn(t,e,n){if(!t||!w.existsSync(t)||!w.lstatSync(t).isFile())return null;let s=n[t];return s||(s=(async()=>{try{return(await _n({filePath:t,fileName:e}))?.data?.filename}catch(o){return f.error(`Failed to upload asset ${t}:`,o),null}})(),n[t]=s),s}const qn=async(t,e)=>{const n=h.basename(t),s=await Ce.call({name:je,path:R.joinURL("/uploads",n),responseType:"stream",method:"GET"});if(s.status>=200&&s.status<400){const o=w.createWriteStream(e);await Mt.pipeline(s.data,o)}else throw new Error(`download asset failed ${s.status}`)},Bn=async(t,e)=>{await Promise.all(t.map(async n=>{try{await qn(n,h.join(e,h.basename(n)))}catch(s){f.error(`Failed to export assets: ${n}, ${s}`)}}))};function et(t){return ve.test(t)?[t]:H.test(t)?(Ue.lastIndex=0,Array.from(t.matchAll(Ue)).map(n=>n[1]).filter(n=>!!n)):[]}async function Z(t,e,n){const{getFilename:s,exportAssets:o}=n,a=h.join(e,s(t));if(w.mkdirSync(h.dirname(a),{recursive:!0}),w.writeFileSync(a,B.stringify(t)),o){const r=re(t,p=>typeof p=="string"&&(ve.test(p)||H.test(p))).map(p=>{const d=Oe.default(t,p);return et(d)}).flat().filter(Boolean);await Bn(r,h.dirname(a))}}const Pe=new le.LRUCache({max:100,ttl:1*60*1e3});async function Fe(t,e,n){const s=re(t,r=>typeof r=="string"&&(ve.test(r)||H.test(r))),o=Gt.default(2),a=s.map(r=>o(async()=>{try{const p=Oe.default(t,r),d=et(p);for(const E of d){const g=h.basename(E),I=n.getFilePath(E,r),l=I?`${I}:${g}`:g,i=Pe.get(l);if(i){H.test(p)||xe.default(t,r,i);return}const S=await Fn(I,g,e);S&&(H.test(p)||xe.default(t,r,S),Pe.set(l,S))}}catch(p){f.error(`Failed to process upload for path ${r.join(".")}:`,p.message||p.reason)}})),c=await Promise.allSettled(a);n.onFinish?.(c)}async function tt(t,{exportAssets:e,pageIds:n="all",componentIds:s="all",rawConfig:o,includeResources:a=!1,routeIds:c="all"}={}){const r=n==="all"?t.pageIds:n,p=W.getComponentDependencies({state:t,pageIds:r,componentIds:s==="all"?Object.keys(t.components):s}),d=c==="all"?t.routeIds:c,E=u=>({id:u.id,name:u.name,isTemplateSection:u.isTemplateSection??!1,templateDescription:u.templateDescription,llmConfig:u.llmConfig,component:u.component,config:u.config,visibility:u.visibility,sections:u?.sectionIds?x(u?.sectionIds?.map(C=>{const D=u.sections?.[C];return D&&E(D)})):void 0}),g=(u,C)=>({id:u.id,createdAt:u.createdAt,updatedAt:u.updatedAt,publishedAt:u.publishedAt,isPublic:u.isPublic??!0,templateConfig:u.templateConfig,meta:u.locales?.[C]??{},sections:x(u.sectionIds.map(D=>{const U=u.sections[D];return U&&E(U)})),dataSource:Object.fromEntries(Object.entries(u.dataSource||{}).map(([D,U])=>[D,U?.[C]??{}]))}),I=u=>({id:u.id,createdAt:u.createdAt,updatedAt:u.updatedAt,publishedAt:u.publishedAt,path:u.path,handler:u.handler,isPublic:u.isPublic??!0,params:u.params??[],enabledGenerate:u.enabledGenerate??!1,displayTemplateId:u.displayTemplateId,dataSource:u.dataSource}),l=x(d.map(u=>{const C=t.routes[u];return C&&I(C)})),i=x(t.supportedLocales.map(u=>u.locale).flatMap(u=>r.map(C=>{const D=t.pages[C];return D&&{locale:u,slug:D.slug,page:g(D,u)}}))),S=Xe(),A=h.join(S,"pages");w.mkdirSync(A,{recursive:!0});const y=h.join(S,"components");w.mkdirSync(y,{recursive:!0});const m=h.join(S,"routes");w.mkdirSync(m,{recursive:!0});for(const{locale:u,slug:C,page:D}of i)await Z(D,A,{getFilename:()=>`${ie(C)||"index"}.${u}.yml`,exportAssets:e});for(const u of l)await Z(u,m,{getFilename:()=>`${ie(u.path)||"index"}.yml`,exportAssets:e});for(const u of p){const C=t.components[u]?.data;C&&await Z(C,y,{getFilename:D=>`${D.name||"unnamed"}.${D.id}.yml`,exportAssets:e})}const b=h.join(S,".blocklet/pages/pages.config.yml");w.mkdirSync(h.dirname(b),{recursive:!0});const O={pages:x(r.map(u=>{const C=t.pages[u];return C&&{id:u,slug:C.slug}})),routes:x(d.map(u=>{const C=t.routes[u];return C&&{id:u,path:C.path}})),components:x(p.map(u=>{const C=t.components[u]?.data;return C&&{id:u,name:C.name}})),...a?{resources:{components:x(Object.keys(t.resources?.components||{}).filter(u=>p.includes(u)).map(u=>({id:u,name:t.resources?.components?.[u]?.component?.name})))}}:{},supportedLocales:t.supportedLocales,config:t.config};w.writeFileSync(b,B.stringify(O));const T=h.join(S,"config.source.json");if(o&&w.writeFileSync(T,JSON.stringify(o)),a){const u=h.join(S,"resources"),C=h.join(u,"components");w.mkdirSync(C,{recursive:!0});for(const G of Object.keys(t?.resources?.components??{}).filter(L=>p.includes(L))){const L=t.resources?.components?.[G]?.component;L&&await Z(L,C,{getFilename:J=>`${J.name||"unnamed"}.${J.id}.yml`,exportAssets:e})}const D=h.join(S,"chunks");w.mkdirSync(D,{recursive:!0});const U=Gn();for(const G of Object.keys(t?.resources?.components??{}).filter(L=>p.includes(L))){const L=t.resources?.components?.[G]?.component;if(L&&L.renderer?.type==="react-component"){const J=L.renderer?.chunks??[];if(J?.length>0)for(const me of J){const De=h.join(D,me),he=U?.[me];try{he&&w.existsSync(he)&&!w.existsSync(De)&&w.copyFileSync(he,De)}catch(lt){f.error(`copy chunk ${me} error`,lt.message)}}}}}return S}async function Vn(t,{importAssets:e,includeResources:n}={}){if(!w.existsSync(t))return null;let s,o=!1;try{w.lstatSync(t).isDirectory()?s=t:/\.(tgz|gz|tar)$/.test(t)&&(o=!0,s=Xe(),await Lt.x({file:t,C:s}));const a=ne.globSync("**/.blocklet/pages/pages.config.yml",{cwd:s,absolute:!0}).at(0),c=a&&h.join(h.dirname(a),"../../pages"),r=a&&h.join(h.dirname(a),"../../components"),p=a&&h.join(h.dirname(a),"../../routes");if(!a)return null;const d=B.parse(w.readFileSync(a).toString()),E=(y,m,b)=>{let O=h.join(y,`${m}${b?`.${b}`:""}.yml`);return(!w.existsSync(O)||!w.lstatSync(O).isFile())&&(O=h.join(y,m,`index${b?`.${b}`:""}.yml`),!w.existsSync(O)||!w.lstatSync(O))?null:B.parse(w.readFileSync(O).toString())},g=(y,m)=>{try{const b=ne.globSync(`*.${m}.yml`,{cwd:y,absolute:!0})[0];return b?B.parse(w.readFileSync(b).toString()):null}catch(b){f.error("parse component error",b)}return null},I=(y,m)=>{let b=h.join(y,`${m}.yml`);return(!w.existsSync(b)||!w.lstatSync(b).isFile())&&(b=h.join(y,m,"index.yml"),!w.existsSync(b)||!w.lstatSync(b))?null:B.parse(w.readFileSync(b).toString())},l=x(d.pages.map(({slug:y})=>{const m=x(d.supportedLocales.map(({locale:T})=>{const u=c?E(c,ie(y),T):void 0;if(u)return{locale:T,page:u};const C=c?E(c,y,T):void 0;return C&&{locale:T,page:C}})),b=m[0]?.page;if(!b)return null;const O=b.sections.map(At.unzipSection);return{id:b.id||Re.nextId(),createdAt:b.createdAt,updatedAt:b.updatedAt,publishedAt:b.publishedAt,isPublic:b.isPublic??!0,templateConfig:b.templateConfig,slug:y,sections:Object.fromEntries(O.map(T=>[T.id,T])),sectionIds:O.map(T=>T.id),locales:Object.fromEntries(m.map(({locale:T,page:u})=>[T,u.meta])),dataSource:b.dataSource?Object.fromEntries([...new Set(m.flatMap(({page:T})=>Object.keys(T.dataSource??{})))].map(T=>[T,Object.fromEntries(m.map(({locale:u,page:C})=>{const D=C.dataSource?.[T];return[u,D||{}]}))])):Object.fromEntries([...new Set(m.flatMap(({page:T})=>T.sections.map(u=>u.id)))].map(T=>[T,Object.fromEntries(m.map(({locale:u,page:C})=>{const D=C.dataSource?.[T];if(D)return[u,D];const U=C.sections.find(G=>G.id===T);return[u,U?.properties||{}]}))]))}})),i=x(d?.routes?.map(({path:y})=>{const m=p?I(p,ie(y)):void 0;return{...m,id:m?.id||Re.nextId(),createdAt:m?.createdAt??new Date().toISOString(),updatedAt:m?.updatedAt??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:m?.path??`/${m?.id}`,params:m?.params,handler:m?.handler??"Pages Kit",isPublic:m?.isPublic??!0,enabledGenerate:m?.enabledGenerate??!1,displayTemplateId:m?.displayTemplateId??void 0,dataSource:m?.dataSource??{}}})??[]),S=r?x(d.components?.map(({id:y})=>g(r,y))??[]):[];if(e){const y=(...m)=>{f.info(`[${o?h.basename(t):h.basename(h.join(t,"../../../../"))}] importAssets:`,...m)};try{y("wait image-bin api ready"),await Jt.default({resources:[`${Ce.getComponentWebEndpoint(zt)}/api/sdk/uploads`],validateStatus:O=>O>=200&&O<=500}),y("image-bin api is ready");const m={},b={};y("start to upload assets"),await Promise.allSettled([Fe(S,m,{getFilePath:O=>r&&h.join(r,O),onFinish:O=>{y(`upload ${O.length} component assets`)}}),Fe(l,b,{getFilePath:(O,T)=>{const u=Oe.default(l,T.slice(0,1));return c&&h.join(c,h.dirname(u.slug),O)},onFinish:O=>{y(`upload ${O.length} page assets`)}})]),y("upload assets done"),Pe.clear(),global.gc&&global.gc()}catch(m){y("Error during asset import:",m)}}const A={};if(n){const y=a&&h.join(h.dirname(a),"../../resources/components"),m=x(d.resources?.components?.map(({id:b})=>g(y,b))??[]);m.length>0&&(A.components=Object.fromEntries(m.map((b,O)=>[b.id,{index:O,component:b}])))}return{supportedLocales:d.supportedLocales,pageIds:l.map(y=>y.id),components:Object.fromEntries(S.map((y,m)=>[y.id,{index:m,data:y}])),pages:Object.fromEntries(l.map(y=>[y.id,y])),config:d.config||{},resources:A,routeIds:i.map(y=>y.id),routes:Object.fromEntries(i.map(y=>[y.id,y])),dataSourceIds:[],dataSources:{}}}finally{o&&s&&w.rmSync(s,{force:!0,recursive:!0})}}async function qe(t,e,{routes:n,mergeMode:s="byUpdateTime",deleteRoutes:o=!1,publishMode:a=void 0}={}){try{a&&Sn(a)}catch(I){f.error("clear preload page cache error",{error:I})}const{pages:c,pageIds:r,routeIds:p,routes:d,supportedLocales:E}=t;if(a==="production"){let I=n??[],l=null;for(const i of p??[]){const S=d?.[i];if(S?.params&&S?.params.length>0&&S?.paramsOptions&&S?.paramsOptions.length>0){const A=te.generateParamCombinations({basePath:S.path,params:S.params,routeId:S.id,paramsOptions:S.paramsOptions,currentIndex:0,currentParams:[],currentOptionIds:[],result:[]}),y=Object.fromEntries(A.map(m=>[`${i}-${m.paramOptionIds.join("-")}`,m]));l={...l||{},...y},n||(I=[...I,...A.map(m=>`${i}-${m.paramOptionIds.join("-")}`)])}else n||I.push(i)}f.info("routeIds to be published: ",I);for(const i of I){let S=i;if(S.includes("-")){const[m]=S.split("-");S=m}const A=d?.[S];if(!A){const m=e.pageIds.indexOf(S);m!==-1&&o&&(e.pageIds.splice(m,1),delete e.pages[S]);for(const b of e.pageIds)b.includes(`${S}-`)&&(e.pageIds.splice(e.pageIds.indexOf(b),1),delete e.pages[b]);f.info("delete main route page",S);continue}if(i.includes("-")&&!l?.[i]){const m=e.pageIds.indexOf(i);m!==-1&&o&&(e.pageIds.splice(m,1),delete e.pages[i]),f.info("delete page",i);continue}if(!A.displayTemplateId){f.info("no display template",i);continue}const y=c[A.displayTemplateId];if(!y){f.info("no template page",i);continue}if(e.pageIds.includes(i)){if(f.info("has need update page",i),s==="replace")e.pages[i]=Se({page:y,route:A,state:t,routeId:i,routePathInfo:l?.[i]}),f.info("replace page",i);else if(s==="byUpdateTime"){const m=e.pages[A.id];(!m||A.updatedAt&&A.updatedAt>m.updatedAt)&&(e.pages[i]=Se({page:y,route:A,state:t,routeId:i,routePathInfo:l?.[i]}),f.info("replace page by update time",i))}}else e.pageIds.push(i),e.pages[i]=Se({page:y,route:A,state:t,routeId:i,routePathInfo:l?.[i]}),f.info("add page",i)}if(o&&!n)for(const i of e.pageIds)I?.includes(i)||(delete e.pages[i],f.info("delete page",i)),e.pageIds=[...e.pageIds].filter(S=>I?.includes(S))}else{for(const I of r){const l=c[I];if(l)if(e.pageIds.includes(l.id)){if(s==="replace")e.pages[l.id]=l;else if(s==="byUpdateTime"){const i=e.pages[l.id];(!i||l.updatedAt&&l.updatedAt>i.updatedAt)&&(e.pages[l.id]=l)}}else e.pageIds.push(l.id),e.pages[l.id]=l}for(const I of p){const l=d[I];if(l)if(e.routeIds.includes(l.id)){if(s==="replace")e.routes[l.id]=l;else if(s==="byUpdateTime"){const i=e.routes[l.id];(!i||l.updatedAt&&l.updatedAt>i.updatedAt)&&(e.routes[l.id]=l)}}else e.routeIds.push(l.id),e.routes[l.id]=l}}if(e.supportedLocales.splice(0,e.supportedLocales.length),e.supportedLocales.push(...Bt.default(E)),o)for(const I of Object.keys(e.components))delete e.components[I];let g=JSON.parse(JSON.stringify(t.components));g=Object.fromEntries(await Promise.all(Object.entries(g).map(async([I,l])=>{const i=await nt(l?.data);return[I,{...l,data:i}]}))),Object.assign(e.components,g),Object.assign(e.config,JSON.parse(JSON.stringify(t.config))),Ae.default(t.resources.components)||(e.resources.components=JSON.parse(JSON.stringify(t.resources.components||{})))}const nt=ue(async t=>{if(!Ae.default(t?.properties))return t;if(t?.renderer?.type==="react-component"){const{script:e,PROPERTIES_SCHEMA:n}=t?.renderer||{};if(n||e&&e.includes("PROPERTIES_SCHEMA"))try{const s=await An(e??"","PROPERTIES_SCHEMA",t.id,n);s&&s.length>0&&t&&(t.properties={},s.forEach((o,a)=>{t?.properties&&(t.properties[o.id]={index:a,data:o})}))}catch(s){f.error("getPropertiesFromCode error",{componentId:t.id,name:t.name},{error:s})}}return t},{subdir:"getPropertiesFromCode"});let ce,Y,de,fe;const st=()=>Ce.getResources({types:[{did:je,type:Ee},{did:Tn,type:Ee}]}),Gn=()=>{const t=st(),e={};return t.forEach(n=>{const s=ne.globSync("**/.blocklet/pages/pages.config.yml",{cwd:n.path,absolute:!0}).at(0),o=s&&h.join(h.dirname(s),"../../chunks");if(o&&w.existsSync(o)){const a=w.readdirSync(o);for(const c of a)e[c]=h.join(o,c)}}),e};function ot(){return ce=(async()=>{const t=st();Y=(await Promise.all(t.map(async n=>{const s=n.path?await Vn(n.path,{importAssets:!1}):void 0;return s?{blockletId:n.did,state:s,blockletTitle:n.title}:void 0}))).filter(n=>!!n),de=Y.reduce((n,s)=>Object.assign(n,Object.fromEntries(Object.values(s.state.pages).map(o=>o?[o?.id,{page:o,blockletId:s.blockletId}]:[]))),{});const e=Y.reduce((n,s)=>Object.assign(n,Object.fromEntries(Object.values(s.state.components).map(o=>[o.data.id,{blockletId:s.blockletId,component:o.data}]))),{});fe=Object.fromEntries(await Promise.all(Object.entries(e).map(async([n,s])=>{const o=await nt(s.component);return[n,{...s,component:o}]})))})(),ce}function Jn(t){const e=Je.default(async()=>{await ot().catch(n=>{f.error("load resource states error",{error:n})}),await t?.({states:Y,pages:de,components:fe})},3e3,{leading:!1,trailing:!0});return e(),P.default.events.on(P.default.Events.componentAdded,e),P.default.events.on(P.default.Events.componentRemoved,e),P.default.events.on(P.default.Events.componentStarted,e),P.default.events.on(P.default.Events.componentStopped,e),P.default.events.on(P.default.Events.componentUpdated,e),P.default.events.on(Ne,e),()=>{P.default.events.off(P.default.Events.componentAdded,e),P.default.events.off(P.default.Events.componentRemoved,e),P.default.events.off(P.default.Events.componentStarted,e),P.default.events.off(P.default.Events.componentStopped,e),P.default.events.off(P.default.Events.componentUpdated,e),P.default.events.off(Ne,e)}}const at=Symbol.for("GLOBAL_RESOURCE_STATES_LISTENER_KEY"),rt=globalThis;rt[at]?.();rt[at]=Jn(async({pages:t,components:e})=>{const n=await j.getProjectIds();f.info(`start update resource states projects(${n.length})`,n),await Promise.race([new Promise(s=>{setTimeout(()=>{s({})},30*1e3)}),Promise.all(n.map(async s=>{it({projectId:s,pages:t,components:e})}))]).catch(s=>{f.error("update resource states failed:",s)})});j.startPeriodicCheck();process.on("beforeExit",()=>{j.stopPeriodicCheck()});process.on("SIGINT",()=>{j.stopPeriodicCheck(),process.exit(0)});process.on("SIGTERM",()=>{j.stopPeriodicCheck(),process.exit(0)});async function it({projectId:t,pages:e,components:n}){const s=j.sharedInstances[t];if(!s){f.info(`projectId: ${t} not found in sharedInstances`);return}if(s.syncedStore.resources.pages=e,(await M.findByPk(t))?.useAllResources)s.syncedStore.resources.components=n;else{const c=(await Te.findAll({where:{projectId:t}})).map(p=>p.componentId),r=Object.fromEntries(Object.entries(n||{}).filter(([p])=>c.includes(p)));s.syncedStore.resources.components=r}f.info(`update [${t}] resource states:`,{pages:Object.keys(s.syncedStore.resources.pages||{}).length,components:Object.keys(s.syncedStore.resources.components||{}).length})}async function ct({ensureLoaded:t=!0}={}){return t&&(ce??=ot(),await ce),{states:Y,pages:de,components:fe}}P.default.events.on(P.default.Events.envUpdate,()=>{j.pageUrlMapCache.clear(),f.info("clear all page url map cache")});exports.COMPONENT_DID=je;exports.Project=M;exports.RESOURCE_TYPE=Ee;exports.SiteState=j;exports.getMultiTenantAllProjectAccessPassports=Ht;exports.getPreloadComponents=In;exports.getResourceStates=ct;exports.isMultiTenant=Kt;exports.logger=f;exports.toPackage=tt;
@@ -1 +0,0 @@
1
- "use strict";const U=require("react/jsx-runtime"),A=require("ufo"),b=require("./home-DUjl5PbP.js"),W=require("@arcblock/ux/lib/Locale/context"),x=require("@blocklet/pages-kit/utils/common"),F=require("@blocklet/pages-kit/utils/page-model");require("@mui/material");const _=require("@syncedstore/core"),K=require("@syncedstore/react"),V=require("ahooks"),y=require("immer"),Y=require("lodash/cloneDeep"),z=require("lodash/debounce"),u=require("react"),T=require("react-router-dom"),H=require("y-indexeddb"),Q=require("y-websocket"),X=require("yjs");require("@blocklet/pages-kit/types");const j=s=>s&&s.__esModule?s:{default:s},Z=j(_),R=j(Y),B=j(z);async function ee(s){return b.api.get(`/api/projects/${s}`).then(c=>c.data)}async function te(s){return b.api.post(`/api/projects/${s.id}/update`,s).then(c=>c.data)}const oe=500,G=u.createContext(null);function re({url:s,name:c,children:P,waitingSynced:w}){const[v,h]=u.useState(!1),{locale:p}=W.useLocaleContext(),m=O(),M=`${m}:MakerLocalState`,e=`${m}:${c}`,[t,r]=V.useLocalStorageState(M,{defaultValue:{},listenStorageChange:!0}),o=u.useRef(t);o.current=t;const i=u.useMemo(()=>Z.default({dataSourceIds:[],dataSources:{},pages:{},pageIds:[],routes:{},routeIds:[],components:{},supportedLocales:[],config:{},resources:{}}),[]),n=u.useMemo(()=>_.getYjsDoc(i),[i]);u.useMemo(()=>new H.IndexeddbPersistence(e,n),[e,n]);const a=u.useMemo(()=>new Q.WebsocketProvider(s,e,n,{params:{},resyncInterval:5*60*1e3}),[s,e,n]),d=u.useCallback(()=>{a&&(a.disconnect(),a.connect())},[a]),g=u.useMemo(()=>new X.UndoManager([n.getArray("pageIds"),n.getMap("pages"),n.getArray("supportedLocales"),n.getMap("config"),n.getMap("dataSources"),n.getArray("dataSourceIds"),n.getArray("routeIds"),n.getMap("routes")],{doc:n}),[n]),[C,L]=u.useState(null),[E,k]=u.useState(!1),[N,q]=u.useState(void 0),$=u.useCallback(async()=>{if(m){k(!0);try{const l=await ee(m);L(l)}catch(l){console.error("Failed to fetch project:",l)}finally{k(!1)}}},[m]),D=u.useCallback(async(l,f)=>{if(q(void 0),!!m){f?.optimisticUpdate&&C&&L(S=>({...S,...l}));try{const S=await te({...l});L(S)}catch(S){console.error("Failed to update project:",S),f?.optimisticUpdate&&L(C),q(S?.response?.data)}}},[m,C]);u.useEffect(()=>{m&&$()},[m,$]);const J=u.useMemo(()=>({doc:n,state:i,localState:{...t,currentLocale:p},setLocalState:l=>r(typeof l=="function"?f=>l(f??{}):l),undoManager:g,projectState:{project:C,isLoadingProject:E,error:N},updateProject:D,forceSync:d}),[n,i,JSON.stringify(t),r,g,C,E,D,N,p,d]);return u.useEffect(()=>{g.on("stack-item-added",({stackItem:l})=>{const{currentPageId:f,currentLocale:S,pages:I}=o.current;l.meta.set("localState",{currentPageId:f,currentLocale:S,pages:I})}),g.on("stack-item-popped",({stackItem:l})=>{const f=l.meta.get("localState");f&&r(S=>({...S,...f}))})},[g,r]),u.useEffect(()=>{a.awareness.setLocalState(t)},[a,t]),u.useEffect(()=>{a.once("synced",()=>h(!0));const l=()=>{r(I=>({...I,networkStatus:void 0}))},f=()=>{r(I=>({...I,networkStatus:"offline"}))},S=B.default(({status:I})=>{I==="connected"?l():I==="disconnected"&&f()},oe);return a.on("status",S),window.addEventListener("online",l),window.addEventListener("offline",f),()=>{a.off("status",S),window.removeEventListener("online",l),window.removeEventListener("offline",f)}},[a,r]),w&&!v?null:U.jsx(G.Provider,{value:J,children:P})}const ne=()=>{const s=u.useContext(G);if(!s)throw new Error("Context is null");const c=K.useSyncedStore(s.state),{setLocalState:P,localState:w}=s,v=T.useNavigate(),h=O(),p=u.useMemo(()=>({get currentPage(){const{localState:{currentPageId:e}}=s;return e?c.pages[e]:void 0},get currentSection(){const{localState:{currentPageId:e,...t}}=s;if(!e)return;const r=t.pages?.[e]?.currentSectionId;if(r)return c.pages[e]?.sections[r]??this.currentPageModel?.getComponentById(r)?.model},get currentSectionProperties(){const{localState:{currentPageId:e,...t}}=s;if(!e)return;const r=t.pages?.[e]?.currentSectionId;if(!r)return;const o=c.pages[e]?.dataSource?.[r];if(!o)return;const{currentLocale:i}=this.currentLocaleMap;return i?o[i]:void 0},get currentSectionPropertiesWithFallback(){const{localState:{currentPageId:e,...t}}=s;if(!e)return;const r=t.pages?.[e]?.currentSectionId;if(!r)return;const o=c.pages[e]?.dataSource?.[r];if(!o)return;const{currentLocale:i,defaultLocale:n,fallbackLocale:a}=this.currentLocaleMap;if(i&&o[i])return o[i];if(n&&o[n])return o[n];if(a&&o[a])return o[a]},get currentLocaleMap(){const{localState:{currentLocale:e},state:{supportedLocales:t,config:{defaultLocale:r}}}=s;return{currentLocale:e,defaultLocale:r,fallbackLocale:t?.[0]?.locale??"en"}},get currentRoute(){const{localState:{currentRouteId:e}}=s;return e?c.routes?.[e]:void 0},get currentPageModel(){const e=this.currentPage??null;if(e)return F.getPageTemplateModel(e,!1)}}),[JSON.stringify(w),c]),m=u.useMemo(()=>({setCurrentSectionId:(e,t)=>{e===w.currentPageId&&t===w.pages?.[e]?.currentSectionId||(v(A.joinURL("/admin/maker",h??"","pages",e)),P(r=>y.produce(r,o=>{o.currentPageId=e,o.currentComponentId=void 0,t!==void 0&&(o.pages??={},o.pages[e]??={},o.pages[e].currentSectionId=t??void 0),t?window.sessionStorage.setItem("iframe_show_id",`"${t}"`):window.sessionStorage.removeItem("iframe_show_id")})))},setCurrentComponentId:e=>{e!==w.currentComponentId&&(v(A.joinURL("/admin/maker",h??"","components",e)),P(t=>y.produce(t,r=>{r.currentComponentId=e})))},setCurrentRouteId:({routeId:e,dynamicParams:t})=>{P(r=>y.produce(r,o=>{o.currentRouteId=e,o.currentDynamicParams=t}))},setCustomComponentPreviewerProperties:(()=>{const e={};let t="";const r=B.default(()=>{P(o=>y.produce(o,i=>{i.customComponentPreviewerProperties??={},i.customComponentPreviewerProperties[t]={...i.customComponentPreviewerProperties[t],...R.default(e[t])},delete e[t]}))},5);return(o,i)=>{const n=e[o]??{};Object.assign(n,i),e[o]=n,t=o,r()}})(),setRouteGenerateProcess:e=>{P(t=>y.produce(t,r=>{e?r.routeGenerateProcess={...r.routeGenerateProcess,...e}:r.routeGenerateProcess={}}))},resetRouteGenerateProcess:()=>{P(e=>y.produce(e,t=>{t.routeGenerateProcess={progress:"complete"}}))}}),[P,v,h,p]),M=u.useMemo(()=>({addPage:(e,t)=>{const r=e?.id??x.nextId(),o={...e,id:r,createdAt:e?.createdAt??new Date().toISOString(),updatedAt:e?.updatedAt??new Date().toISOString(),publishedAt:new Date(0).toISOString(),slug:e?.slug??`/${r}`,sections:e?.sections??{},sectionIds:e?.sectionIds??[],isPublic:e?.isPublic??!0,templateConfig:e?.templateConfig??{isTemplate:e?.templateConfig?.isTemplate??!0,displayTemplateId:e?.templateConfig?.displayTemplateId??void 0,dataSourceIds:e?.templateConfig?.dataSourceIds??void 0,dataSourceParameters:e?.templateConfig?.dataSourceParameters??{},enabledGenerate:e?.templateConfig?.enabledGenerate??!1,agentId:e?.templateConfig?.agentId??void 0}};return s.doc.transact(()=>{c.pages[o.id]=o,c.pageIds.splice(t??c.pageIds.length,0,o.id)}),o},addRoute:(e,t)=>{const r=e?.id??x.nextId(),o={...e,id:r,createdAt:e?.createdAt??new Date().toISOString(),updatedAt:e?.updatedAt??new Date().toISOString(),publishedAt:new Date(0).toISOString(),path:e?.path??`/${r}`,handler:e?.handler??"Pages Kit",isPublic:e?.isPublic??!0,params:e?.params??[],enabledGenerate:e?.enabledGenerate??!1,displayTemplateId:e?.displayTemplateId??void 0,dataSource:e?.dataSource??{}};return s.doc.transact(()=>{c.routes??={},c.routeIds??=[],c.routes[o.id]=o,c.routeIds.splice(t??c.routeIds.length,0,o.id)}),o},deleteRoute:e=>{if(!e)return;const t=c.routeIds?.indexOf(e);t!==void 0&&t!==-1&&s.doc.transact(()=>{c.routeIds?.splice(t,1),delete c.routes?.[e]})},deletePage:e=>{const t=c.pageIds.indexOf(e);t!==-1&&s.doc.transact(()=>{c.pageIds.splice(t,1),delete c.pages[e]})},movePage:(e,t)=>{const{pageIds:r}=c,o=r.indexOf(e);o>=0&&r.splice(t,0,...r.splice(o,1))},addSection:(e,t,r,o)=>{const i=c.pages[e];if(!i)throw new Error(`Page ${e} is not exists`);const n={...t,id:t.id??x.nextId(),isTemplateSection:t.isTemplateSection??!0,llmConfig:t.llmConfig??{}},a=R.default(n.locales);return delete n.locales,s.doc.transact(()=>{if(o&&o.component==="layout-block"){const d=p.currentPageModel?.getComponentById(o.id);d&&(d.model.sections??={},d.model.sections[n.id]=n,d.model.sectionIds??=[],d.model.sectionIds.push(n.id))}else i.sections[n.id]=n,i.sectionIds.splice(r??i.sectionIds.length,0,n.id);a&&(i.dataSource??={},i.dataSource[n.id]=a)}),n},deleteSection:(e,t)=>{const r=c.pages[e];if(!r)throw new Error(`Page ${e} is not exists`);s.doc.transact(()=>{const o=[],i=p.currentPageModel?.getComponentById(t),n=i?.parent;if(i&&(o.push(i.model.id,...i.all().map(a=>a.model.id)),n?.model.component==="layout-block")){const a=n.model.sectionIds?.indexOf(t);a!==void 0&&a!==-1&&(n.model.sectionIds?.splice(a,1),delete n.model.sections?.[t]),n.model.config?.gridSettings&&Object.keys(n.model.config.gridSettings).forEach(d=>{try{delete n.model.config.gridSettings[d]?.[t]}catch{}}),n.model.config?.backgroundSectionId===t&&(n.model.config.backgroundSectionId=void 0)}o.forEach(a=>{const d=r.sectionIds.indexOf(a);d!==-1&&r.sectionIds.splice(d,1),r.sections[a]&&delete r.sections[a],r.dataSource?.[a]&&delete r.dataSource?.[a]})})},lockSection:(e,t)=>{if(!c.pages[e])throw new Error(`Page ${e} is not exists`);const o=p.currentPageModel?.getComponentById(t)?.model;o&&(o.locked=!o.locked)},toggleSectionVisibility:(e,t,r)=>{if(!c.pages[e])throw new Error(`Page ${e} is not exists`);const i=p.currentPageModel?.getComponentById(t)?.model;i&&(i.visibility=r)},moveSection:(e,t,r,o)=>{if(!c.pages[e])throw new Error(`Page ${e} is not exists`);if(o&&o!==t){const n=p.currentPageModel?.getComponentById(t),a=p.currentPageModel?.getComponentById(o),d=n?.parent,g=a?.parent;g&&d&&g?.model?.id===d?.model?.id?s.doc.transact(()=>{d.model.sectionIds.splice(n.getIndex(),1),d.model.sectionIds.splice(a.getIndex(),0,t)}):g&&d&&g?.model?.id!==d?.model?.id&&t!==o&&!n?.model?.sectionIds?.includes(o)&&s.doc.transact(()=>{g.model.sections[t]=JSON.parse(JSON.stringify(n.model)),g.model.sectionIds.splice(a.getIndex(),0,t),d.model.sectionIds.splice(n.getIndex(),1),delete d.model.sections[t]})}},copySection:(e,t)=>{if(!c.pages[e])throw new Error(`Page ${e} is not exists`);const o=p.currentPageModel?.getComponentById(t);if(!o?.model)throw new Error(`Section ${t} is not exists`);const i=JSON.parse(JSON.stringify(o.model)),n=ce(i),a=n.id,d=o?.parent;return d&&(d.model.sections[a]=n,d.model.sectionIds.push(a),m.setCurrentSectionId(e,a),p.currentPage?.dataSource?.[t]&&(p.currentPage.dataSource[a]=JSON.parse(JSON.stringify(p.currentPage.dataSource[t])))),n},addDataSource:e=>{const t=e.id??x.nextId(),r={...e??{},id:t,createdAt:new Date().toISOString()};return s.doc.transact(()=>{c.dataSourceIds??=[],c.dataSources??={},c.dataSourceIds.push(t),c.dataSources[t]=r}),c.dataSources[t]},deleteDataSource:e=>{const t=c.dataSourceIds.indexOf(e);t!==-1&&s.doc.transact(()=>{c.dataSourceIds.splice(t,1),delete c.dataSources[e]})}}),[c,s.doc,p]);return{...s,state:c,actions:M,localActions:m,...p}},O=()=>{const{projectId:s}=T.useParams();return s??b.getProjectIdFromPathnameOrWindow()??""};function ce(s){const c=JSON.parse(JSON.stringify(s)),P=x.nextId();return{...c,id:P}}exports.StoreProvider=re;exports.useProjectId=O;exports.useStore=ne;
@@ -1,69 +0,0 @@
1
- import { styled as a } from "@arcblock/ux/lib/Theme";
2
- import l from "@blocklet/ui-react/lib/Header";
3
- import { Button as f } from "@mui/material";
4
- import { useContext as w, lazy as c, useMemo as h } from "react";
5
- import { useSearchParams as g } from "react-router-dom";
6
- import { createAuthServiceSessionContext as P } from "@arcblock/did-connect/lib/Session";
7
- import { createAxios as S } from "@blocklet/js-sdk";
8
- import { joinURL as m } from "ufo";
9
- import "lodash/isEmpty";
10
- import "yaml";
11
- import { jsx as I } from "react/jsx-runtime";
12
- const { SessionProvider: G, SessionContext: b, SessionConsumer: L, withSession: U } = P();
13
- function s() {
14
- return w(b);
15
- }
16
- function M(...o) {
17
- const { session: t } = s();
18
- return o.includes(t.user?.role);
19
- }
20
- function k(...o) {
21
- const { session: t } = s(), e = M(...o);
22
- return window.blocklet?.tenantMode === "multiple" ? !!t.user : e;
23
- }
24
- const u = window.blocklet?.prefix || "/", p = S({
25
- timeout: 200 * 1e3
26
- }), x = window.location.protocol === "https:" ? "wss" : "ws", W = (o) => m(`${x}://${window.location.hostname}`, u, `api/${o}/ws/pages`), E = "z8ia1mAXo8ZE7ytGF36L5uBf9kD2kenhqFGp9";
27
- blocklet?.componentMountPoints.find((o) => o.did === E)?.mountPoint || m(u, "/image-bin");
28
- function d() {
29
- const { pathname: o } = window.location, e = o.match(/\/admin\/(maker|previewer)\/([^/]+)/)?.[2], n = window.__PROJECT_ID__;
30
- if (!e && !n)
31
- throw new Error("Unable to get projectId from pathname");
32
- return e || n;
33
- }
34
- function v(o) {
35
- return `${o}:pages:version`;
36
- }
37
- const R = ["production", "draft"];
38
- function z({ mode: o, version: t } = {}) {
39
- const e = t && typeof t == "number" ? { mode: o, version: t } : { mode: o };
40
- return p.get(`/api/${d()}/pages`, { params: e }).then((n) => n.data);
41
- }
42
- function V({ mode: o, routes: t }) {
43
- return p.post(`/api/${d()}/pages/publish`, { mode: o, routes: t }).then((e) => e.data);
44
- }
45
- function X() {
46
- const [o] = g(), { session: t } = s(), e = k("owner", "admin", "pagesEditor", "member"), n = h(() => {
47
- const i = o.get("mode");
48
- return R.includes(i) ? i : "production";
49
- }, [o]), r = n === "production" ? n : t.user ? e ? n : "production" : null;
50
- return r ? I(HomeView, { mode: r }) : null;
51
- }
52
- c(() => import("./publish-button-Ceet-m88.js"));
53
- c(() => import("./draft-data-bRUHvvzp.js"));
54
- a(l)`
55
- &.sticky {
56
- position: sticky;
57
- top: 0;
58
- }
59
- `;
60
- a(f)``;
61
- export {
62
- z as a,
63
- W as b,
64
- p as c,
65
- d,
66
- X as e,
67
- v as g,
68
- V as p
69
- };