@bams-app/store 0.0.1

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.
@@ -0,0 +1,146 @@
1
+ [
2
+ {
3
+ "id": "1000",
4
+ "parentId": "0",
5
+ "name": "计划生产订单",
6
+ "pid": "0",
7
+ "menuName": "计划生产订单",
8
+ "openType": "0",
9
+ "path": "pagePlannedProductionOrder",
10
+ "iframeSrc": null,
11
+ "menuType": "menu",
12
+ "children": []
13
+ },
14
+ {
15
+ "id": "1001",
16
+ "parentId": "0",
17
+ "name": "生产订单",
18
+ "pid": "0",
19
+ "menuName": "生产订单",
20
+ "openType": "0",
21
+ "path": "pageProductionOrder",
22
+ "iframeSrc": null,
23
+ "menuType": "menu",
24
+ "children": []
25
+ },
26
+ {
27
+ "id": "1002",
28
+ "parentId": "0",
29
+ "name": "班组生产任务",
30
+ "pid": "0",
31
+ "menuName": "班组生产任务",
32
+ "openType": "0",
33
+ "path": "pageProductionOrderTeam",
34
+ "iframeSrc": null,
35
+ "menuType": "menu",
36
+ "children": []
37
+ },
38
+ {
39
+ "id": "1003",
40
+ "parentId": "0",
41
+ "name": "一控作业记录",
42
+ "pid": "0",
43
+ "menuName": "一控作业记录",
44
+ "openType": "0",
45
+ "path": "pageFirstOperation",
46
+ "iframeSrc": null,
47
+ "menuType": "menu",
48
+ "children": []
49
+ },
50
+ {
51
+ "id": "1004",
52
+ "parentId": "0",
53
+ "name": "二控作业记录",
54
+ "pid": "0",
55
+ "menuName": "二控作业记录",
56
+ "openType": "0",
57
+ "path": "pageSecendOperation",
58
+ "iframeSrc": null,
59
+ "menuType": "menu",
60
+ "children": []
61
+ },
62
+ {
63
+ "id": "1005",
64
+ "parentId": "0",
65
+ "name": "三控作业记录",
66
+ "pid": "0",
67
+ "menuName": "三控作业记录",
68
+ "openType": "0",
69
+ "path": "pageThirdOperation",
70
+ "iframeSrc": null,
71
+ "menuType": "menu",
72
+ "children": []
73
+ },
74
+ {
75
+ "id": "1006",
76
+ "parentId": "0",
77
+ "name": "换纸记录",
78
+ "pid": "0",
79
+ "menuName": "换纸记录",
80
+ "openType": "0",
81
+ "path": "pagePagerReplace",
82
+ "iframeSrc": null,
83
+ "menuType": "menu",
84
+ "children": []
85
+ },
86
+ {
87
+ "id": "1007",
88
+ "parentId": "0",
89
+ "name": "放废记录",
90
+ "pid": "0",
91
+ "menuName": "放废记录",
92
+ "openType": "0",
93
+ "path": "pageDispoalRecord",
94
+ "iframeSrc": null,
95
+ "menuType": "menu",
96
+ "children": []
97
+ },
98
+ {
99
+ "id": "1008",
100
+ "parentId": "0",
101
+ "name": "待确认产品记录",
102
+ "pid": "0",
103
+ "menuName": "待确认产品记录",
104
+ "openType": "0",
105
+ "path": "pagePendingOperation",
106
+ "iframeSrc": null,
107
+ "menuType": "menu",
108
+ "children": []
109
+ },
110
+ {
111
+ "id": "1009",
112
+ "parentId": "0",
113
+ "name": "一控检验记录",
114
+ "pid": "0",
115
+ "menuName": "一控检验记录",
116
+ "openType": "0",
117
+ "path": "pageFirstControlInspectionRecord",
118
+ "iframeSrc": null,
119
+ "menuType": "menu",
120
+ "children": []
121
+ },
122
+ {
123
+ "id": "1010",
124
+ "parentId": "0",
125
+ "name": "二控检验记录",
126
+ "pid": "0",
127
+ "menuName": "二控检验记录",
128
+ "openType": "0",
129
+ "path": "pageSecondControlInspectionRecord",
130
+ "iframeSrc": null,
131
+ "menuType": "menu",
132
+ "children": []
133
+ },
134
+ {
135
+ "id": "1011",
136
+ "parentId": "0",
137
+ "name": "三控检验记录",
138
+ "pid": "0",
139
+ "menuName": "三控检验记录",
140
+ "openType": "0",
141
+ "path": "pageThirdControlInspectionRecord",
142
+ "iframeSrc": null,
143
+ "menuType": "menu",
144
+ "children": []
145
+ }
146
+ ]
@@ -0,0 +1,135 @@
1
+ import fs from "node:fs/promises";
2
+
3
+ const APP_ID = "2053028348377497602";
4
+ const ROOT_PARENT_ID = "2053028348566241282";
5
+ const BASE_URL = "http://192.168.7.14";
6
+ const ENDPOINT = `${BASE_URL.replace(/\/$/, "")}/gateway/sys/sysMenu/save`;
7
+
8
+ // 这里填你之前请求里的 authorization 头
9
+ const AUTHORIZATION = "Sys eyJhbGciOiJSUzI1NiJ9.eyJ1aWQiOiI0NCIsInN1YiI6ImFkbWluIiwiY3JlYXRlVGltZSI6IjIwMjYtMDUtMTEgMTA6NDQ6MTQiLCJ1c2VyQWNjb3VudCI6ImFkbWluIiwidXNlck5hbWUiOiLnrqHnkIblkZgiLCJleHAiOjE3Nzg1MTA2NTQsImFjY291bnQiOiJhZG1pbiJ9.k7Hg1TH3KX8u85TYcSl_AX3iwTlSBDBX1BQ_VfwNV1u3m-xaFUPPupwB1rYR9Ah7CS1HkIVPe3gHliTuDvJM4g";
10
+
11
+ // 这里填你之前请求里的自定义头
12
+ const ACCOUNT_ID = "3";
13
+ const COMPANY_ID = "157023859r55002e314";
14
+
15
+ // 如果你希望每次都带上 cookie(通常不是必须的),可以加一个常量
16
+ const COOKIE = "auth=eyJhbGciOiJSUzI1NiJ9.eyJ1aWQiOiI0NCIsInN1YiI6ImFkbWluIiwiY3JlYXRlVGltZSI6IjIwMjYtMDMtMTIgMTA6MDY6MTAiLCJ1c2VyQWNjb3VudCI6ImFkbWluIiwidXNlck5hbWUiOiLnrqHnkIblkZgiLCJleHAiOjE3NzMzMjQzNzAsImFjY291bnQiOiJhZG1pbiJ9.SBjhaovve2rrHsMN32br_OcoQL4joW3G-ZUc1qglTdICPqqRuWAYR6pWamAM9NIPVJC1etj9VEDi-WV-m5b2RQ";
17
+
18
+ // 如果接口强制需要固定字段,可以在这里补充,暂时先留空
19
+ const EXTRA_DATA = {};
20
+ const CHILDREN_KEY = "children";
21
+
22
+ const inputPath = process.argv[2];
23
+ if (!inputPath) {
24
+ throw new Error("Usage: node save-menus.mjs <menus.json>");
25
+ }
26
+
27
+ function pickMenuFields(node) {
28
+ return {
29
+ menuName: node?.menuName ?? null,
30
+ path: node?.path ?? null,
31
+ };
32
+ }
33
+
34
+ function getChildren(node) {
35
+ const c = node?.[CHILDREN_KEY];
36
+ return Array.isArray(c) ? c : [];
37
+ }
38
+
39
+ function inferMenuType(node) {
40
+ const children = getChildren(node);
41
+ return children.length > 0 ? "dir" : "menu";
42
+ }
43
+
44
+ async function postSaveMenu({ parentId, node, sort }) {
45
+ const { menuName, path } = pickMenuFields(node);
46
+ const menuType = inferMenuType(node);
47
+
48
+ const body = {
49
+ data: {
50
+ appId: APP_ID,
51
+ id: null,
52
+ pid: parentId ?? null,
53
+ menuName,
54
+ path,
55
+ menuCode: path,
56
+ menuType,
57
+ sort,
58
+ ...EXTRA_DATA,
59
+ },
60
+ };
61
+
62
+ const headers = {
63
+ accept: "application/json, text/plain, */*",
64
+ "content-type": "application/json;charset=UTF-8",
65
+ };
66
+
67
+ if (ACCOUNT_ID) headers.accountid = ACCOUNT_ID;
68
+ if (COMPANY_ID) headers.companyid = COMPANY_ID;
69
+ if (AUTHORIZATION) headers.authorization = AUTHORIZATION;
70
+
71
+
72
+ if (COOKIE) headers.cookie = COOKIE;
73
+ // 如果你想完全复刻原请求,还可以加:
74
+ headers.isreturnallparam = "false";
75
+ headers.returndata = "true";
76
+
77
+ const res = await fetch(ENDPOINT, {
78
+ method: "POST",
79
+ headers,
80
+ body: JSON.stringify(body),
81
+ });
82
+
83
+ const text = await res.text();
84
+ let json;
85
+ try {
86
+ json = JSON.parse(text);
87
+ } catch {
88
+ throw new Error(`Non-JSON response (${res.status}): ${text.slice(0, 500)}`);
89
+ }
90
+
91
+ if (!res.ok) {
92
+ throw new Error(`HTTP ${res.status}: ${json?.msg ?? text}`);
93
+ }
94
+ if (!json?.success) {
95
+ throw new Error(json?.msg ?? "save failed");
96
+ }
97
+ const newId = json?.data?.id;
98
+ if (!newId) {
99
+ throw new Error(`save ok but missing data.id: ${text.slice(0, 500)}`);
100
+ }
101
+ return { newId, json };
102
+ }
103
+
104
+ async function saveTree(nodes, rootParentId) {
105
+ const results = [];
106
+
107
+ async function dfs(node, parentId, indexPath, sort) {
108
+ const { newId } = await postSaveMenu({ parentId, node, sort });
109
+ const { menuName, path } = pickMenuFields(node);
110
+ results.push({ indexPath, menuName, path, id: newId, pid: parentId, sort });
111
+
112
+ const children = getChildren(node);
113
+ for (let i = 0; i < children.length; i += 1) {
114
+ await dfs(children[i], newId, `${indexPath}/${i}`, i + 1);
115
+ }
116
+ }
117
+
118
+ for (let i = 0; i < nodes.length; i += 1) {
119
+ await dfs(nodes[i], rootParentId, `${i}`, i + 1);
120
+ }
121
+
122
+ return results;
123
+ }
124
+
125
+ const raw = await fs.readFile(inputPath, "utf-8");
126
+ const menus = JSON.parse(raw);
127
+ if (!Array.isArray(menus)) {
128
+ throw new Error("menus.json must be a JSON array");
129
+ }
130
+
131
+ const output = await saveTree(menus, ROOT_PARENT_ID);
132
+ await fs.writeFile("save-menus.result.json", JSON.stringify(output, null, 2), "utf-8");
133
+
134
+ console.log(`Done. Created ${output.length} nodes.`);
135
+ console.log(`Result saved to save-menus.result.json`);
@@ -0,0 +1,242 @@
1
+ import { getCurrentInstance, onBeforeUnmount } from "vue";
2
+
3
+ // 默认跨 tab 通信通道名。相同 channel 的页面之间才能相互同步。
4
+ const DEFAULT_CHANNEL = "bams-pinia-sync";
5
+ // 缓存已经初始化过的 store,供 usePiniaSync 通过 storeId 查找。
6
+ const STORE_REGISTRY = new Map();
7
+ // 当前浏览器 tab 的唯一标识,用于忽略自己广播出去的消息,避免重复 patch。
8
+ const TAB_ID = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
9
+
10
+ const isClient = () => typeof window !== "undefined";
11
+ const noop = () => { };
12
+
13
+ const resolveOptionValue = (value, store, config) => {
14
+ if (typeof value !== "function") return value;
15
+ return value(store, config);
16
+ };
17
+
18
+ // 将 stores 配置统一转为 Set,便于判断当前 store 是否需要同步。
19
+ const normalizeStoreIds = stores => {
20
+ if (!stores) return null;
21
+ if (Array.isArray(stores)) return new Set(stores);
22
+ if (typeof stores === "string") return new Set([stores]);
23
+ return null;
24
+ };
25
+
26
+ // 合并全局插件配置、单个 store 配置,最终得到当前 store 的同步配置。
27
+ const normalizeStoreConfig = (store, options, pluginOptions) => {
28
+ const storeOptions = options?.sync;
29
+ const enabledStores = normalizeStoreIds(pluginOptions.stores);
30
+
31
+ // store 内显式 sync: false 时,不接入同步。
32
+ if (storeOptions === false) return null;
33
+ // 配置了 stores 白名单时,只有白名单内的 store 才接入同步。
34
+ if (storeOptions == null && enabledStores && !enabledStores.has(store.$id)) return null;
35
+ // 没有 store 级 sync 配置,也没有 stores 白名单时,默认不全量开启,除非 enabled: true。
36
+ if (storeOptions == null && !enabledStores && pluginOptions.enabled !== true) return null;
37
+
38
+ const config = {
39
+ enabled: true,
40
+ channel: pluginOptions.channel || DEFAULT_CHANNEL,
41
+ manual: pluginOptions.manual || false,
42
+ pick: pluginOptions.pick,
43
+ omit: pluginOptions.omit,
44
+ ...pluginOptions.storeOptions?.[store.$id],
45
+ ...(storeOptions === true ? {} : storeOptions || {}),
46
+ };
47
+
48
+ config.channel = resolveOptionValue(config.channel, store, config) || DEFAULT_CHANNEL;
49
+
50
+ if (config.enabled === false) return null;
51
+ return config;
52
+ };
53
+
54
+ // 根据 pick/omit 配置提取需要广播的 state,避免把整个 store 都同步出去。
55
+ const getSyncState = (state, config = {}) => {
56
+ const source = JSON.parse(JSON.stringify(state || {}));
57
+ const pick = config.pick || config.paths;
58
+
59
+ // pick 优先:只同步指定字段。
60
+ if (Array.isArray(pick) && pick.length) {
61
+ return pick.reduce((result, key) => {
62
+ result[key] = source[key];
63
+ return result;
64
+ }, {});
65
+ }
66
+
67
+ // 没有 pick 时,可通过 omit 排除不需要同步的字段。
68
+ if (Array.isArray(config.omit) && config.omit.length) {
69
+ config.omit.forEach(key => {
70
+ delete source[key];
71
+ });
72
+ }
73
+
74
+ return source;
75
+ };
76
+
77
+ // 创建跨 tab 通信层:优先 BroadcastChannel,不支持时降级为 localStorage storage 事件。
78
+ const createTransport = channelName => {
79
+ // SSR 或非浏览器环境下返回空实现,保证不会报错。
80
+ if (!isClient()) {
81
+ return {
82
+ post: noop,
83
+ listen: () => noop,
84
+ close: noop,
85
+ };
86
+ }
87
+
88
+ if ("BroadcastChannel" in window) {
89
+ const channel = new BroadcastChannel(channelName);
90
+ return {
91
+ post: data => channel.postMessage(data),
92
+ listen: handler => {
93
+ channel.addEventListener("message", handler);
94
+ return () => channel.removeEventListener("message", handler);
95
+ },
96
+ close: () => channel.close(),
97
+ };
98
+ }
99
+
100
+ return {
101
+ // storage 事件只会在其他 tab 触发,所以写入后立即删除即可。
102
+ post: data => {
103
+ localStorage.setItem(channelName, JSON.stringify(data));
104
+ localStorage.removeItem(channelName);
105
+ },
106
+ listen: handler => {
107
+ const onStorage = event => {
108
+ if (event.key !== channelName || !event.newValue) return;
109
+ handler({ data: JSON.parse(event.newValue) });
110
+ };
111
+ window.addEventListener("storage", onStorage);
112
+ return () => window.removeEventListener("storage", onStorage);
113
+ },
114
+ close: noop,
115
+ };
116
+ };
117
+
118
+ // 构造统一的同步消息格式。
119
+ const createMessage = (store, config, type = "patch") => ({
120
+ type,
121
+ tabId: TAB_ID,
122
+ storeId: store.$id,
123
+ state: getSyncState(store.$state, config),
124
+ timestamp: Date.now(),
125
+ });
126
+
127
+ // 创建 Pinia 插件。注册后,每个 store 初始化时都会执行一次这里返回的函数。
128
+ export const createPiniaSyncPlugin = (pluginOptions = {}) => {
129
+ // 同一个插件实例下,同一个 channel 复用同一个通信对象。
130
+ const transports = new Map();
131
+
132
+ return context => {
133
+ const { store, options } = context;
134
+ const config = normalizeStoreConfig(store, options, pluginOptions);
135
+
136
+ // 无论当前 store 是否开启同步,都登记起来,方便手动 API 按 storeId 查找。
137
+ STORE_REGISTRY.set(store.$id, store);
138
+
139
+ if (!config) return;
140
+
141
+ if (!transports.has(config.channel)) {
142
+ transports.set(config.channel, createTransport(config.channel));
143
+ }
144
+
145
+ const transport = transports.get(config.channel);
146
+ // 标记当前是否正在应用其他 tab 发来的状态,避免 patch 后再次广播形成回环。
147
+ let applying = false;
148
+
149
+ const applyState = state => {
150
+ applying = true;
151
+ store.$patch(state);
152
+ Promise.resolve().then(() => {
153
+ applying = false;
154
+ });
155
+ };
156
+
157
+ // 监听其他 tab 发来的同步消息。
158
+ const stopListen = transport.listen(event => {
159
+ const message = event.data;
160
+ // 忽略空消息、自己发出的消息、其他 store 的消息。
161
+ if (!message || message.tabId === TAB_ID || message.storeId !== store.$id) return;
162
+
163
+ // 新 tab 请求最新状态时,当前 tab 回传一次自己的 state。
164
+ if (message.type === "request") {
165
+ transport.post(createMessage(store, config, "patch"));
166
+ return;
167
+ }
168
+
169
+ // 收到状态补丁后,更新当前 tab 的 store。
170
+ if (message.type === "patch") {
171
+ applyState(message.state || {});
172
+ }
173
+ });
174
+
175
+ // 主动广播当前 store 状态。
176
+ const broadcast = (type = "patch") => {
177
+ transport.post(createMessage(store, config, type));
178
+ };
179
+
180
+ // 默认自动监听 store 变化并广播;manual: true 时改为只允许手动广播。
181
+ const stopSubscribe = config.manual
182
+ ? noop
183
+ : store.$subscribe(() => {
184
+ if (!applying) broadcast();
185
+ }, { detached: true });
186
+
187
+ // 挂到 store 实例上,方便外部手动刷新、广播或销毁监听。
188
+ store.$sync = {
189
+ refresh: () => transport.post(createMessage(store, config, "request")),
190
+ broadcast,
191
+ destroy: () => {
192
+ stopSubscribe();
193
+ stopListen();
194
+ },
195
+ };
196
+
197
+ // 初始化时默认向其他 tab 请求一次最新状态。
198
+ if (config.immediate !== false) {
199
+ store.$sync.refresh();
200
+ }
201
+ };
202
+ };
203
+
204
+ // 根据 storeId 获取已初始化的 store 实例。
205
+ export const getPiniaSyncStore = storeId => STORE_REGISTRY.get(storeId) || null;
206
+
207
+ // 手动广播某个 store 的当前状态。
208
+ export const broadcastPiniaStore = store => {
209
+ if (!store?.$sync) return false;
210
+ store.$sync.broadcast();
211
+ return true;
212
+ };
213
+
214
+ // 手动向其他 tab 请求某个 store 的最新状态。
215
+ export const refreshPiniaStore = store => {
216
+ if (!store?.$sync) return false;
217
+ store.$sync.refresh();
218
+ return true;
219
+ };
220
+
221
+ // 组合式封装:支持传 store 实例,也支持传 storeId。
222
+ export const usePiniaSync = store => {
223
+ const resolveStore = () => (typeof store === "string" ? getPiniaSyncStore(store) : store);
224
+
225
+ const refresh = () => refreshPiniaStore(resolveStore());
226
+ const broadcast = () => broadcastPiniaStore(resolveStore());
227
+ const destroy = () => resolveStore()?.$sync?.destroy?.();
228
+
229
+ // 仅在组件 setup 生命周期内自动销毁监听;普通 JS 调用不注册生命周期钩子。
230
+ if (getCurrentInstance()) {
231
+ onBeforeUnmount(destroy);
232
+ }
233
+
234
+ return {
235
+ get store() {
236
+ return resolveStore();
237
+ },
238
+ refresh,
239
+ broadcast,
240
+ destroy,
241
+ };
242
+ };