@interware/content-generator 0.1.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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3 -0
  3. package/dist/_chunks/App-6ntGE8c-.js +702 -0
  4. package/dist/_chunks/App-CUBxywy1.mjs +684 -0
  5. package/dist/_chunks/Settings-CwPVYHgw.js +218 -0
  6. package/dist/_chunks/Settings-DTPXHARn.mjs +200 -0
  7. package/dist/_chunks/en-B4KWt_jN.js +4 -0
  8. package/dist/_chunks/en-Byx4XI2L.mjs +4 -0
  9. package/dist/_chunks/es-Cb6O-nM6.js +4 -0
  10. package/dist/_chunks/es-DlGQb34u.mjs +4 -0
  11. package/dist/_chunks/getTranslation-AfxwBFKN.js +4 -0
  12. package/dist/_chunks/getTranslation-Di36t3DD.mjs +5 -0
  13. package/dist/_chunks/index-CkkBgYlg.mjs +126 -0
  14. package/dist/_chunks/index-Dcpjhvs5.js +125 -0
  15. package/dist/admin/index.js +3 -0
  16. package/dist/admin/index.mjs +4 -0
  17. package/dist/admin/src/components/Initializer.d.ts +5 -0
  18. package/dist/admin/src/components/PluginIcon.d.ts +2 -0
  19. package/dist/admin/src/components/commons/dialog/index.d.ts +12 -0
  20. package/dist/admin/src/components/commons/generate-image-dialog/index.d.ts +5 -0
  21. package/dist/admin/src/components/generate-content/Form.d.ts +15 -0
  22. package/dist/admin/src/components/home/table.d.ts +12 -0
  23. package/dist/admin/src/components/index.d.ts +12 -0
  24. package/dist/admin/src/components/settings/Form.d.ts +8 -0
  25. package/dist/admin/src/containers/generate-content/index.d.ts +2 -0
  26. package/dist/admin/src/containers/home/index.d.ts +2 -0
  27. package/dist/admin/src/containers/settings/index.d.ts +7 -0
  28. package/dist/admin/src/hooks/useDialog.d.ts +11 -0
  29. package/dist/admin/src/index.d.ts +10 -0
  30. package/dist/admin/src/lib/use-cases/articles/index.d.ts +5 -0
  31. package/dist/admin/src/lib/use-cases/categories/index.d.ts +5 -0
  32. package/dist/admin/src/lib/use-cases/generate-content/index.d.ts +6 -0
  33. package/dist/admin/src/lib/use-cases/linkedin/index.d.ts +5 -0
  34. package/dist/admin/src/lib/use-cases/settings/index.d.ts +6 -0
  35. package/dist/admin/src/lib/use-cases/users/index.d.ts +5 -0
  36. package/dist/admin/src/pages/App.d.ts +2 -0
  37. package/dist/admin/src/pages/GenerateContent.d.ts +2 -0
  38. package/dist/admin/src/pages/HomePage.d.ts +2 -0
  39. package/dist/admin/src/pages/Settings.d.ts +2 -0
  40. package/dist/admin/src/permissions.d.ts +7 -0
  41. package/dist/admin/src/pluginId.d.ts +1 -0
  42. package/dist/admin/src/reducers/dialog/index.d.ts +6 -0
  43. package/dist/admin/src/types/reducers.d.ts +4 -0
  44. package/dist/admin/src/utils/getTranslation.d.ts +2 -0
  45. package/dist/server/index.js +3149 -0
  46. package/dist/server/index.mjs +3130 -0
  47. package/dist/server/src/bootstrap.d.ts +5 -0
  48. package/dist/server/src/config/index.d.ts +5 -0
  49. package/dist/server/src/content-types/index.d.ts +2 -0
  50. package/dist/server/src/controllers/config.d.ts +8 -0
  51. package/dist/server/src/controllers/controller.d.ts +15 -0
  52. package/dist/server/src/controllers/index.d.ts +22 -0
  53. package/dist/server/src/destroy.d.ts +5 -0
  54. package/dist/server/src/index.d.ts +148 -0
  55. package/dist/server/src/middlewares/index.d.ts +2 -0
  56. package/dist/server/src/policies/index.d.ts +2 -0
  57. package/dist/server/src/register.d.ts +5 -0
  58. package/dist/server/src/routes/admin.d.ts +10 -0
  59. package/dist/server/src/routes/content-api.d.ts +10 -0
  60. package/dist/server/src/routes/index.d.ts +27 -0
  61. package/dist/server/src/services/index.d.ts +83 -0
  62. package/dist/server/src/services/service.d.ts +86 -0
  63. package/package.json +98 -0
@@ -0,0 +1,3149 @@
1
+ "use strict";
2
+ const genai = require("@google/genai");
3
+ const slugify = require("slugify");
4
+ const https = require("https");
5
+ const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
6
+ function _interopNamespace(e) {
7
+ if (e && e.__esModule) return e;
8
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
9
+ if (e) {
10
+ for (const k in e) {
11
+ if (k !== "default") {
12
+ const d = Object.getOwnPropertyDescriptor(e, k);
13
+ Object.defineProperty(n, k, d.get ? d : {
14
+ enumerable: true,
15
+ get: () => e[k]
16
+ });
17
+ }
18
+ }
19
+ }
20
+ n.default = e;
21
+ return Object.freeze(n);
22
+ }
23
+ const slugify__default = /* @__PURE__ */ _interopDefault(slugify);
24
+ const https__namespace = /* @__PURE__ */ _interopNamespace(https);
25
+ const PLUGIN_ID = "strapi-content-generator-gemini";
26
+ const bootstrap = ({ strapi }) => {
27
+ strapi.admin.services.permission.actionProvider.registerMany([
28
+ {
29
+ section: "plugins",
30
+ displayName: "Acceso al generador de contenido",
31
+ uid: "access",
32
+ pluginName: PLUGIN_ID
33
+ }
34
+ ]);
35
+ };
36
+ const destroy = ({ strapi }) => {
37
+ };
38
+ const register = ({ strapi }) => {
39
+ };
40
+ const config$1 = {
41
+ default: {},
42
+ validator() {
43
+ }
44
+ };
45
+ const contentTypes = {};
46
+ const controller = ({ strapi }) => {
47
+ const pluginService = () => strapi.plugin("strapi-content-generator-gemini").service("service");
48
+ return {
49
+ async getArticles(ctx) {
50
+ const contentType = strapi.contentType("api::articulo.articulo");
51
+ await strapi.contentAPI.validate.query(ctx.query, contentType, {
52
+ auth: ctx.state.auth
53
+ });
54
+ const sanitizedQueryParams = await strapi.contentAPI.sanitize.query(
55
+ ctx.query,
56
+ contentType,
57
+ {
58
+ auth: ctx.state.auth
59
+ }
60
+ );
61
+ const documents = await pluginService().getArticulos(sanitizedQueryParams);
62
+ return await strapi.contentAPI.sanitize.output(documents, contentType, {
63
+ auth: ctx.state.auth
64
+ });
65
+ },
66
+ async getCategories(ctx) {
67
+ const contentType = strapi.contentType("api::categoria.categoria");
68
+ await strapi.contentAPI.validate.query(ctx.query, contentType, {
69
+ auth: ctx.state.auth
70
+ });
71
+ const sanitizedQueryParams = await strapi.contentAPI.sanitize.query(
72
+ ctx.query,
73
+ contentType,
74
+ {
75
+ auth: ctx.state.auth
76
+ }
77
+ );
78
+ const documents = await pluginService().getCategorias(sanitizedQueryParams);
79
+ return await strapi.contentAPI.sanitize.output(documents, contentType, {
80
+ auth: ctx.state.auth
81
+ });
82
+ },
83
+ async getUsers(ctx) {
84
+ const contentType = strapi.contentType("plugin::users-permissions.user");
85
+ await strapi.contentAPI.validate.query(ctx.query, contentType, {
86
+ auth: ctx.state.auth
87
+ });
88
+ const sanitizedQueryParams = await strapi.contentAPI.sanitize.query(
89
+ ctx.query,
90
+ contentType,
91
+ {
92
+ auth: ctx.state.auth
93
+ }
94
+ );
95
+ const documents = await pluginService().getUsuarios(sanitizedQueryParams);
96
+ return await strapi.contentAPI.sanitize.output(documents, contentType, {
97
+ auth: ctx.state.auth
98
+ });
99
+ },
100
+ async generateArticle(ctx) {
101
+ ctx.body = await pluginService().generateArticle(ctx);
102
+ },
103
+ async generateImageForArticle(ctx) {
104
+ ctx.body = await pluginService().generateImageForArticle(ctx);
105
+ },
106
+ async publishToLinkedIn(ctx) {
107
+ ctx.body = await pluginService().publishToLinkedIn(ctx);
108
+ },
109
+ async publishToFacebook(ctx) {
110
+ ctx.body = await pluginService().publishToFacebook(ctx);
111
+ },
112
+ async get(ctx) {
113
+ const pluginStore = strapi.store({
114
+ type: "plugin",
115
+ name: "strapi-content-generator-gemini"
116
+ });
117
+ const googleGenAI = await pluginStore.get({ key: "GOOGLE_GEN_AI" });
118
+ const clientURL = await pluginStore.get({ key: "CLIENT_URL" });
119
+ const previewSecret = await pluginStore.get({ key: "PREVIEW_SECRET" });
120
+ ctx.body = { googleGenAI, clientURL, previewSecret };
121
+ },
122
+ async set(ctx) {
123
+ const { key1, key2, key3 } = ctx.request.body;
124
+ const pluginStore = strapi.store({
125
+ type: "plugin",
126
+ name: "strapi-content-generator-gemini"
127
+ });
128
+ await pluginStore.set({ key: "GOOGLE_GEN_AI", value: key1 });
129
+ await pluginStore.set({ key: "CLIENT_URL", value: key2 });
130
+ await pluginStore.set({ key: "PREVIEW_SECRET", value: key3 });
131
+ ctx.body = { ok: true };
132
+ }
133
+ };
134
+ };
135
+ const config = ({ strapi }) => {
136
+ return {
137
+ async get(ctx) {
138
+ const pluginStore = strapi.store({
139
+ type: "plugin",
140
+ name: "strapi-content-generator-gemini"
141
+ });
142
+ const googleGenAI = await pluginStore.get({ key: "GOOGLE_GEN_AI" });
143
+ const linkedInAccessToken = await pluginStore.get({ key: "LINKEDIN_ACCESS_TOKEN" });
144
+ const linkedInOrganizationId = await pluginStore.get({ key: "LINKEDIN_ORGANIZATION_ID" });
145
+ ctx.body = { googleGenAI, linkedInAccessToken, linkedInOrganizationId };
146
+ },
147
+ async set(ctx) {
148
+ const { googleGenAI, linkedInAccessToken, linkedInOrganizationId } = ctx.request.body;
149
+ const pluginStore = strapi.store({
150
+ type: "plugin",
151
+ name: "strapi-content-generator-gemini"
152
+ });
153
+ await pluginStore.set({ key: "GOOGLE_GEN_AI", value: googleGenAI });
154
+ await pluginStore.set({ key: "LINKEDIN_ACCESS_TOKEN", value: linkedInAccessToken });
155
+ await pluginStore.set({ key: "LINKEDIN_ORGANIZATION_ID", value: linkedInOrganizationId });
156
+ ctx.body = { ok: true };
157
+ }
158
+ };
159
+ };
160
+ const controllers = {
161
+ controller,
162
+ config
163
+ };
164
+ const middlewares = {};
165
+ const policies = {};
166
+ const admin = [
167
+ {
168
+ method: "GET",
169
+ path: "/posts",
170
+ handler: "controller.getArticles",
171
+ config: {
172
+ policies: [],
173
+ auth: false
174
+ }
175
+ },
176
+ {
177
+ method: "GET",
178
+ path: "/categories",
179
+ handler: "controller.getCategories",
180
+ config: {
181
+ policies: [],
182
+ auth: false
183
+ }
184
+ },
185
+ {
186
+ method: "GET",
187
+ path: "/users",
188
+ handler: "controller.getUsers",
189
+ config: {
190
+ policies: [],
191
+ auth: false
192
+ }
193
+ },
194
+ {
195
+ method: "POST",
196
+ path: "/generate-article",
197
+ handler: "controller.generateArticle",
198
+ config: {
199
+ policies: [],
200
+ auth: false
201
+ }
202
+ },
203
+ {
204
+ method: "POST",
205
+ path: "/generate-image",
206
+ handler: "controller.generateImageForArticle",
207
+ config: {
208
+ policies: [],
209
+ auth: false
210
+ }
211
+ },
212
+ {
213
+ method: "POST",
214
+ path: "/publish-linkedin",
215
+ handler: "controller.publishToLinkedIn",
216
+ config: {
217
+ policies: [],
218
+ auth: false
219
+ }
220
+ },
221
+ {
222
+ method: "POST",
223
+ path: "/publish-facebook",
224
+ handler: "controller.publishToFacebook",
225
+ config: {
226
+ policies: [],
227
+ auth: false
228
+ }
229
+ }
230
+ ];
231
+ const contentApi = [
232
+ {
233
+ method: "GET",
234
+ path: "/config",
235
+ handler: "config.get",
236
+ config: {
237
+ policies: [],
238
+ auth: false
239
+ }
240
+ },
241
+ {
242
+ method: "POST",
243
+ path: "/config",
244
+ handler: "config.set",
245
+ config: {
246
+ policies: [],
247
+ auth: false
248
+ }
249
+ }
250
+ ];
251
+ const routes = {
252
+ "content-api": {
253
+ type: "content-api",
254
+ routes: [...contentApi]
255
+ },
256
+ admin: {
257
+ type: "admin",
258
+ routes: [...admin]
259
+ }
260
+ };
261
+ function bind(fn, thisArg) {
262
+ return function wrap() {
263
+ return fn.apply(thisArg, arguments);
264
+ };
265
+ }
266
+ const { toString } = Object.prototype;
267
+ const { getPrototypeOf } = Object;
268
+ const { iterator, toStringTag } = Symbol;
269
+ const kindOf = /* @__PURE__ */ ((cache) => (thing) => {
270
+ const str = toString.call(thing);
271
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
272
+ })(/* @__PURE__ */ Object.create(null));
273
+ const kindOfTest = (type) => {
274
+ type = type.toLowerCase();
275
+ return (thing) => kindOf(thing) === type;
276
+ };
277
+ const typeOfTest = (type) => (thing) => typeof thing === type;
278
+ const { isArray } = Array;
279
+ const isUndefined = typeOfTest("undefined");
280
+ function isBuffer(val) {
281
+ return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val);
282
+ }
283
+ const isArrayBuffer = kindOfTest("ArrayBuffer");
284
+ function isArrayBufferView(val) {
285
+ let result;
286
+ if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
287
+ result = ArrayBuffer.isView(val);
288
+ } else {
289
+ result = val && val.buffer && isArrayBuffer(val.buffer);
290
+ }
291
+ return result;
292
+ }
293
+ const isString = typeOfTest("string");
294
+ const isFunction$1 = typeOfTest("function");
295
+ const isNumber = typeOfTest("number");
296
+ const isObject = (thing) => thing !== null && typeof thing === "object";
297
+ const isBoolean = (thing) => thing === true || thing === false;
298
+ const isPlainObject = (val) => {
299
+ if (kindOf(val) !== "object") {
300
+ return false;
301
+ }
302
+ const prototype2 = getPrototypeOf(val);
303
+ return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(toStringTag in val) && !(iterator in val);
304
+ };
305
+ const isEmptyObject = (val) => {
306
+ if (!isObject(val) || isBuffer(val)) {
307
+ return false;
308
+ }
309
+ try {
310
+ return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
311
+ } catch (e) {
312
+ return false;
313
+ }
314
+ };
315
+ const isDate = kindOfTest("Date");
316
+ const isFile = kindOfTest("File");
317
+ const isBlob = kindOfTest("Blob");
318
+ const isFileList = kindOfTest("FileList");
319
+ const isStream = (val) => isObject(val) && isFunction$1(val.pipe);
320
+ const isFormData = (thing) => {
321
+ let kind;
322
+ return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction$1(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
323
+ kind === "object" && isFunction$1(thing.toString) && thing.toString() === "[object FormData]"));
324
+ };
325
+ const isURLSearchParams = kindOfTest("URLSearchParams");
326
+ const [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
327
+ const trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
328
+ function forEach(obj, fn, { allOwnKeys = false } = {}) {
329
+ if (obj === null || typeof obj === "undefined") {
330
+ return;
331
+ }
332
+ let i;
333
+ let l;
334
+ if (typeof obj !== "object") {
335
+ obj = [obj];
336
+ }
337
+ if (isArray(obj)) {
338
+ for (i = 0, l = obj.length; i < l; i++) {
339
+ fn.call(null, obj[i], i, obj);
340
+ }
341
+ } else {
342
+ if (isBuffer(obj)) {
343
+ return;
344
+ }
345
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
346
+ const len = keys.length;
347
+ let key;
348
+ for (i = 0; i < len; i++) {
349
+ key = keys[i];
350
+ fn.call(null, obj[key], key, obj);
351
+ }
352
+ }
353
+ }
354
+ function findKey(obj, key) {
355
+ if (isBuffer(obj)) {
356
+ return null;
357
+ }
358
+ key = key.toLowerCase();
359
+ const keys = Object.keys(obj);
360
+ let i = keys.length;
361
+ let _key;
362
+ while (i-- > 0) {
363
+ _key = keys[i];
364
+ if (key === _key.toLowerCase()) {
365
+ return _key;
366
+ }
367
+ }
368
+ return null;
369
+ }
370
+ const _global = (() => {
371
+ if (typeof globalThis !== "undefined") return globalThis;
372
+ return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
373
+ })();
374
+ const isContextDefined = (context) => !isUndefined(context) && context !== _global;
375
+ function merge() {
376
+ const { caseless, skipUndefined } = isContextDefined(this) && this || {};
377
+ const result = {};
378
+ const assignValue = (val, key) => {
379
+ const targetKey = caseless && findKey(result, key) || key;
380
+ if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
381
+ result[targetKey] = merge(result[targetKey], val);
382
+ } else if (isPlainObject(val)) {
383
+ result[targetKey] = merge({}, val);
384
+ } else if (isArray(val)) {
385
+ result[targetKey] = val.slice();
386
+ } else if (!skipUndefined || !isUndefined(val)) {
387
+ result[targetKey] = val;
388
+ }
389
+ };
390
+ for (let i = 0, l = arguments.length; i < l; i++) {
391
+ arguments[i] && forEach(arguments[i], assignValue);
392
+ }
393
+ return result;
394
+ }
395
+ const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
396
+ forEach(b, (val, key) => {
397
+ if (thisArg && isFunction$1(val)) {
398
+ a[key] = bind(val, thisArg);
399
+ } else {
400
+ a[key] = val;
401
+ }
402
+ }, { allOwnKeys });
403
+ return a;
404
+ };
405
+ const stripBOM = (content) => {
406
+ if (content.charCodeAt(0) === 65279) {
407
+ content = content.slice(1);
408
+ }
409
+ return content;
410
+ };
411
+ const inherits = (constructor, superConstructor, props, descriptors2) => {
412
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
413
+ constructor.prototype.constructor = constructor;
414
+ Object.defineProperty(constructor, "super", {
415
+ value: superConstructor.prototype
416
+ });
417
+ props && Object.assign(constructor.prototype, props);
418
+ };
419
+ const toFlatObject = (sourceObj, destObj, filter2, propFilter) => {
420
+ let props;
421
+ let i;
422
+ let prop;
423
+ const merged = {};
424
+ destObj = destObj || {};
425
+ if (sourceObj == null) return destObj;
426
+ do {
427
+ props = Object.getOwnPropertyNames(sourceObj);
428
+ i = props.length;
429
+ while (i-- > 0) {
430
+ prop = props[i];
431
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
432
+ destObj[prop] = sourceObj[prop];
433
+ merged[prop] = true;
434
+ }
435
+ }
436
+ sourceObj = filter2 !== false && getPrototypeOf(sourceObj);
437
+ } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype);
438
+ return destObj;
439
+ };
440
+ const endsWith = (str, searchString, position) => {
441
+ str = String(str);
442
+ if (position === void 0 || position > str.length) {
443
+ position = str.length;
444
+ }
445
+ position -= searchString.length;
446
+ const lastIndex = str.indexOf(searchString, position);
447
+ return lastIndex !== -1 && lastIndex === position;
448
+ };
449
+ const toArray = (thing) => {
450
+ if (!thing) return null;
451
+ if (isArray(thing)) return thing;
452
+ let i = thing.length;
453
+ if (!isNumber(i)) return null;
454
+ const arr = new Array(i);
455
+ while (i-- > 0) {
456
+ arr[i] = thing[i];
457
+ }
458
+ return arr;
459
+ };
460
+ const isTypedArray = /* @__PURE__ */ ((TypedArray) => {
461
+ return (thing) => {
462
+ return TypedArray && thing instanceof TypedArray;
463
+ };
464
+ })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
465
+ const forEachEntry = (obj, fn) => {
466
+ const generator = obj && obj[iterator];
467
+ const _iterator = generator.call(obj);
468
+ let result;
469
+ while ((result = _iterator.next()) && !result.done) {
470
+ const pair = result.value;
471
+ fn.call(obj, pair[0], pair[1]);
472
+ }
473
+ };
474
+ const matchAll = (regExp, str) => {
475
+ let matches;
476
+ const arr = [];
477
+ while ((matches = regExp.exec(str)) !== null) {
478
+ arr.push(matches);
479
+ }
480
+ return arr;
481
+ };
482
+ const isHTMLForm = kindOfTest("HTMLFormElement");
483
+ const toCamelCase = (str) => {
484
+ return str.toLowerCase().replace(
485
+ /[-_\s]([a-z\d])(\w*)/g,
486
+ function replacer(m, p1, p2) {
487
+ return p1.toUpperCase() + p2;
488
+ }
489
+ );
490
+ };
491
+ const hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
492
+ const isRegExp = kindOfTest("RegExp");
493
+ const reduceDescriptors = (obj, reducer) => {
494
+ const descriptors2 = Object.getOwnPropertyDescriptors(obj);
495
+ const reducedDescriptors = {};
496
+ forEach(descriptors2, (descriptor, name) => {
497
+ let ret;
498
+ if ((ret = reducer(descriptor, name, obj)) !== false) {
499
+ reducedDescriptors[name] = ret || descriptor;
500
+ }
501
+ });
502
+ Object.defineProperties(obj, reducedDescriptors);
503
+ };
504
+ const freezeMethods = (obj) => {
505
+ reduceDescriptors(obj, (descriptor, name) => {
506
+ if (isFunction$1(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) {
507
+ return false;
508
+ }
509
+ const value = obj[name];
510
+ if (!isFunction$1(value)) return;
511
+ descriptor.enumerable = false;
512
+ if ("writable" in descriptor) {
513
+ descriptor.writable = false;
514
+ return;
515
+ }
516
+ if (!descriptor.set) {
517
+ descriptor.set = () => {
518
+ throw Error("Can not rewrite read-only method '" + name + "'");
519
+ };
520
+ }
521
+ });
522
+ };
523
+ const toObjectSet = (arrayOrString, delimiter) => {
524
+ const obj = {};
525
+ const define = (arr) => {
526
+ arr.forEach((value) => {
527
+ obj[value] = true;
528
+ });
529
+ };
530
+ isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
531
+ return obj;
532
+ };
533
+ const noop = () => {
534
+ };
535
+ const toFiniteNumber = (value, defaultValue) => {
536
+ return value != null && Number.isFinite(value = +value) ? value : defaultValue;
537
+ };
538
+ function isSpecCompliantForm(thing) {
539
+ return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
540
+ }
541
+ const toJSONObject = (obj) => {
542
+ const stack = new Array(10);
543
+ const visit = (source, i) => {
544
+ if (isObject(source)) {
545
+ if (stack.indexOf(source) >= 0) {
546
+ return;
547
+ }
548
+ if (isBuffer(source)) {
549
+ return source;
550
+ }
551
+ if (!("toJSON" in source)) {
552
+ stack[i] = source;
553
+ const target = isArray(source) ? [] : {};
554
+ forEach(source, (value, key) => {
555
+ const reducedValue = visit(value, i + 1);
556
+ !isUndefined(reducedValue) && (target[key] = reducedValue);
557
+ });
558
+ stack[i] = void 0;
559
+ return target;
560
+ }
561
+ }
562
+ return source;
563
+ };
564
+ return visit(obj, 0);
565
+ };
566
+ const isAsyncFn = kindOfTest("AsyncFunction");
567
+ const isThenable = (thing) => thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
568
+ const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
569
+ if (setImmediateSupported) {
570
+ return setImmediate;
571
+ }
572
+ return postMessageSupported ? ((token, callbacks) => {
573
+ _global.addEventListener("message", ({ source, data }) => {
574
+ if (source === _global && data === token) {
575
+ callbacks.length && callbacks.shift()();
576
+ }
577
+ }, false);
578
+ return (cb) => {
579
+ callbacks.push(cb);
580
+ _global.postMessage(token, "*");
581
+ };
582
+ })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
583
+ })(
584
+ typeof setImmediate === "function",
585
+ isFunction$1(_global.postMessage)
586
+ );
587
+ const asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate;
588
+ const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]);
589
+ const utils$1 = {
590
+ isArray,
591
+ isArrayBuffer,
592
+ isBuffer,
593
+ isFormData,
594
+ isArrayBufferView,
595
+ isString,
596
+ isNumber,
597
+ isBoolean,
598
+ isObject,
599
+ isPlainObject,
600
+ isEmptyObject,
601
+ isReadableStream,
602
+ isRequest,
603
+ isResponse,
604
+ isHeaders,
605
+ isUndefined,
606
+ isDate,
607
+ isFile,
608
+ isBlob,
609
+ isRegExp,
610
+ isFunction: isFunction$1,
611
+ isStream,
612
+ isURLSearchParams,
613
+ isTypedArray,
614
+ isFileList,
615
+ forEach,
616
+ merge,
617
+ extend,
618
+ trim,
619
+ stripBOM,
620
+ inherits,
621
+ toFlatObject,
622
+ kindOf,
623
+ kindOfTest,
624
+ endsWith,
625
+ toArray,
626
+ forEachEntry,
627
+ matchAll,
628
+ isHTMLForm,
629
+ hasOwnProperty,
630
+ hasOwnProp: hasOwnProperty,
631
+ // an alias to avoid ESLint no-prototype-builtins detection
632
+ reduceDescriptors,
633
+ freezeMethods,
634
+ toObjectSet,
635
+ toCamelCase,
636
+ noop,
637
+ toFiniteNumber,
638
+ findKey,
639
+ global: _global,
640
+ isContextDefined,
641
+ isSpecCompliantForm,
642
+ toJSONObject,
643
+ isAsyncFn,
644
+ isThenable,
645
+ setImmediate: _setImmediate,
646
+ asap,
647
+ isIterable
648
+ };
649
+ function AxiosError$1(message, code, config2, request, response) {
650
+ Error.call(this);
651
+ if (Error.captureStackTrace) {
652
+ Error.captureStackTrace(this, this.constructor);
653
+ } else {
654
+ this.stack = new Error().stack;
655
+ }
656
+ this.message = message;
657
+ this.name = "AxiosError";
658
+ code && (this.code = code);
659
+ config2 && (this.config = config2);
660
+ request && (this.request = request);
661
+ if (response) {
662
+ this.response = response;
663
+ this.status = response.status ? response.status : null;
664
+ }
665
+ }
666
+ utils$1.inherits(AxiosError$1, Error, {
667
+ toJSON: function toJSON() {
668
+ return {
669
+ // Standard
670
+ message: this.message,
671
+ name: this.name,
672
+ // Microsoft
673
+ description: this.description,
674
+ number: this.number,
675
+ // Mozilla
676
+ fileName: this.fileName,
677
+ lineNumber: this.lineNumber,
678
+ columnNumber: this.columnNumber,
679
+ stack: this.stack,
680
+ // Axios
681
+ config: utils$1.toJSONObject(this.config),
682
+ code: this.code,
683
+ status: this.status
684
+ };
685
+ }
686
+ });
687
+ const prototype$1 = AxiosError$1.prototype;
688
+ const descriptors = {};
689
+ [
690
+ "ERR_BAD_OPTION_VALUE",
691
+ "ERR_BAD_OPTION",
692
+ "ECONNABORTED",
693
+ "ETIMEDOUT",
694
+ "ERR_NETWORK",
695
+ "ERR_FR_TOO_MANY_REDIRECTS",
696
+ "ERR_DEPRECATED",
697
+ "ERR_BAD_RESPONSE",
698
+ "ERR_BAD_REQUEST",
699
+ "ERR_CANCELED",
700
+ "ERR_NOT_SUPPORT",
701
+ "ERR_INVALID_URL"
702
+ // eslint-disable-next-line func-names
703
+ ].forEach((code) => {
704
+ descriptors[code] = { value: code };
705
+ });
706
+ Object.defineProperties(AxiosError$1, descriptors);
707
+ Object.defineProperty(prototype$1, "isAxiosError", { value: true });
708
+ AxiosError$1.from = (error, code, config2, request, response, customProps) => {
709
+ const axiosError = Object.create(prototype$1);
710
+ utils$1.toFlatObject(error, axiosError, function filter2(obj) {
711
+ return obj !== Error.prototype;
712
+ }, (prop) => {
713
+ return prop !== "isAxiosError";
714
+ });
715
+ const msg = error && error.message ? error.message : "Error";
716
+ const errCode = code == null && error ? error.code : code;
717
+ AxiosError$1.call(axiosError, msg, errCode, config2, request, response);
718
+ if (error && axiosError.cause == null) {
719
+ Object.defineProperty(axiosError, "cause", { value: error, configurable: true });
720
+ }
721
+ axiosError.name = error && error.name || "Error";
722
+ customProps && Object.assign(axiosError, customProps);
723
+ return axiosError;
724
+ };
725
+ const httpAdapter = null;
726
+ function isVisitable(thing) {
727
+ return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
728
+ }
729
+ function removeBrackets(key) {
730
+ return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key;
731
+ }
732
+ function renderKey(path, key, dots) {
733
+ if (!path) return key;
734
+ return path.concat(key).map(function each(token, i) {
735
+ token = removeBrackets(token);
736
+ return !dots && i ? "[" + token + "]" : token;
737
+ }).join(dots ? "." : "");
738
+ }
739
+ function isFlatArray(arr) {
740
+ return utils$1.isArray(arr) && !arr.some(isVisitable);
741
+ }
742
+ const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
743
+ return /^is[A-Z]/.test(prop);
744
+ });
745
+ function toFormData$1(obj, formData, options) {
746
+ if (!utils$1.isObject(obj)) {
747
+ throw new TypeError("target must be an object");
748
+ }
749
+ formData = formData || new FormData();
750
+ options = utils$1.toFlatObject(options, {
751
+ metaTokens: true,
752
+ dots: false,
753
+ indexes: false
754
+ }, false, function defined(option, source) {
755
+ return !utils$1.isUndefined(source[option]);
756
+ });
757
+ const metaTokens = options.metaTokens;
758
+ const visitor = options.visitor || defaultVisitor;
759
+ const dots = options.dots;
760
+ const indexes = options.indexes;
761
+ const _Blob = options.Blob || typeof Blob !== "undefined" && Blob;
762
+ const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
763
+ if (!utils$1.isFunction(visitor)) {
764
+ throw new TypeError("visitor must be a function");
765
+ }
766
+ function convertValue(value) {
767
+ if (value === null) return "";
768
+ if (utils$1.isDate(value)) {
769
+ return value.toISOString();
770
+ }
771
+ if (utils$1.isBoolean(value)) {
772
+ return value.toString();
773
+ }
774
+ if (!useBlob && utils$1.isBlob(value)) {
775
+ throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");
776
+ }
777
+ if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
778
+ return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
779
+ }
780
+ return value;
781
+ }
782
+ function defaultVisitor(value, key, path) {
783
+ let arr = value;
784
+ if (value && !path && typeof value === "object") {
785
+ if (utils$1.endsWith(key, "{}")) {
786
+ key = metaTokens ? key : key.slice(0, -2);
787
+ value = JSON.stringify(value);
788
+ } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) {
789
+ key = removeBrackets(key);
790
+ arr.forEach(function each(el, index2) {
791
+ !(utils$1.isUndefined(el) || el === null) && formData.append(
792
+ // eslint-disable-next-line no-nested-ternary
793
+ indexes === true ? renderKey([key], index2, dots) : indexes === null ? key : key + "[]",
794
+ convertValue(el)
795
+ );
796
+ });
797
+ return false;
798
+ }
799
+ }
800
+ if (isVisitable(value)) {
801
+ return true;
802
+ }
803
+ formData.append(renderKey(path, key, dots), convertValue(value));
804
+ return false;
805
+ }
806
+ const stack = [];
807
+ const exposedHelpers = Object.assign(predicates, {
808
+ defaultVisitor,
809
+ convertValue,
810
+ isVisitable
811
+ });
812
+ function build(value, path) {
813
+ if (utils$1.isUndefined(value)) return;
814
+ if (stack.indexOf(value) !== -1) {
815
+ throw Error("Circular reference detected in " + path.join("."));
816
+ }
817
+ stack.push(value);
818
+ utils$1.forEach(value, function each(el, key) {
819
+ const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
820
+ formData,
821
+ el,
822
+ utils$1.isString(key) ? key.trim() : key,
823
+ path,
824
+ exposedHelpers
825
+ );
826
+ if (result === true) {
827
+ build(el, path ? path.concat(key) : [key]);
828
+ }
829
+ });
830
+ stack.pop();
831
+ }
832
+ if (!utils$1.isObject(obj)) {
833
+ throw new TypeError("data must be an object");
834
+ }
835
+ build(obj);
836
+ return formData;
837
+ }
838
+ function encode$1(str) {
839
+ const charMap = {
840
+ "!": "%21",
841
+ "'": "%27",
842
+ "(": "%28",
843
+ ")": "%29",
844
+ "~": "%7E",
845
+ "%20": "+",
846
+ "%00": "\0"
847
+ };
848
+ return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
849
+ return charMap[match];
850
+ });
851
+ }
852
+ function AxiosURLSearchParams(params, options) {
853
+ this._pairs = [];
854
+ params && toFormData$1(params, this, options);
855
+ }
856
+ const prototype = AxiosURLSearchParams.prototype;
857
+ prototype.append = function append(name, value) {
858
+ this._pairs.push([name, value]);
859
+ };
860
+ prototype.toString = function toString2(encoder) {
861
+ const _encode = encoder ? function(value) {
862
+ return encoder.call(this, value, encode$1);
863
+ } : encode$1;
864
+ return this._pairs.map(function each(pair) {
865
+ return _encode(pair[0]) + "=" + _encode(pair[1]);
866
+ }, "").join("&");
867
+ };
868
+ function encode(val) {
869
+ return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+");
870
+ }
871
+ function buildURL(url, params, options) {
872
+ if (!params) {
873
+ return url;
874
+ }
875
+ const _encode = options && options.encode || encode;
876
+ if (utils$1.isFunction(options)) {
877
+ options = {
878
+ serialize: options
879
+ };
880
+ }
881
+ const serializeFn = options && options.serialize;
882
+ let serializedParams;
883
+ if (serializeFn) {
884
+ serializedParams = serializeFn(params, options);
885
+ } else {
886
+ serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, options).toString(_encode);
887
+ }
888
+ if (serializedParams) {
889
+ const hashmarkIndex = url.indexOf("#");
890
+ if (hashmarkIndex !== -1) {
891
+ url = url.slice(0, hashmarkIndex);
892
+ }
893
+ url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
894
+ }
895
+ return url;
896
+ }
897
+ class InterceptorManager {
898
+ constructor() {
899
+ this.handlers = [];
900
+ }
901
+ /**
902
+ * Add a new interceptor to the stack
903
+ *
904
+ * @param {Function} fulfilled The function to handle `then` for a `Promise`
905
+ * @param {Function} rejected The function to handle `reject` for a `Promise`
906
+ *
907
+ * @return {Number} An ID used to remove interceptor later
908
+ */
909
+ use(fulfilled, rejected, options) {
910
+ this.handlers.push({
911
+ fulfilled,
912
+ rejected,
913
+ synchronous: options ? options.synchronous : false,
914
+ runWhen: options ? options.runWhen : null
915
+ });
916
+ return this.handlers.length - 1;
917
+ }
918
+ /**
919
+ * Remove an interceptor from the stack
920
+ *
921
+ * @param {Number} id The ID that was returned by `use`
922
+ *
923
+ * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
924
+ */
925
+ eject(id) {
926
+ if (this.handlers[id]) {
927
+ this.handlers[id] = null;
928
+ }
929
+ }
930
+ /**
931
+ * Clear all interceptors from the stack
932
+ *
933
+ * @returns {void}
934
+ */
935
+ clear() {
936
+ if (this.handlers) {
937
+ this.handlers = [];
938
+ }
939
+ }
940
+ /**
941
+ * Iterate over all the registered interceptors
942
+ *
943
+ * This method is particularly useful for skipping over any
944
+ * interceptors that may have become `null` calling `eject`.
945
+ *
946
+ * @param {Function} fn The function to call for each interceptor
947
+ *
948
+ * @returns {void}
949
+ */
950
+ forEach(fn) {
951
+ utils$1.forEach(this.handlers, function forEachHandler(h) {
952
+ if (h !== null) {
953
+ fn(h);
954
+ }
955
+ });
956
+ }
957
+ }
958
+ const transitionalDefaults = {
959
+ silentJSONParsing: true,
960
+ forcedJSONParsing: true,
961
+ clarifyTimeoutError: false
962
+ };
963
+ const URLSearchParams$1 = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams;
964
+ const FormData$1 = typeof FormData !== "undefined" ? FormData : null;
965
+ const Blob$1 = typeof Blob !== "undefined" ? Blob : null;
966
+ const platform$1 = {
967
+ isBrowser: true,
968
+ classes: {
969
+ URLSearchParams: URLSearchParams$1,
970
+ FormData: FormData$1,
971
+ Blob: Blob$1
972
+ },
973
+ protocols: ["http", "https", "file", "blob", "url", "data"]
974
+ };
975
+ const hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined";
976
+ const _navigator = typeof navigator === "object" && navigator || void 0;
977
+ const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0);
978
+ const hasStandardBrowserWebWorkerEnv = (() => {
979
+ return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef
980
+ self instanceof WorkerGlobalScope && typeof self.importScripts === "function";
981
+ })();
982
+ const origin = hasBrowserEnv && window.location.href || "http://localhost";
983
+ const utils = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
984
+ __proto__: null,
985
+ hasBrowserEnv,
986
+ hasStandardBrowserEnv,
987
+ hasStandardBrowserWebWorkerEnv,
988
+ navigator: _navigator,
989
+ origin
990
+ }, Symbol.toStringTag, { value: "Module" }));
991
+ const platform = {
992
+ ...utils,
993
+ ...platform$1
994
+ };
995
+ function toURLEncodedForm(data, options) {
996
+ return toFormData$1(data, new platform.classes.URLSearchParams(), {
997
+ visitor: function(value, key, path, helpers) {
998
+ if (platform.isNode && utils$1.isBuffer(value)) {
999
+ this.append(key, value.toString("base64"));
1000
+ return false;
1001
+ }
1002
+ return helpers.defaultVisitor.apply(this, arguments);
1003
+ },
1004
+ ...options
1005
+ });
1006
+ }
1007
+ function parsePropPath(name) {
1008
+ return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
1009
+ return match[0] === "[]" ? "" : match[1] || match[0];
1010
+ });
1011
+ }
1012
+ function arrayToObject(arr) {
1013
+ const obj = {};
1014
+ const keys = Object.keys(arr);
1015
+ let i;
1016
+ const len = keys.length;
1017
+ let key;
1018
+ for (i = 0; i < len; i++) {
1019
+ key = keys[i];
1020
+ obj[key] = arr[key];
1021
+ }
1022
+ return obj;
1023
+ }
1024
+ function formDataToJSON(formData) {
1025
+ function buildPath(path, value, target, index2) {
1026
+ let name = path[index2++];
1027
+ if (name === "__proto__") return true;
1028
+ const isNumericKey = Number.isFinite(+name);
1029
+ const isLast = index2 >= path.length;
1030
+ name = !name && utils$1.isArray(target) ? target.length : name;
1031
+ if (isLast) {
1032
+ if (utils$1.hasOwnProp(target, name)) {
1033
+ target[name] = [target[name], value];
1034
+ } else {
1035
+ target[name] = value;
1036
+ }
1037
+ return !isNumericKey;
1038
+ }
1039
+ if (!target[name] || !utils$1.isObject(target[name])) {
1040
+ target[name] = [];
1041
+ }
1042
+ const result = buildPath(path, value, target[name], index2);
1043
+ if (result && utils$1.isArray(target[name])) {
1044
+ target[name] = arrayToObject(target[name]);
1045
+ }
1046
+ return !isNumericKey;
1047
+ }
1048
+ if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
1049
+ const obj = {};
1050
+ utils$1.forEachEntry(formData, (name, value) => {
1051
+ buildPath(parsePropPath(name), value, obj, 0);
1052
+ });
1053
+ return obj;
1054
+ }
1055
+ return null;
1056
+ }
1057
+ function stringifySafely(rawValue, parser, encoder) {
1058
+ if (utils$1.isString(rawValue)) {
1059
+ try {
1060
+ (parser || JSON.parse)(rawValue);
1061
+ return utils$1.trim(rawValue);
1062
+ } catch (e) {
1063
+ if (e.name !== "SyntaxError") {
1064
+ throw e;
1065
+ }
1066
+ }
1067
+ }
1068
+ return (encoder || JSON.stringify)(rawValue);
1069
+ }
1070
+ const defaults = {
1071
+ transitional: transitionalDefaults,
1072
+ adapter: ["xhr", "http", "fetch"],
1073
+ transformRequest: [function transformRequest(data, headers) {
1074
+ const contentType = headers.getContentType() || "";
1075
+ const hasJSONContentType = contentType.indexOf("application/json") > -1;
1076
+ const isObjectPayload = utils$1.isObject(data);
1077
+ if (isObjectPayload && utils$1.isHTMLForm(data)) {
1078
+ data = new FormData(data);
1079
+ }
1080
+ const isFormData2 = utils$1.isFormData(data);
1081
+ if (isFormData2) {
1082
+ return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
1083
+ }
1084
+ if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) {
1085
+ return data;
1086
+ }
1087
+ if (utils$1.isArrayBufferView(data)) {
1088
+ return data.buffer;
1089
+ }
1090
+ if (utils$1.isURLSearchParams(data)) {
1091
+ headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
1092
+ return data.toString();
1093
+ }
1094
+ let isFileList2;
1095
+ if (isObjectPayload) {
1096
+ if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
1097
+ return toURLEncodedForm(data, this.formSerializer).toString();
1098
+ }
1099
+ if ((isFileList2 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
1100
+ const _FormData = this.env && this.env.FormData;
1101
+ return toFormData$1(
1102
+ isFileList2 ? { "files[]": data } : data,
1103
+ _FormData && new _FormData(),
1104
+ this.formSerializer
1105
+ );
1106
+ }
1107
+ }
1108
+ if (isObjectPayload || hasJSONContentType) {
1109
+ headers.setContentType("application/json", false);
1110
+ return stringifySafely(data);
1111
+ }
1112
+ return data;
1113
+ }],
1114
+ transformResponse: [function transformResponse(data) {
1115
+ const transitional2 = this.transitional || defaults.transitional;
1116
+ const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing;
1117
+ const JSONRequested = this.responseType === "json";
1118
+ if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
1119
+ return data;
1120
+ }
1121
+ if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
1122
+ const silentJSONParsing = transitional2 && transitional2.silentJSONParsing;
1123
+ const strictJSONParsing = !silentJSONParsing && JSONRequested;
1124
+ try {
1125
+ return JSON.parse(data, this.parseReviver);
1126
+ } catch (e) {
1127
+ if (strictJSONParsing) {
1128
+ if (e.name === "SyntaxError") {
1129
+ throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response);
1130
+ }
1131
+ throw e;
1132
+ }
1133
+ }
1134
+ }
1135
+ return data;
1136
+ }],
1137
+ /**
1138
+ * A timeout in milliseconds to abort a request. If set to 0 (default) a
1139
+ * timeout is not created.
1140
+ */
1141
+ timeout: 0,
1142
+ xsrfCookieName: "XSRF-TOKEN",
1143
+ xsrfHeaderName: "X-XSRF-TOKEN",
1144
+ maxContentLength: -1,
1145
+ maxBodyLength: -1,
1146
+ env: {
1147
+ FormData: platform.classes.FormData,
1148
+ Blob: platform.classes.Blob
1149
+ },
1150
+ validateStatus: function validateStatus(status) {
1151
+ return status >= 200 && status < 300;
1152
+ },
1153
+ headers: {
1154
+ common: {
1155
+ "Accept": "application/json, text/plain, */*",
1156
+ "Content-Type": void 0
1157
+ }
1158
+ }
1159
+ };
1160
+ utils$1.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => {
1161
+ defaults.headers[method] = {};
1162
+ });
1163
+ const ignoreDuplicateOf = utils$1.toObjectSet([
1164
+ "age",
1165
+ "authorization",
1166
+ "content-length",
1167
+ "content-type",
1168
+ "etag",
1169
+ "expires",
1170
+ "from",
1171
+ "host",
1172
+ "if-modified-since",
1173
+ "if-unmodified-since",
1174
+ "last-modified",
1175
+ "location",
1176
+ "max-forwards",
1177
+ "proxy-authorization",
1178
+ "referer",
1179
+ "retry-after",
1180
+ "user-agent"
1181
+ ]);
1182
+ const parseHeaders = (rawHeaders) => {
1183
+ const parsed = {};
1184
+ let key;
1185
+ let val;
1186
+ let i;
1187
+ rawHeaders && rawHeaders.split("\n").forEach(function parser(line) {
1188
+ i = line.indexOf(":");
1189
+ key = line.substring(0, i).trim().toLowerCase();
1190
+ val = line.substring(i + 1).trim();
1191
+ if (!key || parsed[key] && ignoreDuplicateOf[key]) {
1192
+ return;
1193
+ }
1194
+ if (key === "set-cookie") {
1195
+ if (parsed[key]) {
1196
+ parsed[key].push(val);
1197
+ } else {
1198
+ parsed[key] = [val];
1199
+ }
1200
+ } else {
1201
+ parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
1202
+ }
1203
+ });
1204
+ return parsed;
1205
+ };
1206
+ const $internals = Symbol("internals");
1207
+ function normalizeHeader(header) {
1208
+ return header && String(header).trim().toLowerCase();
1209
+ }
1210
+ function normalizeValue(value) {
1211
+ if (value === false || value == null) {
1212
+ return value;
1213
+ }
1214
+ return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
1215
+ }
1216
+ function parseTokens(str) {
1217
+ const tokens = /* @__PURE__ */ Object.create(null);
1218
+ const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1219
+ let match;
1220
+ while (match = tokensRE.exec(str)) {
1221
+ tokens[match[1]] = match[2];
1222
+ }
1223
+ return tokens;
1224
+ }
1225
+ const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
1226
+ function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) {
1227
+ if (utils$1.isFunction(filter2)) {
1228
+ return filter2.call(this, value, header);
1229
+ }
1230
+ if (isHeaderNameFilter) {
1231
+ value = header;
1232
+ }
1233
+ if (!utils$1.isString(value)) return;
1234
+ if (utils$1.isString(filter2)) {
1235
+ return value.indexOf(filter2) !== -1;
1236
+ }
1237
+ if (utils$1.isRegExp(filter2)) {
1238
+ return filter2.test(value);
1239
+ }
1240
+ }
1241
+ function formatHeader(header) {
1242
+ return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1243
+ return char.toUpperCase() + str;
1244
+ });
1245
+ }
1246
+ function buildAccessors(obj, header) {
1247
+ const accessorName = utils$1.toCamelCase(" " + header);
1248
+ ["get", "set", "has"].forEach((methodName) => {
1249
+ Object.defineProperty(obj, methodName + accessorName, {
1250
+ value: function(arg1, arg2, arg3) {
1251
+ return this[methodName].call(this, header, arg1, arg2, arg3);
1252
+ },
1253
+ configurable: true
1254
+ });
1255
+ });
1256
+ }
1257
+ let AxiosHeaders$1 = class AxiosHeaders {
1258
+ constructor(headers) {
1259
+ headers && this.set(headers);
1260
+ }
1261
+ set(header, valueOrRewrite, rewrite) {
1262
+ const self2 = this;
1263
+ function setHeader(_value, _header, _rewrite) {
1264
+ const lHeader = normalizeHeader(_header);
1265
+ if (!lHeader) {
1266
+ throw new Error("header name must be a non-empty string");
1267
+ }
1268
+ const key = utils$1.findKey(self2, lHeader);
1269
+ if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) {
1270
+ self2[key || _header] = normalizeValue(_value);
1271
+ }
1272
+ }
1273
+ const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1274
+ if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1275
+ setHeaders(header, valueOrRewrite);
1276
+ } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1277
+ setHeaders(parseHeaders(header), valueOrRewrite);
1278
+ } else if (utils$1.isObject(header) && utils$1.isIterable(header)) {
1279
+ let obj = {}, dest, key;
1280
+ for (const entry of header) {
1281
+ if (!utils$1.isArray(entry)) {
1282
+ throw TypeError("Object iterator must return a key-value pair");
1283
+ }
1284
+ obj[key = entry[0]] = (dest = obj[key]) ? utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1];
1285
+ }
1286
+ setHeaders(obj, valueOrRewrite);
1287
+ } else {
1288
+ header != null && setHeader(valueOrRewrite, header, rewrite);
1289
+ }
1290
+ return this;
1291
+ }
1292
+ get(header, parser) {
1293
+ header = normalizeHeader(header);
1294
+ if (header) {
1295
+ const key = utils$1.findKey(this, header);
1296
+ if (key) {
1297
+ const value = this[key];
1298
+ if (!parser) {
1299
+ return value;
1300
+ }
1301
+ if (parser === true) {
1302
+ return parseTokens(value);
1303
+ }
1304
+ if (utils$1.isFunction(parser)) {
1305
+ return parser.call(this, value, key);
1306
+ }
1307
+ if (utils$1.isRegExp(parser)) {
1308
+ return parser.exec(value);
1309
+ }
1310
+ throw new TypeError("parser must be boolean|regexp|function");
1311
+ }
1312
+ }
1313
+ }
1314
+ has(header, matcher) {
1315
+ header = normalizeHeader(header);
1316
+ if (header) {
1317
+ const key = utils$1.findKey(this, header);
1318
+ return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1319
+ }
1320
+ return false;
1321
+ }
1322
+ delete(header, matcher) {
1323
+ const self2 = this;
1324
+ let deleted = false;
1325
+ function deleteHeader(_header) {
1326
+ _header = normalizeHeader(_header);
1327
+ if (_header) {
1328
+ const key = utils$1.findKey(self2, _header);
1329
+ if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
1330
+ delete self2[key];
1331
+ deleted = true;
1332
+ }
1333
+ }
1334
+ }
1335
+ if (utils$1.isArray(header)) {
1336
+ header.forEach(deleteHeader);
1337
+ } else {
1338
+ deleteHeader(header);
1339
+ }
1340
+ return deleted;
1341
+ }
1342
+ clear(matcher) {
1343
+ const keys = Object.keys(this);
1344
+ let i = keys.length;
1345
+ let deleted = false;
1346
+ while (i--) {
1347
+ const key = keys[i];
1348
+ if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
1349
+ delete this[key];
1350
+ deleted = true;
1351
+ }
1352
+ }
1353
+ return deleted;
1354
+ }
1355
+ normalize(format) {
1356
+ const self2 = this;
1357
+ const headers = {};
1358
+ utils$1.forEach(this, (value, header) => {
1359
+ const key = utils$1.findKey(headers, header);
1360
+ if (key) {
1361
+ self2[key] = normalizeValue(value);
1362
+ delete self2[header];
1363
+ return;
1364
+ }
1365
+ const normalized = format ? formatHeader(header) : String(header).trim();
1366
+ if (normalized !== header) {
1367
+ delete self2[header];
1368
+ }
1369
+ self2[normalized] = normalizeValue(value);
1370
+ headers[normalized] = true;
1371
+ });
1372
+ return this;
1373
+ }
1374
+ concat(...targets) {
1375
+ return this.constructor.concat(this, ...targets);
1376
+ }
1377
+ toJSON(asStrings) {
1378
+ const obj = /* @__PURE__ */ Object.create(null);
1379
+ utils$1.forEach(this, (value, header) => {
1380
+ value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value);
1381
+ });
1382
+ return obj;
1383
+ }
1384
+ [Symbol.iterator]() {
1385
+ return Object.entries(this.toJSON())[Symbol.iterator]();
1386
+ }
1387
+ toString() {
1388
+ return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n");
1389
+ }
1390
+ getSetCookie() {
1391
+ return this.get("set-cookie") || [];
1392
+ }
1393
+ get [Symbol.toStringTag]() {
1394
+ return "AxiosHeaders";
1395
+ }
1396
+ static from(thing) {
1397
+ return thing instanceof this ? thing : new this(thing);
1398
+ }
1399
+ static concat(first, ...targets) {
1400
+ const computed = new this(first);
1401
+ targets.forEach((target) => computed.set(target));
1402
+ return computed;
1403
+ }
1404
+ static accessor(header) {
1405
+ const internals = this[$internals] = this[$internals] = {
1406
+ accessors: {}
1407
+ };
1408
+ const accessors = internals.accessors;
1409
+ const prototype2 = this.prototype;
1410
+ function defineAccessor(_header) {
1411
+ const lHeader = normalizeHeader(_header);
1412
+ if (!accessors[lHeader]) {
1413
+ buildAccessors(prototype2, _header);
1414
+ accessors[lHeader] = true;
1415
+ }
1416
+ }
1417
+ utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1418
+ return this;
1419
+ }
1420
+ };
1421
+ AxiosHeaders$1.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]);
1422
+ utils$1.reduceDescriptors(AxiosHeaders$1.prototype, ({ value }, key) => {
1423
+ let mapped = key[0].toUpperCase() + key.slice(1);
1424
+ return {
1425
+ get: () => value,
1426
+ set(headerValue) {
1427
+ this[mapped] = headerValue;
1428
+ }
1429
+ };
1430
+ });
1431
+ utils$1.freezeMethods(AxiosHeaders$1);
1432
+ function transformData(fns, response) {
1433
+ const config2 = this || defaults;
1434
+ const context = response || config2;
1435
+ const headers = AxiosHeaders$1.from(context.headers);
1436
+ let data = context.data;
1437
+ utils$1.forEach(fns, function transform(fn) {
1438
+ data = fn.call(config2, data, headers.normalize(), response ? response.status : void 0);
1439
+ });
1440
+ headers.normalize();
1441
+ return data;
1442
+ }
1443
+ function isCancel$1(value) {
1444
+ return !!(value && value.__CANCEL__);
1445
+ }
1446
+ function CanceledError$1(message, config2, request) {
1447
+ AxiosError$1.call(this, message == null ? "canceled" : message, AxiosError$1.ERR_CANCELED, config2, request);
1448
+ this.name = "CanceledError";
1449
+ }
1450
+ utils$1.inherits(CanceledError$1, AxiosError$1, {
1451
+ __CANCEL__: true
1452
+ });
1453
+ function settle(resolve, reject, response) {
1454
+ const validateStatus2 = response.config.validateStatus;
1455
+ if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
1456
+ resolve(response);
1457
+ } else {
1458
+ reject(new AxiosError$1(
1459
+ "Request failed with status code " + response.status,
1460
+ [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
1461
+ response.config,
1462
+ response.request,
1463
+ response
1464
+ ));
1465
+ }
1466
+ }
1467
+ function parseProtocol(url) {
1468
+ const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
1469
+ return match && match[1] || "";
1470
+ }
1471
+ function speedometer(samplesCount, min) {
1472
+ samplesCount = samplesCount || 10;
1473
+ const bytes = new Array(samplesCount);
1474
+ const timestamps = new Array(samplesCount);
1475
+ let head = 0;
1476
+ let tail = 0;
1477
+ let firstSampleTS;
1478
+ min = min !== void 0 ? min : 1e3;
1479
+ return function push(chunkLength) {
1480
+ const now = Date.now();
1481
+ const startedAt = timestamps[tail];
1482
+ if (!firstSampleTS) {
1483
+ firstSampleTS = now;
1484
+ }
1485
+ bytes[head] = chunkLength;
1486
+ timestamps[head] = now;
1487
+ let i = tail;
1488
+ let bytesCount = 0;
1489
+ while (i !== head) {
1490
+ bytesCount += bytes[i++];
1491
+ i = i % samplesCount;
1492
+ }
1493
+ head = (head + 1) % samplesCount;
1494
+ if (head === tail) {
1495
+ tail = (tail + 1) % samplesCount;
1496
+ }
1497
+ if (now - firstSampleTS < min) {
1498
+ return;
1499
+ }
1500
+ const passed = startedAt && now - startedAt;
1501
+ return passed ? Math.round(bytesCount * 1e3 / passed) : void 0;
1502
+ };
1503
+ }
1504
+ function throttle(fn, freq) {
1505
+ let timestamp = 0;
1506
+ let threshold = 1e3 / freq;
1507
+ let lastArgs;
1508
+ let timer;
1509
+ const invoke = (args, now = Date.now()) => {
1510
+ timestamp = now;
1511
+ lastArgs = null;
1512
+ if (timer) {
1513
+ clearTimeout(timer);
1514
+ timer = null;
1515
+ }
1516
+ fn(...args);
1517
+ };
1518
+ const throttled = (...args) => {
1519
+ const now = Date.now();
1520
+ const passed = now - timestamp;
1521
+ if (passed >= threshold) {
1522
+ invoke(args, now);
1523
+ } else {
1524
+ lastArgs = args;
1525
+ if (!timer) {
1526
+ timer = setTimeout(() => {
1527
+ timer = null;
1528
+ invoke(lastArgs);
1529
+ }, threshold - passed);
1530
+ }
1531
+ }
1532
+ };
1533
+ const flush = () => lastArgs && invoke(lastArgs);
1534
+ return [throttled, flush];
1535
+ }
1536
+ const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
1537
+ let bytesNotified = 0;
1538
+ const _speedometer = speedometer(50, 250);
1539
+ return throttle((e) => {
1540
+ const loaded = e.loaded;
1541
+ const total = e.lengthComputable ? e.total : void 0;
1542
+ const progressBytes = loaded - bytesNotified;
1543
+ const rate = _speedometer(progressBytes);
1544
+ const inRange = loaded <= total;
1545
+ bytesNotified = loaded;
1546
+ const data = {
1547
+ loaded,
1548
+ total,
1549
+ progress: total ? loaded / total : void 0,
1550
+ bytes: progressBytes,
1551
+ rate: rate ? rate : void 0,
1552
+ estimated: rate && total && inRange ? (total - loaded) / rate : void 0,
1553
+ event: e,
1554
+ lengthComputable: total != null,
1555
+ [isDownloadStream ? "download" : "upload"]: true
1556
+ };
1557
+ listener(data);
1558
+ }, freq);
1559
+ };
1560
+ const progressEventDecorator = (total, throttled) => {
1561
+ const lengthComputable = total != null;
1562
+ return [(loaded) => throttled[0]({
1563
+ lengthComputable,
1564
+ total,
1565
+ loaded
1566
+ }), throttled[1]];
1567
+ };
1568
+ const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
1569
+ const isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url) => {
1570
+ url = new URL(url, platform.origin);
1571
+ return origin2.protocol === url.protocol && origin2.host === url.host && (isMSIE || origin2.port === url.port);
1572
+ })(
1573
+ new URL(platform.origin),
1574
+ platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
1575
+ ) : () => true;
1576
+ const cookies = platform.hasStandardBrowserEnv ? (
1577
+ // Standard browser envs support document.cookie
1578
+ {
1579
+ write(name, value, expires, path, domain, secure) {
1580
+ const cookie = [name + "=" + encodeURIComponent(value)];
1581
+ utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString());
1582
+ utils$1.isString(path) && cookie.push("path=" + path);
1583
+ utils$1.isString(domain) && cookie.push("domain=" + domain);
1584
+ secure === true && cookie.push("secure");
1585
+ document.cookie = cookie.join("; ");
1586
+ },
1587
+ read(name) {
1588
+ const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
1589
+ return match ? decodeURIComponent(match[3]) : null;
1590
+ },
1591
+ remove(name) {
1592
+ this.write(name, "", Date.now() - 864e5);
1593
+ }
1594
+ }
1595
+ ) : (
1596
+ // Non-standard browser env (web workers, react-native) lack needed support.
1597
+ {
1598
+ write() {
1599
+ },
1600
+ read() {
1601
+ return null;
1602
+ },
1603
+ remove() {
1604
+ }
1605
+ }
1606
+ );
1607
+ function isAbsoluteURL(url) {
1608
+ return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
1609
+ }
1610
+ function combineURLs(baseURL, relativeURL) {
1611
+ return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
1612
+ }
1613
+ function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
1614
+ let isRelativeUrl = !isAbsoluteURL(requestedURL);
1615
+ if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
1616
+ return combineURLs(baseURL, requestedURL);
1617
+ }
1618
+ return requestedURL;
1619
+ }
1620
+ const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
1621
+ function mergeConfig$1(config1, config2) {
1622
+ config2 = config2 || {};
1623
+ const config3 = {};
1624
+ function getMergedValue(target, source, prop, caseless) {
1625
+ if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
1626
+ return utils$1.merge.call({ caseless }, target, source);
1627
+ } else if (utils$1.isPlainObject(source)) {
1628
+ return utils$1.merge({}, source);
1629
+ } else if (utils$1.isArray(source)) {
1630
+ return source.slice();
1631
+ }
1632
+ return source;
1633
+ }
1634
+ function mergeDeepProperties(a, b, prop, caseless) {
1635
+ if (!utils$1.isUndefined(b)) {
1636
+ return getMergedValue(a, b, prop, caseless);
1637
+ } else if (!utils$1.isUndefined(a)) {
1638
+ return getMergedValue(void 0, a, prop, caseless);
1639
+ }
1640
+ }
1641
+ function valueFromConfig2(a, b) {
1642
+ if (!utils$1.isUndefined(b)) {
1643
+ return getMergedValue(void 0, b);
1644
+ }
1645
+ }
1646
+ function defaultToConfig2(a, b) {
1647
+ if (!utils$1.isUndefined(b)) {
1648
+ return getMergedValue(void 0, b);
1649
+ } else if (!utils$1.isUndefined(a)) {
1650
+ return getMergedValue(void 0, a);
1651
+ }
1652
+ }
1653
+ function mergeDirectKeys(a, b, prop) {
1654
+ if (prop in config2) {
1655
+ return getMergedValue(a, b);
1656
+ } else if (prop in config1) {
1657
+ return getMergedValue(void 0, a);
1658
+ }
1659
+ }
1660
+ const mergeMap = {
1661
+ url: valueFromConfig2,
1662
+ method: valueFromConfig2,
1663
+ data: valueFromConfig2,
1664
+ baseURL: defaultToConfig2,
1665
+ transformRequest: defaultToConfig2,
1666
+ transformResponse: defaultToConfig2,
1667
+ paramsSerializer: defaultToConfig2,
1668
+ timeout: defaultToConfig2,
1669
+ timeoutMessage: defaultToConfig2,
1670
+ withCredentials: defaultToConfig2,
1671
+ withXSRFToken: defaultToConfig2,
1672
+ adapter: defaultToConfig2,
1673
+ responseType: defaultToConfig2,
1674
+ xsrfCookieName: defaultToConfig2,
1675
+ xsrfHeaderName: defaultToConfig2,
1676
+ onUploadProgress: defaultToConfig2,
1677
+ onDownloadProgress: defaultToConfig2,
1678
+ decompress: defaultToConfig2,
1679
+ maxContentLength: defaultToConfig2,
1680
+ maxBodyLength: defaultToConfig2,
1681
+ beforeRedirect: defaultToConfig2,
1682
+ transport: defaultToConfig2,
1683
+ httpAgent: defaultToConfig2,
1684
+ httpsAgent: defaultToConfig2,
1685
+ cancelToken: defaultToConfig2,
1686
+ socketPath: defaultToConfig2,
1687
+ responseEncoding: defaultToConfig2,
1688
+ validateStatus: mergeDirectKeys,
1689
+ headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
1690
+ };
1691
+ utils$1.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) {
1692
+ const merge2 = mergeMap[prop] || mergeDeepProperties;
1693
+ const configValue = merge2(config1[prop], config2[prop], prop);
1694
+ utils$1.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config3[prop] = configValue);
1695
+ });
1696
+ return config3;
1697
+ }
1698
+ const resolveConfig = (config2) => {
1699
+ const newConfig = mergeConfig$1({}, config2);
1700
+ let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
1701
+ newConfig.headers = headers = AxiosHeaders$1.from(headers);
1702
+ newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config2.params, config2.paramsSerializer);
1703
+ if (auth) {
1704
+ headers.set(
1705
+ "Authorization",
1706
+ "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : ""))
1707
+ );
1708
+ }
1709
+ if (utils$1.isFormData(data)) {
1710
+ if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
1711
+ headers.setContentType(void 0);
1712
+ } else if (utils$1.isFunction(data.getHeaders)) {
1713
+ const formHeaders = data.getHeaders();
1714
+ const allowedHeaders = ["content-type", "content-length"];
1715
+ Object.entries(formHeaders).forEach(([key, val]) => {
1716
+ if (allowedHeaders.includes(key.toLowerCase())) {
1717
+ headers.set(key, val);
1718
+ }
1719
+ });
1720
+ }
1721
+ }
1722
+ if (platform.hasStandardBrowserEnv) {
1723
+ withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
1724
+ if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(newConfig.url)) {
1725
+ const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
1726
+ if (xsrfValue) {
1727
+ headers.set(xsrfHeaderName, xsrfValue);
1728
+ }
1729
+ }
1730
+ }
1731
+ return newConfig;
1732
+ };
1733
+ const isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
1734
+ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1735
+ return new Promise(function dispatchXhrRequest(resolve, reject) {
1736
+ const _config = resolveConfig(config2);
1737
+ let requestData = _config.data;
1738
+ const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
1739
+ let { responseType, onUploadProgress, onDownloadProgress } = _config;
1740
+ let onCanceled;
1741
+ let uploadThrottled, downloadThrottled;
1742
+ let flushUpload, flushDownload;
1743
+ function done() {
1744
+ flushUpload && flushUpload();
1745
+ flushDownload && flushDownload();
1746
+ _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
1747
+ _config.signal && _config.signal.removeEventListener("abort", onCanceled);
1748
+ }
1749
+ let request = new XMLHttpRequest();
1750
+ request.open(_config.method.toUpperCase(), _config.url, true);
1751
+ request.timeout = _config.timeout;
1752
+ function onloadend() {
1753
+ if (!request) {
1754
+ return;
1755
+ }
1756
+ const responseHeaders = AxiosHeaders$1.from(
1757
+ "getAllResponseHeaders" in request && request.getAllResponseHeaders()
1758
+ );
1759
+ const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response;
1760
+ const response = {
1761
+ data: responseData,
1762
+ status: request.status,
1763
+ statusText: request.statusText,
1764
+ headers: responseHeaders,
1765
+ config: config2,
1766
+ request
1767
+ };
1768
+ settle(function _resolve(value) {
1769
+ resolve(value);
1770
+ done();
1771
+ }, function _reject(err) {
1772
+ reject(err);
1773
+ done();
1774
+ }, response);
1775
+ request = null;
1776
+ }
1777
+ if ("onloadend" in request) {
1778
+ request.onloadend = onloadend;
1779
+ } else {
1780
+ request.onreadystatechange = function handleLoad() {
1781
+ if (!request || request.readyState !== 4) {
1782
+ return;
1783
+ }
1784
+ if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
1785
+ return;
1786
+ }
1787
+ setTimeout(onloadend);
1788
+ };
1789
+ }
1790
+ request.onabort = function handleAbort() {
1791
+ if (!request) {
1792
+ return;
1793
+ }
1794
+ reject(new AxiosError$1("Request aborted", AxiosError$1.ECONNABORTED, config2, request));
1795
+ request = null;
1796
+ };
1797
+ request.onerror = function handleError(event) {
1798
+ const msg = event && event.message ? event.message : "Network Error";
1799
+ const err = new AxiosError$1(msg, AxiosError$1.ERR_NETWORK, config2, request);
1800
+ err.event = event || null;
1801
+ reject(err);
1802
+ request = null;
1803
+ };
1804
+ request.ontimeout = function handleTimeout() {
1805
+ let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded";
1806
+ const transitional2 = _config.transitional || transitionalDefaults;
1807
+ if (_config.timeoutErrorMessage) {
1808
+ timeoutErrorMessage = _config.timeoutErrorMessage;
1809
+ }
1810
+ reject(new AxiosError$1(
1811
+ timeoutErrorMessage,
1812
+ transitional2.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
1813
+ config2,
1814
+ request
1815
+ ));
1816
+ request = null;
1817
+ };
1818
+ requestData === void 0 && requestHeaders.setContentType(null);
1819
+ if ("setRequestHeader" in request) {
1820
+ utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
1821
+ request.setRequestHeader(key, val);
1822
+ });
1823
+ }
1824
+ if (!utils$1.isUndefined(_config.withCredentials)) {
1825
+ request.withCredentials = !!_config.withCredentials;
1826
+ }
1827
+ if (responseType && responseType !== "json") {
1828
+ request.responseType = _config.responseType;
1829
+ }
1830
+ if (onDownloadProgress) {
1831
+ [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
1832
+ request.addEventListener("progress", downloadThrottled);
1833
+ }
1834
+ if (onUploadProgress && request.upload) {
1835
+ [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
1836
+ request.upload.addEventListener("progress", uploadThrottled);
1837
+ request.upload.addEventListener("loadend", flushUpload);
1838
+ }
1839
+ if (_config.cancelToken || _config.signal) {
1840
+ onCanceled = (cancel) => {
1841
+ if (!request) {
1842
+ return;
1843
+ }
1844
+ reject(!cancel || cancel.type ? new CanceledError$1(null, config2, request) : cancel);
1845
+ request.abort();
1846
+ request = null;
1847
+ };
1848
+ _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
1849
+ if (_config.signal) {
1850
+ _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled);
1851
+ }
1852
+ }
1853
+ const protocol = parseProtocol(_config.url);
1854
+ if (protocol && platform.protocols.indexOf(protocol) === -1) {
1855
+ reject(new AxiosError$1("Unsupported protocol " + protocol + ":", AxiosError$1.ERR_BAD_REQUEST, config2));
1856
+ return;
1857
+ }
1858
+ request.send(requestData || null);
1859
+ });
1860
+ };
1861
+ const composeSignals = (signals, timeout) => {
1862
+ const { length } = signals = signals ? signals.filter(Boolean) : [];
1863
+ if (timeout || length) {
1864
+ let controller2 = new AbortController();
1865
+ let aborted;
1866
+ const onabort = function(reason) {
1867
+ if (!aborted) {
1868
+ aborted = true;
1869
+ unsubscribe();
1870
+ const err = reason instanceof Error ? reason : this.reason;
1871
+ controller2.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err));
1872
+ }
1873
+ };
1874
+ let timer = timeout && setTimeout(() => {
1875
+ timer = null;
1876
+ onabort(new AxiosError$1(`timeout ${timeout} of ms exceeded`, AxiosError$1.ETIMEDOUT));
1877
+ }, timeout);
1878
+ const unsubscribe = () => {
1879
+ if (signals) {
1880
+ timer && clearTimeout(timer);
1881
+ timer = null;
1882
+ signals.forEach((signal2) => {
1883
+ signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
1884
+ });
1885
+ signals = null;
1886
+ }
1887
+ };
1888
+ signals.forEach((signal2) => signal2.addEventListener("abort", onabort));
1889
+ const { signal } = controller2;
1890
+ signal.unsubscribe = () => utils$1.asap(unsubscribe);
1891
+ return signal;
1892
+ }
1893
+ };
1894
+ const streamChunk = function* (chunk, chunkSize) {
1895
+ let len = chunk.byteLength;
1896
+ if (len < chunkSize) {
1897
+ yield chunk;
1898
+ return;
1899
+ }
1900
+ let pos = 0;
1901
+ let end;
1902
+ while (pos < len) {
1903
+ end = pos + chunkSize;
1904
+ yield chunk.slice(pos, end);
1905
+ pos = end;
1906
+ }
1907
+ };
1908
+ const readBytes = async function* (iterable, chunkSize) {
1909
+ for await (const chunk of readStream(iterable)) {
1910
+ yield* streamChunk(chunk, chunkSize);
1911
+ }
1912
+ };
1913
+ const readStream = async function* (stream) {
1914
+ if (stream[Symbol.asyncIterator]) {
1915
+ yield* stream;
1916
+ return;
1917
+ }
1918
+ const reader = stream.getReader();
1919
+ try {
1920
+ for (; ; ) {
1921
+ const { done, value } = await reader.read();
1922
+ if (done) {
1923
+ break;
1924
+ }
1925
+ yield value;
1926
+ }
1927
+ } finally {
1928
+ await reader.cancel();
1929
+ }
1930
+ };
1931
+ const trackStream = (stream, chunkSize, onProgress, onFinish) => {
1932
+ const iterator2 = readBytes(stream, chunkSize);
1933
+ let bytes = 0;
1934
+ let done;
1935
+ let _onFinish = (e) => {
1936
+ if (!done) {
1937
+ done = true;
1938
+ onFinish && onFinish(e);
1939
+ }
1940
+ };
1941
+ return new ReadableStream({
1942
+ async pull(controller2) {
1943
+ try {
1944
+ const { done: done2, value } = await iterator2.next();
1945
+ if (done2) {
1946
+ _onFinish();
1947
+ controller2.close();
1948
+ return;
1949
+ }
1950
+ let len = value.byteLength;
1951
+ if (onProgress) {
1952
+ let loadedBytes = bytes += len;
1953
+ onProgress(loadedBytes);
1954
+ }
1955
+ controller2.enqueue(new Uint8Array(value));
1956
+ } catch (err) {
1957
+ _onFinish(err);
1958
+ throw err;
1959
+ }
1960
+ },
1961
+ cancel(reason) {
1962
+ _onFinish(reason);
1963
+ return iterator2.return();
1964
+ }
1965
+ }, {
1966
+ highWaterMark: 2
1967
+ });
1968
+ };
1969
+ const DEFAULT_CHUNK_SIZE = 64 * 1024;
1970
+ const { isFunction } = utils$1;
1971
+ const globalFetchAPI = (({ Request, Response }) => ({
1972
+ Request,
1973
+ Response
1974
+ }))(utils$1.global);
1975
+ const {
1976
+ ReadableStream: ReadableStream$1,
1977
+ TextEncoder
1978
+ } = utils$1.global;
1979
+ const test = (fn, ...args) => {
1980
+ try {
1981
+ return !!fn(...args);
1982
+ } catch (e) {
1983
+ return false;
1984
+ }
1985
+ };
1986
+ const factory = (env) => {
1987
+ env = utils$1.merge.call({
1988
+ skipUndefined: true
1989
+ }, globalFetchAPI, env);
1990
+ const { fetch: envFetch, Request, Response } = env;
1991
+ const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === "function";
1992
+ const isRequestSupported = isFunction(Request);
1993
+ const isResponseSupported = isFunction(Response);
1994
+ if (!isFetchSupported) {
1995
+ return false;
1996
+ }
1997
+ const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1);
1998
+ const encodeText = isFetchSupported && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : async (str) => new Uint8Array(await new Request(str).arrayBuffer()));
1999
+ const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
2000
+ let duplexAccessed = false;
2001
+ const hasContentType = new Request(platform.origin, {
2002
+ body: new ReadableStream$1(),
2003
+ method: "POST",
2004
+ get duplex() {
2005
+ duplexAccessed = true;
2006
+ return "half";
2007
+ }
2008
+ }).headers.has("Content-Type");
2009
+ return duplexAccessed && !hasContentType;
2010
+ });
2011
+ const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils$1.isReadableStream(new Response("").body));
2012
+ const resolvers = {
2013
+ stream: supportsResponseStream && ((res) => res.body)
2014
+ };
2015
+ isFetchSupported && (() => {
2016
+ ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => {
2017
+ !resolvers[type] && (resolvers[type] = (res, config2) => {
2018
+ let method = res && res[type];
2019
+ if (method) {
2020
+ return method.call(res);
2021
+ }
2022
+ throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config2);
2023
+ });
2024
+ });
2025
+ })();
2026
+ const getBodyLength = async (body) => {
2027
+ if (body == null) {
2028
+ return 0;
2029
+ }
2030
+ if (utils$1.isBlob(body)) {
2031
+ return body.size;
2032
+ }
2033
+ if (utils$1.isSpecCompliantForm(body)) {
2034
+ const _request = new Request(platform.origin, {
2035
+ method: "POST",
2036
+ body
2037
+ });
2038
+ return (await _request.arrayBuffer()).byteLength;
2039
+ }
2040
+ if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
2041
+ return body.byteLength;
2042
+ }
2043
+ if (utils$1.isURLSearchParams(body)) {
2044
+ body = body + "";
2045
+ }
2046
+ if (utils$1.isString(body)) {
2047
+ return (await encodeText(body)).byteLength;
2048
+ }
2049
+ };
2050
+ const resolveBodyLength = async (headers, body) => {
2051
+ const length = utils$1.toFiniteNumber(headers.getContentLength());
2052
+ return length == null ? getBodyLength(body) : length;
2053
+ };
2054
+ return async (config2) => {
2055
+ let {
2056
+ url,
2057
+ method,
2058
+ data,
2059
+ signal,
2060
+ cancelToken,
2061
+ timeout,
2062
+ onDownloadProgress,
2063
+ onUploadProgress,
2064
+ responseType,
2065
+ headers,
2066
+ withCredentials = "same-origin",
2067
+ fetchOptions
2068
+ } = resolveConfig(config2);
2069
+ let _fetch = envFetch || fetch;
2070
+ responseType = responseType ? (responseType + "").toLowerCase() : "text";
2071
+ let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
2072
+ let request = null;
2073
+ const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
2074
+ composedSignal.unsubscribe();
2075
+ });
2076
+ let requestContentLength;
2077
+ try {
2078
+ if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
2079
+ let _request = new Request(url, {
2080
+ method: "POST",
2081
+ body: data,
2082
+ duplex: "half"
2083
+ });
2084
+ let contentTypeHeader;
2085
+ if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
2086
+ headers.setContentType(contentTypeHeader);
2087
+ }
2088
+ if (_request.body) {
2089
+ const [onProgress, flush] = progressEventDecorator(
2090
+ requestContentLength,
2091
+ progressEventReducer(asyncDecorator(onUploadProgress))
2092
+ );
2093
+ data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
2094
+ }
2095
+ }
2096
+ if (!utils$1.isString(withCredentials)) {
2097
+ withCredentials = withCredentials ? "include" : "omit";
2098
+ }
2099
+ const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype;
2100
+ const resolvedOptions = {
2101
+ ...fetchOptions,
2102
+ signal: composedSignal,
2103
+ method: method.toUpperCase(),
2104
+ headers: headers.normalize().toJSON(),
2105
+ body: data,
2106
+ duplex: "half",
2107
+ credentials: isCredentialsSupported ? withCredentials : void 0
2108
+ };
2109
+ request = isRequestSupported && new Request(url, resolvedOptions);
2110
+ let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions));
2111
+ const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
2112
+ if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
2113
+ const options = {};
2114
+ ["status", "statusText", "headers"].forEach((prop) => {
2115
+ options[prop] = response[prop];
2116
+ });
2117
+ const responseContentLength = utils$1.toFiniteNumber(response.headers.get("content-length"));
2118
+ const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
2119
+ responseContentLength,
2120
+ progressEventReducer(asyncDecorator(onDownloadProgress), true)
2121
+ ) || [];
2122
+ response = new Response(
2123
+ trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
2124
+ flush && flush();
2125
+ unsubscribe && unsubscribe();
2126
+ }),
2127
+ options
2128
+ );
2129
+ }
2130
+ responseType = responseType || "text";
2131
+ let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || "text"](response, config2);
2132
+ !isStreamResponse && unsubscribe && unsubscribe();
2133
+ return await new Promise((resolve, reject) => {
2134
+ settle(resolve, reject, {
2135
+ data: responseData,
2136
+ headers: AxiosHeaders$1.from(response.headers),
2137
+ status: response.status,
2138
+ statusText: response.statusText,
2139
+ config: config2,
2140
+ request
2141
+ });
2142
+ });
2143
+ } catch (err) {
2144
+ unsubscribe && unsubscribe();
2145
+ if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) {
2146
+ throw Object.assign(
2147
+ new AxiosError$1("Network Error", AxiosError$1.ERR_NETWORK, config2, request),
2148
+ {
2149
+ cause: err.cause || err
2150
+ }
2151
+ );
2152
+ }
2153
+ throw AxiosError$1.from(err, err && err.code, config2, request);
2154
+ }
2155
+ };
2156
+ };
2157
+ const seedCache = /* @__PURE__ */ new Map();
2158
+ const getFetch = (config2) => {
2159
+ let env = config2 ? config2.env : {};
2160
+ const { fetch: fetch2, Request, Response } = env;
2161
+ const seeds = [
2162
+ Request,
2163
+ Response,
2164
+ fetch2
2165
+ ];
2166
+ let len = seeds.length, i = len, seed, target, map = seedCache;
2167
+ while (i--) {
2168
+ seed = seeds[i];
2169
+ target = map.get(seed);
2170
+ target === void 0 && map.set(seed, target = i ? /* @__PURE__ */ new Map() : factory(env));
2171
+ map = target;
2172
+ }
2173
+ return target;
2174
+ };
2175
+ getFetch();
2176
+ const knownAdapters = {
2177
+ http: httpAdapter,
2178
+ xhr: xhrAdapter,
2179
+ fetch: {
2180
+ get: getFetch
2181
+ }
2182
+ };
2183
+ utils$1.forEach(knownAdapters, (fn, value) => {
2184
+ if (fn) {
2185
+ try {
2186
+ Object.defineProperty(fn, "name", { value });
2187
+ } catch (e) {
2188
+ }
2189
+ Object.defineProperty(fn, "adapterName", { value });
2190
+ }
2191
+ });
2192
+ const renderReason = (reason) => `- ${reason}`;
2193
+ const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
2194
+ const adapters = {
2195
+ getAdapter: (adapters2, config2) => {
2196
+ adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2];
2197
+ const { length } = adapters2;
2198
+ let nameOrAdapter;
2199
+ let adapter;
2200
+ const rejectedReasons = {};
2201
+ for (let i = 0; i < length; i++) {
2202
+ nameOrAdapter = adapters2[i];
2203
+ let id;
2204
+ adapter = nameOrAdapter;
2205
+ if (!isResolvedHandle(nameOrAdapter)) {
2206
+ adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
2207
+ if (adapter === void 0) {
2208
+ throw new AxiosError$1(`Unknown adapter '${id}'`);
2209
+ }
2210
+ }
2211
+ if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config2)))) {
2212
+ break;
2213
+ }
2214
+ rejectedReasons[id || "#" + i] = adapter;
2215
+ }
2216
+ if (!adapter) {
2217
+ const reasons = Object.entries(rejectedReasons).map(
2218
+ ([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build")
2219
+ );
2220
+ let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified";
2221
+ throw new AxiosError$1(
2222
+ `There is no suitable adapter to dispatch the request ` + s,
2223
+ "ERR_NOT_SUPPORT"
2224
+ );
2225
+ }
2226
+ return adapter;
2227
+ },
2228
+ adapters: knownAdapters
2229
+ };
2230
+ function throwIfCancellationRequested(config2) {
2231
+ if (config2.cancelToken) {
2232
+ config2.cancelToken.throwIfRequested();
2233
+ }
2234
+ if (config2.signal && config2.signal.aborted) {
2235
+ throw new CanceledError$1(null, config2);
2236
+ }
2237
+ }
2238
+ function dispatchRequest(config2) {
2239
+ throwIfCancellationRequested(config2);
2240
+ config2.headers = AxiosHeaders$1.from(config2.headers);
2241
+ config2.data = transformData.call(
2242
+ config2,
2243
+ config2.transformRequest
2244
+ );
2245
+ if (["post", "put", "patch"].indexOf(config2.method) !== -1) {
2246
+ config2.headers.setContentType("application/x-www-form-urlencoded", false);
2247
+ }
2248
+ const adapter = adapters.getAdapter(config2.adapter || defaults.adapter, config2);
2249
+ return adapter(config2).then(function onAdapterResolution(response) {
2250
+ throwIfCancellationRequested(config2);
2251
+ response.data = transformData.call(
2252
+ config2,
2253
+ config2.transformResponse,
2254
+ response
2255
+ );
2256
+ response.headers = AxiosHeaders$1.from(response.headers);
2257
+ return response;
2258
+ }, function onAdapterRejection(reason) {
2259
+ if (!isCancel$1(reason)) {
2260
+ throwIfCancellationRequested(config2);
2261
+ if (reason && reason.response) {
2262
+ reason.response.data = transformData.call(
2263
+ config2,
2264
+ config2.transformResponse,
2265
+ reason.response
2266
+ );
2267
+ reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
2268
+ }
2269
+ }
2270
+ return Promise.reject(reason);
2271
+ });
2272
+ }
2273
+ const VERSION$1 = "1.12.2";
2274
+ const validators$1 = {};
2275
+ ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => {
2276
+ validators$1[type] = function validator2(thing) {
2277
+ return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type;
2278
+ };
2279
+ });
2280
+ const deprecatedWarnings = {};
2281
+ validators$1.transitional = function transitional(validator2, version, message) {
2282
+ function formatMessage(opt, desc) {
2283
+ return "[Axios v" + VERSION$1 + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : "");
2284
+ }
2285
+ return (value, opt, opts) => {
2286
+ if (validator2 === false) {
2287
+ throw new AxiosError$1(
2288
+ formatMessage(opt, " has been removed" + (version ? " in " + version : "")),
2289
+ AxiosError$1.ERR_DEPRECATED
2290
+ );
2291
+ }
2292
+ if (version && !deprecatedWarnings[opt]) {
2293
+ deprecatedWarnings[opt] = true;
2294
+ console.warn(
2295
+ formatMessage(
2296
+ opt,
2297
+ " has been deprecated since v" + version + " and will be removed in the near future"
2298
+ )
2299
+ );
2300
+ }
2301
+ return validator2 ? validator2(value, opt, opts) : true;
2302
+ };
2303
+ };
2304
+ validators$1.spelling = function spelling(correctSpelling) {
2305
+ return (value, opt) => {
2306
+ console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
2307
+ return true;
2308
+ };
2309
+ };
2310
+ function assertOptions(options, schema, allowUnknown) {
2311
+ if (typeof options !== "object") {
2312
+ throw new AxiosError$1("options must be an object", AxiosError$1.ERR_BAD_OPTION_VALUE);
2313
+ }
2314
+ const keys = Object.keys(options);
2315
+ let i = keys.length;
2316
+ while (i-- > 0) {
2317
+ const opt = keys[i];
2318
+ const validator2 = schema[opt];
2319
+ if (validator2) {
2320
+ const value = options[opt];
2321
+ const result = value === void 0 || validator2(value, opt, options);
2322
+ if (result !== true) {
2323
+ throw new AxiosError$1("option " + opt + " must be " + result, AxiosError$1.ERR_BAD_OPTION_VALUE);
2324
+ }
2325
+ continue;
2326
+ }
2327
+ if (allowUnknown !== true) {
2328
+ throw new AxiosError$1("Unknown option " + opt, AxiosError$1.ERR_BAD_OPTION);
2329
+ }
2330
+ }
2331
+ }
2332
+ const validator = {
2333
+ assertOptions,
2334
+ validators: validators$1
2335
+ };
2336
+ const validators = validator.validators;
2337
+ let Axios$1 = class Axios {
2338
+ constructor(instanceConfig) {
2339
+ this.defaults = instanceConfig || {};
2340
+ this.interceptors = {
2341
+ request: new InterceptorManager(),
2342
+ response: new InterceptorManager()
2343
+ };
2344
+ }
2345
+ /**
2346
+ * Dispatch a request
2347
+ *
2348
+ * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
2349
+ * @param {?Object} config
2350
+ *
2351
+ * @returns {Promise} The Promise to be fulfilled
2352
+ */
2353
+ async request(configOrUrl, config2) {
2354
+ try {
2355
+ return await this._request(configOrUrl, config2);
2356
+ } catch (err) {
2357
+ if (err instanceof Error) {
2358
+ let dummy = {};
2359
+ Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
2360
+ const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : "";
2361
+ try {
2362
+ if (!err.stack) {
2363
+ err.stack = stack;
2364
+ } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) {
2365
+ err.stack += "\n" + stack;
2366
+ }
2367
+ } catch (e) {
2368
+ }
2369
+ }
2370
+ throw err;
2371
+ }
2372
+ }
2373
+ _request(configOrUrl, config2) {
2374
+ if (typeof configOrUrl === "string") {
2375
+ config2 = config2 || {};
2376
+ config2.url = configOrUrl;
2377
+ } else {
2378
+ config2 = configOrUrl || {};
2379
+ }
2380
+ config2 = mergeConfig$1(this.defaults, config2);
2381
+ const { transitional: transitional2, paramsSerializer, headers } = config2;
2382
+ if (transitional2 !== void 0) {
2383
+ validator.assertOptions(transitional2, {
2384
+ silentJSONParsing: validators.transitional(validators.boolean),
2385
+ forcedJSONParsing: validators.transitional(validators.boolean),
2386
+ clarifyTimeoutError: validators.transitional(validators.boolean)
2387
+ }, false);
2388
+ }
2389
+ if (paramsSerializer != null) {
2390
+ if (utils$1.isFunction(paramsSerializer)) {
2391
+ config2.paramsSerializer = {
2392
+ serialize: paramsSerializer
2393
+ };
2394
+ } else {
2395
+ validator.assertOptions(paramsSerializer, {
2396
+ encode: validators.function,
2397
+ serialize: validators.function
2398
+ }, true);
2399
+ }
2400
+ }
2401
+ if (config2.allowAbsoluteUrls !== void 0) ;
2402
+ else if (this.defaults.allowAbsoluteUrls !== void 0) {
2403
+ config2.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
2404
+ } else {
2405
+ config2.allowAbsoluteUrls = true;
2406
+ }
2407
+ validator.assertOptions(config2, {
2408
+ baseUrl: validators.spelling("baseURL"),
2409
+ withXsrfToken: validators.spelling("withXSRFToken")
2410
+ }, true);
2411
+ config2.method = (config2.method || this.defaults.method || "get").toLowerCase();
2412
+ let contextHeaders = headers && utils$1.merge(
2413
+ headers.common,
2414
+ headers[config2.method]
2415
+ );
2416
+ headers && utils$1.forEach(
2417
+ ["delete", "get", "head", "post", "put", "patch", "common"],
2418
+ (method) => {
2419
+ delete headers[method];
2420
+ }
2421
+ );
2422
+ config2.headers = AxiosHeaders$1.concat(contextHeaders, headers);
2423
+ const requestInterceptorChain = [];
2424
+ let synchronousRequestInterceptors = true;
2425
+ this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
2426
+ if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config2) === false) {
2427
+ return;
2428
+ }
2429
+ synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
2430
+ requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
2431
+ });
2432
+ const responseInterceptorChain = [];
2433
+ this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
2434
+ responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
2435
+ });
2436
+ let promise;
2437
+ let i = 0;
2438
+ let len;
2439
+ if (!synchronousRequestInterceptors) {
2440
+ const chain = [dispatchRequest.bind(this), void 0];
2441
+ chain.unshift(...requestInterceptorChain);
2442
+ chain.push(...responseInterceptorChain);
2443
+ len = chain.length;
2444
+ promise = Promise.resolve(config2);
2445
+ while (i < len) {
2446
+ promise = promise.then(chain[i++], chain[i++]);
2447
+ }
2448
+ return promise;
2449
+ }
2450
+ len = requestInterceptorChain.length;
2451
+ let newConfig = config2;
2452
+ while (i < len) {
2453
+ const onFulfilled = requestInterceptorChain[i++];
2454
+ const onRejected = requestInterceptorChain[i++];
2455
+ try {
2456
+ newConfig = onFulfilled(newConfig);
2457
+ } catch (error) {
2458
+ onRejected.call(this, error);
2459
+ break;
2460
+ }
2461
+ }
2462
+ try {
2463
+ promise = dispatchRequest.call(this, newConfig);
2464
+ } catch (error) {
2465
+ return Promise.reject(error);
2466
+ }
2467
+ i = 0;
2468
+ len = responseInterceptorChain.length;
2469
+ while (i < len) {
2470
+ promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
2471
+ }
2472
+ return promise;
2473
+ }
2474
+ getUri(config2) {
2475
+ config2 = mergeConfig$1(this.defaults, config2);
2476
+ const fullPath = buildFullPath(config2.baseURL, config2.url, config2.allowAbsoluteUrls);
2477
+ return buildURL(fullPath, config2.params, config2.paramsSerializer);
2478
+ }
2479
+ };
2480
+ utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) {
2481
+ Axios$1.prototype[method] = function(url, config2) {
2482
+ return this.request(mergeConfig$1(config2 || {}, {
2483
+ method,
2484
+ url,
2485
+ data: (config2 || {}).data
2486
+ }));
2487
+ };
2488
+ });
2489
+ utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
2490
+ function generateHTTPMethod(isForm) {
2491
+ return function httpMethod(url, data, config2) {
2492
+ return this.request(mergeConfig$1(config2 || {}, {
2493
+ method,
2494
+ headers: isForm ? {
2495
+ "Content-Type": "multipart/form-data"
2496
+ } : {},
2497
+ url,
2498
+ data
2499
+ }));
2500
+ };
2501
+ }
2502
+ Axios$1.prototype[method] = generateHTTPMethod();
2503
+ Axios$1.prototype[method + "Form"] = generateHTTPMethod(true);
2504
+ });
2505
+ let CancelToken$1 = class CancelToken {
2506
+ constructor(executor) {
2507
+ if (typeof executor !== "function") {
2508
+ throw new TypeError("executor must be a function.");
2509
+ }
2510
+ let resolvePromise;
2511
+ this.promise = new Promise(function promiseExecutor(resolve) {
2512
+ resolvePromise = resolve;
2513
+ });
2514
+ const token = this;
2515
+ this.promise.then((cancel) => {
2516
+ if (!token._listeners) return;
2517
+ let i = token._listeners.length;
2518
+ while (i-- > 0) {
2519
+ token._listeners[i](cancel);
2520
+ }
2521
+ token._listeners = null;
2522
+ });
2523
+ this.promise.then = (onfulfilled) => {
2524
+ let _resolve;
2525
+ const promise = new Promise((resolve) => {
2526
+ token.subscribe(resolve);
2527
+ _resolve = resolve;
2528
+ }).then(onfulfilled);
2529
+ promise.cancel = function reject() {
2530
+ token.unsubscribe(_resolve);
2531
+ };
2532
+ return promise;
2533
+ };
2534
+ executor(function cancel(message, config2, request) {
2535
+ if (token.reason) {
2536
+ return;
2537
+ }
2538
+ token.reason = new CanceledError$1(message, config2, request);
2539
+ resolvePromise(token.reason);
2540
+ });
2541
+ }
2542
+ /**
2543
+ * Throws a `CanceledError` if cancellation has been requested.
2544
+ */
2545
+ throwIfRequested() {
2546
+ if (this.reason) {
2547
+ throw this.reason;
2548
+ }
2549
+ }
2550
+ /**
2551
+ * Subscribe to the cancel signal
2552
+ */
2553
+ subscribe(listener) {
2554
+ if (this.reason) {
2555
+ listener(this.reason);
2556
+ return;
2557
+ }
2558
+ if (this._listeners) {
2559
+ this._listeners.push(listener);
2560
+ } else {
2561
+ this._listeners = [listener];
2562
+ }
2563
+ }
2564
+ /**
2565
+ * Unsubscribe from the cancel signal
2566
+ */
2567
+ unsubscribe(listener) {
2568
+ if (!this._listeners) {
2569
+ return;
2570
+ }
2571
+ const index2 = this._listeners.indexOf(listener);
2572
+ if (index2 !== -1) {
2573
+ this._listeners.splice(index2, 1);
2574
+ }
2575
+ }
2576
+ toAbortSignal() {
2577
+ const controller2 = new AbortController();
2578
+ const abort = (err) => {
2579
+ controller2.abort(err);
2580
+ };
2581
+ this.subscribe(abort);
2582
+ controller2.signal.unsubscribe = () => this.unsubscribe(abort);
2583
+ return controller2.signal;
2584
+ }
2585
+ /**
2586
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
2587
+ * cancels the `CancelToken`.
2588
+ */
2589
+ static source() {
2590
+ let cancel;
2591
+ const token = new CancelToken(function executor(c) {
2592
+ cancel = c;
2593
+ });
2594
+ return {
2595
+ token,
2596
+ cancel
2597
+ };
2598
+ }
2599
+ };
2600
+ function spread$1(callback) {
2601
+ return function wrap(arr) {
2602
+ return callback.apply(null, arr);
2603
+ };
2604
+ }
2605
+ function isAxiosError$1(payload) {
2606
+ return utils$1.isObject(payload) && payload.isAxiosError === true;
2607
+ }
2608
+ const HttpStatusCode$1 = {
2609
+ Continue: 100,
2610
+ SwitchingProtocols: 101,
2611
+ Processing: 102,
2612
+ EarlyHints: 103,
2613
+ Ok: 200,
2614
+ Created: 201,
2615
+ Accepted: 202,
2616
+ NonAuthoritativeInformation: 203,
2617
+ NoContent: 204,
2618
+ ResetContent: 205,
2619
+ PartialContent: 206,
2620
+ MultiStatus: 207,
2621
+ AlreadyReported: 208,
2622
+ ImUsed: 226,
2623
+ MultipleChoices: 300,
2624
+ MovedPermanently: 301,
2625
+ Found: 302,
2626
+ SeeOther: 303,
2627
+ NotModified: 304,
2628
+ UseProxy: 305,
2629
+ Unused: 306,
2630
+ TemporaryRedirect: 307,
2631
+ PermanentRedirect: 308,
2632
+ BadRequest: 400,
2633
+ Unauthorized: 401,
2634
+ PaymentRequired: 402,
2635
+ Forbidden: 403,
2636
+ NotFound: 404,
2637
+ MethodNotAllowed: 405,
2638
+ NotAcceptable: 406,
2639
+ ProxyAuthenticationRequired: 407,
2640
+ RequestTimeout: 408,
2641
+ Conflict: 409,
2642
+ Gone: 410,
2643
+ LengthRequired: 411,
2644
+ PreconditionFailed: 412,
2645
+ PayloadTooLarge: 413,
2646
+ UriTooLong: 414,
2647
+ UnsupportedMediaType: 415,
2648
+ RangeNotSatisfiable: 416,
2649
+ ExpectationFailed: 417,
2650
+ ImATeapot: 418,
2651
+ MisdirectedRequest: 421,
2652
+ UnprocessableEntity: 422,
2653
+ Locked: 423,
2654
+ FailedDependency: 424,
2655
+ TooEarly: 425,
2656
+ UpgradeRequired: 426,
2657
+ PreconditionRequired: 428,
2658
+ TooManyRequests: 429,
2659
+ RequestHeaderFieldsTooLarge: 431,
2660
+ UnavailableForLegalReasons: 451,
2661
+ InternalServerError: 500,
2662
+ NotImplemented: 501,
2663
+ BadGateway: 502,
2664
+ ServiceUnavailable: 503,
2665
+ GatewayTimeout: 504,
2666
+ HttpVersionNotSupported: 505,
2667
+ VariantAlsoNegotiates: 506,
2668
+ InsufficientStorage: 507,
2669
+ LoopDetected: 508,
2670
+ NotExtended: 510,
2671
+ NetworkAuthenticationRequired: 511
2672
+ };
2673
+ Object.entries(HttpStatusCode$1).forEach(([key, value]) => {
2674
+ HttpStatusCode$1[value] = key;
2675
+ });
2676
+ function createInstance(defaultConfig) {
2677
+ const context = new Axios$1(defaultConfig);
2678
+ const instance = bind(Axios$1.prototype.request, context);
2679
+ utils$1.extend(instance, Axios$1.prototype, context, { allOwnKeys: true });
2680
+ utils$1.extend(instance, context, null, { allOwnKeys: true });
2681
+ instance.create = function create(instanceConfig) {
2682
+ return createInstance(mergeConfig$1(defaultConfig, instanceConfig));
2683
+ };
2684
+ return instance;
2685
+ }
2686
+ const axios = createInstance(defaults);
2687
+ axios.Axios = Axios$1;
2688
+ axios.CanceledError = CanceledError$1;
2689
+ axios.CancelToken = CancelToken$1;
2690
+ axios.isCancel = isCancel$1;
2691
+ axios.VERSION = VERSION$1;
2692
+ axios.toFormData = toFormData$1;
2693
+ axios.AxiosError = AxiosError$1;
2694
+ axios.Cancel = axios.CanceledError;
2695
+ axios.all = function all(promises) {
2696
+ return Promise.all(promises);
2697
+ };
2698
+ axios.spread = spread$1;
2699
+ axios.isAxiosError = isAxiosError$1;
2700
+ axios.mergeConfig = mergeConfig$1;
2701
+ axios.AxiosHeaders = AxiosHeaders$1;
2702
+ axios.formToJSON = (thing) => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
2703
+ axios.getAdapter = adapters.getAdapter;
2704
+ axios.HttpStatusCode = HttpStatusCode$1;
2705
+ axios.default = axios;
2706
+ const {
2707
+ Axios: Axios2,
2708
+ AxiosError,
2709
+ CanceledError,
2710
+ isCancel,
2711
+ CancelToken: CancelToken2,
2712
+ VERSION,
2713
+ all: all2,
2714
+ Cancel,
2715
+ isAxiosError,
2716
+ spread,
2717
+ toFormData,
2718
+ AxiosHeaders: AxiosHeaders2,
2719
+ HttpStatusCode,
2720
+ formToJSON,
2721
+ getAdapter,
2722
+ mergeConfig
2723
+ } = axios;
2724
+ function imageUrlToBase64(url) {
2725
+ return new Promise((resolve, reject) => {
2726
+ https__namespace.get(url, (response) => {
2727
+ if (response.statusCode < 200 || response.statusCode >= 300) {
2728
+ return reject(
2729
+ new Error(
2730
+ `Failed to download image, status code: ${response.statusCode}`
2731
+ )
2732
+ );
2733
+ }
2734
+ const chunks = [];
2735
+ response.on("data", (chunk) => {
2736
+ chunks.push(chunk);
2737
+ });
2738
+ response.on("end", () => {
2739
+ const buffer = Buffer.concat(chunks);
2740
+ resolve(buffer.toString("base64"));
2741
+ });
2742
+ }).on("error", (error) => {
2743
+ reject(error);
2744
+ });
2745
+ });
2746
+ }
2747
+ const service = ({ strapi }) => {
2748
+ return {
2749
+ // ───────────────────────────────
2750
+ // 🤖 AI Configuration
2751
+ // ───────────────────────────────
2752
+ async geminiConfig() {
2753
+ const pluginStore = strapi.store({
2754
+ type: "plugin",
2755
+ name: "strapi-content-generator-gemini"
2756
+ });
2757
+ const googleGenAI = await pluginStore.get({ key: "GOOGLE_GEN_AI" });
2758
+ if (!googleGenAI) {
2759
+ throw new Error(
2760
+ "La variable de entorno GOOGLE_GEN_AI no está configurada."
2761
+ );
2762
+ }
2763
+ const ai = new genai.GoogleGenAI({ apiKey: googleGenAI });
2764
+ return ai;
2765
+ },
2766
+ /**
2767
+ * Fetches articles.
2768
+ */
2769
+ async getArticulos(sanitizedQueryParams) {
2770
+ return await strapi.entityService.findMany("api::articulo.articulo", sanitizedQueryParams);
2771
+ },
2772
+ async getCategorias(sanitizedQueryParams) {
2773
+ return await strapi.entityService.findMany("api::categoria.categoria", sanitizedQueryParams);
2774
+ },
2775
+ async getUsuarios(sanitizedQueryParams) {
2776
+ return await strapi.entityService.findMany("plugin::users-permissions.user", sanitizedQueryParams);
2777
+ },
2778
+ // ───────────────────────────────
2779
+ // 🧠 Generate Article with AI
2780
+ // ───────────────────────────────
2781
+ async generateArticle(ctx) {
2782
+ const { titulo, categoria, autor, keywords, instrucciones } = ctx.request.body;
2783
+ const promptArticulo = `
2784
+ Genera un artículo en español neutro, orientado a SEO, con estructura clara, sin emojis, sin texto fuera del JSON, respetando estrictamente el schema proporcionado.
2785
+
2786
+ Requisitos para "content":
2787
+ - HTML compatible con @_sh/strapi-plugin-ckeditor (DefaultHTML editor)
2788
+ - Debe incluir:
2789
+ - Título en H1
2790
+ - Introducción
2791
+ - Subtítulos H2 (puedes usar hasta H6)
2792
+ - Listas
2793
+ - Tablas (sólo si el contenido lo amerita)
2794
+ - Ejemplo práctico (sólo si el contenido lo amerita)
2795
+ - Conclusión o comentarios finales (no es necesario etiquetarlo con un encabezado)
2796
+
2797
+ SEO:
2798
+ - Incluir metadatos necesarios para Facebook y LinkedIn
2799
+ - Omitir author, publisher, image y robots
2800
+ - og:url es: https:://interware.com.mx/blog/{SLUG DEL TÍTULO}
2801
+
2802
+ Restricciones:
2803
+ - No usar frases como: deja tu opinión, comenta, suscríbete, etc.
2804
+
2805
+ ${titulo ? `Básate en el título: "${titulo}".` : ""}
2806
+ ${categoria ? `Categoría(s): "${categoria}".` : ""}
2807
+ ${keywords ? `Palabras clave: "${keywords}".` : ""}
2808
+ ${instrucciones ? `Instrucciones adicionales: "${instrucciones}".` : ""}
2809
+ `;
2810
+ try {
2811
+ const ai = await this.geminiConfig();
2812
+ const result = await ai.models.generateContent({
2813
+ model: "gemini-2.5-flash",
2814
+ contents: promptArticulo,
2815
+ config: {
2816
+ responseMimeType: "application/json",
2817
+ temperature: 0.2,
2818
+ responseSchema: {
2819
+ type: "object",
2820
+ required: ["titulo", "descripcion", "content", "seo", "minute_read"],
2821
+ properties: {
2822
+ titulo: {
2823
+ type: "string",
2824
+ minLength: 40,
2825
+ maxLength: 70,
2826
+ description: "Título del artículo"
2827
+ },
2828
+ descripcion: {
2829
+ type: "string",
2830
+ minLength: 80,
2831
+ maxLength: 160,
2832
+ description: "Descripción breve del artículo"
2833
+ },
2834
+ content: {
2835
+ type: "string",
2836
+ description: "Contenido HTML compatible con CKEditor"
2837
+ },
2838
+ seo: {
2839
+ type: "object",
2840
+ required: ["metaTitle", "metaDescription", "metadata"],
2841
+ properties: {
2842
+ metaTitle: {
2843
+ type: "string"
2844
+ },
2845
+ metaDescription: {
2846
+ type: "string"
2847
+ },
2848
+ metadata: {
2849
+ type: "array",
2850
+ items: {
2851
+ type: "object",
2852
+ required: ["name", "content"],
2853
+ properties: {
2854
+ name: { type: "string" },
2855
+ content: { type: "string" }
2856
+ }
2857
+ }
2858
+ }
2859
+ }
2860
+ },
2861
+ minute_read: {
2862
+ type: "number",
2863
+ minimum: 1,
2864
+ maximum: 30,
2865
+ description: "Tiempo de lectura calculado usando 200 palabras por minuto"
2866
+ }
2867
+ }
2868
+ }
2869
+ }
2870
+ });
2871
+ const rawText = result.candidates?.[0]?.content?.parts?.[0]?.text ?? "";
2872
+ if (!rawText) {
2873
+ throw new Error(
2874
+ "La IA no generó texto. Revisa el prompt o el modelo."
2875
+ );
2876
+ }
2877
+ const parsed = JSON.parse(rawText);
2878
+ const article = await strapi.documents("api::articulo.articulo").create({
2879
+ data: {
2880
+ titulo: parsed.titulo,
2881
+ descripcion: parsed.descripcion,
2882
+ content: parsed.content,
2883
+ seo: parsed.seo,
2884
+ minute_read: parsed.minute_read,
2885
+ slug: slugify__default.default(parsed.titulo, { lower: true, strict: true }),
2886
+ categoria,
2887
+ autor,
2888
+ image: null
2889
+ },
2890
+ status: "draft"
2891
+ });
2892
+ return article;
2893
+ } catch (err) {
2894
+ console.error("🚀 ~ generateArticle ~ err:", err);
2895
+ throw new Error(
2896
+ "Error al generar el artículo. Revisa el prompt, el modelo o el JSON generado."
2897
+ );
2898
+ }
2899
+ },
2900
+ // ───────────────────────────────
2901
+ // 🖼️ Generate Image for Article
2902
+ // ───────────────────────────────
2903
+ async generateImageForArticle(ctx) {
2904
+ const { articleId, imageInstructions } = ctx.request.body;
2905
+ if (!articleId) {
2906
+ throw new Error(
2907
+ "Se requiere 'articleId' en el cuerpo de la petición."
2908
+ );
2909
+ }
2910
+ try {
2911
+ const article = await strapi.documents("api::articulo.articulo").findOne({
2912
+ documentId: articleId
2913
+ });
2914
+ const reference_1 = await imageUrlToBase64(
2915
+ "https://api.interware.com.mx/static/images/event.png"
2916
+ );
2917
+ const reference_2 = await imageUrlToBase64(
2918
+ "https://api.interware.com.mx/static/images/info_data.png"
2919
+ );
2920
+ const reference_3 = await imageUrlToBase64(
2921
+ "https://api.interware.com.mx/static/images/Oportunidad_IWRobot.png"
2922
+ );
2923
+ const prompt = [
2924
+ {
2925
+ text: `
2926
+ Ilustración digital editorial para blog 1920x1080.
2927
+
2928
+ REGLA CRÍTICA:
2929
+ La imagen NO debe contener texto de ningún tipo.
2930
+ No incluir palabras, letras, números, tipografía, símbolos tipográficos, rótulos, títulos,
2931
+ ni elementos gráficos que simulen texto.
2932
+
2933
+ Estilo:
2934
+ Estilo contemporáneo, corporativo y atemporal.
2935
+ Estética limpia, profesional y coherente.
2936
+ Lenguaje visual sobrio, tecnológico y confiable.
2937
+
2938
+ Paleta de colores:
2939
+ Extraer exclusivamente la paleta cromática principal de las imagenes de referencia.
2940
+ Si vas a usar la ilustración del robot, no cambies ni estilo ni forma.
2941
+ No introducir colores nuevos.
2942
+
2943
+ Iluminación uniforme y suave.
2944
+ Diseño plano con ligera profundidad.
2945
+ Estilo vectorial semi-realista, no fotográfico, no 3D.
2946
+ Fondo minimalista.
2947
+
2948
+ Concepto visual a representar:
2949
+ Interpretar visualmente el siguiente tema de forma simbólica y abstracta,
2950
+ usando metáforas gráficas y elementos visuales, SIN TEXTO:
2951
+ ${article.titulo} — ${article.descripcion}
2952
+
2953
+ Instrucciones adicionales:
2954
+ ${imageInstructions || "Ninguna"}
2955
+ `
2956
+ },
2957
+ {
2958
+ inlineData: {
2959
+ mimeType: "image/png",
2960
+ data: reference_1
2961
+ }
2962
+ },
2963
+ {
2964
+ inlineData: {
2965
+ mimeType: "image/png",
2966
+ data: reference_2
2967
+ }
2968
+ },
2969
+ {
2970
+ inlineData: {
2971
+ mimeType: "image/png",
2972
+ data: reference_3
2973
+ }
2974
+ }
2975
+ ];
2976
+ const ai = await this.geminiConfig();
2977
+ const result = await ai.models.generateContent({
2978
+ model: "gemini-2.5-flash-image",
2979
+ contents: prompt,
2980
+ config: {
2981
+ responseModalities: ["IMAGE"],
2982
+ imageConfig: {
2983
+ aspectRatio: "16:9"
2984
+ }
2985
+ }
2986
+ });
2987
+ const parts = result?.candidates?.[0]?.content?.parts;
2988
+ if (!Array.isArray(parts)) {
2989
+ throw new Error("Respuesta inválida del modelo (parts no encontrado)");
2990
+ }
2991
+ const imagePart = parts.find(
2992
+ (p) => typeof p === "object" && p.inlineData && typeof p.inlineData.data === "string" && p.inlineData.mimeType?.startsWith("image/")
2993
+ );
2994
+ if (!imagePart) {
2995
+ throw new Error("No se encontró ninguna imagen en la respuesta del modelo");
2996
+ }
2997
+ const buffer = Buffer.from(imagePart.inlineData.data, "base64");
2998
+ const uploadedFiles = await strapi.plugins.upload.services.upload.upload({
2999
+ data: {
3000
+ fileInfo: {
3001
+ name: `article-${articleId}.png`,
3002
+ alternativeText: `Imagen para el artículo ${article.titulo}`,
3003
+ caption: `Imagen generada por IA para el artículo ${article.titulo}`
3004
+ }
3005
+ },
3006
+ files: {
3007
+ filepath: buffer,
3008
+ originalFilename: `article-${articleId}.png`,
3009
+ mimetype: "image/png"
3010
+ }
3011
+ });
3012
+ if (!uploadedFiles || uploadedFiles.length === 0) {
3013
+ throw new Error("La subida de la imagen falló.");
3014
+ }
3015
+ const articleModel = await strapi.getModel("api::articulo.articulo");
3016
+ const sanitizedData = await strapi.contentAPI.sanitize.input(
3017
+ {
3018
+ image: uploadedFiles[0].id
3019
+ },
3020
+ articleModel
3021
+ );
3022
+ await strapi.documents("api::articulo.articulo").update({
3023
+ documentId: articleId,
3024
+ data: sanitizedData
3025
+ });
3026
+ return {
3027
+ message: "Imagen generada y asociada correctamente.",
3028
+ image: uploadedFiles[0]
3029
+ };
3030
+ } catch (err) {
3031
+ throw new Error("Error al generar la imagen para el artículo.");
3032
+ }
3033
+ },
3034
+ // ───────────────────────────────
3035
+ // 🌐 Social Media Publishing
3036
+ // ───────────────────────────────
3037
+ async publishToLinkedIn(ctx) {
3038
+ const { articleId } = ctx.request.body;
3039
+ const pluginStore = strapi.store({
3040
+ type: "plugin",
3041
+ name: "strapi-content-generator-gemini"
3042
+ });
3043
+ const linkedInAccessToken = await pluginStore.get({ key: "LINKEDIN_ACCESS_TOKEN" });
3044
+ const linkedInOrganizationId = await pluginStore.get({ key: "LINKEDIN_ORGANIZATION_ID" });
3045
+ if (!articleId) {
3046
+ throw new Error("Se requiere 'articleId' en el cuerpo de la petición.");
3047
+ }
3048
+ if (!linkedInAccessToken) {
3049
+ throw new Error(
3050
+ "La variable de entorno LINKEDIN_ACCESS_TOKEN no está configurada."
3051
+ );
3052
+ }
3053
+ if (!linkedInOrganizationId) {
3054
+ throw new Error(
3055
+ "La variable de entorno LINKEDIN_ORGANIZATION_ID no está configurada."
3056
+ );
3057
+ }
3058
+ try {
3059
+ const article = await strapi.documents("api::articulo.articulo").findOne({
3060
+ documentId: articleId,
3061
+ populate: {
3062
+ image: true
3063
+ }
3064
+ });
3065
+ if (!article) {
3066
+ throw new Error(`Artículo con ID ${articleId} no encontrado.`);
3067
+ }
3068
+ const postBody = {
3069
+ author: `urn:li:organization:${linkedInOrganizationId}`,
3070
+ lifecycleState: "PUBLISHED",
3071
+ specificContent: {
3072
+ "com.linkedin.ugc.ShareContent": {
3073
+ shareCommentary: {
3074
+ text: `${article.titulo}
3075
+
3076
+ ${article.descripcion}`
3077
+ },
3078
+ shareMediaCategory: "ARTICLE",
3079
+ media: [
3080
+ {
3081
+ status: "READY",
3082
+ originalUrl: `https://interware.com.mx/blog/${article.slug}`,
3083
+ title: {
3084
+ text: article.titulo
3085
+ },
3086
+ description: {
3087
+ text: article.descripcion
3088
+ }
3089
+ }
3090
+ ]
3091
+ }
3092
+ },
3093
+ visibility: {
3094
+ "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
3095
+ }
3096
+ };
3097
+ const response = await axios.post(
3098
+ "https://api.linkedin.com/v2/ugcPosts",
3099
+ postBody,
3100
+ {
3101
+ headers: {
3102
+ Authorization: `Bearer ${linkedInAccessToken}`,
3103
+ "Content-Type": "application/json",
3104
+ "X-Restli-Protocol-Version": "2.0.0"
3105
+ }
3106
+ }
3107
+ );
3108
+ strapi.log.info("Successfully published to LinkedIn:", JSON.stringify(response.data));
3109
+ await strapi.documents("api::articulo.articulo").update({
3110
+ documentId: articleId,
3111
+ data: {
3112
+ linkedInPostId: response.data.id
3113
+ }
3114
+ });
3115
+ return {
3116
+ message: "Publicado en LinkedIn correctamente.",
3117
+ linkedinResponse: response.data
3118
+ };
3119
+ } catch (error) {
3120
+ console.error(
3121
+ "Error al publicar en LinkedIn:",
3122
+ error.response ? error.response.data : error.message
3123
+ );
3124
+ throw new Error("Error al publicar en LinkedIn.");
3125
+ }
3126
+ },
3127
+ async publishToFacebook(ctx) {
3128
+ const { articleId } = ctx.request.body;
3129
+ console.log("Publishing to Facebook (not implemented):", articleId);
3130
+ return { message: "Publicación en Facebook no implementada aún." };
3131
+ }
3132
+ };
3133
+ };
3134
+ const services = {
3135
+ service
3136
+ };
3137
+ const index = {
3138
+ register,
3139
+ bootstrap,
3140
+ destroy,
3141
+ config: config$1,
3142
+ controllers,
3143
+ routes,
3144
+ services,
3145
+ contentTypes,
3146
+ policies,
3147
+ middlewares
3148
+ };
3149
+ module.exports = index;