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