mixi2-js 1.2.1 → 1.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/dist/index.cjs CHANGED
@@ -1,812 +1,604 @@
1
- "use strict";
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
7
  var __getProtoOf = Object.getPrototypeOf;
7
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
9
  var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
19
18
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- Client: () => Client,
34
- EventReason: () => EventReason,
35
- EventType: () => EventType,
36
- LanguageCode: () => LanguageCode,
37
- MediaType: () => MediaType,
38
- MediaUploadStatus: () => MediaUploadStatus,
39
- MediaUploadType: () => MediaUploadType,
40
- OAuth2Authenticator: () => OAuth2Authenticator,
41
- PostAccessLevel: () => PostAccessLevel,
42
- PostMaskType: () => PostMaskType,
43
- PostMediaType: () => PostMediaType,
44
- PostPublishingType: () => PostPublishingType,
45
- PostVisibility: () => PostVisibility,
46
- StampSetType: () => StampSetType,
47
- StreamWatcher: () => StreamWatcher,
48
- UserAccessLevel: () => UserAccessLevel,
49
- UserVisibility: () => UserVisibility,
50
- WebhookServer: () => WebhookServer
51
- });
52
- module.exports = __toCommonJS(index_exports);
53
-
54
- // node_modules/tsup/assets/cjs_shims.js
55
- var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
56
- var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
57
-
58
- // src/auth.ts
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ const require_types = require("./types-D9t_NdQ0.cjs");
25
+ let _grpc_grpc_js = require("@grpc/grpc-js");
26
+ _grpc_grpc_js = __toESM(_grpc_grpc_js);
27
+ let path = require("path");
28
+ path = __toESM(path);
29
+ let url = require("url");
30
+ let _grpc_proto_loader = require("@grpc/proto-loader");
31
+ _grpc_proto_loader = __toESM(_grpc_proto_loader);
32
+ let http = require("http");
33
+ http = __toESM(http);
34
+ let crypto = require("crypto");
35
+ crypto = __toESM(crypto);
36
+ //#region src/auth.ts
59
37
  var OAuth2Authenticator = class {
60
- clientId;
61
- clientSecret;
62
- tokenUrl;
63
- accessToken = null;
64
- expiresAt = null;
65
- refreshPromise = null;
66
- constructor(options) {
67
- this.clientId = options.clientId;
68
- this.clientSecret = options.clientSecret;
69
- this.tokenUrl = options.tokenUrl;
70
- }
71
- async getAccessToken() {
72
- if (this.accessToken && this.expiresAt && Date.now() < this.expiresAt) {
73
- return this.accessToken;
74
- }
75
- if (!this.refreshPromise) {
76
- this.refreshPromise = this.refreshToken().finally(() => {
77
- this.refreshPromise = null;
78
- });
79
- }
80
- await this.refreshPromise;
81
- return this.accessToken;
82
- }
83
- async refreshToken() {
84
- const credentials3 = Buffer.from(
85
- `${encodeURIComponent(this.clientId)}:${encodeURIComponent(this.clientSecret)}`
86
- ).toString("base64");
87
- const response = await fetch(this.tokenUrl, {
88
- method: "POST",
89
- headers: {
90
- "Content-Type": "application/x-www-form-urlencoded",
91
- Authorization: `Basic ${credentials3}`
92
- },
93
- body: "grant_type=client_credentials"
94
- });
95
- if (!response.ok) {
96
- throw new Error(
97
- `Failed to acquire access token: ${response.status} ${response.statusText}`
98
- );
99
- }
100
- const data = await response.json();
101
- this.accessToken = data.access_token;
102
- this.expiresAt = Date.now() + (data.expires_in - 60) * 1e3;
103
- }
38
+ clientId;
39
+ clientSecret;
40
+ tokenUrl;
41
+ accessToken = null;
42
+ expiresAt = null;
43
+ refreshPromise = null;
44
+ constructor(options) {
45
+ this.clientId = options.clientId;
46
+ this.clientSecret = options.clientSecret;
47
+ this.tokenUrl = options.tokenUrl;
48
+ }
49
+ async getAccessToken() {
50
+ if (this.accessToken && this.expiresAt && Date.now() < this.expiresAt) return this.accessToken;
51
+ if (!this.refreshPromise) this.refreshPromise = this.refreshToken().finally(() => {
52
+ this.refreshPromise = null;
53
+ });
54
+ await this.refreshPromise;
55
+ return this.accessToken;
56
+ }
57
+ async refreshToken() {
58
+ const credentials = Buffer.from(`${encodeURIComponent(this.clientId)}:${encodeURIComponent(this.clientSecret)}`).toString("base64");
59
+ const response = await fetch(this.tokenUrl, {
60
+ method: "POST",
61
+ headers: {
62
+ "Content-Type": "application/x-www-form-urlencoded",
63
+ Authorization: `Basic ${credentials}`
64
+ },
65
+ body: "grant_type=client_credentials"
66
+ });
67
+ if (!response.ok) throw new Error(`Failed to acquire access token: ${response.status} ${response.statusText}`);
68
+ const data = await response.json();
69
+ this.accessToken = data.access_token;
70
+ this.expiresAt = Date.now() + (data.expires_in - 60) * 1e3;
71
+ }
104
72
  };
105
-
106
- // src/types.ts
107
- var EventType = /* @__PURE__ */ ((EventType2) => {
108
- EventType2[EventType2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
109
- EventType2[EventType2["PING"] = 1] = "PING";
110
- EventType2[EventType2["POST_CREATED"] = 2] = "POST_CREATED";
111
- EventType2[EventType2["CHAT_MESSAGE_RECEIVED"] = 4] = "CHAT_MESSAGE_RECEIVED";
112
- return EventType2;
113
- })(EventType || {});
114
- var EventReason = /* @__PURE__ */ ((EventReason2) => {
115
- EventReason2[EventReason2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
116
- EventReason2[EventReason2["PING"] = 1] = "PING";
117
- EventReason2[EventReason2["POST_REPLY"] = 2] = "POST_REPLY";
118
- EventReason2[EventReason2["POST_MENTIONED"] = 3] = "POST_MENTIONED";
119
- EventReason2[EventReason2["POST_QUOTED"] = 4] = "POST_QUOTED";
120
- EventReason2[EventReason2["DIRECT_MESSAGE_RECEIVED"] = 8] = "DIRECT_MESSAGE_RECEIVED";
121
- return EventReason2;
122
- })(EventReason || {});
123
- var MediaType = /* @__PURE__ */ ((MediaType2) => {
124
- MediaType2[MediaType2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
125
- MediaType2[MediaType2["IMAGE"] = 1] = "IMAGE";
126
- MediaType2[MediaType2["VIDEO"] = 2] = "VIDEO";
127
- return MediaType2;
128
- })(MediaType || {});
129
- var PostMediaType = /* @__PURE__ */ ((PostMediaType2) => {
130
- PostMediaType2[PostMediaType2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
131
- PostMediaType2[PostMediaType2["IMAGE"] = 1] = "IMAGE";
132
- PostMediaType2[PostMediaType2["VIDEO"] = 2] = "VIDEO";
133
- return PostMediaType2;
134
- })(PostMediaType || {});
135
- var PostVisibility = /* @__PURE__ */ ((PostVisibility2) => {
136
- PostVisibility2[PostVisibility2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
137
- PostVisibility2[PostVisibility2["VISIBLE"] = 1] = "VISIBLE";
138
- PostVisibility2[PostVisibility2["INVISIBLE"] = 2] = "INVISIBLE";
139
- return PostVisibility2;
140
- })(PostVisibility || {});
141
- var PostAccessLevel = /* @__PURE__ */ ((PostAccessLevel2) => {
142
- PostAccessLevel2[PostAccessLevel2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
143
- PostAccessLevel2[PostAccessLevel2["PUBLIC"] = 1] = "PUBLIC";
144
- PostAccessLevel2[PostAccessLevel2["PRIVATE"] = 2] = "PRIVATE";
145
- return PostAccessLevel2;
146
- })(PostAccessLevel || {});
147
- var PostMaskType = /* @__PURE__ */ ((PostMaskType2) => {
148
- PostMaskType2[PostMaskType2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
149
- PostMaskType2[PostMaskType2["SENSITIVE"] = 1] = "SENSITIVE";
150
- PostMaskType2[PostMaskType2["SPOILER"] = 2] = "SPOILER";
151
- return PostMaskType2;
152
- })(PostMaskType || {});
153
- var PostPublishingType = /* @__PURE__ */ ((PostPublishingType2) => {
154
- PostPublishingType2[PostPublishingType2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
155
- PostPublishingType2[PostPublishingType2["NOT_PUBLISHING"] = 1] = "NOT_PUBLISHING";
156
- return PostPublishingType2;
157
- })(PostPublishingType || {});
158
- var UserVisibility = /* @__PURE__ */ ((UserVisibility2) => {
159
- UserVisibility2[UserVisibility2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
160
- UserVisibility2[UserVisibility2["VISIBLE"] = 1] = "VISIBLE";
161
- UserVisibility2[UserVisibility2["INVISIBLE"] = 2] = "INVISIBLE";
162
- return UserVisibility2;
163
- })(UserVisibility || {});
164
- var UserAccessLevel = /* @__PURE__ */ ((UserAccessLevel2) => {
165
- UserAccessLevel2[UserAccessLevel2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
166
- UserAccessLevel2[UserAccessLevel2["PUBLIC"] = 1] = "PUBLIC";
167
- UserAccessLevel2[UserAccessLevel2["PRIVATE"] = 2] = "PRIVATE";
168
- return UserAccessLevel2;
169
- })(UserAccessLevel || {});
170
- var LanguageCode = /* @__PURE__ */ ((LanguageCode2) => {
171
- LanguageCode2[LanguageCode2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
172
- LanguageCode2[LanguageCode2["JP"] = 1] = "JP";
173
- LanguageCode2[LanguageCode2["EN"] = 2] = "EN";
174
- return LanguageCode2;
175
- })(LanguageCode || {});
176
- var StampSetType = /* @__PURE__ */ ((StampSetType2) => {
177
- StampSetType2[StampSetType2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
178
- StampSetType2[StampSetType2["DEFAULT"] = 1] = "DEFAULT";
179
- StampSetType2[StampSetType2["SEASONAL"] = 2] = "SEASONAL";
180
- return StampSetType2;
181
- })(StampSetType || {});
182
- var MediaUploadType = /* @__PURE__ */ ((MediaUploadType2) => {
183
- MediaUploadType2[MediaUploadType2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
184
- MediaUploadType2[MediaUploadType2["IMAGE"] = 1] = "IMAGE";
185
- MediaUploadType2[MediaUploadType2["VIDEO"] = 2] = "VIDEO";
186
- return MediaUploadType2;
187
- })(MediaUploadType || {});
188
- var MediaUploadStatus = /* @__PURE__ */ ((MediaUploadStatus2) => {
189
- MediaUploadStatus2[MediaUploadStatus2["UNSPECIFIED"] = 0] = "UNSPECIFIED";
190
- MediaUploadStatus2[MediaUploadStatus2["UPLOAD_PENDING"] = 1] = "UPLOAD_PENDING";
191
- MediaUploadStatus2[MediaUploadStatus2["PROCESSING"] = 2] = "PROCESSING";
192
- MediaUploadStatus2[MediaUploadStatus2["COMPLETED"] = 3] = "COMPLETED";
193
- MediaUploadStatus2[MediaUploadStatus2["FAILED"] = 4] = "FAILED";
194
- return MediaUploadStatus2;
195
- })(MediaUploadStatus || {});
196
-
197
- // src/client.ts
198
- var grpc2 = __toESM(require("@grpc/grpc-js"), 1);
199
-
200
- // src/proto.ts
201
- var import_path = __toESM(require("path"), 1);
202
- var import_url = require("url");
203
- var grpc = __toESM(require("@grpc/grpc-js"), 1);
204
- var protoLoader = __toESM(require("@grpc/proto-loader"), 1);
205
- var __filename2 = (0, import_url.fileURLToPath)(importMetaUrl);
206
- var __dirname = import_path.default.dirname(__filename2);
207
- var PROTO_DIR = import_path.default.resolve(__dirname, "..", "proto");
208
- var PROTO_LOADER_OPTIONS = {
209
- keepCase: false,
210
- longs: Number,
211
- enums: Number,
212
- defaults: true,
213
- oneofs: true
73
+ //#endregion
74
+ //#region src/proto.ts
75
+ const __filename$1 = (0, url.fileURLToPath)(require("url").pathToFileURL(__filename).href);
76
+ const __dirname$1 = path.default.dirname(__filename$1);
77
+ const PROTO_DIR = path.default.resolve(__dirname$1, "..", "proto");
78
+ const PROTO_LOADER_OPTIONS = {
79
+ keepCase: false,
80
+ longs: Number,
81
+ enums: Number,
82
+ defaults: true,
83
+ oneofs: true
214
84
  };
215
- var _packageDefinition = null;
216
- var _grpcObject = null;
85
+ let _packageDefinition = null;
86
+ let _grpcObject = null;
217
87
  function getPackageDefinition() {
218
- if (!_packageDefinition) {
219
- _packageDefinition = protoLoader.loadSync(
220
- [
221
- "social/mixi/application/service/application_api/v1/service.proto",
222
- "social/mixi/application/service/application_stream/v1/service.proto",
223
- "social/mixi/application/service/client_endpoint/v1/service.proto"
224
- ],
225
- { ...PROTO_LOADER_OPTIONS, includeDirs: [PROTO_DIR] }
226
- );
227
- }
228
- return _packageDefinition;
88
+ if (!_packageDefinition) _packageDefinition = _grpc_proto_loader.loadSync([
89
+ "social/mixi/application/service/application_api/v1/service.proto",
90
+ "social/mixi/application/service/application_stream/v1/service.proto",
91
+ "social/mixi/application/service/client_endpoint/v1/service.proto"
92
+ ], {
93
+ ...PROTO_LOADER_OPTIONS,
94
+ includeDirs: [PROTO_DIR]
95
+ });
96
+ return _packageDefinition;
229
97
  }
230
98
  function getGrpcObject() {
231
- if (!_grpcObject) {
232
- _grpcObject = grpc.loadPackageDefinition(getPackageDefinition());
233
- }
234
- return _grpcObject;
99
+ if (!_grpcObject) _grpcObject = _grpc_grpc_js.loadPackageDefinition(getPackageDefinition());
100
+ return _grpcObject;
235
101
  }
236
- function resolveNested(obj, path2) {
237
- const parts = path2.split(".");
238
- let current = obj;
239
- for (const part of parts) {
240
- current = current[part];
241
- if (current === void 0) {
242
- throw new Error(`Could not resolve gRPC path: ${path2}`);
243
- }
244
- }
245
- return current;
102
+ function resolveNested(obj, path$2) {
103
+ const parts = path$2.split(".");
104
+ let current = obj;
105
+ for (const part of parts) {
106
+ current = current[part];
107
+ if (current === void 0) throw new Error(`Could not resolve gRPC path: ${path$2}`);
108
+ }
109
+ return current;
246
110
  }
247
111
  function getApiServiceClient() {
248
- const grpcObj = getGrpcObject();
249
- return resolveNested(
250
- grpcObj,
251
- "social.mixi.application.service.application_api.v1.ApplicationService"
252
- );
112
+ return resolveNested(getGrpcObject(), "social.mixi.application.service.application_api.v1.ApplicationService");
253
113
  }
254
114
  function getStreamServiceClient() {
255
- const grpcObj = getGrpcObject();
256
- return resolveNested(
257
- grpcObj,
258
- "social.mixi.application.service.application_stream.v1.ApplicationService"
259
- );
115
+ return resolveNested(getGrpcObject(), "social.mixi.application.service.application_stream.v1.ApplicationService");
260
116
  }
261
117
  function getSendEventRequestType() {
262
- const pkgDef = getPackageDefinition();
263
- const msgDef = pkgDef["social.mixi.application.service.client_endpoint.v1.SendEventRequest"];
264
- if (!msgDef || !("type" in msgDef)) {
265
- throw new Error("SendEventRequest message type not found in proto");
266
- }
267
- const pbType = msgDef.type;
268
- return pbType;
118
+ const msgDef = getPackageDefinition()["social.mixi.application.service.client_endpoint.v1.SendEventRequest"];
119
+ if (!msgDef || !("type" in msgDef)) throw new Error("SendEventRequest message type not found in proto");
120
+ return msgDef.type;
269
121
  }
270
-
271
- // src/convert.ts
122
+ //#endregion
123
+ //#region src/convert.ts
272
124
  function toDate(ts) {
273
- if (!ts) return null;
274
- if (ts instanceof Date) return ts;
275
- const obj = ts;
276
- if (obj.seconds !== void 0) {
277
- const ms = Number(obj.seconds) * 1e3 + Math.floor((obj.nanos || 0) / 1e6);
278
- return new Date(ms);
279
- }
280
- return null;
125
+ if (!ts) return null;
126
+ if (ts instanceof Date) return ts;
127
+ const obj = ts;
128
+ if (obj.seconds !== void 0) {
129
+ const ms = Number(obj.seconds) * 1e3 + Math.floor((obj.nanos || 0) / 1e6);
130
+ return new Date(ms);
131
+ }
132
+ return null;
281
133
  }
282
134
  function convertUserAvatar(raw) {
283
- if (!raw) return null;
284
- const r = raw;
285
- return {
286
- largeImageUrl: r.largeImageUrl || "",
287
- largeImageMimeType: r.largeImageMimeType || "",
288
- largeImageHeight: r.largeImageHeight || 0,
289
- largeImageWidth: r.largeImageWidth || 0,
290
- smallImageUrl: r.smallImageUrl || "",
291
- smallImageMimeType: r.smallImageMimeType || "",
292
- smallImageHeight: r.smallImageHeight || 0,
293
- smallImageWidth: r.smallImageWidth || 0
294
- };
135
+ if (!raw) return null;
136
+ const r = raw;
137
+ return {
138
+ largeImageUrl: r.largeImageUrl || "",
139
+ largeImageMimeType: r.largeImageMimeType || "",
140
+ largeImageHeight: r.largeImageHeight || 0,
141
+ largeImageWidth: r.largeImageWidth || 0,
142
+ smallImageUrl: r.smallImageUrl || "",
143
+ smallImageMimeType: r.smallImageMimeType || "",
144
+ smallImageHeight: r.smallImageHeight || 0,
145
+ smallImageWidth: r.smallImageWidth || 0
146
+ };
295
147
  }
296
148
  function convertUser(raw) {
297
- const r = raw;
298
- return {
299
- userId: r.userId || "",
300
- isDisabled: r.isDisabled || false,
301
- name: r.name || "",
302
- displayName: r.displayName || "",
303
- profile: r.profile || "",
304
- userAvatar: convertUserAvatar(r.userAvatar),
305
- visibility: r.visibility || 0,
306
- accessLevel: r.accessLevel || 0
307
- };
149
+ const r = raw;
150
+ return {
151
+ userId: r.userId || "",
152
+ isDisabled: r.isDisabled || false,
153
+ name: r.name || "",
154
+ displayName: r.displayName || "",
155
+ profile: r.profile || "",
156
+ userAvatar: convertUserAvatar(r.userAvatar),
157
+ visibility: r.visibility || 0,
158
+ accessLevel: r.accessLevel || 0
159
+ };
308
160
  }
309
161
  function convertMediaImage(raw) {
310
- if (!raw) return void 0;
311
- const r = raw;
312
- return {
313
- largeImageUrl: r.largeImageUrl || "",
314
- largeImageMimeType: r.largeImageMimeType || "",
315
- largeImageHeight: r.largeImageHeight || 0,
316
- largeImageWidth: r.largeImageWidth || 0,
317
- smallImageUrl: r.smallImageUrl || "",
318
- smallImageMimeType: r.smallImageMimeType || "",
319
- smallImageHeight: r.smallImageHeight || 0,
320
- smallImageWidth: r.smallImageWidth || 0
321
- };
162
+ if (!raw) return void 0;
163
+ const r = raw;
164
+ return {
165
+ largeImageUrl: r.largeImageUrl || "",
166
+ largeImageMimeType: r.largeImageMimeType || "",
167
+ largeImageHeight: r.largeImageHeight || 0,
168
+ largeImageWidth: r.largeImageWidth || 0,
169
+ smallImageUrl: r.smallImageUrl || "",
170
+ smallImageMimeType: r.smallImageMimeType || "",
171
+ smallImageHeight: r.smallImageHeight || 0,
172
+ smallImageWidth: r.smallImageWidth || 0
173
+ };
322
174
  }
323
175
  function convertMediaVideo(raw) {
324
- if (!raw) return void 0;
325
- const r = raw;
326
- return {
327
- videoUrl: r.videoUrl || "",
328
- videoMimeType: r.videoMimeType || "",
329
- videoHeight: r.videoHeight || 0,
330
- videoWidth: r.videoWidth || 0,
331
- previewImageUrl: r.previewImageUrl || "",
332
- previewImageMimeType: r.previewImageMimeType || "",
333
- previewImageHeight: r.previewImageHeight || 0,
334
- previewImageWidth: r.previewImageWidth || 0,
335
- duration: r.duration || 0
336
- };
176
+ if (!raw) return void 0;
177
+ const r = raw;
178
+ return {
179
+ videoUrl: r.videoUrl || "",
180
+ videoMimeType: r.videoMimeType || "",
181
+ videoHeight: r.videoHeight || 0,
182
+ videoWidth: r.videoWidth || 0,
183
+ previewImageUrl: r.previewImageUrl || "",
184
+ previewImageMimeType: r.previewImageMimeType || "",
185
+ previewImageHeight: r.previewImageHeight || 0,
186
+ previewImageWidth: r.previewImageWidth || 0,
187
+ duration: r.duration || 0
188
+ };
337
189
  }
338
190
  function convertMedia(raw) {
339
- const r = raw;
340
- return {
341
- mediaType: r.mediaType || 0,
342
- image: convertMediaImage(r.image),
343
- video: convertMediaVideo(r.video)
344
- };
191
+ const r = raw;
192
+ return {
193
+ mediaType: r.mediaType || 0,
194
+ image: convertMediaImage(r.image),
195
+ video: convertMediaVideo(r.video)
196
+ };
345
197
  }
346
198
  function convertMediaStamp(raw) {
347
- if (!raw) return null;
348
- const r = raw;
349
- return {
350
- url: r.url || "",
351
- mimeType: r.mimeType || "",
352
- height: r.height || 0,
353
- width: r.width || 0
354
- };
199
+ if (!raw) return null;
200
+ const r = raw;
201
+ return {
202
+ url: r.url || "",
203
+ mimeType: r.mimeType || "",
204
+ height: r.height || 0,
205
+ width: r.width || 0
206
+ };
355
207
  }
356
208
  function convertPostMedia(raw) {
357
- const r = raw;
358
- return {
359
- mediaType: r.mediaType || 0,
360
- image: r.image ? convertMediaImage(r.image) : void 0,
361
- video: r.video ? convertMediaVideo(r.video) : void 0
362
- };
209
+ const r = raw;
210
+ return {
211
+ mediaType: r.mediaType || 0,
212
+ image: r.image ? convertMediaImage(r.image) : void 0,
213
+ video: r.video ? convertMediaVideo(r.video) : void 0
214
+ };
363
215
  }
364
216
  function convertPostMask(raw) {
365
- if (!raw) return void 0;
366
- const r = raw;
367
- return {
368
- maskType: r.maskType || 0,
369
- caption: r.caption || ""
370
- };
217
+ if (!raw) return void 0;
218
+ const r = raw;
219
+ return {
220
+ maskType: r.maskType || 0,
221
+ caption: r.caption || ""
222
+ };
371
223
  }
372
224
  function convertPostStamp(raw) {
373
- const r = raw;
374
- return {
375
- stamp: convertMediaStamp(r.stamp),
376
- count: Number(r.count) || 0
377
- };
225
+ const r = raw;
226
+ return {
227
+ stamp: convertMediaStamp(r.stamp),
228
+ count: Number(r.count) || 0
229
+ };
378
230
  }
379
231
  function convertPost(raw) {
380
- const r = raw;
381
- return {
382
- postId: r.postId || "",
383
- isDeleted: r.isDeleted || false,
384
- creatorId: r.creatorId || "",
385
- text: r.text || "",
386
- createdAt: toDate(r.createdAt),
387
- postMediaList: (r.postMediaList || []).map(convertPostMedia),
388
- inReplyToPostId: r.inReplyToPostId || void 0,
389
- postMask: convertPostMask(r.postMask),
390
- visibility: r.visibility || 0,
391
- accessLevel: r.accessLevel || 0,
392
- stamps: (r.stamps || []).map(convertPostStamp),
393
- readerStampId: r.readerStampId || void 0
394
- };
232
+ const r = raw;
233
+ return {
234
+ postId: r.postId || "",
235
+ isDeleted: r.isDeleted || false,
236
+ creatorId: r.creatorId || "",
237
+ text: r.text || "",
238
+ createdAt: toDate(r.createdAt),
239
+ postMediaList: (r.postMediaList || []).map(convertPostMedia),
240
+ inReplyToPostId: r.inReplyToPostId || void 0,
241
+ postMask: convertPostMask(r.postMask),
242
+ visibility: r.visibility || 0,
243
+ accessLevel: r.accessLevel || 0,
244
+ stamps: (r.stamps || []).map(convertPostStamp),
245
+ readerStampId: r.readerStampId || void 0
246
+ };
395
247
  }
396
248
  function convertChatMessage(raw) {
397
- const r = raw;
398
- return {
399
- roomId: r.roomId || "",
400
- messageId: r.messageId || "",
401
- creatorId: r.creatorId || "",
402
- text: r.text || "",
403
- createdAt: toDate(r.createdAt),
404
- mediaList: (r.mediaList || []).map(convertMedia),
405
- postId: r.postId || void 0
406
- };
249
+ const r = raw;
250
+ return {
251
+ roomId: r.roomId || "",
252
+ messageId: r.messageId || "",
253
+ creatorId: r.creatorId || "",
254
+ text: r.text || "",
255
+ createdAt: toDate(r.createdAt),
256
+ mediaList: (r.mediaList || []).map(convertMedia),
257
+ postId: r.postId || void 0
258
+ };
407
259
  }
408
260
  function convertOfficialStamp(raw) {
409
- const r = raw;
410
- return {
411
- stampId: r.stampId || "",
412
- index: r.index || 0,
413
- searchTags: r.searchTags || [],
414
- url: r.url || ""
415
- };
261
+ const r = raw;
262
+ return {
263
+ stampId: r.stampId || "",
264
+ index: r.index || 0,
265
+ searchTags: r.searchTags || [],
266
+ url: r.url || ""
267
+ };
416
268
  }
417
269
  function convertOfficialStampSet(raw) {
418
- const r = raw;
419
- return {
420
- name: r.name || "",
421
- spriteUrl: r.spriteUrl || "",
422
- stamps: (r.stamps || []).map(convertOfficialStamp),
423
- stampSetId: r.stampSetId || "",
424
- startAt: toDate(r.startAt) || void 0,
425
- endAt: toDate(r.endAt) || void 0,
426
- stampSetType: r.stampSetType || 0
427
- };
270
+ const r = raw;
271
+ return {
272
+ name: r.name || "",
273
+ spriteUrl: r.spriteUrl || "",
274
+ stamps: (r.stamps || []).map(convertOfficialStamp),
275
+ stampSetId: r.stampSetId || "",
276
+ startAt: toDate(r.startAt) ?? void 0,
277
+ endAt: toDate(r.endAt) ?? void 0,
278
+ stampSetType: r.stampSetType || 0
279
+ };
428
280
  }
429
281
  function convertPostCreatedEvent(raw) {
430
- const r = raw;
431
- return {
432
- eventReasonList: r.eventReasonList || [],
433
- post: r.post ? convertPost(r.post) : null,
434
- issuer: r.issuer ? convertUser(r.issuer) : null
435
- };
282
+ const r = raw;
283
+ return {
284
+ eventReasonList: r.eventReasonList || [],
285
+ post: r.post ? convertPost(r.post) : null,
286
+ issuer: r.issuer ? convertUser(r.issuer) : null
287
+ };
436
288
  }
437
289
  function convertChatMessageReceivedEvent(raw) {
438
- const r = raw;
439
- return {
440
- eventReasonList: r.eventReasonList || [],
441
- message: r.message ? convertChatMessage(r.message) : null,
442
- issuer: r.issuer ? convertUser(r.issuer) : null
443
- };
290
+ const r = raw;
291
+ return {
292
+ eventReasonList: r.eventReasonList || [],
293
+ message: r.message ? convertChatMessage(r.message) : null,
294
+ issuer: r.issuer ? convertUser(r.issuer) : null
295
+ };
444
296
  }
445
297
  function convertEvent(raw) {
446
- const r = raw;
447
- return {
448
- eventId: r.eventId || "",
449
- eventType: r.eventType || 0,
450
- pingEvent: r.pingEvent || void 0,
451
- postCreatedEvent: r.postCreatedEvent ? convertPostCreatedEvent(r.postCreatedEvent) : void 0,
452
- chatMessageReceivedEvent: r.chatMessageReceivedEvent ? convertChatMessageReceivedEvent(r.chatMessageReceivedEvent) : void 0
453
- };
298
+ const r = raw;
299
+ return {
300
+ eventId: r.eventId || "",
301
+ eventType: r.eventType || 0,
302
+ pingEvent: r.pingEvent || void 0,
303
+ postCreatedEvent: r.postCreatedEvent ? convertPostCreatedEvent(r.postCreatedEvent) : void 0,
304
+ chatMessageReceivedEvent: r.chatMessageReceivedEvent ? convertChatMessageReceivedEvent(r.chatMessageReceivedEvent) : void 0
305
+ };
454
306
  }
455
-
456
- // src/client.ts
307
+ //#endregion
308
+ //#region src/client.ts
457
309
  var Client = class {
458
- grpcClient;
459
- authenticator;
460
- authKey;
461
- constructor(options) {
462
- const ClientConstructor = getApiServiceClient();
463
- this.grpcClient = new ClientConstructor(
464
- options.apiAddress,
465
- grpc2.credentials.createSsl()
466
- );
467
- this.authenticator = options.authenticator;
468
- this.authKey = options.authKey;
469
- }
470
- async getMetadata() {
471
- const token = await this.authenticator.getAccessToken();
472
- const metadata = new grpc2.Metadata();
473
- metadata.add("authorization", `Bearer ${token}`);
474
- if (this.authKey) {
475
- metadata.add("x-auth-key", this.authKey);
476
- }
477
- return metadata;
478
- }
479
- call(method, request) {
480
- return this.getMetadata().then((metadata) => {
481
- return new Promise((resolve, reject) => {
482
- const fn = this.grpcClient[method];
483
- if (!fn) {
484
- reject(new Error(`Method "${method}" not found on gRPC client`));
485
- return;
486
- }
487
- fn.call(
488
- this.grpcClient,
489
- request,
490
- metadata,
491
- (err, response) => {
492
- if (err) reject(err);
493
- else resolve(response);
494
- }
495
- );
496
- });
497
- });
498
- }
499
- async getUsers(userIdList) {
500
- const response = await this.call("getUsers", { userIdList });
501
- return (response.users || []).map(convertUser);
502
- }
503
- async getPosts(postIdList) {
504
- const response = await this.call("getPosts", { postIdList });
505
- return (response.posts || []).map(convertPost);
506
- }
507
- async createPost(request) {
508
- const response = await this.call(
509
- "createPost",
510
- request
511
- );
512
- return convertPost(response.post);
513
- }
514
- async initiatePostMediaUpload(request) {
515
- return this.call("initiatePostMediaUpload", request);
516
- }
517
- async getPostMediaStatus(mediaId) {
518
- return this.call(
519
- "getPostMediaStatus",
520
- { mediaId }
521
- );
522
- }
523
- async sendChatMessage(request) {
524
- const response = await this.call("sendChatMessage", request);
525
- return convertChatMessage(response.message);
526
- }
527
- async getStamps(request) {
528
- const response = await this.call("getStamps", request || {});
529
- return (response.officialStampSets || []).map(convertOfficialStampSet);
530
- }
531
- async addStampToPost(postId, stampId) {
532
- const response = await this.call("addStampToPost", { postId, stampId });
533
- return convertPost(response.post);
534
- }
535
- close() {
536
- this.grpcClient.close();
537
- }
310
+ grpcClient;
311
+ authenticator;
312
+ authKey;
313
+ constructor(options) {
314
+ this.grpcClient = new (getApiServiceClient())(options.apiAddress, _grpc_grpc_js.credentials.createSsl());
315
+ this.authenticator = options.authenticator;
316
+ this.authKey = options.authKey;
317
+ }
318
+ async getMetadata() {
319
+ const token = await this.authenticator.getAccessToken();
320
+ const metadata = new _grpc_grpc_js.Metadata();
321
+ metadata.add("authorization", `Bearer ${token}`);
322
+ if (this.authKey) metadata.add("x-auth-key", this.authKey);
323
+ return metadata;
324
+ }
325
+ call(method, request) {
326
+ return this.getMetadata().then((metadata) => {
327
+ return new Promise((resolve, reject) => {
328
+ const fn = this.grpcClient[method];
329
+ if (!fn) {
330
+ reject(/* @__PURE__ */ new Error(`Method "${method}" not found on gRPC client`));
331
+ return;
332
+ }
333
+ fn.call(this.grpcClient, request, metadata, (err, response) => {
334
+ if (err) reject(err);
335
+ else resolve(response);
336
+ });
337
+ });
338
+ });
339
+ }
340
+ async getUsers(userIdList) {
341
+ return ((await this.call("getUsers", { userIdList })).users || []).map(convertUser);
342
+ }
343
+ async getPosts(postIdList) {
344
+ return ((await this.call("getPosts", { postIdList })).posts || []).map(convertPost);
345
+ }
346
+ async createPost(request) {
347
+ return convertPost((await this.call("createPost", request)).post);
348
+ }
349
+ async initiatePostMediaUpload(request) {
350
+ return this.call("initiatePostMediaUpload", request);
351
+ }
352
+ async getPostMediaStatus(mediaId) {
353
+ return this.call("getPostMediaStatus", { mediaId });
354
+ }
355
+ async sendChatMessage(request) {
356
+ return convertChatMessage((await this.call("sendChatMessage", request)).message);
357
+ }
358
+ async getStamps(request) {
359
+ return ((await this.call("getStamps", request || {})).officialStampSets || []).map(convertOfficialStampSet);
360
+ }
361
+ async addStampToPost(postId, stampId) {
362
+ return convertPost((await this.call("addStampToPost", {
363
+ postId,
364
+ stampId
365
+ })).post);
366
+ }
367
+ close() {
368
+ this.grpcClient.close();
369
+ }
538
370
  };
539
-
540
- // src/webhook.ts
541
- var import_http = __toESM(require("http"), 1);
542
- var import_crypto = __toESM(require("crypto"), 1);
543
- var TIMESTAMP_TOLERANCE = 300;
371
+ //#endregion
372
+ //#region src/webhook.ts
373
+ const TIMESTAMP_TOLERANCE = 300;
544
374
  var WebhookServer = class {
545
- server;
546
- port;
547
- publicKey;
548
- handler;
549
- syncHandling;
550
- constructor(options) {
551
- this.port = options.port || 8080;
552
- this.handler = options.handler;
553
- this.syncHandling = options.syncHandling || false;
554
- const derPrefix = Buffer.from("302a300506032b6570032100", "hex");
555
- const derKey = Buffer.concat([derPrefix, options.publicKey]);
556
- this.publicKey = import_crypto.default.createPublicKey({
557
- key: derKey,
558
- format: "der",
559
- type: "spki"
560
- });
561
- this.server = import_http.default.createServer(this.requestListener.bind(this));
562
- }
563
- async requestListener(req, res) {
564
- if (req.method === "GET" && req.url === "/healthz") {
565
- res.writeHead(200);
566
- res.end("OK");
567
- return;
568
- }
569
- if (req.method === "POST" && req.url === "/events") {
570
- await this.handleEvent(req, res);
571
- return;
572
- }
573
- res.writeHead(404);
574
- res.end("Not Found");
575
- }
576
- async handleEvent(req, res) {
577
- const signatureBase64 = req.headers["x-mixi2-application-event-signature"];
578
- if (!signatureBase64) {
579
- res.writeHead(401);
580
- res.end("missing x-mixi2-application-event-signature");
581
- return;
582
- }
583
- const signature = Buffer.from(signatureBase64, "base64");
584
- if (signature.length === 0) {
585
- res.writeHead(401);
586
- res.end("x-mixi2-application-event-signature is invalid");
587
- return;
588
- }
589
- const timestamp = req.headers["x-mixi2-application-event-timestamp"];
590
- if (!timestamp) {
591
- res.writeHead(401);
592
- res.end("missing x-mixi2-application-event-timestamp");
593
- return;
594
- }
595
- const unixTime = parseInt(timestamp, 10);
596
- if (isNaN(unixTime)) {
597
- res.writeHead(401);
598
- res.end("x-mixi2-application-event-timestamp is invalid");
599
- return;
600
- }
601
- const diff = Math.floor(Date.now() / 1e3) - unixTime;
602
- if (diff > TIMESTAMP_TOLERANCE) {
603
- res.writeHead(401);
604
- res.end("x-mixi2-application-event-timestamp is too old");
605
- return;
606
- }
607
- if (diff < -TIMESTAMP_TOLERANCE) {
608
- res.writeHead(401);
609
- res.end("x-mixi2-application-event-timestamp is in the future");
610
- return;
611
- }
612
- const body = await new Promise((resolve, reject) => {
613
- const chunks = [];
614
- req.on("data", (chunk) => chunks.push(chunk));
615
- req.on("end", () => resolve(Buffer.concat(chunks)));
616
- req.on("error", reject);
617
- });
618
- const dataToVerify = Buffer.concat([body, Buffer.from(timestamp)]);
619
- const isValid = import_crypto.default.verify(
620
- null,
621
- dataToVerify,
622
- this.publicKey,
623
- signature
624
- );
625
- if (!isValid) {
626
- res.writeHead(401);
627
- res.end("Signature is invalid");
628
- return;
629
- }
630
- let events;
631
- try {
632
- const sendEventType = getSendEventRequestType();
633
- const decoded = sendEventType.decode(new Uint8Array(body));
634
- events = (decoded.events || []).map(convertEvent);
635
- } catch {
636
- res.writeHead(400);
637
- res.end("Failed to parse request body");
638
- return;
639
- }
640
- res.writeHead(204);
641
- res.end();
642
- for (const event of events) {
643
- if (event.eventType === 1 /* PING */) {
644
- continue;
645
- }
646
- if (this.syncHandling) {
647
- try {
648
- await this.handler.handle(event);
649
- } catch (err) {
650
- console.error(`Failed to handle event ${event.eventId}:`, err);
651
- }
652
- } else {
653
- Promise.resolve(this.handler.handle(event)).catch((err) => {
654
- console.error(`Failed to handle event ${event.eventId}:`, err);
655
- });
656
- }
657
- }
658
- }
659
- start() {
660
- return new Promise((resolve) => {
661
- this.server.listen(this.port, () => {
662
- resolve();
663
- });
664
- });
665
- }
666
- shutdown() {
667
- return new Promise((resolve, reject) => {
668
- this.server.close((err) => {
669
- if (err) reject(err);
670
- else resolve();
671
- });
672
- });
673
- }
674
- get address() {
675
- return `:${this.port}`;
676
- }
677
- get httpServer() {
678
- return this.server;
679
- }
680
- get eventHandlerFunc() {
681
- return this.handleEvent.bind(this);
682
- }
375
+ server;
376
+ port;
377
+ publicKey;
378
+ handler;
379
+ syncHandling;
380
+ constructor(options) {
381
+ this.port = options.port || 8080;
382
+ this.handler = options.handler;
383
+ this.syncHandling = options.syncHandling || false;
384
+ const derPrefix = Buffer.from("302a300506032b6570032100", "hex");
385
+ const derKey = Buffer.concat([derPrefix, options.publicKey]);
386
+ this.publicKey = crypto.default.createPublicKey({
387
+ key: derKey,
388
+ format: "der",
389
+ type: "spki"
390
+ });
391
+ this.server = http.default.createServer(this.requestListener.bind(this));
392
+ }
393
+ async requestListener(req, res) {
394
+ if (req.method === "GET" && req.url === "/healthz") {
395
+ res.writeHead(200);
396
+ res.end("OK");
397
+ return;
398
+ }
399
+ if (req.method === "POST" && req.url === "/events") {
400
+ await this.handleEvent(req, res);
401
+ return;
402
+ }
403
+ res.writeHead(404);
404
+ res.end("Not Found");
405
+ }
406
+ async handleEvent(req, res) {
407
+ const signatureBase64 = req.headers["x-mixi2-application-event-signature"];
408
+ if (!signatureBase64) {
409
+ res.writeHead(401);
410
+ res.end("missing x-mixi2-application-event-signature");
411
+ return;
412
+ }
413
+ const signature = Buffer.from(signatureBase64, "base64");
414
+ if (signature.length === 0) {
415
+ res.writeHead(401);
416
+ res.end("x-mixi2-application-event-signature is invalid");
417
+ return;
418
+ }
419
+ const timestamp = req.headers["x-mixi2-application-event-timestamp"];
420
+ if (!timestamp) {
421
+ res.writeHead(401);
422
+ res.end("missing x-mixi2-application-event-timestamp");
423
+ return;
424
+ }
425
+ const unixTime = parseInt(timestamp, 10);
426
+ if (isNaN(unixTime)) {
427
+ res.writeHead(401);
428
+ res.end("x-mixi2-application-event-timestamp is invalid");
429
+ return;
430
+ }
431
+ const diff = Math.floor(Date.now() / 1e3) - unixTime;
432
+ if (diff > TIMESTAMP_TOLERANCE) {
433
+ res.writeHead(401);
434
+ res.end("x-mixi2-application-event-timestamp is too old");
435
+ return;
436
+ }
437
+ if (diff < -TIMESTAMP_TOLERANCE) {
438
+ res.writeHead(401);
439
+ res.end("x-mixi2-application-event-timestamp is in the future");
440
+ return;
441
+ }
442
+ const body = await new Promise((resolve, reject) => {
443
+ const chunks = [];
444
+ req.on("data", (chunk) => chunks.push(chunk));
445
+ req.on("end", () => resolve(Buffer.concat(chunks)));
446
+ req.on("error", reject);
447
+ });
448
+ const dataToVerify = Buffer.concat([body, Buffer.from(timestamp)]);
449
+ if (!crypto.default.verify(null, dataToVerify, this.publicKey, signature)) {
450
+ res.writeHead(401);
451
+ res.end("Signature is invalid");
452
+ return;
453
+ }
454
+ let events;
455
+ try {
456
+ events = (getSendEventRequestType().decode(new Uint8Array(body)).events || []).map(convertEvent);
457
+ } catch {
458
+ res.writeHead(400);
459
+ res.end("Failed to parse request body");
460
+ return;
461
+ }
462
+ res.writeHead(204);
463
+ res.end();
464
+ for (const event of events) {
465
+ if (event.eventType === require_types.EventType.PING) continue;
466
+ if (this.syncHandling) try {
467
+ await this.handler.handle(event);
468
+ } catch (err) {
469
+ console.error(`Failed to handle event ${event.eventId}:`, err);
470
+ }
471
+ else Promise.resolve(this.handler.handle(event)).catch((err) => {
472
+ console.error(`Failed to handle event ${event.eventId}:`, err);
473
+ });
474
+ }
475
+ }
476
+ start() {
477
+ return new Promise((resolve) => {
478
+ this.server.listen(this.port, () => {
479
+ resolve();
480
+ });
481
+ });
482
+ }
483
+ shutdown() {
484
+ return new Promise((resolve, reject) => {
485
+ this.server.close((err) => {
486
+ if (err) reject(err);
487
+ else resolve();
488
+ });
489
+ });
490
+ }
491
+ get address() {
492
+ return `:${this.port}`;
493
+ }
494
+ get httpServer() {
495
+ return this.server;
496
+ }
497
+ get eventHandlerFunc() {
498
+ return this.handleEvent.bind(this);
499
+ }
683
500
  };
684
-
685
- // src/stream.ts
686
- var grpc3 = __toESM(require("@grpc/grpc-js"), 1);
501
+ //#endregion
502
+ //#region src/stream.ts
687
503
  var StreamWatcher = class {
688
- authenticator;
689
- authKey;
690
- streamClient;
691
- aborted = false;
692
- constructor(options) {
693
- const ClientConstructor = getStreamServiceClient();
694
- this.streamClient = new ClientConstructor(
695
- options.streamAddress,
696
- grpc3.credentials.createSsl()
697
- );
698
- this.authenticator = options.authenticator;
699
- this.authKey = options.authKey;
700
- }
701
- async getMetadata() {
702
- const token = await this.authenticator.getAccessToken();
703
- const metadata = new grpc3.Metadata();
704
- metadata.add("authorization", `Bearer ${token}`);
705
- if (this.authKey) {
706
- metadata.add("x-auth-key", this.authKey);
707
- }
708
- return metadata;
709
- }
710
- async connect() {
711
- const metadata = await this.getMetadata();
712
- const fn = this.streamClient["subscribeEvents"];
713
- if (!fn) {
714
- throw new Error("subscribeEvents method not found on stream client");
715
- }
716
- return fn.call(
717
- this.streamClient,
718
- {},
719
- metadata
720
- );
721
- }
722
- async reconnect() {
723
- const maxRetries = 3;
724
- let lastError;
725
- for (let i = 0; i < maxRetries; i++) {
726
- if (this.aborted) {
727
- throw new Error("Watcher aborted");
728
- }
729
- await new Promise(
730
- (resolve) => setTimeout(resolve, Math.pow(2, i) * 1e3)
731
- );
732
- try {
733
- const stream = await this.connect();
734
- return stream;
735
- } catch (err) {
736
- lastError = err instanceof Error ? err : new Error(String(err));
737
- console.warn(
738
- `Reconnect attempt ${i + 1}/${maxRetries} failed:`,
739
- lastError.message
740
- );
741
- }
742
- }
743
- throw lastError || new Error("Failed to reconnect");
744
- }
745
- async watch(handler) {
746
- this.aborted = false;
747
- let stream = await this.connect();
748
- return new Promise((resolve, reject) => {
749
- const setupStream = (s) => {
750
- s.on("data", (response) => {
751
- const events = (response.events || []).map(
752
- convertEvent
753
- );
754
- for (const event of events) {
755
- if (event.eventType === 1 /* PING */) {
756
- continue;
757
- }
758
- this.handleEvent(handler, event);
759
- }
760
- });
761
- let disconnected = false;
762
- const handleDisconnect = async () => {
763
- if (disconnected) return;
764
- disconnected = true;
765
- if (this.aborted) {
766
- resolve();
767
- return;
768
- }
769
- try {
770
- stream = await this.reconnect();
771
- setupStream(stream);
772
- } catch (reconnectErr) {
773
- reject(reconnectErr);
774
- }
775
- };
776
- s.on("error", handleDisconnect);
777
- s.on("end", handleDisconnect);
778
- };
779
- setupStream(stream);
780
- });
781
- }
782
- handleEvent(handler, event) {
783
- Promise.resolve(handler.handle(event)).catch((err) => {
784
- console.error(`Failed to handle event ${event.eventId}:`, err);
785
- });
786
- }
787
- stop() {
788
- this.aborted = true;
789
- this.streamClient.close();
790
- }
504
+ authenticator;
505
+ authKey;
506
+ streamClient;
507
+ maxRetries;
508
+ aborted = false;
509
+ constructor(options) {
510
+ this.streamClient = new (getStreamServiceClient())(options.streamAddress, _grpc_grpc_js.credentials.createSsl());
511
+ this.authenticator = options.authenticator;
512
+ this.authKey = options.authKey;
513
+ this.maxRetries = options.maxRetries ?? 3;
514
+ }
515
+ async getMetadata() {
516
+ const token = await this.authenticator.getAccessToken();
517
+ const metadata = new _grpc_grpc_js.Metadata();
518
+ metadata.add("authorization", `Bearer ${token}`);
519
+ if (this.authKey) metadata.add("x-auth-key", this.authKey);
520
+ return metadata;
521
+ }
522
+ async connect() {
523
+ const metadata = await this.getMetadata();
524
+ const fn = this.streamClient["subscribeEvents"];
525
+ if (!fn) throw new Error("subscribeEvents method not found on stream client");
526
+ return fn.call(this.streamClient, {}, metadata);
527
+ }
528
+ async reconnect() {
529
+ const maxRetries = this.maxRetries;
530
+ let lastError;
531
+ for (let i = 0; i < maxRetries; i++) {
532
+ if (this.aborted) throw new Error("Watcher aborted");
533
+ await new Promise((resolve) => setTimeout(resolve, Math.pow(2, i) * 1e3));
534
+ try {
535
+ return await this.connect();
536
+ } catch (err) {
537
+ lastError = err instanceof Error ? err : new Error(String(err));
538
+ console.warn(`Reconnect attempt ${i + 1}/${maxRetries} failed:`, lastError.message);
539
+ }
540
+ }
541
+ throw lastError || /* @__PURE__ */ new Error("Failed to reconnect");
542
+ }
543
+ async watch(handler) {
544
+ this.aborted = false;
545
+ let stream = await this.connect();
546
+ return new Promise((resolve, reject) => {
547
+ const setupStream = (s) => {
548
+ s.on("data", (response) => {
549
+ const events = (response.events || []).map(convertEvent);
550
+ for (const event of events) {
551
+ if (event.eventType === require_types.EventType.PING) continue;
552
+ this.handleEvent(handler, event);
553
+ }
554
+ });
555
+ let disconnected = false;
556
+ const handleDisconnect = async () => {
557
+ if (disconnected) return;
558
+ disconnected = true;
559
+ if (this.aborted) {
560
+ resolve();
561
+ return;
562
+ }
563
+ try {
564
+ stream = await this.reconnect();
565
+ setupStream(stream);
566
+ } catch (reconnectErr) {
567
+ reject(reconnectErr);
568
+ }
569
+ };
570
+ s.on("error", handleDisconnect);
571
+ s.on("end", handleDisconnect);
572
+ };
573
+ setupStream(stream);
574
+ });
575
+ }
576
+ handleEvent(handler, event) {
577
+ Promise.resolve(handler.handle(event)).catch((err) => {
578
+ console.error(`Failed to handle event ${event.eventId}:`, err);
579
+ });
580
+ }
581
+ stop() {
582
+ this.aborted = true;
583
+ this.streamClient.close();
584
+ }
791
585
  };
792
- // Annotate the CommonJS export names for ESM import in node:
793
- 0 && (module.exports = {
794
- Client,
795
- EventReason,
796
- EventType,
797
- LanguageCode,
798
- MediaType,
799
- MediaUploadStatus,
800
- MediaUploadType,
801
- OAuth2Authenticator,
802
- PostAccessLevel,
803
- PostMaskType,
804
- PostMediaType,
805
- PostPublishingType,
806
- PostVisibility,
807
- StampSetType,
808
- StreamWatcher,
809
- UserAccessLevel,
810
- UserVisibility,
811
- WebhookServer
812
- });
586
+ //#endregion
587
+ exports.Client = Client;
588
+ exports.EventReason = require_types.EventReason;
589
+ exports.EventType = require_types.EventType;
590
+ exports.LanguageCode = require_types.LanguageCode;
591
+ exports.MediaType = require_types.MediaType;
592
+ exports.MediaUploadStatus = require_types.MediaUploadStatus;
593
+ exports.MediaUploadType = require_types.MediaUploadType;
594
+ exports.OAuth2Authenticator = OAuth2Authenticator;
595
+ exports.PostAccessLevel = require_types.PostAccessLevel;
596
+ exports.PostMaskType = require_types.PostMaskType;
597
+ exports.PostMediaType = require_types.PostMediaType;
598
+ exports.PostPublishingType = require_types.PostPublishingType;
599
+ exports.PostVisibility = require_types.PostVisibility;
600
+ exports.StampSetType = require_types.StampSetType;
601
+ exports.StreamWatcher = StreamWatcher;
602
+ exports.UserAccessLevel = require_types.UserAccessLevel;
603
+ exports.UserVisibility = require_types.UserVisibility;
604
+ exports.WebhookServer = WebhookServer;