@weaverse/core 0.2.1 → 0.3.0

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/README.md CHANGED
@@ -1,115 +0,0 @@
1
- # TSDX User Guide
2
-
3
- Congrats! You just saved yourself hours of work by bootstrapping this project with TSDX. Let’s get you oriented with
4
- what’s here and how to use it.
5
-
6
- > This TSDX setup is meant for developing libraries (not apps!) that can be published to NPM. If you’re looking to build a Node app, you could use `ts-node-dev`, plain `ts-node`, or simple `tsc`.
7
-
8
- > If you’re new to TypeScript, checkout [this handy cheatsheet](https://devhints.io/typescript)
9
-
10
- ## Commands
11
-
12
- TSDX scaffolds your new library inside `/src`.
13
-
14
- To run TSDX, use:
15
-
16
- ```bash
17
- npm start # or yarn start
18
- ```
19
-
20
- This builds to `/dist` and runs the project in watch mode so any edits you save inside `src` causes a rebuild to `/dist`
21
- .
22
-
23
- To do a one-off build, use `npm run build` or `yarn build`.
24
-
25
- To run tests, use `npm test` or `yarn test`.
26
-
27
- ## Configuration
28
-
29
- Code quality is set up for you with `prettier`, `husky`, and `lint-staged`. Adjust the respective fields
30
- in `package.json` accordingly.
31
-
32
- ### Jest
33
-
34
- Jest tests are set up to run with `npm test` or `yarn test`.
35
-
36
- ### Bundle Analysis
37
-
38
- [`size-limit`](https://github.com/ai/size-limit) is set up to calculate the real cost of your library
39
- with `npm run size` and visualize the bundle with `npm run analyze`.
40
-
41
- #### Setup Files
42
-
43
- This is the folder structure we set up for you:
44
-
45
- ```txt
46
- /src
47
- index.tsx # EDIT THIS
48
- /test
49
- blah.test.tsx # EDIT THIS
50
- .gitignore
51
- package.json
52
- README.md # EDIT THIS
53
- tsconfig.json
54
- ```
55
-
56
- ### Rollup
57
-
58
- TSDX uses [Rollup](https://rollupjs.org) as a bundler and generates multiple rollup configs for various module formats
59
- and build settings. See [Optimizations](#optimizations) for details.
60
-
61
- ### TypeScript
62
-
63
- `tsconfig.json` is set up to interpret `dom` and `esnext` types, as well as `react` for `jsx`. Adjust according to your
64
- needs.
65
-
66
- ## Continuous Integration
67
-
68
- ### GitHub Actions
69
-
70
- Two actions are added by default:
71
-
72
- - `main` which installs deps w/ cache, lints, tests, and builds on all pushes against a Node and OS matrix
73
- - `size` which comments cost comparison of your library on every pull request
74
- using [`size-limit`](https://github.com/ai/size-limit)
75
-
76
- ## Optimizations
77
-
78
- Please see the main `tsdx` [optimizations docs](https://github.com/palmerhq/tsdx#optimizations). In particular, know
79
- that you can take advantage of development-only optimizations:
80
-
81
- ```js
82
- // ./types/index.d.ts
83
- declare var __DEV__: boolean;
84
-
85
- // inside your code...
86
- if (__DEV__) {
87
- console.log('foo');
88
- }
89
- ```
90
-
91
- You can also choose to install and use [invariant](https://github.com/palmerhq/tsdx#invariant)
92
- and [warning](https://github.com/palmerhq/tsdx#warning) functions.
93
-
94
- ## Module Formats
95
-
96
- CJS, ESModules, and UMD module formats are supported.
97
-
98
- The appropriate paths are configured in `package.json` and `dist/index.js` accordingly. Please report if any issues are
99
- found.
100
-
101
- ## Named Exports
102
-
103
- Per Palmer Group guidelines, [always use named exports.](https://github.com/palmerhq/typescript#exports) Code split
104
- inside your React app instead of your React library.
105
-
106
- ## Including Styles
107
-
108
- There are many ways to ship styles, including with CSS-in-JS. TSDX has no opinion on this, configure how you like.
109
-
110
- For vanilla CSS, you can include it at the root directory and add it to the `files` section in your `package.json`, so
111
- that it can be imported separately by your users and run through their bundler's loader.
112
-
113
- ## Publishing to NPM
114
-
115
- We recommend using [np](https://github.com/sindresorhus/np).
package/dist/index.d.ts CHANGED
@@ -1,3 +1,127 @@
1
- import { ProjectDataItemType, ProjectDataType, Weaverse, WeaverseItemStore, WeaverseType } from './core';
2
- import { isBrowser, isIframe, isReactNative } from './utils';
3
- export { Weaverse, WeaverseType, WeaverseItemStore, ProjectDataType, ProjectDataItemType, isBrowser, isReactNative, isIframe };
1
+ import Stitches from '@stitches/core/types/stitches';
2
+
3
+ interface ProjectDataItemType {
4
+ type: string;
5
+ name?: string;
6
+ id: string | number;
7
+ description?: string;
8
+ childIds?: Array<string | number>;
9
+ css?: {
10
+ [key: string]: string;
11
+ };
12
+ }
13
+ interface ProjectDataType {
14
+ items: ProjectDataItemType[];
15
+ }
16
+ declare type WeaverseType = {
17
+ [key: string]: any;
18
+ appUrl?: string;
19
+ projectKey?: string;
20
+ projectData?: ProjectDataType;
21
+ };
22
+ declare class Weaverse {
23
+ /**
24
+ * For storing, registering element React component from Weaverse or created by user/developer
25
+ * @type {Map<string, React.Component>}
26
+ */
27
+ elementInstances: Map<string, any>;
28
+ /**
29
+ * list of element/items store to provide data, handle state update, state sharing, etc.
30
+ * @type {Map<string, any>}
31
+ */
32
+ itemInstances: Map<string | number, WeaverseItemStore>;
33
+ /**
34
+ * Weaverse base URL that can provide by user/developer. for local development, use localhost:3000
35
+ * @type {string}
36
+ */
37
+ appUrl: string;
38
+ /**
39
+ * Weaverse project key to access project data via API
40
+ * @type {string}
41
+ */
42
+ projectKey: string;
43
+ /**
44
+ * Weaverse project data, by default, user can provide project data via React Component:
45
+ * <WeaverseRoot defaultData={projectData} /> it will be used to server-side rendering
46
+ */
47
+ projectData: ProjectDataType;
48
+ /**
49
+ * storing subscribe callback function for any component that want to listen to the change of WeaverseRoot
50
+ * @type {Map<string, (data: any) => void>}
51
+ */
52
+ listeners: Set<any>;
53
+ /**
54
+ * check whether the sdk is inEditor or not
55
+ * if isEditor is true, it means the sdk is inEditor mode, render the editor UI
56
+ * else render the preview UI, plain HTML + CSS + React hydrate
57
+ * @type {boolean}
58
+ */
59
+ isEditor: boolean;
60
+ /**
61
+ * stitches instance for handling CSS stylesheet, media, theme for Weaverse project
62
+ */
63
+ stitchesInstance: Stitches | any;
64
+ studioBridge?: any;
65
+ /**
66
+ * constructor
67
+ * @param appUrl {string} Weaverse base URL that can provide by user/developer. for local development, use localhost:3000
68
+ * @param projectKey {string} Weaverse project key to access project data via API
69
+ * @param projectData {ProjectDataType} Weaverse project data, by default, user can provide project data via React Component.
70
+ */
71
+ constructor({ appUrl, projectKey, projectData }?: WeaverseType);
72
+ /**
73
+ * register the custom React Component to Weaverse, store it into Weaverse.elementInstances
74
+ * @param name {string} unique name of the custom React Component
75
+ * @param element {React.Component} custom React Component
76
+ */
77
+ registerElement(name: string, element: any): void;
78
+ init(): void;
79
+ loadStudio(): void;
80
+ subscribe(fn: any): void;
81
+ unsubscribe(fn: any): void;
82
+ triggerUpdate(): void;
83
+ /**
84
+ * fetch data from Weaverse API (https://weaverse.io/api/v1/projects/:projectKey)
85
+ */
86
+ fetchProjectData(): Promise<any>;
87
+ /**
88
+ * fetch and update the project data, then trigger update to re-render the WeaverseRoot
89
+ */
90
+ updateProjectData(): void;
91
+ triggerEditorUpdate(type?: string): void;
92
+ initItemData(): void;
93
+ }
94
+ /**
95
+ * WeaverseItemStore is a store for Weaverse item, it can be used to subscribe/update the item data
96
+ * @param itemData {ProjectDataItemType} Weaverse item data
97
+ * @param weaverse {Weaverse} Weaverse instance
98
+ * Usage:
99
+ * ```jsx
100
+ * useEffect(() => {
101
+ * let handleUpdate = (update: any) => {
102
+ * setData({...update})
103
+ * }
104
+ * itemInstance.subscribe(handleUpdate)
105
+ * return () => {
106
+ * itemInstance.unsubscribe(handleUpdate)
107
+ * }
108
+ * }, [])
109
+ * ```
110
+ */
111
+ declare class WeaverseItemStore {
112
+ data: any;
113
+ listeners: Set<any>;
114
+ Component: any;
115
+ ref: any;
116
+ constructor(itemData: any, weaverse: Weaverse);
117
+ setData: (data: any) => void;
118
+ subscribe: (fn: any) => void;
119
+ unsubscribe: (fn: any) => void;
120
+ triggerUpdate: () => void;
121
+ }
122
+
123
+ declare const isReactNative: boolean;
124
+ declare const isBrowser: boolean;
125
+ declare const isIframe: boolean;
126
+
127
+ export { ProjectDataItemType, ProjectDataType, Weaverse, WeaverseItemStore, WeaverseType, isBrowser, isIframe, isReactNative };
package/dist/index.js CHANGED
@@ -1,8 +1,214 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __commonJS = (cb, mod) => function __require() {
12
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ };
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __reExport = (target, module2, copyDefault, desc) => {
19
+ if (module2 && typeof module2 === "object" || typeof module2 === "function") {
20
+ for (let key of __getOwnPropNames(module2))
21
+ if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
22
+ __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
23
+ }
24
+ return target;
25
+ };
26
+ var __toESM = (module2, isNodeMode) => {
27
+ return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", !isNodeMode && module2 && module2.__esModule ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
28
+ };
29
+ var __toCommonJS = /* @__PURE__ */ ((cache) => {
30
+ return (module2, temp) => {
31
+ return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp);
32
+ };
33
+ })(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0);
1
34
 
2
- 'use strict'
35
+ // ../../node_modules/tsup/assets/cjs_shims.js
36
+ var init_cjs_shims = __esm({
37
+ "../../node_modules/tsup/assets/cjs_shims.js"() {
38
+ }
39
+ });
3
40
 
4
- if (process.env.NODE_ENV === 'production') {
5
- module.exports = require('./core.cjs.production.min.js')
6
- } else {
7
- module.exports = require('./core.cjs.development.js')
8
- }
41
+ // src/utils/fetch.js
42
+ var require_fetch = __commonJS({
43
+ "src/utils/fetch.js"(exports, module2) {
44
+ init_cjs_shims();
45
+ function r(m) {
46
+ return m && m.default || m;
47
+ }
48
+ module2.exports = globalThis.fetch = globalThis.fetch || (typeof process == "undefined" ? r(require("unfetch")) : function(url, opts) {
49
+ return r(require("node-fetch"))(String(url).replace(/^\/\//g, "https://"), opts);
50
+ });
51
+ }
52
+ });
53
+
54
+ // src/index.ts
55
+ var src_exports = {};
56
+ __export(src_exports, {
57
+ Weaverse: () => Weaverse,
58
+ WeaverseItemStore: () => WeaverseItemStore,
59
+ isBrowser: () => isBrowser,
60
+ isIframe: () => isIframe,
61
+ isReactNative: () => isReactNative
62
+ });
63
+ init_cjs_shims();
64
+
65
+ // src/core.ts
66
+ init_cjs_shims();
67
+ var import_fetch = __toESM(require_fetch());
68
+
69
+ // src/utils/index.ts
70
+ init_cjs_shims();
71
+ var isReactNative = typeof navigator === "object" && navigator.product === "ReactNative";
72
+ var isBrowser = typeof window !== "undefined" && !isReactNative;
73
+ var isIframe = isBrowser && window.top !== window.self;
74
+
75
+ // src/core.ts
76
+ var stitches = __toESM(require("@stitches/core"));
77
+ var Weaverse = class {
78
+ constructor({ appUrl, projectKey, projectData } = {}) {
79
+ this.elementInstances = /* @__PURE__ */ new Map();
80
+ this.itemInstances = /* @__PURE__ */ new Map();
81
+ this.appUrl = process.env.NODE_ENV === "development" ? "http://localhost:3000" : "https://weaverse.io";
82
+ this.projectKey = "";
83
+ this.projectData = {
84
+ items: []
85
+ };
86
+ this.listeners = /* @__PURE__ */ new Set();
87
+ this.isEditor = false;
88
+ this.appUrl = appUrl || this.appUrl;
89
+ this.projectKey = projectKey || this.projectKey;
90
+ projectData && (this.projectData = projectData);
91
+ this.init();
92
+ }
93
+ registerElement(name, element) {
94
+ this.elementInstances.set(name, element);
95
+ }
96
+ init() {
97
+ this.stitchesInstance = stitches.createStitches({
98
+ prefix: "weaverse",
99
+ media: {
100
+ bp1: "(min-width: 640px)",
101
+ bp2: "(max-width: 768px)",
102
+ bp3: "(min-width: 1024px)"
103
+ }
104
+ });
105
+ this.loadStudio();
106
+ }
107
+ loadStudio() {
108
+ if (isIframe) {
109
+ let initStudio = () => {
110
+ let StudioBridge = window.WeaverseStudioBridge;
111
+ this.studioBridge = new StudioBridge(this);
112
+ this.studioBridge.subscribeMessageEvent();
113
+ this.triggerUpdate();
114
+ console.log("studio bridge initialized", this.studioBridge);
115
+ };
116
+ window.addEventListener("message", (e) => {
117
+ var _a;
118
+ if (((_a = e.data) == null ? void 0 : _a.type) === "weaverse.editor.ready") {
119
+ this.isEditor = true;
120
+ if (!window.WeaverseStudioBridge) {
121
+ const studioBridgeScript = document.createElement("script");
122
+ studioBridgeScript.src = `${this.appUrl}/assets/studio/studio-bridge.js`;
123
+ studioBridgeScript.onload = initStudio;
124
+ document.body.appendChild(studioBridgeScript);
125
+ } else {
126
+ initStudio();
127
+ }
128
+ }
129
+ });
130
+ }
131
+ }
132
+ subscribe(fn) {
133
+ this.listeners.add(fn);
134
+ }
135
+ unsubscribe(fn) {
136
+ this.listeners.delete(fn);
137
+ }
138
+ triggerUpdate() {
139
+ this.listeners.forEach((fn) => fn());
140
+ this.triggerEditorUpdate();
141
+ }
142
+ fetchProjectData() {
143
+ return (0, import_fetch.default)(this.appUrl + `/api/public/${this.projectKey}`).then((r) => r.json()).catch(console.error);
144
+ }
145
+ updateProjectData() {
146
+ if (this.projectKey) {
147
+ this.fetchProjectData().then((data) => {
148
+ if (data) {
149
+ this.projectData = data;
150
+ this.initItemData();
151
+ this.triggerUpdate();
152
+ }
153
+ }).catch((err) => {
154
+ console.error(err);
155
+ });
156
+ }
157
+ }
158
+ triggerEditorUpdate(type = "weaverse.workspace.init") {
159
+ if (this.isEditor && this.studioBridge) {
160
+ this.studioBridge.sendMessageToEditor(type, {
161
+ projectData: this.projectData,
162
+ projectKey: this.projectKey,
163
+ appUrl: this.appUrl
164
+ });
165
+ }
166
+ }
167
+ initItemData() {
168
+ let data = this.projectData;
169
+ if (data.items) {
170
+ data.items.forEach((item) => {
171
+ let itemStore = this.itemInstances.get(item.id) || new WeaverseItemStore(item, this);
172
+ this.itemInstances.set(item.id, itemStore);
173
+ });
174
+ }
175
+ }
176
+ };
177
+ var WeaverseItemStore = class {
178
+ constructor(itemData = {}, weaverse) {
179
+ this.data = {};
180
+ this.listeners = /* @__PURE__ */ new Set();
181
+ this.ref = {
182
+ current: null
183
+ };
184
+ this.setData = (data) => {
185
+ this.data = Object.assign(this.data, data);
186
+ this.triggerUpdate();
187
+ };
188
+ this.subscribe = (fn) => {
189
+ this.listeners.add(fn);
190
+ };
191
+ this.unsubscribe = (fn) => {
192
+ this.listeners.delete(fn);
193
+ };
194
+ this.triggerUpdate = () => {
195
+ this.listeners.forEach((fn) => {
196
+ return fn(this.data);
197
+ });
198
+ };
199
+ this.data = itemData;
200
+ let { type } = itemData;
201
+ if (type) {
202
+ this.Component = weaverse.elementInstances.get(type);
203
+ }
204
+ }
205
+ };
206
+ module.exports = __toCommonJS(src_exports);
207
+ // Annotate the CommonJS export names for ESM import in node:
208
+ 0 && (module.exports = {
209
+ Weaverse,
210
+ WeaverseItemStore,
211
+ isBrowser,
212
+ isIframe,
213
+ isReactNative
214
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,202 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
8
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined")
12
+ return require.apply(this, arguments);
13
+ throw new Error('Dynamic require of "' + x + '" is not supported');
14
+ });
15
+ var __esm = (fn, res) => function __init() {
16
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
17
+ };
18
+ var __commonJS = (cb, mod) => function __require2() {
19
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
20
+ };
21
+ var __reExport = (target, module, copyDefault, desc) => {
22
+ if (module && typeof module === "object" || typeof module === "function") {
23
+ for (let key of __getOwnPropNames(module))
24
+ if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
25
+ __defProp(target, key, { get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable });
26
+ }
27
+ return target;
28
+ };
29
+ var __toESM = (module, isNodeMode) => {
30
+ return __reExport(__markAsModule(__defProp(module != null ? __create(__getProtoOf(module)) : {}, "default", !isNodeMode && module && module.__esModule ? { get: () => module.default, enumerable: true } : { value: module, enumerable: true })), module);
31
+ };
32
+
33
+ // ../../node_modules/tsup/assets/esm_shims.js
34
+ var init_esm_shims = __esm({
35
+ "../../node_modules/tsup/assets/esm_shims.js"() {
36
+ }
37
+ });
38
+
39
+ // src/utils/fetch.js
40
+ var require_fetch = __commonJS({
41
+ "src/utils/fetch.js"(exports, module) {
42
+ init_esm_shims();
43
+ function r(m) {
44
+ return m && m.default || m;
45
+ }
46
+ module.exports = globalThis.fetch = globalThis.fetch || (typeof process == "undefined" ? r(__require("unfetch")) : function(url, opts) {
47
+ return r(__require("node-fetch"))(String(url).replace(/^\/\//g, "https://"), opts);
48
+ });
49
+ }
50
+ });
51
+
52
+ // src/index.ts
53
+ init_esm_shims();
54
+
55
+ // src/core.ts
56
+ init_esm_shims();
57
+ var import_fetch = __toESM(require_fetch());
58
+
59
+ // src/utils/index.ts
60
+ init_esm_shims();
61
+ var isReactNative = typeof navigator === "object" && navigator.product === "ReactNative";
62
+ var isBrowser = typeof window !== "undefined" && !isReactNative;
63
+ var isIframe = isBrowser && window.top !== window.self;
64
+
65
+ // src/core.ts
66
+ import * as stitches from "@stitches/core";
67
+ var Weaverse = class {
68
+ constructor({ appUrl, projectKey, projectData } = {}) {
69
+ this.elementInstances = /* @__PURE__ */ new Map();
70
+ this.itemInstances = /* @__PURE__ */ new Map();
71
+ this.appUrl = process.env.NODE_ENV === "development" ? "http://localhost:3000" : "https://weaverse.io";
72
+ this.projectKey = "";
73
+ this.projectData = {
74
+ items: []
75
+ };
76
+ this.listeners = /* @__PURE__ */ new Set();
77
+ this.isEditor = false;
78
+ this.appUrl = appUrl || this.appUrl;
79
+ this.projectKey = projectKey || this.projectKey;
80
+ projectData && (this.projectData = projectData);
81
+ this.init();
82
+ }
83
+ registerElement(name, element) {
84
+ this.elementInstances.set(name, element);
85
+ }
86
+ init() {
87
+ this.stitchesInstance = stitches.createStitches({
88
+ prefix: "weaverse",
89
+ media: {
90
+ bp1: "(min-width: 640px)",
91
+ bp2: "(max-width: 768px)",
92
+ bp3: "(min-width: 1024px)"
93
+ }
94
+ });
95
+ this.loadStudio();
96
+ }
97
+ loadStudio() {
98
+ if (isIframe) {
99
+ let initStudio = () => {
100
+ let StudioBridge = window.WeaverseStudioBridge;
101
+ this.studioBridge = new StudioBridge(this);
102
+ this.studioBridge.subscribeMessageEvent();
103
+ this.triggerUpdate();
104
+ console.log("studio bridge initialized", this.studioBridge);
105
+ };
106
+ window.addEventListener("message", (e) => {
107
+ var _a;
108
+ if (((_a = e.data) == null ? void 0 : _a.type) === "weaverse.editor.ready") {
109
+ this.isEditor = true;
110
+ if (!window.WeaverseStudioBridge) {
111
+ const studioBridgeScript = document.createElement("script");
112
+ studioBridgeScript.src = `${this.appUrl}/assets/studio/studio-bridge.js`;
113
+ studioBridgeScript.onload = initStudio;
114
+ document.body.appendChild(studioBridgeScript);
115
+ } else {
116
+ initStudio();
117
+ }
118
+ }
119
+ });
120
+ }
121
+ }
122
+ subscribe(fn) {
123
+ this.listeners.add(fn);
124
+ }
125
+ unsubscribe(fn) {
126
+ this.listeners.delete(fn);
127
+ }
128
+ triggerUpdate() {
129
+ this.listeners.forEach((fn) => fn());
130
+ this.triggerEditorUpdate();
131
+ }
132
+ fetchProjectData() {
133
+ return (0, import_fetch.default)(this.appUrl + `/api/public/${this.projectKey}`).then((r) => r.json()).catch(console.error);
134
+ }
135
+ updateProjectData() {
136
+ if (this.projectKey) {
137
+ this.fetchProjectData().then((data) => {
138
+ if (data) {
139
+ this.projectData = data;
140
+ this.initItemData();
141
+ this.triggerUpdate();
142
+ }
143
+ }).catch((err) => {
144
+ console.error(err);
145
+ });
146
+ }
147
+ }
148
+ triggerEditorUpdate(type = "weaverse.workspace.init") {
149
+ if (this.isEditor && this.studioBridge) {
150
+ this.studioBridge.sendMessageToEditor(type, {
151
+ projectData: this.projectData,
152
+ projectKey: this.projectKey,
153
+ appUrl: this.appUrl
154
+ });
155
+ }
156
+ }
157
+ initItemData() {
158
+ let data = this.projectData;
159
+ if (data.items) {
160
+ data.items.forEach((item) => {
161
+ let itemStore = this.itemInstances.get(item.id) || new WeaverseItemStore(item, this);
162
+ this.itemInstances.set(item.id, itemStore);
163
+ });
164
+ }
165
+ }
166
+ };
167
+ var WeaverseItemStore = class {
168
+ constructor(itemData = {}, weaverse) {
169
+ this.data = {};
170
+ this.listeners = /* @__PURE__ */ new Set();
171
+ this.ref = {
172
+ current: null
173
+ };
174
+ this.setData = (data) => {
175
+ this.data = Object.assign(this.data, data);
176
+ this.triggerUpdate();
177
+ };
178
+ this.subscribe = (fn) => {
179
+ this.listeners.add(fn);
180
+ };
181
+ this.unsubscribe = (fn) => {
182
+ this.listeners.delete(fn);
183
+ };
184
+ this.triggerUpdate = () => {
185
+ this.listeners.forEach((fn) => {
186
+ return fn(this.data);
187
+ });
188
+ };
189
+ this.data = itemData;
190
+ let { type } = itemData;
191
+ if (type) {
192
+ this.Component = weaverse.elementInstances.get(type);
193
+ }
194
+ }
195
+ };
196
+ export {
197
+ Weaverse,
198
+ WeaverseItemStore,
199
+ isBrowser,
200
+ isIframe,
201
+ isReactNative
202
+ };