niimbot-canvas-sdk 1.0.0 → 1.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.
@@ -1,10 +1,10 @@
1
1
  var d = Object.defineProperty;
2
2
  var g = (n, t, e) => t in n ? d(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
3
  var i = (n, t, e) => (g(n, typeof t != "symbol" ? t + "" : t, e), e);
4
- import u from "penpal";
5
- import l from "eventemitter3";
6
- import { customAlphabet as m } from "nanoid";
7
- class h extends l {
4
+ import { WindowMessenger as u, connect as l, debug as m } from "penpal";
5
+ import b from "eventemitter3";
6
+ import { customAlphabet as A } from "nanoid";
7
+ class h extends b {
8
8
  on(t, e, s) {
9
9
  return super.on(t, e, s);
10
10
  }
@@ -18,7 +18,7 @@ class h extends l {
18
18
  return super.emit(t, ...e);
19
19
  }
20
20
  }
21
- class b {
21
+ class I {
22
22
  constructor() {
23
23
  i(this, "queue", []);
24
24
  i(this, "maxSize", 100);
@@ -49,7 +49,7 @@ class b {
49
49
  this.queue = [];
50
50
  }
51
51
  }
52
- class A {
52
+ class f {
53
53
  constructor(t, e = !1) {
54
54
  this.context = t, this.debug = e;
55
55
  }
@@ -69,8 +69,8 @@ class A {
69
69
  console.error(...this.formatMessage("ERROR", ...t));
70
70
  }
71
71
  }
72
- const I = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", f = m(I, 12);
73
- class p extends h {
72
+ const p = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", y = A(p, 12);
73
+ class v extends h {
74
74
  constructor(e, s = {}) {
75
75
  super();
76
76
  i(this, "connection", null);
@@ -88,26 +88,37 @@ class p extends h {
88
88
  retryDelay: 1e3,
89
89
  childOrigin: "*",
90
90
  ...s
91
- }, this.messageQueue = new b(), this.logger = new A("PenpalBridge", this.options.debug);
91
+ }, this.messageQueue = new I(), this.logger = new f("PenpalBridge", this.options.debug);
92
92
  }
93
93
  /**
94
94
  * 建立连接
95
95
  */
96
96
  async connect(e = {}) {
97
97
  try {
98
- this.logger.info("正在建立连接..."), this.connection = u.connectToChild({
99
- iframe: this.iframe,
98
+ this.logger.info("正在建立连接...");
99
+ const s = new u({
100
+ remoteWindow: this.iframe,
101
+ // Defaults to the current origin.
102
+ allowedOrigins: ["http://127.0.0.1:3000"]
103
+ // Alternatively,
104
+ // allowedOrigins: [new Url(iframe.src).origin]
105
+ });
106
+ this.connection = l({
107
+ messenger: s,
108
+ // Methods the parent window is exposing to the iframe window.
100
109
  methods: {
101
- // 宿主提供给画板的方法
102
- ping: () => "pong",
103
- emitEvent: (s, a) => {
104
- this.emit(s, a);
110
+ add(a, o) {
111
+ return a + o;
112
+ },
113
+ emitEvent: (a, o) => {
114
+ this.emit(a, o);
105
115
  },
106
116
  // 接收来自画板的请求
107
117
  ...e
108
118
  },
109
119
  timeout: this.options.timeout,
110
- childOrigin: this.options.childOrigin
120
+ // childOrigin: this.options.childOrigin,
121
+ log: m("parent")
111
122
  }), await this.connection.promise, this.isConnected = !0, this.reconnectAttempts = 0, await this.processQueuedMessages(), this.logger.info("连接建立成功"), this.emit("connected");
112
123
  } catch (s) {
113
124
  throw this.logger.error("连接失败:", s), await this.handleReconnect(), s;
@@ -117,22 +128,22 @@ class p extends h {
117
128
  * 发送消息到画板
118
129
  */
119
130
  async send(e, s) {
120
- var c;
131
+ var o;
121
132
  const a = {
122
133
  action: e,
123
134
  params: s,
124
135
  timestamp: Date.now(),
125
- messageId: f()
136
+ messageId: y()
126
137
  };
127
138
  if (!this.isConnected)
128
139
  throw this.messageQueue.enqueue(a), new Error("Connection not ready, message queued");
129
140
  try {
130
- if (this.logger.debug("发送消息:", a), !((c = this.connection) != null && c.child))
141
+ if (this.logger.debug("发送消息:", a), !((o = this.connection) != null && o.child))
131
142
  throw new Error("连接未就绪");
132
- const o = await this.connection.child.handleMessage(a);
133
- return this.logger.debug("收到响应:", o), this.validateResponse(o);
134
- } catch (o) {
135
- throw this.logger.error("发送消息失败:", o), this.messageQueue.enqueue(a), o;
143
+ const c = await this.connection.child.handleMessage(a);
144
+ return this.logger.debug("收到响应:", c), this.validateResponse(c);
145
+ } catch (c) {
146
+ throw this.logger.error("发送消息失败:", c), this.messageQueue.enqueue(a), c;
136
147
  }
137
148
  }
138
149
  /**
@@ -191,7 +202,7 @@ class p extends h {
191
202
  return this.isConnected;
192
203
  }
193
204
  }
194
- class y {
205
+ class E {
195
206
  constructor(t) {
196
207
  this.bridge = t;
197
208
  }
@@ -229,7 +240,7 @@ class y {
229
240
  return this.bridge.send("canvas.getSnapshot");
230
241
  }
231
242
  }
232
- class v {
243
+ class w {
233
244
  constructor(t) {
234
245
  this.bridge = t;
235
246
  }
@@ -246,7 +257,7 @@ class v {
246
257
  return this.bridge.send("abilities.disable", { name: t });
247
258
  }
248
259
  }
249
- class E {
260
+ class P {
250
261
  constructor(t) {
251
262
  this.bridge = t;
252
263
  }
@@ -260,7 +271,7 @@ class E {
260
271
  return this.bridge.send("theme.updateToken", t);
261
272
  }
262
273
  }
263
- class P {
274
+ class C {
264
275
  constructor(t) {
265
276
  this.bridge = t;
266
277
  }
@@ -274,7 +285,7 @@ class P {
274
285
  return this.bridge.send("i18n.updateMessages", t);
275
286
  }
276
287
  }
277
- class w {
288
+ class D {
278
289
  constructor(t) {
279
290
  this.bridge = t;
280
291
  }
@@ -304,7 +315,7 @@ const r = {
304
315
  KEY_DOWN: "key-down",
305
316
  KEY_UP: "key-up"
306
317
  };
307
- class C extends h {
318
+ class O extends h {
308
319
  constructor(e, s) {
309
320
  super();
310
321
  i(this, "bridge");
@@ -316,11 +327,11 @@ class C extends h {
316
327
  i(this, "config");
317
328
  i(this, "iframe");
318
329
  i(this, "isInitialized", !1);
319
- this.validateConfig(s), this.config = s, this.iframe = e, this.bridge = new p(e, {
330
+ this.validateConfig(s), this.config = s, this.iframe = e, this.bridge = new v(e, {
320
331
  debug: s.debug || !1,
321
332
  timeout: 3e4,
322
333
  childOrigin: this.extractOrigin(e.src)
323
- }), this.canvasAPI = new y(this.bridge), this.abilityAPI = new v(this.bridge), this.themeAPI = new E(this.bridge), this.i18nAPI = new P(this.bridge), this.authAPI = new w(this.bridge), this.setupEventHandlers();
334
+ }), this.canvasAPI = new E(this.bridge), this.abilityAPI = new w(this.bridge), this.themeAPI = new P(this.bridge), this.i18nAPI = new C(this.bridge), this.authAPI = new D(this.bridge), this.setupEventHandlers();
324
335
  }
325
336
  /**
326
337
  * 初始化SDK
@@ -411,9 +422,9 @@ class C extends h {
411
422
  }), this.bridge.on("canvas-selection-changed", (e) => {
412
423
  this.emit(r.SELECTION_CHANGED, e);
413
424
  }), this.bridge.on("connected", () => {
414
- this.emit(r.CONNECTED);
425
+ console.log("链接建立成功"), this.emit(r.CONNECTED);
415
426
  }), this.bridge.on("disconnected", () => {
416
- this.emit(r.DISCONNECTED);
427
+ console.log("链接断开"), this.emit(r.DISCONNECTED);
417
428
  });
418
429
  }
419
430
  validateConfig(e) {
@@ -434,11 +445,11 @@ class C extends h {
434
445
  }
435
446
  }
436
447
  }
437
- function R(n, t) {
438
- return new C(n, t);
448
+ function S(n, t) {
449
+ return new O(n, t);
439
450
  }
440
451
  export {
441
452
  r as CANVAS_EVENTS,
442
- C as NiimbotCanvasSDK,
443
- R as createCanvas
453
+ O as NiimbotCanvasSDK,
454
+ S as createCanvas
444
455
  };
@@ -1 +1 @@
1
- (function(n,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("penpal"),require("eventemitter3"),require("nanoid")):typeof define=="function"&&define.amd?define(["exports","penpal","eventemitter3","nanoid"],a):(n=typeof globalThis<"u"?globalThis:n||self,a(n.NiimbotCanvasSDK={},n.Penpal,n.EventEmitter3,n.nanoid))})(this,function(n,a,h,m){"use strict";var T=Object.defineProperty;var D=(n,a,h)=>a in n?T(n,a,{enumerable:!0,configurable:!0,writable:!0,value:h}):n[a]=h;var i=(n,a,h)=>(D(n,typeof a!="symbol"?a+"":a,h),h);class u extends h{on(t,e,s){return super.on(t,e,s)}once(t,e,s){return super.once(t,e,s)}off(t,e,s){return super.off(t,e,s)}emit(t,...e){return super.emit(t,...e)}}class b{constructor(){i(this,"queue",[]);i(this,"maxSize",100)}enqueue(t,e=3){this.queue.length>=this.maxSize&&this.queue.shift();const s={...t,retryCount:0,maxRetries:e};return this.queue.push(s),t.messageId}dequeue(){return this.queue.shift()}hasMessages(){return this.queue.length>0}getMessageById(t){return this.queue.find(e=>e.messageId===t)}removeMessageById(t){const e=this.queue.findIndex(s=>s.messageId===t);e!==-1&&this.queue.splice(e,1)}clear(){this.queue=[]}}class A{constructor(t,e=!1){this.context=t,this.debug=e}formatMessage(t,...e){return[`[${new Date().toISOString()}] [${this.context}] [${t}]`,...e]}info(...t){console.info(...this.formatMessage("INFO",...t))}debug(...t){this.debug&&console.debug(...this.formatMessage("DEBUG",...t))}warn(...t){console.warn(...this.formatMessage("WARN",...t))}error(...t){console.error(...this.formatMessage("ERROR",...t))}}const f="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",p=m.customAlphabet(f,12);class I extends u{constructor(e,s={}){super();i(this,"connection",null);i(this,"iframe");i(this,"options");i(this,"messageQueue");i(this,"logger");i(this,"isConnected",!1);i(this,"reconnectAttempts",0);i(this,"maxReconnectAttempts",3);this.iframe=e,this.options={timeout:3e4,debug:!1,retryCount:3,retryDelay:1e3,childOrigin:"*",...s},this.messageQueue=new b,this.logger=new A("PenpalBridge",this.options.debug)}async connect(e={}){try{this.logger.info("正在建立连接..."),this.connection=a.connectToChild({iframe:this.iframe,methods:{ping:()=>"pong",emitEvent:(s,c)=>{this.emit(s,c)},...e},timeout:this.options.timeout,childOrigin:this.options.childOrigin}),await this.connection.promise,this.isConnected=!0,this.reconnectAttempts=0,await this.processQueuedMessages(),this.logger.info("连接建立成功"),this.emit("connected")}catch(s){throw this.logger.error("连接失败:",s),await this.handleReconnect(),s}}async send(e,s){var l;const c={action:e,params:s,timestamp:Date.now(),messageId:p()};if(!this.isConnected)throw this.messageQueue.enqueue(c),new Error("Connection not ready, message queued");try{if(this.logger.debug("发送消息:",c),!((l=this.connection)!=null&&l.child))throw new Error("连接未就绪");const d=await this.connection.child.handleMessage(c);return this.logger.debug("收到响应:",d),this.validateResponse(d)}catch(d){throw this.logger.error("发送消息失败:",d),this.messageQueue.enqueue(c),d}}async processQueuedMessages(){for(;this.messageQueue.hasMessages();){const e=this.messageQueue.dequeue();if(e)try{await this.send(e.action,e.params)}catch(s){this.logger.warn("队列消息发送失败:",s),this.messageQueue.enqueue(e)}}}async handleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){this.logger.error("重连次数达到上限"),this.emit("connection-lost");return}this.reconnectAttempts++,this.logger.info(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`),await new Promise(e=>setTimeout(e,this.options.retryDelay*this.reconnectAttempts));try{await this.connect()}catch{await this.handleReconnect()}}validateResponse(e){if(!e||e.success===void 0)throw new Error("Invalid response format");if(!e.success){const s=e.error||{code:"UNKNOWN",message:"Unknown error"};throw new Error(`${s.code}: ${s.message}`)}return e.data}disconnect(){this.connection&&(this.connection.destroy(),this.isConnected=!1,this.emit("disconnected"),this.logger.info("连接已断开"))}getConnectionStatus(){return this.isConnected}}class v{constructor(t){this.bridge=t}async initialize(t){return this.bridge.send("canvas.initialize",t)}async setData(t){return this.bridge.send("canvas.setData",t)}async getData(){return this.bridge.send("canvas.getData")}async clear(){return this.bridge.send("canvas.clear")}async undo(){return this.bridge.send("canvas.undo")}async redo(){return this.bridge.send("canvas.redo")}async export(t){return this.bridge.send("canvas.export",{format:t})}async save(){return this.bridge.send("canvas.save")}async invoke(t,...e){return this.bridge.send("canvas.invoke",{method:t,args:e})}async setZoom(t){return this.bridge.send("canvas.setZoom",{zoom:t})}async getSnapshot(){return this.bridge.send("canvas.getSnapshot")}}class y{constructor(t){this.bridge=t}async setAbilities(t){return this.bridge.send("abilities.set",t)}async getAbilities(){return this.bridge.send("abilities.get")}async enableAbility(t){return this.bridge.send("abilities.enable",{name:t})}async disableAbility(t){return this.bridge.send("abilities.disable",{name:t})}}class E{constructor(t){this.bridge=t}async setTheme(t){return this.bridge.send("theme.set",{theme:t})}async getCurrentTheme(){return this.bridge.send("theme.get")}async updateToken(t){return this.bridge.send("theme.updateToken",t)}}class P{constructor(t){this.bridge=t}async setLocale(t,e){return this.bridge.send("i18n.setLocale",{locale:t,messages:e})}async getCurrentLocale(){return this.bridge.send("i18n.getLocale")}async updateMessages(t){return this.bridge.send("i18n.updateMessages",t)}}class w{constructor(t){this.bridge=t}async validateToken(){return this.bridge.send("auth.validateToken")}}const o={READY:"ready",CHANGE:"change",SAVE:"save",ERROR:"error",SELECTION_CHANGED:"selection-changed",CONNECTED:"connected",DISCONNECTED:"disconnected",LOADED:"loaded",BEFORE_UNLOAD:"before-unload",OBJECT_ADDED:"object-added",OBJECT_MODIFIED:"object-modified",OBJECT_REMOVED:"object-removed",MOUSE_DOWN:"mouse-down",MOUSE_UP:"mouse-up",MOUSE_MOVE:"mouse-move",KEY_DOWN:"key-down",KEY_UP:"key-up"};class g extends u{constructor(e,s){super();i(this,"bridge");i(this,"canvasAPI");i(this,"abilityAPI");i(this,"themeAPI");i(this,"i18nAPI");i(this,"authAPI");i(this,"config");i(this,"iframe");i(this,"isInitialized",!1);this.validateConfig(s),this.config=s,this.iframe=e,this.bridge=new I(e,{debug:s.debug||!1,timeout:3e4,childOrigin:this.extractOrigin(e.src)}),this.canvasAPI=new v(this.bridge),this.abilityAPI=new y(this.bridge),this.themeAPI=new E(this.bridge),this.i18nAPI=new P(this.bridge),this.authAPI=new w(this.bridge),this.setupEventHandlers()}async init(){if(!this.isInitialized)try{await this.bridge.connect({getConfig:()=>this.config,log:(e,s)=>{console.log(`[Canvas ${e.toUpperCase()}]`,s)}}),await this.canvasAPI.initialize(this.config),this.config.abilities&&await this.abilityAPI.setAbilities(this.config.abilities),this.config.theme&&await this.themeAPI.setTheme(this.config.theme),this.config.locale&&await this.i18nAPI.setLocale(this.config.locale,this.config.messages),this.isInitialized=!0,this.emit(o.READY)}catch(e){throw this.emit(o.ERROR,e),e}}get canvas(){return{setData:e=>this.canvasAPI.setData(e),getData:()=>this.canvasAPI.getData(),clear:()=>this.canvasAPI.clear(),undo:()=>this.canvasAPI.undo(),redo:()=>this.canvasAPI.redo(),export:(e="png")=>this.canvasAPI.export(e),save:()=>this.canvasAPI.save(),setZoom:e=>this.canvasAPI.setZoom(e),getSnapshot:()=>this.canvasAPI.getSnapshot(),invoke:(e,...s)=>this.canvasAPI.invoke(e,...s)}}get abilities(){return{set:e=>this.abilityAPI.setAbilities(e),get:()=>this.abilityAPI.getAbilities(),enable:e=>this.abilityAPI.enableAbility(e),disable:e=>this.abilityAPI.disableAbility(e),updateConfig:(e,s)=>this.abilityAPI.updateAbilityConfig(e,s)}}get theme(){return{set:e=>this.themeAPI.setTheme(e),get:()=>this.themeAPI.getCurrentTheme(),updateToken:e=>this.themeAPI.updateToken(e),reset:()=>this.themeAPI.resetTheme()}}get i18n(){return{setLocale:(e,s)=>this.i18nAPI.setLocale(e,s),getLocale:()=>this.i18nAPI.getCurrentLocale(),updateMessages:e=>this.i18nAPI.updateMessages(e),getMessages:()=>this.i18nAPI.getMessages(),getTranslation:e=>this.i18nAPI.getTranslation(e)}}get auth(){return{validateToken:()=>this.authAPI.validateToken(),refreshToken:e=>this.authAPI.refreshToken(e),getTokenInfo:()=>this.authAPI.getTokenInfo()}}get utils(){return{getConnectionStatus:()=>this.bridge.getConnectionStatus(),disconnect:()=>this.bridge.disconnect(),reconnect:async()=>{this.bridge.disconnect(),this.isInitialized=!1,await this.init()},isInitialized:()=>this.isInitialized}}setupEventHandlers(){this.bridge.on("canvas-change",e=>{this.emit(o.CHANGE,e)}),this.bridge.on("canvas-save",e=>{this.emit(o.SAVE,e)}),this.bridge.on("canvas-error",e=>{this.emit(o.ERROR,e)}),this.bridge.on("canvas-selection-changed",e=>{this.emit(o.SELECTION_CHANGED,e)}),this.bridge.on("connected",()=>{this.emit(o.CONNECTED)}),this.bridge.on("disconnected",()=>{this.emit(o.DISCONNECTED)})}validateConfig(e){if(!e.token)throw new Error("Token is required");if(e.abilities){const s=["text","image","barcode","multiLayout","shape","qrCode"];Object.keys(e.abilities).forEach(c=>{s.includes(c)||console.warn(`Unknown ability: ${c}`)})}}extractOrigin(e){try{return new URL(e).origin}catch{return"*"}}}function C(r,t){return new g(r,t)}n.CANVAS_EVENTS=o,n.NiimbotCanvasSDK=g,n.createCanvas=C,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})});
1
+ (function(n,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("penpal"),require("eventemitter3"),require("nanoid")):typeof define=="function"&&define.amd?define(["exports","penpal","eventemitter3","nanoid"],a):(n=typeof globalThis<"u"?globalThis:n||self,a(n.NiimbotCanvasSDK={},n.Penpal,n.EventEmitter3,n.nanoid))})(this,function(n,a,h,m){"use strict";var D=Object.defineProperty;var T=(n,a,h)=>a in n?D(n,a,{enumerable:!0,configurable:!0,writable:!0,value:h}):n[a]=h;var i=(n,a,h)=>(T(n,typeof a!="symbol"?a+"":a,h),h);class g extends h{on(t,e,s){return super.on(t,e,s)}once(t,e,s){return super.once(t,e,s)}off(t,e,s){return super.off(t,e,s)}emit(t,...e){return super.emit(t,...e)}}class b{constructor(){i(this,"queue",[]);i(this,"maxSize",100)}enqueue(t,e=3){this.queue.length>=this.maxSize&&this.queue.shift();const s={...t,retryCount:0,maxRetries:e};return this.queue.push(s),t.messageId}dequeue(){return this.queue.shift()}hasMessages(){return this.queue.length>0}getMessageById(t){return this.queue.find(e=>e.messageId===t)}removeMessageById(t){const e=this.queue.findIndex(s=>s.messageId===t);e!==-1&&this.queue.splice(e,1)}clear(){this.queue=[]}}class A{constructor(t,e=!1){this.context=t,this.debug=e}formatMessage(t,...e){return[`[${new Date().toISOString()}] [${this.context}] [${t}]`,...e]}info(...t){console.info(...this.formatMessage("INFO",...t))}debug(...t){this.debug&&console.debug(...this.formatMessage("DEBUG",...t))}warn(...t){console.warn(...this.formatMessage("WARN",...t))}error(...t){console.error(...this.formatMessage("ERROR",...t))}}const f="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",I=m.customAlphabet(f,12);class v extends g{constructor(e,s={}){super();i(this,"connection",null);i(this,"iframe");i(this,"options");i(this,"messageQueue");i(this,"logger");i(this,"isConnected",!1);i(this,"reconnectAttempts",0);i(this,"maxReconnectAttempts",3);this.iframe=e,this.options={timeout:3e4,debug:!1,retryCount:3,retryDelay:1e3,childOrigin:"*",...s},this.messageQueue=new b,this.logger=new A("PenpalBridge",this.options.debug)}async connect(e={}){try{this.logger.info("正在建立连接...");const s=new a.WindowMessenger({remoteWindow:this.iframe,allowedOrigins:["http://127.0.0.1:3000"]});this.connection=a.connect({messenger:s,methods:{add(o,d){return o+d},emitEvent:(o,d)=>{this.emit(o,d)},...e},timeout:this.options.timeout,log:a.debug("parent")}),await this.connection.promise,this.isConnected=!0,this.reconnectAttempts=0,await this.processQueuedMessages(),this.logger.info("连接建立成功"),this.emit("connected")}catch(s){throw this.logger.error("连接失败:",s),await this.handleReconnect(),s}}async send(e,s){var d;const o={action:e,params:s,timestamp:Date.now(),messageId:I()};if(!this.isConnected)throw this.messageQueue.enqueue(o),new Error("Connection not ready, message queued");try{if(this.logger.debug("发送消息:",o),!((d=this.connection)!=null&&d.child))throw new Error("连接未就绪");const u=await this.connection.child.handleMessage(o);return this.logger.debug("收到响应:",u),this.validateResponse(u)}catch(u){throw this.logger.error("发送消息失败:",u),this.messageQueue.enqueue(o),u}}async processQueuedMessages(){for(;this.messageQueue.hasMessages();){const e=this.messageQueue.dequeue();if(e)try{await this.send(e.action,e.params)}catch(s){this.logger.warn("队列消息发送失败:",s),this.messageQueue.enqueue(e)}}}async handleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){this.logger.error("重连次数达到上限"),this.emit("connection-lost");return}this.reconnectAttempts++,this.logger.info(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`),await new Promise(e=>setTimeout(e,this.options.retryDelay*this.reconnectAttempts));try{await this.connect()}catch{await this.handleReconnect()}}validateResponse(e){if(!e||e.success===void 0)throw new Error("Invalid response format");if(!e.success){const s=e.error||{code:"UNKNOWN",message:"Unknown error"};throw new Error(`${s.code}: ${s.message}`)}return e.data}disconnect(){this.connection&&(this.connection.destroy(),this.isConnected=!1,this.emit("disconnected"),this.logger.info("连接已断开"))}getConnectionStatus(){return this.isConnected}}class p{constructor(t){this.bridge=t}async initialize(t){return this.bridge.send("canvas.initialize",t)}async setData(t){return this.bridge.send("canvas.setData",t)}async getData(){return this.bridge.send("canvas.getData")}async clear(){return this.bridge.send("canvas.clear")}async undo(){return this.bridge.send("canvas.undo")}async redo(){return this.bridge.send("canvas.redo")}async export(t){return this.bridge.send("canvas.export",{format:t})}async save(){return this.bridge.send("canvas.save")}async invoke(t,...e){return this.bridge.send("canvas.invoke",{method:t,args:e})}async setZoom(t){return this.bridge.send("canvas.setZoom",{zoom:t})}async getSnapshot(){return this.bridge.send("canvas.getSnapshot")}}class y{constructor(t){this.bridge=t}async setAbilities(t){return this.bridge.send("abilities.set",t)}async getAbilities(){return this.bridge.send("abilities.get")}async enableAbility(t){return this.bridge.send("abilities.enable",{name:t})}async disableAbility(t){return this.bridge.send("abilities.disable",{name:t})}}class E{constructor(t){this.bridge=t}async setTheme(t){return this.bridge.send("theme.set",{theme:t})}async getCurrentTheme(){return this.bridge.send("theme.get")}async updateToken(t){return this.bridge.send("theme.updateToken",t)}}class w{constructor(t){this.bridge=t}async setLocale(t,e){return this.bridge.send("i18n.setLocale",{locale:t,messages:e})}async getCurrentLocale(){return this.bridge.send("i18n.getLocale")}async updateMessages(t){return this.bridge.send("i18n.updateMessages",t)}}class P{constructor(t){this.bridge=t}async validateToken(){return this.bridge.send("auth.validateToken")}}const c={READY:"ready",CHANGE:"change",SAVE:"save",ERROR:"error",SELECTION_CHANGED:"selection-changed",CONNECTED:"connected",DISCONNECTED:"disconnected",LOADED:"loaded",BEFORE_UNLOAD:"before-unload",OBJECT_ADDED:"object-added",OBJECT_MODIFIED:"object-modified",OBJECT_REMOVED:"object-removed",MOUSE_DOWN:"mouse-down",MOUSE_UP:"mouse-up",MOUSE_MOVE:"mouse-move",KEY_DOWN:"key-down",KEY_UP:"key-up"};class l extends g{constructor(e,s){super();i(this,"bridge");i(this,"canvasAPI");i(this,"abilityAPI");i(this,"themeAPI");i(this,"i18nAPI");i(this,"authAPI");i(this,"config");i(this,"iframe");i(this,"isInitialized",!1);this.validateConfig(s),this.config=s,this.iframe=e,this.bridge=new v(e,{debug:s.debug||!1,timeout:3e4,childOrigin:this.extractOrigin(e.src)}),this.canvasAPI=new p(this.bridge),this.abilityAPI=new y(this.bridge),this.themeAPI=new E(this.bridge),this.i18nAPI=new w(this.bridge),this.authAPI=new P(this.bridge),this.setupEventHandlers()}async init(){if(!this.isInitialized)try{await this.bridge.connect({getConfig:()=>this.config,log:(e,s)=>{console.log(`[Canvas ${e.toUpperCase()}]`,s)}}),await this.canvasAPI.initialize(this.config),this.config.abilities&&await this.abilityAPI.setAbilities(this.config.abilities),this.config.theme&&await this.themeAPI.setTheme(this.config.theme),this.config.locale&&await this.i18nAPI.setLocale(this.config.locale,this.config.messages),this.isInitialized=!0,this.emit(c.READY)}catch(e){throw this.emit(c.ERROR,e),e}}get canvas(){return{setData:e=>this.canvasAPI.setData(e),getData:()=>this.canvasAPI.getData(),clear:()=>this.canvasAPI.clear(),undo:()=>this.canvasAPI.undo(),redo:()=>this.canvasAPI.redo(),export:(e="png")=>this.canvasAPI.export(e),save:()=>this.canvasAPI.save(),setZoom:e=>this.canvasAPI.setZoom(e),getSnapshot:()=>this.canvasAPI.getSnapshot(),invoke:(e,...s)=>this.canvasAPI.invoke(e,...s)}}get abilities(){return{set:e=>this.abilityAPI.setAbilities(e),get:()=>this.abilityAPI.getAbilities(),enable:e=>this.abilityAPI.enableAbility(e),disable:e=>this.abilityAPI.disableAbility(e),updateConfig:(e,s)=>this.abilityAPI.updateAbilityConfig(e,s)}}get theme(){return{set:e=>this.themeAPI.setTheme(e),get:()=>this.themeAPI.getCurrentTheme(),updateToken:e=>this.themeAPI.updateToken(e),reset:()=>this.themeAPI.resetTheme()}}get i18n(){return{setLocale:(e,s)=>this.i18nAPI.setLocale(e,s),getLocale:()=>this.i18nAPI.getCurrentLocale(),updateMessages:e=>this.i18nAPI.updateMessages(e),getMessages:()=>this.i18nAPI.getMessages(),getTranslation:e=>this.i18nAPI.getTranslation(e)}}get auth(){return{validateToken:()=>this.authAPI.validateToken(),refreshToken:e=>this.authAPI.refreshToken(e),getTokenInfo:()=>this.authAPI.getTokenInfo()}}get utils(){return{getConnectionStatus:()=>this.bridge.getConnectionStatus(),disconnect:()=>this.bridge.disconnect(),reconnect:async()=>{this.bridge.disconnect(),this.isInitialized=!1,await this.init()},isInitialized:()=>this.isInitialized}}setupEventHandlers(){this.bridge.on("canvas-change",e=>{this.emit(c.CHANGE,e)}),this.bridge.on("canvas-save",e=>{this.emit(c.SAVE,e)}),this.bridge.on("canvas-error",e=>{this.emit(c.ERROR,e)}),this.bridge.on("canvas-selection-changed",e=>{this.emit(c.SELECTION_CHANGED,e)}),this.bridge.on("connected",()=>{console.log("链接建立成功"),this.emit(c.CONNECTED)}),this.bridge.on("disconnected",()=>{console.log("链接断开"),this.emit(c.DISCONNECTED)})}validateConfig(e){if(!e.token)throw new Error("Token is required");if(e.abilities){const s=["text","image","barcode","multiLayout","shape","qrCode"];Object.keys(e.abilities).forEach(o=>{s.includes(o)||console.warn(`Unknown ability: ${o}`)})}}extractOrigin(e){try{return new URL(e).origin}catch{return"*"}}}function C(r,t){return new l(r,t)}n.CANVAS_EVENTS=c,n.NiimbotCanvasSDK=l,n.createCanvas=C,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "niimbot-canvas-sdk",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Niimbot Canvas iframe communication SDK",
5
5
  "type": "module",
6
6
  "main": "dist/niimbot-canvas-sdk.umd.js",
@@ -33,8 +33,8 @@
33
33
  },
34
34
  "dependencies": {
35
35
  "eventemitter3": "^5.0.1",
36
- "nanoid": "^5.0.3",
37
- "penpal": "^6.0.0"
36
+ "nanoid": "^5.1.6",
37
+ "penpal": "^7.0.4"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@types/node": "^20.0.0",
@@ -60,4 +60,4 @@
60
60
  ],
61
61
  "author": "Niimbot Team",
62
62
  "license": "MIT"
63
- }
63
+ }