@interware/content-generator 0.4.4 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +21 -1
  2. package/dist/_chunks/{App-BQr5_g5u.mjs → App-DPVBu7QB.mjs} +37 -726
  3. package/dist/_chunks/{App-CfwvfmvL.js → App-DVTFrZvf.js} +31 -720
  4. package/dist/_chunks/ImageStudioTabs-B2UbKYq7.js +5299 -0
  5. package/dist/_chunks/ImageStudioTabs-mlNL6aQ2.mjs +5298 -0
  6. package/dist/_chunks/Settings-DziRY70a.js +155 -0
  7. package/dist/_chunks/Settings-RrBQdijj.mjs +155 -0
  8. package/dist/_chunks/StudioApp-AUyPNhh2.mjs +17 -0
  9. package/dist/_chunks/StudioApp-Cswkzh7F.js +17 -0
  10. package/dist/_chunks/{getTranslation-DNhP1INv.js → getTranslation-D88uLXGd.js} +1 -1
  11. package/dist/_chunks/{getTranslation-B9ND5RaH.mjs → getTranslation-DfxaP_TC.mjs} +1 -1
  12. package/dist/_chunks/{index-Dyq8dxMX.mjs → index-CqDdi211.mjs} +25 -7
  13. package/dist/_chunks/{index-DGPqyrzz.js → index-Ddp0Qvqo.js} +24 -6
  14. package/dist/admin/index.js +1 -1
  15. package/dist/admin/index.mjs +1 -1
  16. package/dist/admin/src/components/PluginIcon.d.ts +4 -2
  17. package/dist/admin/src/components/PluginProviders.d.ts +8 -0
  18. package/dist/admin/src/components/generate-video/Form.d.ts +1 -1
  19. package/dist/admin/src/components/settings/Form.d.ts +4 -5
  20. package/dist/admin/src/containers/settings/index.d.ts +7 -7
  21. package/dist/admin/src/features/background-removal/RemoveBackgroundButton.d.ts +7 -0
  22. package/dist/admin/src/features/background-removal/RemoveBackgroundDialog.d.ts +15 -0
  23. package/dist/admin/src/features/background-removal/colorKey.d.ts +29 -0
  24. package/dist/admin/src/features/background-removal/imageCanvas.d.ts +20 -0
  25. package/dist/admin/src/features/background-removal/mask.d.ts +10 -0
  26. package/dist/admin/src/features/background-removal/runtime.d.ts +31 -0
  27. package/dist/admin/src/features/generator/EditEmpty.d.ts +13 -0
  28. package/dist/admin/src/features/generator/GeneratorTab.d.ts +7 -0
  29. package/dist/admin/src/features/generator/GroundingSources.d.ts +9 -0
  30. package/dist/admin/src/features/generator/ModeSwitch.d.ts +6 -0
  31. package/dist/admin/src/features/generator/PromptComposer.d.ts +25 -0
  32. package/dist/admin/src/features/generator/ReferencePicker.d.ts +26 -0
  33. package/dist/admin/src/features/generator/VersionHistory.d.ts +13 -0
  34. package/dist/admin/src/features/generator/generatorApi.d.ts +71 -0
  35. package/dist/admin/src/features/generator/model.d.ts +60 -0
  36. package/dist/admin/src/features/generator/useGeneratorApi.d.ts +21 -0
  37. package/dist/admin/src/features/image-studio/ImageStudioTabs.d.ts +26 -0
  38. package/dist/admin/src/features/image-studio/SegmentedSwitch.d.ts +18 -0
  39. package/dist/admin/src/features/image-studio/checkerboard.d.ts +5 -0
  40. package/dist/admin/src/features/library/FileCard.d.ts +17 -0
  41. package/dist/admin/src/features/library/FolderTree.d.ts +14 -0
  42. package/dist/admin/src/features/library/LibraryDialogs.d.ts +46 -0
  43. package/dist/admin/src/features/library/LibraryImagePicker.d.ts +15 -0
  44. package/dist/admin/src/features/library/LibraryTab.d.ts +2 -0
  45. package/dist/admin/src/features/library/SaveToLibraryDialog.d.ts +15 -0
  46. package/dist/admin/src/features/library/model.d.ts +40 -0
  47. package/dist/admin/src/features/library/studioRoot.d.ts +11 -0
  48. package/dist/admin/src/features/library/uploadApi.d.ts +77 -0
  49. package/dist/admin/src/features/library/useLibraryApi.d.ts +34 -0
  50. package/dist/admin/src/features/templates/editor/ColorField.d.ts +11 -0
  51. package/dist/admin/src/features/templates/editor/Editor.d.ts +19 -0
  52. package/dist/admin/src/features/templates/editor/EditorBar.d.ts +9 -0
  53. package/dist/admin/src/features/templates/editor/EditorMenuBar.d.ts +58 -0
  54. package/dist/admin/src/features/templates/editor/EditorToolbar.d.ts +20 -0
  55. package/dist/admin/src/features/templates/editor/ElementPalette.d.ts +10 -0
  56. package/dist/admin/src/features/templates/editor/FloatingPanel.d.ts +17 -0
  57. package/dist/admin/src/features/templates/editor/FullscreenView.d.ts +11 -0
  58. package/dist/admin/src/features/templates/editor/IconPicker.d.ts +9 -0
  59. package/dist/admin/src/features/templates/editor/Inspector.d.ts +17 -0
  60. package/dist/admin/src/features/templates/editor/LayersPanel.d.ts +12 -0
  61. package/dist/admin/src/features/templates/editor/Precision.d.ts +23 -0
  62. package/dist/admin/src/features/templates/editor/RangeField.d.ts +12 -0
  63. package/dist/admin/src/features/templates/editor/SaveTemplateDialog.d.ts +14 -0
  64. package/dist/admin/src/features/templates/editor/Stage.d.ts +29 -0
  65. package/dist/admin/src/features/templates/editor/TemplateFolderSelect.d.ts +9 -0
  66. package/dist/admin/src/features/templates/editor/TemplatePicker.d.ts +23 -0
  67. package/dist/admin/src/features/templates/editor/TemplatesTab.d.ts +5 -0
  68. package/dist/admin/src/features/templates/editor/TypographyControls.d.ts +24 -0
  69. package/dist/admin/src/features/templates/editor/icons.d.ts +7 -0
  70. package/dist/admin/src/features/templates/editor/overlays.d.ts +20 -0
  71. package/dist/admin/src/features/templates/editor/useCanvasNav.d.ts +25 -0
  72. package/dist/admin/src/features/templates/editor/useFitScale.d.ts +3 -0
  73. package/dist/admin/src/features/templates/export/fontEmbed.d.ts +22 -0
  74. package/dist/admin/src/features/templates/export/imageSource.d.ts +21 -0
  75. package/dist/admin/src/features/templates/export/pdf.d.ts +6 -0
  76. package/dist/admin/src/features/templates/export/render.d.ts +22 -0
  77. package/dist/admin/src/features/templates/export/useEditorIO.d.ts +18 -0
  78. package/dist/admin/src/features/templates/fonts/catalog.d.ts +47 -0
  79. package/dist/admin/src/features/templates/fonts/customFonts.d.ts +19 -0
  80. package/dist/admin/src/features/templates/fonts/useCustomFonts.d.ts +9 -0
  81. package/dist/admin/src/features/templates/fonts/useFonts.d.ts +2 -0
  82. package/dist/admin/src/features/templates/model/drag.d.ts +10 -0
  83. package/dist/admin/src/features/templates/model/editorReducer.d.ts +58 -0
  84. package/dist/admin/src/features/templates/model/layers.d.ts +42 -0
  85. package/dist/admin/src/features/templates/model/palette.d.ts +38 -0
  86. package/dist/admin/src/features/templates/model/presets.d.ts +17 -0
  87. package/dist/admin/src/features/templates/model/shortcuts.d.ts +19 -0
  88. package/dist/admin/src/features/templates/model/snap.d.ts +24 -0
  89. package/dist/admin/src/features/templates/model/templates.d.ts +8 -0
  90. package/dist/admin/src/features/templates/model/types.d.ts +154 -0
  91. package/dist/admin/src/features/templates/model/viewport.d.ts +36 -0
  92. package/dist/admin/src/features/templates/render/IWLogo.d.ts +7 -0
  93. package/dist/admin/src/features/templates/render/LayerCanvas.d.ts +13 -0
  94. package/dist/admin/src/features/templates/render/fonts.d.ts +5 -0
  95. package/dist/admin/src/features/templates/render/icons.d.ts +10 -0
  96. package/dist/admin/src/features/templates/render/renderLayer.d.ts +9 -0
  97. package/dist/admin/src/features/templates/store/persist.d.ts +41 -0
  98. package/dist/admin/src/features/templates/store/templatesApi.d.ts +49 -0
  99. package/dist/admin/src/features/templates/store/useMyTemplates.d.ts +19 -0
  100. package/dist/admin/src/features/templates/store/useTemplateSaving.d.ts +14 -0
  101. package/dist/admin/src/features/templates/store/useTemplatesApi.d.ts +23 -0
  102. package/dist/admin/src/hooks/useAdminTheme.d.ts +8 -0
  103. package/dist/admin/src/hooks/useThemeColors.d.ts +9 -0
  104. package/dist/admin/src/lib/dataUrl.d.ts +6 -0
  105. package/dist/admin/src/lib/promptRules.d.ts +23 -0
  106. package/dist/admin/src/lib/use-cases/articles/index.d.ts +12 -1
  107. package/dist/admin/src/lib/use-cases/categories/index.d.ts +12 -1
  108. package/dist/admin/src/lib/use-cases/facebook/index.d.ts +1 -1
  109. package/dist/admin/src/lib/use-cases/generate-content/index.d.ts +2 -2
  110. package/dist/admin/src/lib/use-cases/images/index.d.ts +1 -4
  111. package/dist/admin/src/lib/use-cases/linkedin/index.d.ts +1 -1
  112. package/dist/admin/src/lib/use-cases/settings/index.d.ts +13 -2
  113. package/dist/admin/src/lib/use-cases/users/index.d.ts +12 -1
  114. package/dist/admin/src/pages/ImageStudio.d.ts +3 -0
  115. package/dist/admin/src/pages/StudioApp.d.ts +3 -0
  116. package/dist/admin/src/pluginId.d.ts +6 -0
  117. package/dist/admin/src/test-setup.d.ts +1 -0
  118. package/dist/admin/src/test-utils.d.ts +5 -0
  119. package/dist/server/index.js +2408 -1261
  120. package/dist/server/index.mjs +2415 -1267
  121. package/dist/server/src/bootstrap.d.ts +1 -1
  122. package/dist/server/src/content-types/index.d.ts +66 -1
  123. package/dist/server/src/content-types/template/index.d.ts +65 -0
  124. package/dist/server/src/content-types/template/schema.d.ts +69 -0
  125. package/dist/server/src/controllers/config.d.ts +2 -0
  126. package/dist/server/src/controllers/controller.d.ts +0 -5
  127. package/dist/server/src/controllers/image-studio.d.ts +23 -0
  128. package/dist/server/src/controllers/index.d.ts +128 -5
  129. package/dist/server/src/controllers/templates.d.ts +26 -0
  130. package/dist/server/src/image-studio/geminiConfig.d.ts +40 -0
  131. package/dist/server/src/image-studio/models.d.ts +38 -0
  132. package/dist/server/src/image-studio/prompt.d.ts +7 -0
  133. package/dist/server/src/image-studio/validate.d.ts +41 -0
  134. package/dist/server/src/index.d.ts +229 -75
  135. package/dist/server/src/routes/admin.d.ts +6 -2
  136. package/dist/server/src/routes/content-api.d.ts +4 -9
  137. package/dist/server/src/routes/index.d.ts +7 -11
  138. package/dist/server/src/routes/policies.d.ts +14 -0
  139. package/dist/server/src/services/image-studio.d.ts +62 -0
  140. package/dist/server/src/services/index.d.ts +27 -57
  141. package/dist/server/src/services/service.d.ts +0 -57
  142. package/dist/server/src/services/templates.d.ts +81 -0
  143. package/dist/server/src/templates/folders.d.ts +14 -0
  144. package/dist/server/src/templates/validate.d.ts +23 -0
  145. package/dist/server/src/utils/folders.d.ts +15 -0
  146. package/dist/server/src/utils/secrets.d.ts +9 -0
  147. package/package.json +22 -10
  148. package/static/background-worker.d.mts +15 -0
  149. package/static/background-worker.mjs +87 -0
  150. package/dist/_chunks/Settings-BrqTzJp-.js +0 -262
  151. package/dist/_chunks/Settings-CdZnYLLK.mjs +0 -244
  152. package/dist/admin/src/components/Navigation.d.ts +0 -2
  153. package/dist/admin/src/components/generate-image/Form.d.ts +0 -15
  154. package/dist/admin/src/components/generate-images/Image.d.ts +0 -5
  155. package/dist/admin/src/components/generate-images/Images.d.ts +0 -2
  156. package/dist/admin/src/components/generate-images/Modal.d.ts +0 -9
  157. package/dist/admin/src/containers/generate-image/index.d.ts +0 -2
  158. package/dist/admin/src/containers/generate-images/index.d.ts +0 -2
  159. package/dist/admin/src/hooks/generate-images/useImages.d.ts +0 -12
  160. package/dist/admin/src/pages/GenerateImage.d.ts +0 -2
  161. package/dist/admin/src/pages/GenerateImages.d.ts +0 -2
@@ -1,7 +1,29 @@
1
- import { VideoGenerationReferenceType, Modality, GoogleGenAI } from "@google/genai";
2
1
  import * as fs from "fs";
2
+ import { promises } from "fs";
3
+ import { HarmCategory, PersonGeneration, Modality, HarmBlockThreshold, VideoGenerationReferenceType, GoogleGenAI } from "@google/genai";
3
4
  const PLUGIN_ID = "strapi-content-generator-gemini";
4
- const bootstrap = ({ strapi }) => {
5
+ const FOLDER_UID = "plugin::upload.folder";
6
+ const hasValidPath = (path) => /^(\/\d+)+$/.test(path);
7
+ const repairFolderPaths = async (strapi, name2) => {
8
+ const query = strapi.db.query(FOLDER_UID);
9
+ const folders = await query.findMany({ where: { name: name2 }, populate: ["parent"] });
10
+ const repaired = [];
11
+ for (const f of folders) {
12
+ if (hasValidPath(f.path)) continue;
13
+ const to = `${f.parent?.path ?? ""}/${f.pathId}`;
14
+ await query.update({ where: { id: f.id }, data: { path: to } });
15
+ repaired.push({ id: f.id, from: f.path, to });
16
+ }
17
+ return repaired;
18
+ };
19
+ const ensureFolder = async (strapi, name2) => {
20
+ const folders = await strapi.db.query(FOLDER_UID).findMany({ where: { name: name2 }, populate: ["parent"] });
21
+ const atRoot = folders.find((f) => !f.parent);
22
+ if (atRoot) return atRoot.id;
23
+ const created = await strapi.plugin("upload").service("folder").create({ name: name2, parent: null });
24
+ return created.id;
25
+ };
26
+ const bootstrap = async ({ strapi }) => {
5
27
  strapi.admin.services.permission.actionProvider.registerMany([
6
28
  {
7
29
  section: "plugins",
@@ -10,17 +32,56 @@ const bootstrap = ({ strapi }) => {
10
32
  pluginName: PLUGIN_ID
11
33
  }
12
34
  ]);
35
+ try {
36
+ for (const r of await repairFolderPaths(strapi, "Generated")) {
37
+ strapi.log.info(`[content-generator] path de carpeta ${r.id} corregido: ${r.from} → ${r.to}`);
38
+ }
39
+ } catch (err) {
40
+ strapi.log.warn(`[content-generator] no se pudo revisar el path de «Generated»: ${err.message}`);
41
+ }
13
42
  };
14
43
  const destroy = ({ strapi }) => {
15
44
  };
16
45
  const register = ({ strapi }) => {
17
46
  };
18
- const config$1 = {
47
+ const config$2 = {
19
48
  default: {},
20
49
  validator() {
21
50
  }
22
51
  };
23
- const contentTypes = {};
52
+ const schema = {
53
+ kind: "collectionType",
54
+ collectionName: "iw_image_templates",
55
+ info: {
56
+ singularName: "template",
57
+ pluralName: "templates",
58
+ displayName: "Template de imagen",
59
+ description: "Templates del Estudio de imágenes (content-generator)"
60
+ },
61
+ options: { draftAndPublish: false },
62
+ pluginOptions: {
63
+ "content-manager": { visible: false },
64
+ "content-type-builder": { visible: false }
65
+ },
66
+ attributes: {
67
+ name: { type: "string", required: true, maxLength: 120 },
68
+ folder: { type: "string", default: "" },
69
+ width: { type: "integer", required: true },
70
+ height: { type: "integer", required: true },
71
+ background: { type: "string", default: "#FFFFFF" },
72
+ safeMargin: { type: "integer", default: 0 },
73
+ gridUnit: { type: "integer", default: 60 },
74
+ layers: { type: "json", required: true },
75
+ /** Base de la que se copió (origen). */
76
+ baseId: { type: "string" },
77
+ /** Si está, esta fila es la versión editada de esa plantilla base (S4.15): una por base. */
78
+ replacesBase: { type: "string" }
79
+ }
80
+ };
81
+ const template = { schema };
82
+ const contentTypes = {
83
+ template
84
+ };
24
85
  const controller = ({ strapi }) => {
25
86
  const pluginService = () => strapi.plugin("strapi-content-generator-gemini").service("service");
26
87
  return {
@@ -75,39 +136,12 @@ const controller = ({ strapi }) => {
75
136
  auth: ctx.state.auth
76
137
  });
77
138
  },
78
- async getImages(ctx) {
79
- const contentType = strapi.contentType("plugin::upload.file");
80
- const files = await pluginService().getImagenes();
81
- return await strapi.contentAPI.sanitize.output(files, contentType, {
82
- auth: ctx.state.auth
83
- });
84
- },
85
- async deleteImage(ctx) {
86
- const contentType = strapi.contentType("plugin::upload.file");
87
- await strapi.contentAPI.validate.query(ctx.query, contentType, {
88
- auth: ctx.state.auth
89
- });
90
- const sanitizedQueryParams = await strapi.contentAPI.sanitize.query(
91
- ctx.query,
92
- contentType,
93
- {
94
- auth: ctx.state.auth
95
- }
96
- );
97
- const file = await pluginService().eliminarImagen(sanitizedQueryParams);
98
- return await strapi.contentAPI.sanitize.output(file, contentType, {
99
- auth: ctx.state.auth
100
- });
101
- },
102
139
  async generateArticle(ctx) {
103
140
  ctx.body = await pluginService().generateArticle(ctx);
104
141
  },
105
142
  async generateImageForArticle(ctx) {
106
143
  ctx.body = await pluginService().generateImageForArticle(ctx);
107
144
  },
108
- async generateImage(ctx) {
109
- ctx.body = await pluginService().generateImage(ctx);
110
- },
111
145
  async downloadFile(ctx) {
112
146
  await pluginService().downloadFile(ctx);
113
147
  },
@@ -119,195 +153,719 @@ const controller = ({ strapi }) => {
119
153
  },
120
154
  async publishToFacebook(ctx) {
121
155
  ctx.body = await pluginService().publishToFacebook(ctx);
122
- },
123
- async get(ctx) {
124
- const pluginStore = strapi.store({
125
- type: "plugin",
126
- name: "strapi-content-generator-gemini"
127
- });
128
- const googleGenAI = await pluginStore.get({ key: "GOOGLE_GEN_AI" });
129
- const clientURL = await pluginStore.get({ key: "CLIENT_URL" });
130
- const previewSecret = await pluginStore.get({ key: "PREVIEW_SECRET" });
131
- ctx.body = { googleGenAI, clientURL, previewSecret };
132
- },
133
- async set(ctx) {
134
- const { key1, key2, key3 } = ctx.request.body;
135
- const pluginStore = strapi.store({
136
- type: "plugin",
137
- name: "strapi-content-generator-gemini"
138
- });
139
- await pluginStore.set({ key: "GOOGLE_GEN_AI", value: key1 });
140
- await pluginStore.set({ key: "CLIENT_URL", value: key2 });
141
- await pluginStore.set({ key: "PREVIEW_SECRET", value: key3 });
142
- ctx.body = { ok: true };
143
156
  }
144
157
  };
145
158
  };
146
- const config = ({ strapi }) => {
159
+ const maskSecret = (value) => {
160
+ if (typeof value !== "string" || value.length === 0) {
161
+ return { configured: false, last4: null };
162
+ }
163
+ return { configured: true, last4: value.slice(-4) };
164
+ };
165
+ const CREDENTIALS = {
166
+ googleGenAI: "GOOGLE_GEN_AI",
167
+ linkedInAccessToken: "LINKEDIN_ACCESS_TOKEN",
168
+ linkedInOrganizationId: "LINKEDIN_ORGANIZATION_ID",
169
+ facebookClientToken: "FACEBOOK_CLIENT_TOKEN",
170
+ facebookPageId: "FACEBOOK_PAGE_ID"
171
+ };
172
+ const FIELDS$1 = Object.keys(CREDENTIALS);
173
+ const config$1 = ({ strapi }) => {
174
+ const pluginStore = () => strapi.store({
175
+ type: "plugin",
176
+ name: "strapi-content-generator-gemini"
177
+ });
147
178
  return {
179
+ /** Devuelve si cada credencial está guardada y sus últimos 4 caracteres, nunca el valor. */
148
180
  async get(ctx) {
149
- const pluginStore = strapi.store({
150
- type: "plugin",
151
- name: "strapi-content-generator-gemini"
152
- });
153
- const googleGenAI = await pluginStore.get({ key: "GOOGLE_GEN_AI" });
154
- const linkedInAccessToken = await pluginStore.get({ key: "LINKEDIN_ACCESS_TOKEN" });
155
- const linkedInOrganizationId = await pluginStore.get({ key: "LINKEDIN_ORGANIZATION_ID" });
156
- const facebookClientToken = await pluginStore.get({ key: "FACEBOOK_CLIENT_TOKEN" });
157
- const facebookPageId = await pluginStore.get({ key: "FACEBOOK_PAGE_ID" });
158
- ctx.body = { googleGenAI, linkedInAccessToken, linkedInOrganizationId, facebookClientToken, facebookPageId };
181
+ const store = pluginStore();
182
+ const entries = await Promise.all(
183
+ FIELDS$1.map(async (field) => [field, maskSecret(await store.get({ key: CREDENTIALS[field] }))])
184
+ );
185
+ ctx.body = Object.fromEntries(entries);
159
186
  },
187
+ /** Escribe solo las credenciales conocidas que llegan como texto no vacío. */
160
188
  async set(ctx) {
161
- const { googleGenAI, linkedInAccessToken, linkedInOrganizationId, facebookClientToken, facebookPageId } = ctx.request.body;
162
- const pluginStore = strapi.store({
163
- type: "plugin",
164
- name: "strapi-content-generator-gemini"
165
- });
166
- await pluginStore.set({ key: "GOOGLE_GEN_AI", value: googleGenAI });
167
- await pluginStore.set({ key: "LINKEDIN_ACCESS_TOKEN", value: linkedInAccessToken });
168
- await pluginStore.set({ key: "LINKEDIN_ORGANIZATION_ID", value: linkedInOrganizationId });
169
- await pluginStore.set({ key: "FACEBOOK_CLIENT_TOKEN", value: facebookClientToken });
170
- await pluginStore.set({ key: "FACEBOOK_PAGE_ID", value: facebookPageId });
189
+ const body = ctx.request.body ?? {};
190
+ const store = pluginStore();
191
+ for (const field of FIELDS$1) {
192
+ const value = body[field];
193
+ if (typeof value === "string" && value.length > 0) {
194
+ await store.set({ key: CREDENTIALS[field], value });
195
+ }
196
+ }
171
197
  ctx.body = { ok: true };
172
198
  }
173
199
  };
174
200
  };
175
- const controllers = {
176
- controller,
177
- config
201
+ const PEOPLE_CLAUSE = "STRICTLY NO people, NO humans, NO faces, NO hands.";
202
+ const HARM_CATEGORIES = [
203
+ HarmCategory.HARM_CATEGORY_HARASSMENT,
204
+ HarmCategory.HARM_CATEGORY_HATE_SPEECH,
205
+ HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
206
+ HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT
207
+ ];
208
+ const safetySettings = (safety) => HARM_CATEGORIES.map((category) => ({
209
+ category,
210
+ threshold: safety ? HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE : HarmBlockThreshold.BLOCK_ONLY_HIGH
211
+ }));
212
+ const PEOPLE = {
213
+ none: "ALLOW_NONE",
214
+ adults: PersonGeneration.ALLOW_ADULT
178
215
  };
179
- const middlewares = {};
180
- const policies = {};
181
- const admin = [
182
- {
183
- method: "GET",
184
- path: "/posts",
185
- handler: "controller.getArticles",
186
- config: {
187
- policies: [],
188
- auth: false
189
- }
190
- },
191
- {
192
- method: "GET",
193
- path: "/categories",
194
- handler: "controller.getCategories",
195
- config: {
196
- policies: [],
197
- auth: false
216
+ const imageConfig = ({ aspectRatio, imageSize, allowPeople }, backend = "gemini-api") => ({
217
+ ...aspectRatio ? { aspectRatio } : {},
218
+ ...imageSize ? { imageSize } : {},
219
+ ...backend === "vertex" ? { personGeneration: allowPeople ? PEOPLE.adults : PEOPLE.none } : {}
220
+ });
221
+ const promptPart = (text2, allowPeople, backend = "gemini-api") => ({
222
+ text: backend === "gemini-api" && !allowPeople ? `${text2} ${PEOPLE_CLAUSE}` : text2
223
+ });
224
+ const searchTool = () => ({ googleSearch: { searchTypes: { webSearch: {}, imageSearch: {} } } });
225
+ const generateConfig = ({ aspectRatio, imageSize, allowPeople, safety, grounding }, backend = "gemini-api") => ({
226
+ // Con búsqueda el modelo responde texto e imagen.
227
+ responseModalities: grounding ? [Modality.TEXT, Modality.IMAGE] : [Modality.IMAGE],
228
+ imageConfig: imageConfig({ aspectRatio, imageSize, allowPeople }, backend),
229
+ safetySettings: safetySettings(safety),
230
+ ...grounding ? { tools: [searchTool()] } : {}
231
+ });
232
+ const editConfig = ({ safety, allowPeople, aspectRatio }, backend = "gemini-api") => ({
233
+ responseModalities: [Modality.IMAGE],
234
+ imageConfig: imageConfig({ aspectRatio, allowPeople }, backend),
235
+ safetySettings: safetySettings(safety)
236
+ });
237
+ const inlinePart = (bytes, mimeType) => ({ inlineData: { mimeType, data: bytes.toString("base64") } });
238
+ const RATIOS = ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"];
239
+ const FLASH_RATIOS = [...RATIOS, "1:4", "4:1", "1:8", "8:1"];
240
+ const FLASH = { maxReferences: 6, sizes: ["512", "1K", "2K", "4K"], aspectRatios: FLASH_RATIOS, canEdit: true, grounding: true };
241
+ const FLASH_LITE = { maxReferences: 6, sizes: ["512", "1K"], aspectRatios: RATIOS, canEdit: true, grounding: false };
242
+ const PRO = { maxReferences: 6, sizes: ["1K", "2K", "4K"], aspectRatios: RATIOS, canEdit: true, grounding: false };
243
+ const IMAGE_MODELS = [
244
+ { id: "gemini-3.1-flash-image", label: "Nano Banana 2", ...FLASH },
245
+ { id: "gemini-3.1-flash-image-preview", label: "Nano Banana 2 (preview)", ...FLASH },
246
+ { id: "gemini-3.1-flash-lite-image", label: "Nano Banana 2 Lite", ...FLASH_LITE },
247
+ { id: "gemini-3.1-flash-lite-image-preview", label: "Nano Banana 2 Lite (preview)", ...FLASH_LITE },
248
+ { id: "gemini-3-pro-image", label: "Nano Banana Pro", ...PRO },
249
+ { id: "gemini-3-pro-image-preview", label: "Nano Banana Pro (preview)", ...PRO },
250
+ { id: "gemini-2.5-flash-image", label: "Nano Banana (legado)", maxReferences: 3, sizes: [], aspectRatios: RATIOS, canEdit: true, grounding: false }
251
+ ];
252
+ const findModel = (id) => IMAGE_MODELS.find((m) => m.id === id);
253
+ const availableModels = (listed) => {
254
+ if (!listed) return { models: IMAGE_MODELS, verified: false };
255
+ const ids = new Set(listed.map((n) => n.replace(/^models\//, "")));
256
+ const models = IMAGE_MODELS.filter((m) => ids.has(m.id) && !(m.id.endsWith("-preview") && ids.has(m.id.replace(/-preview$/, ""))));
257
+ return models.length ? { models, verified: true } : { models: IMAGE_MODELS, verified: false };
258
+ };
259
+ const editModelFor = (id) => {
260
+ const chosen = findModel(id);
261
+ if (chosen?.canEdit) return chosen;
262
+ return IMAGE_MODELS.find((m) => m.canEdit);
263
+ };
264
+ const PROMPT_MAX = 2e3;
265
+ const CONTROL = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g;
266
+ const INVISIBLE = /[­​-‏‪-‮⁠-⁤⁦-⁩]/g;
267
+ const TAG = /<\/?[a-z][^>]*>/gi;
268
+ const sanitizePrompt = (text2) => text2.normalize("NFC").replace(CONTROL, "").replace(INVISIBLE, "").replace(TAG, "").replace(/\s+/g, " ").trim();
269
+ const PROMPT_LABELS = { label: "El prompt", empty: "Escribe un prompt." };
270
+ const INSTRUCTION_LABELS = { label: "La instrucción", empty: "Describe el cambio que quieres." };
271
+ const checkPrompt = (text2, { label, empty } = PROMPT_LABELS) => {
272
+ const clean2 = sanitizePrompt(text2);
273
+ if (!clean2) return { ok: false, error: empty };
274
+ if ([...clean2].length > PROMPT_MAX) return { ok: false, error: `${label} puede tener hasta ${PROMPT_MAX} caracteres.` };
275
+ return { ok: true, text: clean2 };
276
+ };
277
+ const cleanPrompt = sanitizePrompt;
278
+ const EXPAND_INSTRUCTION = (concept) => [
279
+ "Eres experto en prompts para generadores de imágenes con IA.",
280
+ "Expande y mejora este concepto con sujeto, composición, estilo, iluminación y color.",
281
+ "Responde solo con el prompt mejorado, en español, sin explicaciones, comillas ni viñetas.",
282
+ `Concepto: ${concept}`
283
+ ].join("\n");
284
+ class BlockedError extends Error {
285
+ }
286
+ const sourceOf = (chunk) => {
287
+ if (chunk.web?.uri) return { title: chunk.web.title || new URL(chunk.web.uri).hostname, uri: chunk.web.uri };
288
+ const img = chunk.image;
289
+ if (img?.sourceUri) return { title: img.title || img.domain || new URL(img.sourceUri).hostname, uri: img.sourceUri };
290
+ return null;
291
+ };
292
+ const groundingFrom = (res) => {
293
+ const meta = res.candidates?.[0]?.groundingMetadata;
294
+ const sources = (meta?.groundingChunks ?? []).map(sourceOf).filter((src) => src !== null).filter((src, i, all3) => all3.findIndex((o) => o.title === src.title) === i);
295
+ const queries = [.../* @__PURE__ */ new Set([...meta?.webSearchQueries ?? [], ...meta?.imageSearchQueries ?? []])];
296
+ const suggestions = meta?.searchEntryPoint?.renderedContent;
297
+ if (!sources.length && !queries.length && !suggestions) return void 0;
298
+ return { ...suggestions ? { suggestions } : {}, queries, sources };
299
+ };
300
+ const EXPAND_MODEL = "gemini-2.5-flash";
301
+ const BLOCK_REASONS = {
302
+ SAFETY: "El modelo bloqueó la solicitud por seguridad. Ajusta el prompt o la imagen.",
303
+ PROHIBITED_CONTENT: "El modelo bloqueó la solicitud por contenido no permitido.",
304
+ IMAGE_SAFETY: "El modelo bloqueó la imagen resultante por seguridad."
305
+ };
306
+ const imageFrom = (res, model) => {
307
+ const parts = res.candidates?.[0]?.content?.parts ?? [];
308
+ const part = parts.find((p) => p.inlineData?.data && (p.inlineData.mimeType ?? "").startsWith("image/"));
309
+ if (part?.inlineData?.data) return { image: part.inlineData.data, mimeType: part.inlineData.mimeType ?? "image/png", model };
310
+ const reason = res.promptFeedback?.blockReason ?? res.candidates?.[0]?.finishReason;
311
+ throw new BlockedError(BLOCK_REASONS[String(reason)] ?? "El modelo no devolvió una imagen. Intenta con otro prompt.");
312
+ };
313
+ const inline = async (file, read) => inlinePart(await read(file.filepath), file.mimetype ?? "image/png");
314
+ const userTurn = (parts) => [{ role: "user", parts }];
315
+ const createImageStudio = (getModels, read = (p) => promises.readFile(p), backend = "gemini-api") => ({
316
+ async models() {
317
+ try {
318
+ const api = await getModels();
319
+ const names = [];
320
+ for await (const m of await api.list({ config: { pageSize: 100 } })) if (m.name) names.push(m.name);
321
+ return availableModels(names);
322
+ } catch {
323
+ return availableModels(null);
198
324
  }
199
325
  },
200
- {
201
- method: "GET",
202
- path: "/users",
203
- handler: "controller.getUsers",
204
- config: {
205
- policies: [],
206
- auth: false
207
- }
326
+ /**
327
+ * Imagen para un artículo (S4.12): antes usaba Imagen 4, que Google apagó. Usa el primer modelo
328
+ * disponible del catálogo y ajusta proporción y tamaño a lo que admite. Devuelve base64.
329
+ */
330
+ async generateForArticle(prompt, aspectRatio, imageSize) {
331
+ const [model] = (await this.models()).models;
332
+ const { image } = await this.generate({
333
+ prompt,
334
+ model,
335
+ aspectRatio: model.aspectRatios.includes(aspectRatio) ? aspectRatio : "16:9",
336
+ imageSize: model.sizes.includes(imageSize) ? imageSize : void 0,
337
+ safety: true,
338
+ // El estilo de marca de los artículos no lleva personas (su JSON ya lo pide); ahora también el parámetro.
339
+ allowPeople: false,
340
+ grounding: false,
341
+ references: []
342
+ });
343
+ return image;
208
344
  },
209
- {
210
- method: "GET",
211
- path: "/images",
212
- handler: "controller.getImages",
213
- config: {
214
- policies: [],
215
- auth: false
216
- }
345
+ async generate(input) {
346
+ const api = await getModels();
347
+ const text2 = cleanPrompt(input.prompt);
348
+ const { model } = input;
349
+ const refs = await Promise.all(input.references.map((f) => inline(f, read)));
350
+ const request = {
351
+ model: model.id,
352
+ contents: userTurn([promptPart(text2, input.allowPeople, backend), ...refs]),
353
+ config: generateConfig(input, backend)
354
+ };
355
+ const res = await api.generateContent(request);
356
+ const image = imageFrom(res, model.id);
357
+ const grounding = input.grounding ? groundingFrom(res) : void 0;
358
+ return grounding ? { ...image, grounding } : image;
217
359
  },
218
- {
219
- method: "DELETE",
220
- path: "/delete-image",
221
- handler: "controller.deleteImage",
222
- config: {
223
- policies: [],
224
- auth: false
225
- }
360
+ async edit(input) {
361
+ const api = await getModels();
362
+ const parts = [
363
+ await inline(input.image, read),
364
+ ...await Promise.all(input.references.map((f) => inline(f, read))),
365
+ promptPart(input.instruction, input.allowPeople, backend)
366
+ ];
367
+ const request = { model: input.model.id, contents: userTurn(parts), config: editConfig(input, backend) };
368
+ const res = await api.generateContent(request);
369
+ return imageFrom(res, input.model.id);
226
370
  },
227
- {
228
- method: "POST",
229
- path: "/download-file",
230
- handler: "controller.downloadFile",
231
- config: {
232
- policies: [],
233
- auth: false
371
+ async expand(prompt) {
372
+ const api = await getModels();
373
+ const res = await api.generateContent({ model: EXPAND_MODEL, contents: EXPAND_INSTRUCTION(cleanPrompt(prompt)) });
374
+ const text2 = (res.text ?? "").trim().replace(/^["'«“]+|["'»”]+$/g, "").trim();
375
+ if (!text2) throw new BlockedError("No se pudo expandir la idea. Intenta de nuevo.");
376
+ return text2;
377
+ }
378
+ });
379
+ const imageStudio$1 = ({ strapi }) => createImageStudio(async () => (await strapi.plugin("strapi-content-generator-gemini").service("service").geminiConfig()).models);
380
+ class InputError extends Error {
381
+ }
382
+ const ALLOWED = ["image/png", "image/jpeg", "image/webp"];
383
+ const MAX_BYTES = 10 * 1024 * 1024;
384
+ const str = (v) => typeof v === "string" ? v : "";
385
+ const bool = (v) => v === true || v === "true";
386
+ const list = (v) => v ? Array.isArray(v) ? v : [v] : [];
387
+ const clean = (text2, labels) => {
388
+ const r = checkPrompt(text2, labels);
389
+ if ("error" in r) throw new InputError(r.error);
390
+ return r.text;
391
+ };
392
+ const checkImage = (f) => {
393
+ if (!ALLOWED.includes(f.mimetype ?? "")) throw new InputError("Las imágenes deben ser PNG, JPG o WEBP.");
394
+ if (f.size > MAX_BYTES) throw new InputError("Cada imagen puede pesar hasta 10 MB.");
395
+ return f;
396
+ };
397
+ const parseGenerateInput = (fields, files) => {
398
+ const prompt = clean(str(fields.prompt));
399
+ const model = findModel(str(fields.model));
400
+ if (!model) throw new InputError("Modelo no disponible.");
401
+ const aspectRatio = str(fields.aspectRatio) || "1:1";
402
+ if (!model.aspectRatios.includes(aspectRatio)) throw new InputError(`Proporción no disponible para ${model.label}.`);
403
+ const references = list(files.references).map(checkImage);
404
+ if (references.length && model.maxReferences === 0) throw new InputError(`${model.label} no acepta imágenes de referencia.`);
405
+ if (references.length > model.maxReferences) throw new InputError(`Máximo ${model.maxReferences} imágenes de referencia con ${model.label}.`);
406
+ const size2 = str(fields.imageSize);
407
+ return {
408
+ prompt,
409
+ model,
410
+ aspectRatio,
411
+ imageSize: model.sizes.includes(size2) ? size2 : void 0,
412
+ safety: fields.safety === void 0 ? true : bool(fields.safety),
413
+ allowPeople: bool(fields.allowPeople),
414
+ grounding: model.grounding && bool(fields.grounding),
415
+ references
416
+ };
417
+ };
418
+ const parseEditInput = (fields, files) => {
419
+ const instruction = clean(str(fields.instruction), INSTRUCTION_LABELS);
420
+ const [image] = list(files.image);
421
+ if (!image) throw new InputError("Falta la imagen a editar.");
422
+ const model = editModelFor(str(fields.model) || void 0);
423
+ const max = Math.max(0, model.maxReferences - 1);
424
+ const references = list(files.references).map(checkImage);
425
+ if (references.length > max) throw new InputError(`Máximo ${max} elementos para el cambio con ${model.label}.`);
426
+ return {
427
+ instruction,
428
+ model,
429
+ image: checkImage(image),
430
+ references,
431
+ // Sin los campos (clientes anteriores a S4.13): con seguridad y sin excluir personas, como antes.
432
+ safety: fields.safety === void 0 ? true : bool(fields.safety),
433
+ allowPeople: fields.allowPeople === void 0 ? true : bool(fields.allowPeople),
434
+ aspectRatio: model.aspectRatios.includes(str(fields.aspectRatio)) ? str(fields.aspectRatio) : void 0
435
+ };
436
+ };
437
+ const fail$2 = (ctx, status, name2, message) => {
438
+ ctx.status = status;
439
+ ctx.body = { data: null, error: { status, name: name2, message } };
440
+ };
441
+ const imageStudio = ({ strapi }) => {
442
+ const studio = () => strapi.plugin("strapi-content-generator-gemini").service("image-studio");
443
+ const run = async (ctx, work) => {
444
+ try {
445
+ ctx.body = await work();
446
+ } catch (err) {
447
+ if (err instanceof InputError) return fail$2(ctx, 400, "BadRequestError", err.message);
448
+ if (err instanceof BlockedError) return fail$2(ctx, 422, "UnprocessableEntityError", err.message);
449
+ strapi.log.error(`[image-studio] ${err instanceof Error ? err.message : String(err)}`);
450
+ return fail$2(ctx, 502, "BadGatewayError", "El servicio de imágenes no respondió. Intenta de nuevo en un momento.");
234
451
  }
235
- },
452
+ };
453
+ return {
454
+ models: (ctx) => run(ctx, () => studio().models()),
455
+ generate: (ctx) => run(ctx, () => studio().generate(parseGenerateInput(ctx.request.body ?? {}, ctx.request.files ?? {}))),
456
+ edit: (ctx) => run(ctx, () => studio().edit(parseEditInput(ctx.request.body ?? {}, ctx.request.files ?? {}))),
457
+ expand: (ctx) => run(ctx, async () => {
458
+ const raw = typeof ctx.request.body?.prompt === "string" ? ctx.request.body.prompt : "";
459
+ const prompt = clean(raw, { label: "La idea", empty: "Escribe una idea para expandir." });
460
+ return { prompt: await studio().expand(prompt) };
461
+ })
462
+ };
463
+ };
464
+ const NAVY = "#1F2A44";
465
+ const RED = "#E4002B";
466
+ const TEAL = "#00C7B1";
467
+ const GREY = "#5B6473";
468
+ const PAPER = "#EEF1F5";
469
+ const WHITE = "#FFFFFF";
470
+ const WHITE_75 = "rgba(255,255,255,0.75)";
471
+ const WHITE_60 = "rgba(255,255,255,0.6)";
472
+ const WHITE_20 = "rgba(255,255,255,0.2)";
473
+ const BASE_TEMPLATES = [
236
474
  {
237
- method: "POST",
238
- path: "/generate-article",
239
- handler: "controller.generateArticle",
240
- config: {
241
- policies: [],
242
- auth: false
243
- }
475
+ id: "cuadrado_01",
476
+ name: "Cuadrado 01",
477
+ category: "Redes sociales",
478
+ tag: "1:1",
479
+ width: 1080,
480
+ height: 1080,
481
+ background: PAPER,
482
+ safeMargin: 80,
483
+ gridUnit: 60,
484
+ layers: [
485
+ { id: "logo", type: "logo", label: "Logo", x: 80, y: 80, color: NAVY, logoScale: 1.1 },
486
+ { id: "titulo", type: "text", label: "Título", x: 80, y: 280, w: 920, content: "Orquestación digital para empresas", fontSize: 90, fontWeight: 800, color: NAVY, font: "display", lineHeight: 1.08, letterSpacing: "-0.02em" },
487
+ { id: "divider", type: "rect", label: "Divisor", x: 80, y: 530, w: 420, h: 3, color: RED },
488
+ { id: "cuerpo", type: "text", label: "Cuerpo", x: 80, y: 580, w: 700, content: "29 años integrando, modernizando y operando los sistemas de las empresas en México.", fontSize: 36, fontWeight: 500, color: NAVY, lineHeight: 1.5 }
489
+ ]
244
490
  },
245
491
  {
246
- method: "POST",
247
- path: "/generate-image",
248
- handler: "controller.generateImageForArticle",
249
- config: {
250
- policies: [],
251
- auth: false
252
- }
492
+ id: "cuadrado_dark",
493
+ name: "Cuadrado Dark",
494
+ category: "Redes sociales",
495
+ tag: "1:1",
496
+ width: 1080,
497
+ height: 1080,
498
+ background: NAVY,
499
+ safeMargin: 80,
500
+ gridUnit: 60,
501
+ layers: [
502
+ { id: "accent_top", type: "rect", label: "Acento superior", x: 0, y: 0, w: 1080, h: 6, color: RED },
503
+ { id: "watermark", type: "logo", label: "Marca de agua", x: 600, y: 700, color: WHITE, logoScale: 2.6, opacity: 0.1 },
504
+ { id: "logo", type: "logo", label: "Logo", x: 80, y: 86, color: WHITE, logoScale: 1.1 },
505
+ { id: "titulo", type: "text", label: "Título", x: 80, y: 280, w: 920, content: "Detectamos y resolvemos fallas antes de que lleguen a tu cliente", fontSize: 78, fontWeight: 800, color: WHITE, font: "display", lineHeight: 1.08, letterSpacing: "-0.02em" },
506
+ { id: "divider", type: "rect", label: "Divisor", x: 80, y: 560, w: 360, h: 3, color: TEAL },
507
+ { id: "cuerpo", type: "text", label: "Cuerpo", x: 80, y: 610, w: 700, content: "Observabilidad y operación continua para sistemas de misión crítica.", fontSize: 34, fontWeight: 500, color: WHITE_75, lineHeight: 1.5 }
508
+ ]
253
509
  },
254
510
  {
255
- method: "POST",
256
- path: "/generate-image-with-config",
257
- handler: "controller.generateImage",
258
- config: {
259
- policies: [],
260
- auth: false
261
- }
511
+ id: "horizontal_01",
512
+ name: "Horizontal 01",
513
+ category: "Web / Blog",
514
+ tag: "16:9",
515
+ width: 1920,
516
+ height: 1080,
517
+ background: PAPER,
518
+ safeMargin: 100,
519
+ gridUnit: 80,
520
+ layers: [
521
+ { id: "right_panel", type: "rect", label: "Panel derecho", x: 1056, y: 0, w: 864, h: 1080, color: NAVY },
522
+ { id: "watermark", type: "logo", label: "Marca de agua", x: 1100, y: 200, color: WHITE, logoScale: 8, opacity: 0.08 },
523
+ { id: "logo", type: "logo", label: "Logo", x: 100, y: 100, color: NAVY, logoScale: 1.3 },
524
+ { id: "subtitulo", type: "text", label: "Subtítulo", x: 100, y: 600, w: 900, content: "Perspectivas para líderes de TI", fontSize: 28, fontWeight: 700, color: RED, textTransform: "uppercase", letterSpacing: "0.06em" },
525
+ { id: "titulo", type: "text", label: "Título", x: 100, y: 660, w: 900, content: "Evolución por continuidad", fontSize: 96, fontWeight: 800, color: NAVY, font: "display", lineHeight: 1, letterSpacing: "-0.02em" },
526
+ { id: "divider", type: "rect", label: "Divisor", x: 100, y: 880, w: 300, h: 4, color: NAVY },
527
+ { id: "url", type: "text", label: "URL", x: 100, y: 990, w: 800, content: "interware.com.mx", fontSize: 22, fontWeight: 500, color: GREY },
528
+ { id: "logo_right", type: "logo", label: "Logo derecho", x: 1700, y: 990, color: WHITE_60, logoScale: 1.5 }
529
+ ]
262
530
  },
263
531
  {
264
- method: "POST",
265
- path: "/generate-video-with-scenes",
266
- handler: "controller.generateVideo",
267
- config: {
268
- policies: [],
269
- auth: false
270
- }
532
+ id: "story_01",
533
+ name: "Story / Reels",
534
+ category: "Redes sociales",
535
+ tag: "9:16",
536
+ width: 1080,
537
+ height: 1920,
538
+ background: NAVY,
539
+ safeMargin: 80,
540
+ gridUnit: 80,
541
+ layers: [
542
+ { id: "watermark", type: "logo", label: "Marca de agua", x: 700, y: -40, color: WHITE, logoScale: 7, opacity: 0.06, rotate: -15 },
543
+ { id: "accent", type: "rect", label: "Acento superior", x: 0, y: 0, w: 1080, h: 8, color: TEAL },
544
+ { id: "logo", type: "logo", label: "Logo", x: 80, y: 60, color: WHITE, logoScale: 1.1 },
545
+ { id: "line", type: "rect", label: "Línea", x: 80, y: 672, w: 60, h: 5, color: TEAL },
546
+ { id: "titulo", type: "text", label: "Título", x: 80, y: 720, w: 920, content: "Tu operación, orquestada", fontSize: 100, fontWeight: 800, color: WHITE, font: "display", lineHeight: 1.05, letterSpacing: "-0.02em" },
547
+ { id: "cta", type: "badge", label: "CTA", x: 80, y: 1670, content: "Conoce más →", paddingX: 32, paddingY: 16, bg: WHITE, fontSize: 34, fontWeight: 700, color: NAVY }
548
+ ]
271
549
  },
272
550
  {
273
- method: "POST",
274
- path: "/publish-linkedin",
275
- handler: "controller.publishToLinkedIn",
276
- config: {
277
- policies: [],
278
- auth: false
279
- }
551
+ id: "blog_hero",
552
+ name: "Blog Hero",
553
+ category: "Web / Blog",
554
+ tag: "~2:1",
555
+ width: 1200,
556
+ height: 630,
557
+ background: PAPER,
558
+ safeMargin: 72,
559
+ gridUnit: 60,
560
+ layers: [
561
+ { id: "strip", type: "rect", label: "Franja izquierda", x: 0, y: 0, w: 8, h: 630, color: RED },
562
+ { id: "logo", type: "logo", label: "Logo", x: 80, y: 72, color: NAVY, logoScale: 1 },
563
+ { id: "categoria", type: "badge", label: "Categoría", x: 900, y: 72, content: "Infraestructura", paddingX: 18, paddingY: 8, bg: NAVY, fontSize: 22, fontWeight: 700, color: WHITE, textTransform: "uppercase", letterSpacing: "0.06em" },
564
+ { id: "titulo", type: "text", label: "Título", x: 80, y: 300, w: 1040, content: "La deuda técnica también se paga en horas de operación", fontSize: 60, fontWeight: 800, color: NAVY, font: "display", lineHeight: 1.1, letterSpacing: "-0.02em" },
565
+ { id: "divider", type: "rect", label: "Divisor", x: 80, y: 475, w: 200, h: 3, color: RED },
566
+ { id: "autor", type: "text", label: "Autor", x: 80, y: 500, w: 800, content: "Por el equipo de InterWare", fontSize: 24, fontWeight: 600, color: GREY }
567
+ ]
280
568
  },
281
569
  {
282
- method: "POST",
283
- path: "/publish-facebook",
284
- handler: "controller.publishToFacebook",
285
- config: {
286
- policies: [],
287
- auth: false
288
- }
570
+ id: "linkedin_banner",
571
+ name: "LinkedIn Banner",
572
+ category: "LinkedIn",
573
+ tag: "4:1",
574
+ width: 1584,
575
+ height: 396,
576
+ background: NAVY,
577
+ safeMargin: 60,
578
+ gridUnit: 60,
579
+ layers: [
580
+ { id: "watermark", type: "logo", label: "Marca de agua", x: 1100, y: -40, color: WHITE, logoScale: 9, opacity: 0.05 },
581
+ { id: "strip", type: "rect", label: "Franja", x: 0, y: 0, w: 6, h: 396, color: TEAL, gradient: `linear-gradient(to bottom, ${TEAL}, ${NAVY})` },
582
+ { id: "logo", type: "logo", label: "Logo", x: 60, y: 150, color: WHITE, logoScale: 1.4 },
583
+ { id: "vdivider", type: "rect", label: "Divisor vertical", x: 320, y: 158, w: 2, h: 80, color: WHITE_20 },
584
+ { id: "nombre", type: "text", label: "Nombre", x: 360, y: 140, w: 1100, content: "InterWare de México", fontSize: 44, fontWeight: 800, color: WHITE, font: "display", letterSpacing: "-0.01em" },
585
+ { id: "tagline", type: "text", label: "Tagline", x: 360, y: 200, w: 1100, content: "Orquestación digital para empresas", fontSize: 26, fontWeight: 500, color: WHITE_60 }
586
+ ]
289
587
  }
290
588
  ];
291
- const contentApi = [
292
- {
293
- method: "GET",
294
- path: "/config",
295
- handler: "config.get",
296
- config: {
297
- policies: [],
298
- auth: false
589
+ new Set(BASE_TEMPLATES.map((t) => t.id));
590
+ const cleanPath = (path) => path.split("/").map((s) => s.trim()).filter(Boolean).join("/");
591
+ const parentOf = (path) => path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
592
+ const isUnder = (path, base) => path === base || path.startsWith(`${base}/`);
593
+ const renamePath = (path, from, to) => isUnder(path, from) ? to + path.slice(from.length) : path;
594
+ const folderTree = (paths) => {
595
+ const all3 = /* @__PURE__ */ new Set();
596
+ for (const p of paths.map(cleanPath).filter(Boolean)) {
597
+ let cur = p;
598
+ while (cur) {
599
+ all3.add(cur);
600
+ cur = parentOf(cur);
299
601
  }
300
- },
301
- {
302
- method: "POST",
303
- path: "/config",
304
- handler: "config.set",
305
- config: {
306
- policies: [],
307
- auth: false
602
+ }
603
+ return [...all3].sort((a, b) => a.localeCompare(b, "es"));
604
+ };
605
+ class TemplateInputError extends Error {
606
+ }
607
+ const LAYER_TYPES = ["text", "list", "quote", "rect", "shape", "badge", "logo", "image", "icon", "avatar", "qr"];
608
+ const MAX_LAYERS = 200;
609
+ const fail$1 = (message) => {
610
+ throw new TemplateInputError(message);
611
+ };
612
+ const hasDataUrl = (value) => {
613
+ if (typeof value === "string") return value.startsWith("data:");
614
+ if (Array.isArray(value)) return value.some(hasDataUrl);
615
+ if (value && typeof value === "object") return Object.values(value).some(hasDataUrl);
616
+ return false;
617
+ };
618
+ const name = (v) => {
619
+ const n = typeof v === "string" ? v.trim() : "";
620
+ if (!n || n.length > 120) fail$1("El nombre debe tener entre 1 y 120 caracteres.");
621
+ return n;
622
+ };
623
+ const size = (v) => {
624
+ if (!Number.isInteger(v) || v < 100 || v > 4e3) fail$1("Las medidas deben ser enteros de 100 a 4000 px.");
625
+ return v;
626
+ };
627
+ const nonNegative = (v, label) => {
628
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0) fail$1(`${label} debe ser un número positivo.`);
629
+ return v;
630
+ };
631
+ const layers = (v) => {
632
+ if (!Array.isArray(v) || v.length > MAX_LAYERS) fail$1(`Las capas deben ser una lista de hasta ${MAX_LAYERS}.`);
633
+ v.forEach((l, i) => {
634
+ const layer = l ?? {};
635
+ if (typeof layer.id !== "string" || !layer.id) fail$1(`La capa ${i + 1} no tiene id.`);
636
+ if (!LAYER_TYPES.includes(layer.type)) fail$1(`La capa ${i + 1} tiene un tipo desconocido.`);
637
+ if (typeof layer.x !== "number" || typeof layer.y !== "number") fail$1(`La capa ${i + 1} no tiene posición.`);
638
+ });
639
+ if (hasDataUrl(v)) fail$1("Las imágenes deben guardarse en la Media Library, no dentro del template.");
640
+ return v;
641
+ };
642
+ const text = (v, fallback) => typeof v === "string" ? v : fallback;
643
+ const validateTemplate = (input) => {
644
+ const t = input ?? {};
645
+ const out = {
646
+ name: name(t.name),
647
+ folder: cleanPath(text(t.folder, "")),
648
+ width: size(t.width),
649
+ height: size(t.height),
650
+ background: text(t.background, "#FFFFFF"),
651
+ safeMargin: nonNegative(t.safeMargin ?? 0, "El margen seguro"),
652
+ gridUnit: nonNegative(t.gridUnit ?? 60, "La cuadrícula"),
653
+ layers: layers(t.layers)
654
+ };
655
+ if (typeof t.baseId === "string" && t.baseId) out.baseId = t.baseId;
656
+ return out;
657
+ };
658
+ const validateTemplatePatch = (input) => {
659
+ const t = input ?? {};
660
+ const out = {};
661
+ if ("name" in t) out.name = name(t.name);
662
+ if ("folder" in t) out.folder = cleanPath(text(t.folder, ""));
663
+ if ("width" in t) out.width = size(t.width);
664
+ if ("height" in t) out.height = size(t.height);
665
+ if ("background" in t) out.background = text(t.background, "#FFFFFF");
666
+ if ("safeMargin" in t) out.safeMargin = nonNegative(t.safeMargin, "El margen seguro");
667
+ if ("gridUnit" in t) out.gridUnit = nonNegative(t.gridUnit, "La cuadrícula");
668
+ if ("layers" in t) out.layers = layers(t.layers);
669
+ if (!Object.keys(out).length) fail$1("Nada que actualizar.");
670
+ return out;
671
+ };
672
+ const TEMPLATE_UID = "plugin::strapi-content-generator-gemini.template";
673
+ const FOLDERS_KEY = "TEMPLATE_FOLDERS";
674
+ class TemplateNotFoundError extends Error {
675
+ }
676
+ const FIELDS = ["name", "folder", "width", "height", "background", "safeMargin", "gridUnit", "layers", "baseId", "replacesBase"];
677
+ const BASE_IDS = new Set(BASE_TEMPLATES.map((t) => t.id));
678
+ const checkBaseId = (baseId) => {
679
+ if (typeof baseId !== "string" || !BASE_IDS.has(baseId)) throw new TemplateInputError("Plantilla base desconocida.");
680
+ return baseId;
681
+ };
682
+ const toStored = (d) => {
683
+ const out = { documentId: d.documentId, updatedAt: d.updatedAt };
684
+ for (const f of FIELDS) if (d[f] !== void 0 && d[f] !== null) out[f] = d[f];
685
+ out.folder = typeof d.folder === "string" ? d.folder : "";
686
+ return out;
687
+ };
688
+ const createTemplatesService = (docs, store) => {
689
+ const all3 = async () => (await docs.findMany({})).map(toStored);
690
+ const storedFolders = async () => {
691
+ const v = await store.get({ key: FOLDERS_KEY });
692
+ return Array.isArray(v) ? v : [];
693
+ };
694
+ const saveFolders = (folders) => store.set({ key: FOLDERS_KEY, value: folderTree(folders) });
695
+ const tree = async () => folderTree([...await storedFolders(), ...(await all3()).map((t) => t.folder)]);
696
+ const mustExist = async (documentId) => {
697
+ const d = await docs.findOne({ documentId });
698
+ if (!d) throw new TemplateNotFoundError("El template no existe o fue eliminado.");
699
+ return d;
700
+ };
701
+ const moveTemplates = async (path, to) => {
702
+ for (const t of await all3()) {
703
+ if (isUnder(t.folder, path)) await docs.update({ documentId: t.documentId, data: { folder: to(t.folder) } });
704
+ }
705
+ };
706
+ return {
707
+ async list() {
708
+ return (await all3()).sort((a, b) => a.name.localeCompare(b.name, "es", { sensitivity: "base" }));
709
+ },
710
+ async findOne(documentId) {
711
+ return toStored(await mustExist(documentId));
712
+ },
713
+ async create(input) {
714
+ return toStored(await docs.create({ data: validateTemplate(input) }));
715
+ },
716
+ async update(documentId, patch) {
717
+ const data = validateTemplatePatch(patch);
718
+ await mustExist(documentId);
719
+ return toStored(await docs.update({ documentId, data }));
720
+ },
721
+ async remove(documentId) {
722
+ await mustExist(documentId);
723
+ await docs.delete({ documentId });
724
+ },
725
+ /**
726
+ * Guarda la versión editada de una plantilla base (S4.15): la crea la primera vez y después la
727
+ * actualiza. Vive en la raíz y conserva la base como origen.
728
+ */
729
+ async saveBase(baseId, input) {
730
+ const id = checkBaseId(baseId);
731
+ const data = { ...validateTemplate(input), folder: "", baseId: id, replacesBase: id };
732
+ const current = (await all3()).find((t) => t.replacesBase === id);
733
+ return toStored(current ? await docs.update({ documentId: current.documentId, data }) : await docs.create({ data }));
734
+ },
735
+ /** Vuelve a la versión de InterWare: borra la editada, si existe. */
736
+ async restoreBase(baseId) {
737
+ const id = checkBaseId(baseId);
738
+ const current = (await all3()).find((t) => t.replacesBase === id);
739
+ if (current) await docs.delete({ documentId: current.documentId });
740
+ },
741
+ folders: tree,
742
+ async createFolder(path) {
743
+ const p = cleanPath(typeof path === "string" ? path : "");
744
+ if (!p) throw new TemplateInputError("Escribe el nombre de la carpeta.");
745
+ if ((await tree()).includes(p)) throw new TemplateInputError("Ya existe una carpeta con ese nombre.");
746
+ await saveFolders([...await storedFolders(), p]);
747
+ return tree();
748
+ },
749
+ async renameFolder(from, to) {
750
+ const src = cleanPath(typeof from === "string" ? from : "");
751
+ const dst = cleanPath(typeof to === "string" ? to : "");
752
+ if (!src || !dst) throw new TemplateInputError("Indica la carpeta y su nombre nuevo.");
753
+ if (src === dst) return tree();
754
+ const current = await tree();
755
+ if (!current.includes(src)) throw new TemplateInputError("La carpeta no existe.");
756
+ if (current.includes(dst) || isUnder(dst, src)) throw new TemplateInputError("Ya existe una carpeta con ese nombre.");
757
+ await saveFolders(current.map((p) => renamePath(p, src, dst)));
758
+ await moveTemplates(src, (f) => renamePath(f, src, dst));
759
+ return tree();
760
+ },
761
+ async deleteFolder(path) {
762
+ const p = cleanPath(typeof path === "string" ? path : "");
763
+ if (!p) throw new TemplateInputError("No se puede eliminar la raíz.");
764
+ const target = parentOf(p);
765
+ await saveFolders((await tree()).filter((f) => !isUnder(f, p)));
766
+ await moveTemplates(p, () => target);
767
+ return tree();
768
+ }
769
+ };
770
+ };
771
+ const templates$1 = ({ strapi }) => {
772
+ const docs = () => strapi.documents(TEMPLATE_UID);
773
+ const store = () => strapi.store({ type: "plugin", name: "strapi-content-generator-gemini" });
774
+ return createTemplatesService(
775
+ {
776
+ findMany: (p) => docs().findMany(p),
777
+ findOne: (p) => docs().findOne(p),
778
+ create: (p) => docs().create(p),
779
+ update: (p) => docs().update(p),
780
+ delete: (p) => docs().delete(p)
781
+ },
782
+ { get: (p) => store().get(p), set: (p) => store().set(p) }
783
+ );
784
+ };
785
+ const fail = (ctx, status, name2, message) => {
786
+ ctx.status = status;
787
+ ctx.body = { data: null, error: { status, name: name2, message } };
788
+ };
789
+ const templates = ({ strapi }) => {
790
+ const svc = () => strapi.plugin("strapi-content-generator-gemini").service("templates");
791
+ const run = async (ctx, work, status = 200) => {
792
+ try {
793
+ ctx.body = await work();
794
+ ctx.status = status;
795
+ } catch (err) {
796
+ if (err instanceof TemplateInputError) return fail(ctx, 400, "BadRequestError", err.message);
797
+ if (err instanceof TemplateNotFoundError) return fail(ctx, 404, "NotFoundError", err.message);
798
+ strapi.log.error(`[templates] ${err instanceof Error ? err.message : String(err)}`);
799
+ return fail(ctx, 500, "InternalServerError", "No se pudo completar la operación con los templates.");
308
800
  }
801
+ };
802
+ const body = (ctx) => ctx.request.body ?? {};
803
+ return {
804
+ list: (ctx) => run(ctx, async () => ({ templates: await svc().list() })),
805
+ create: (ctx) => run(ctx, () => svc().create(body(ctx)), 201),
806
+ findOne: (ctx) => run(ctx, () => svc().findOne(ctx.params.documentId)),
807
+ update: (ctx) => run(ctx, () => svc().update(ctx.params.documentId, body(ctx))),
808
+ remove: (ctx) => run(ctx, async () => {
809
+ await svc().remove(ctx.params.documentId);
810
+ return { ok: true };
811
+ }),
812
+ saveBase: (ctx) => run(ctx, () => svc().saveBase(ctx.params.baseId, body(ctx))),
813
+ restoreBase: (ctx) => run(ctx, async () => {
814
+ await svc().restoreBase(ctx.params.baseId);
815
+ return { ok: true };
816
+ }),
817
+ folders: (ctx) => run(ctx, async () => ({ folders: await svc().folders() })),
818
+ createFolder: (ctx) => run(ctx, async () => ({ folders: await svc().createFolder(body(ctx).path) })),
819
+ renameFolder: (ctx) => run(ctx, async () => ({ folders: await svc().renameFolder(body(ctx).from, body(ctx).to) })),
820
+ deleteFolder: (ctx) => run(ctx, async () => ({ folders: await svc().deleteFolder(body(ctx).path) }))
821
+ };
822
+ };
823
+ const controllers = {
824
+ controller,
825
+ config: config$1,
826
+ "image-studio": imageStudio,
827
+ templates
828
+ };
829
+ const middlewares = {};
830
+ const policies = {};
831
+ const ACCESS_ACTION = "plugin::strapi-content-generator-gemini.access";
832
+ const ADMIN_ACCESS_POLICIES = [
833
+ "admin::isAuthenticatedAdmin",
834
+ {
835
+ name: "admin::hasPermissions",
836
+ config: { actions: [ACCESS_ACTION] }
309
837
  }
310
838
  ];
839
+ const config = { policies: ADMIN_ACCESS_POLICIES };
840
+ const admin = [
841
+ { method: "GET", path: "/posts", handler: "controller.getArticles", config },
842
+ { method: "GET", path: "/categories", handler: "controller.getCategories", config },
843
+ { method: "GET", path: "/users", handler: "controller.getUsers", config },
844
+ { method: "POST", path: "/download-file", handler: "controller.downloadFile", config },
845
+ { method: "POST", path: "/generate-article", handler: "controller.generateArticle", config },
846
+ { method: "POST", path: "/generate-image", handler: "controller.generateImageForArticle", config },
847
+ { method: "GET", path: "/image-studio/models", handler: "image-studio.models", config },
848
+ { method: "POST", path: "/image-studio/generate", handler: "image-studio.generate", config },
849
+ { method: "POST", path: "/image-studio/edit", handler: "image-studio.edit", config },
850
+ { method: "POST", path: "/image-studio/expand", handler: "image-studio.expand", config },
851
+ { method: "POST", path: "/generate-video-with-scenes", handler: "controller.generateVideo", config },
852
+ { method: "POST", path: "/publish-linkedin", handler: "controller.publishToLinkedIn", config },
853
+ { method: "POST", path: "/publish-facebook", handler: "controller.publishToFacebook", config },
854
+ { method: "GET", path: "/templates", handler: "templates.list", config },
855
+ { method: "POST", path: "/templates", handler: "templates.create", config },
856
+ { method: "GET", path: "/templates/:documentId", handler: "templates.findOne", config },
857
+ { method: "PUT", path: "/templates/:documentId", handler: "templates.update", config },
858
+ { method: "DELETE", path: "/templates/:documentId", handler: "templates.remove", config },
859
+ { method: "PUT", path: "/templates/base/:baseId", handler: "templates.saveBase", config },
860
+ { method: "DELETE", path: "/templates/base/:baseId", handler: "templates.restoreBase", config },
861
+ { method: "GET", path: "/template-folders", handler: "templates.folders", config },
862
+ { method: "POST", path: "/template-folders", handler: "templates.createFolder", config },
863
+ { method: "POST", path: "/template-folders/rename", handler: "templates.renameFolder", config },
864
+ { method: "POST", path: "/template-folders/delete", handler: "templates.deleteFolder", config },
865
+ { method: "GET", path: "/config", handler: "config.get", config },
866
+ { method: "POST", path: "/config", handler: "config.set", config }
867
+ ];
868
+ const contentApi = [];
311
869
  const routes = {
312
870
  "content-api": {
313
871
  type: "content-api",
@@ -326,9 +884,26 @@ function bind(fn, thisArg) {
326
884
  const { toString } = Object.prototype;
327
885
  const { getPrototypeOf } = Object;
328
886
  const { iterator, toStringTag } = Symbol;
887
+ const hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
888
+ const hasOwnInPrototypeChain = (thing, prop) => {
889
+ let obj = thing;
890
+ const seen = [];
891
+ while (obj != null && obj !== Object.prototype) {
892
+ if (seen.indexOf(obj) !== -1) {
893
+ return false;
894
+ }
895
+ seen.push(obj);
896
+ if (hasOwnProperty(obj, prop)) {
897
+ return true;
898
+ }
899
+ obj = getPrototypeOf(obj);
900
+ }
901
+ return false;
902
+ };
903
+ const getSafeProp = (obj, prop) => obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : void 0;
329
904
  const kindOf = /* @__PURE__ */ ((cache) => (thing) => {
330
- const str = toString.call(thing);
331
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
905
+ const str2 = toString.call(thing);
906
+ return cache[str2] || (cache[str2] = str2.slice(8, -1).toLowerCase());
332
907
  })(/* @__PURE__ */ Object.create(null));
333
908
  const kindOfTest = (type) => {
334
909
  type = type.toLowerCase();
@@ -356,11 +931,14 @@ const isNumber = typeOfTest("number");
356
931
  const isObject = (thing) => thing !== null && typeof thing === "object";
357
932
  const isBoolean = (thing) => thing === true || thing === false;
358
933
  const isPlainObject = (val) => {
359
- if (kindOf(val) !== "object") {
934
+ if (!isObject(val)) {
360
935
  return false;
361
936
  }
362
937
  const prototype2 = getPrototypeOf(val);
363
- return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(toStringTag in val) && !(iterator in val);
938
+ return (prototype2 === null || prototype2 === Object.prototype || getPrototypeOf(prototype2) === null) && // Treat any genuine (non-Object.prototype-polluted) Symbol.toStringTag or
939
+ // Symbol.iterator as evidence the value is a tagged/iterable type rather
940
+ // than a plain object, while ignoring keys injected onto Object.prototype.
941
+ !hasOwnInPrototypeChain(val, toStringTag) && !hasOwnInPrototypeChain(val, iterator);
364
942
  };
365
943
  const isEmptyObject = (val) => {
366
944
  if (!isObject(val) || isBuffer(val)) {
@@ -374,17 +952,42 @@ const isEmptyObject = (val) => {
374
952
  };
375
953
  const isDate = kindOfTest("Date");
376
954
  const isFile = kindOfTest("File");
955
+ const isReactNativeBlob = (value) => {
956
+ return !!(value && typeof value.uri !== "undefined");
957
+ };
958
+ const isReactNative = (formData) => formData && typeof formData.getParts !== "undefined";
377
959
  const isBlob = kindOfTest("Blob");
378
960
  const isFileList = kindOfTest("FileList");
379
961
  const isStream = (val) => isObject(val) && isFunction$1(val.pipe);
962
+ function getGlobal() {
963
+ if (typeof globalThis !== "undefined") return globalThis;
964
+ if (typeof self !== "undefined") return self;
965
+ if (typeof window !== "undefined") return window;
966
+ if (typeof global !== "undefined") return global;
967
+ return {};
968
+ }
969
+ const G = getGlobal();
970
+ const FormDataCtor = typeof G.FormData !== "undefined" ? G.FormData : void 0;
380
971
  const isFormData = (thing) => {
381
- let kind;
382
- return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction$1(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
383
- kind === "object" && isFunction$1(thing.toString) && thing.toString() === "[object FormData]"));
972
+ if (!thing) return false;
973
+ if (FormDataCtor && thing instanceof FormDataCtor) return true;
974
+ const proto = getPrototypeOf(thing);
975
+ if (!proto || proto === Object.prototype) return false;
976
+ if (!isFunction$1(thing.append)) return false;
977
+ const kind = kindOf(thing);
978
+ return kind === "formdata" || // detect form-data instance
979
+ kind === "object" && isFunction$1(thing.toString) && thing.toString() === "[object FormData]";
384
980
  };
385
981
  const isURLSearchParams = kindOfTest("URLSearchParams");
386
- const [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
387
- const trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
982
+ const [isReadableStream, isRequest, isResponse, isHeaders] = [
983
+ "ReadableStream",
984
+ "Request",
985
+ "Response",
986
+ "Headers"
987
+ ].map(kindOfTest);
988
+ const trim = (str2) => {
989
+ return str2.trim ? str2.trim() : str2.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
990
+ };
388
991
  function forEach(obj, fn, { allOwnKeys = false } = {}) {
389
992
  if (obj === null || typeof obj === "undefined") {
390
993
  return;
@@ -432,13 +1035,17 @@ const _global = (() => {
432
1035
  return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
433
1036
  })();
434
1037
  const isContextDefined = (context) => !isUndefined(context) && context !== _global;
435
- function merge() {
1038
+ function merge(...objs) {
436
1039
  const { caseless, skipUndefined } = isContextDefined(this) && this || {};
437
1040
  const result = {};
438
1041
  const assignValue = (val, key) => {
439
- const targetKey = caseless && findKey(result, key) || key;
440
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
441
- result[targetKey] = merge(result[targetKey], val);
1042
+ if (key === "__proto__" || key === "constructor" || key === "prototype") {
1043
+ return;
1044
+ }
1045
+ const targetKey = caseless && typeof key === "string" && findKey(result, key) || key;
1046
+ const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : void 0;
1047
+ if (isPlainObject(existing) && isPlainObject(val)) {
1048
+ result[targetKey] = merge(existing, val);
442
1049
  } else if (isPlainObject(val)) {
443
1050
  result[targetKey] = merge({}, val);
444
1051
  } else if (isArray(val)) {
@@ -447,19 +1054,51 @@ function merge() {
447
1054
  result[targetKey] = val;
448
1055
  }
449
1056
  };
450
- for (let i = 0, l = arguments.length; i < l; i++) {
451
- arguments[i] && forEach(arguments[i], assignValue);
1057
+ for (let i = 0, l = objs.length; i < l; i++) {
1058
+ const source = objs[i];
1059
+ if (!source || isBuffer(source)) {
1060
+ continue;
1061
+ }
1062
+ forEach(source, assignValue);
1063
+ if (typeof source !== "object" || isArray(source)) {
1064
+ continue;
1065
+ }
1066
+ const symbols = Object.getOwnPropertySymbols(source);
1067
+ for (let j = 0; j < symbols.length; j++) {
1068
+ const symbol = symbols[j];
1069
+ if (propertyIsEnumerable.call(source, symbol)) {
1070
+ assignValue(source[symbol], symbol);
1071
+ }
1072
+ }
452
1073
  }
453
1074
  return result;
454
1075
  }
455
1076
  const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
456
- forEach(b, (val, key) => {
457
- if (thisArg && isFunction$1(val)) {
458
- a[key] = bind(val, thisArg);
459
- } else {
460
- a[key] = val;
461
- }
462
- }, { allOwnKeys });
1077
+ forEach(
1078
+ b,
1079
+ (val, key) => {
1080
+ if (thisArg && isFunction$1(val)) {
1081
+ Object.defineProperty(a, key, {
1082
+ // Null-proto descriptor so a polluted Object.prototype.get cannot
1083
+ // hijack defineProperty's accessor-vs-data resolution.
1084
+ __proto__: null,
1085
+ value: bind(val, thisArg),
1086
+ writable: true,
1087
+ enumerable: true,
1088
+ configurable: true
1089
+ });
1090
+ } else {
1091
+ Object.defineProperty(a, key, {
1092
+ __proto__: null,
1093
+ value: val,
1094
+ writable: true,
1095
+ enumerable: true,
1096
+ configurable: true
1097
+ });
1098
+ }
1099
+ },
1100
+ { allOwnKeys }
1101
+ );
463
1102
  return a;
464
1103
  };
465
1104
  const stripBOM = (content) => {
@@ -468,10 +1107,17 @@ const stripBOM = (content) => {
468
1107
  }
469
1108
  return content;
470
1109
  };
471
- const inherits = (constructor, superConstructor, props, descriptors2) => {
472
- constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
473
- constructor.prototype.constructor = constructor;
1110
+ const inherits = (constructor, superConstructor, props, descriptors) => {
1111
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors);
1112
+ Object.defineProperty(constructor.prototype, "constructor", {
1113
+ __proto__: null,
1114
+ value: constructor,
1115
+ writable: true,
1116
+ enumerable: false,
1117
+ configurable: true
1118
+ });
474
1119
  Object.defineProperty(constructor, "super", {
1120
+ __proto__: null,
475
1121
  value: superConstructor.prototype
476
1122
  });
477
1123
  props && Object.assign(constructor.prototype, props);
@@ -497,13 +1143,13 @@ const toFlatObject = (sourceObj, destObj, filter2, propFilter) => {
497
1143
  } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype);
498
1144
  return destObj;
499
1145
  };
500
- const endsWith = (str, searchString, position) => {
501
- str = String(str);
502
- if (position === void 0 || position > str.length) {
503
- position = str.length;
1146
+ const endsWith = (str2, searchString, position) => {
1147
+ str2 = String(str2);
1148
+ if (position === void 0 || position > str2.length) {
1149
+ position = str2.length;
504
1150
  }
505
1151
  position -= searchString.length;
506
- const lastIndex = str.indexOf(searchString, position);
1152
+ const lastIndex = str2.indexOf(searchString, position);
507
1153
  return lastIndex !== -1 && lastIndex === position;
508
1154
  };
509
1155
  const toArray = (thing) => {
@@ -531,42 +1177,39 @@ const forEachEntry = (obj, fn) => {
531
1177
  fn.call(obj, pair[0], pair[1]);
532
1178
  }
533
1179
  };
534
- const matchAll = (regExp, str) => {
1180
+ const matchAll = (regExp, str2) => {
535
1181
  let matches;
536
1182
  const arr = [];
537
- while ((matches = regExp.exec(str)) !== null) {
1183
+ while ((matches = regExp.exec(str2)) !== null) {
538
1184
  arr.push(matches);
539
1185
  }
540
1186
  return arr;
541
1187
  };
542
1188
  const isHTMLForm = kindOfTest("HTMLFormElement");
543
- const toCamelCase = (str) => {
544
- return str.toLowerCase().replace(
545
- /[-_\s]([a-z\d])(\w*)/g,
546
- function replacer(m, p1, p2) {
547
- return p1.toUpperCase() + p2;
548
- }
549
- );
1189
+ const toCamelCase = (str2) => {
1190
+ return str2.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
1191
+ return p1.toUpperCase() + p2;
1192
+ });
550
1193
  };
551
- const hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
1194
+ const { propertyIsEnumerable } = Object.prototype;
552
1195
  const isRegExp = kindOfTest("RegExp");
553
1196
  const reduceDescriptors = (obj, reducer) => {
554
- const descriptors2 = Object.getOwnPropertyDescriptors(obj);
1197
+ const descriptors = Object.getOwnPropertyDescriptors(obj);
555
1198
  const reducedDescriptors = {};
556
- forEach(descriptors2, (descriptor, name) => {
1199
+ forEach(descriptors, (descriptor, name2) => {
557
1200
  let ret;
558
- if ((ret = reducer(descriptor, name, obj)) !== false) {
559
- reducedDescriptors[name] = ret || descriptor;
1201
+ if ((ret = reducer(descriptor, name2, obj)) !== false) {
1202
+ reducedDescriptors[name2] = ret || descriptor;
560
1203
  }
561
1204
  });
562
1205
  Object.defineProperties(obj, reducedDescriptors);
563
1206
  };
564
1207
  const freezeMethods = (obj) => {
565
- reduceDescriptors(obj, (descriptor, name) => {
566
- if (isFunction$1(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) {
1208
+ reduceDescriptors(obj, (descriptor, name2) => {
1209
+ if (isFunction$1(obj) && ["arguments", "caller", "callee"].includes(name2)) {
567
1210
  return false;
568
1211
  }
569
- const value = obj[name];
1212
+ const value = obj[name2];
570
1213
  if (!isFunction$1(value)) return;
571
1214
  descriptor.enumerable = false;
572
1215
  if ("writable" in descriptor) {
@@ -575,7 +1218,7 @@ const freezeMethods = (obj) => {
575
1218
  }
576
1219
  if (!descriptor.set) {
577
1220
  descriptor.set = () => {
578
- throw Error("Can not rewrite read-only method '" + name + "'");
1221
+ throw Error("Can not rewrite read-only method '" + name2 + "'");
579
1222
  };
580
1223
  }
581
1224
  });
@@ -599,29 +1242,29 @@ function isSpecCompliantForm(thing) {
599
1242
  return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
600
1243
  }
601
1244
  const toJSONObject = (obj) => {
602
- const stack = new Array(10);
603
- const visit = (source, i) => {
1245
+ const visited = /* @__PURE__ */ new WeakSet();
1246
+ const visit = (source) => {
604
1247
  if (isObject(source)) {
605
- if (stack.indexOf(source) >= 0) {
1248
+ if (visited.has(source)) {
606
1249
  return;
607
1250
  }
608
1251
  if (isBuffer(source)) {
609
1252
  return source;
610
1253
  }
611
1254
  if (!("toJSON" in source)) {
612
- stack[i] = source;
1255
+ visited.add(source);
613
1256
  const target = isArray(source) ? [] : {};
614
1257
  forEach(source, (value, key) => {
615
- const reducedValue = visit(value, i + 1);
1258
+ const reducedValue = visit(value);
616
1259
  !isUndefined(reducedValue) && (target[key] = reducedValue);
617
1260
  });
618
- stack[i] = void 0;
1261
+ visited.delete(source);
619
1262
  return target;
620
1263
  }
621
1264
  }
622
1265
  return source;
623
1266
  };
624
- return visit(obj, 0);
1267
+ return visit(obj);
625
1268
  };
626
1269
  const isAsyncFn = kindOfTest("AsyncFunction");
627
1270
  const isThenable = (thing) => thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
@@ -630,22 +1273,24 @@ const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
630
1273
  return setImmediate;
631
1274
  }
632
1275
  return postMessageSupported ? ((token, callbacks) => {
633
- _global.addEventListener("message", ({ source, data }) => {
634
- if (source === _global && data === token) {
635
- callbacks.length && callbacks.shift()();
636
- }
637
- }, false);
1276
+ _global.addEventListener(
1277
+ "message",
1278
+ ({ source, data }) => {
1279
+ if (source === _global && data === token) {
1280
+ callbacks.length && callbacks.shift()();
1281
+ }
1282
+ },
1283
+ false
1284
+ );
638
1285
  return (cb) => {
639
1286
  callbacks.push(cb);
640
1287
  _global.postMessage(token, "*");
641
1288
  };
642
1289
  })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
643
- })(
644
- typeof setImmediate === "function",
645
- isFunction$1(_global.postMessage)
646
- );
1290
+ })(typeof setImmediate === "function", isFunction$1(_global.postMessage));
647
1291
  const asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate;
648
1292
  const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]);
1293
+ const isSafeIterable = (thing) => thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing);
649
1294
  const utils$1 = {
650
1295
  isArray,
651
1296
  isArrayBuffer,
@@ -665,6 +1310,8 @@ const utils$1 = {
665
1310
  isUndefined,
666
1311
  isDate,
667
1312
  isFile,
1313
+ isReactNativeBlob,
1314
+ isReactNative,
668
1315
  isBlob,
669
1316
  isRegExp,
670
1317
  isFunction: isFunction$1,
@@ -689,6 +1336,8 @@ const utils$1 = {
689
1336
  hasOwnProperty,
690
1337
  hasOwnProp: hasOwnProperty,
691
1338
  // an alias to avoid ESLint no-prototype-builtins detection
1339
+ hasOwnInPrototypeChain,
1340
+ getSafeProp,
692
1341
  reduceDescriptors,
693
1342
  freezeMethods,
694
1343
  toObjectSet,
@@ -704,98 +1353,483 @@ const utils$1 = {
704
1353
  isThenable,
705
1354
  setImmediate: _setImmediate,
706
1355
  asap,
707
- isIterable
708
- };
709
- function AxiosError$1(message, code, config2, request, response) {
710
- Error.call(this);
711
- if (Error.captureStackTrace) {
712
- Error.captureStackTrace(this, this.constructor);
713
- } else {
714
- this.stack = new Error().stack;
715
- }
716
- this.message = message;
717
- this.name = "AxiosError";
718
- code && (this.code = code);
719
- config2 && (this.config = config2);
720
- request && (this.request = request);
721
- if (response) {
722
- this.response = response;
723
- this.status = response.status ? response.status : null;
724
- }
725
- }
726
- utils$1.inherits(AxiosError$1, Error, {
727
- toJSON: function toJSON() {
728
- return {
729
- // Standard
730
- message: this.message,
731
- name: this.name,
732
- // Microsoft
733
- description: this.description,
734
- number: this.number,
735
- // Mozilla
736
- fileName: this.fileName,
737
- lineNumber: this.lineNumber,
738
- columnNumber: this.columnNumber,
739
- stack: this.stack,
740
- // Axios
741
- config: utils$1.toJSONObject(this.config),
742
- code: this.code,
743
- status: this.status
744
- };
745
- }
746
- });
747
- const prototype$1 = AxiosError$1.prototype;
748
- const descriptors = {};
749
- [
750
- "ERR_BAD_OPTION_VALUE",
751
- "ERR_BAD_OPTION",
752
- "ECONNABORTED",
753
- "ETIMEDOUT",
754
- "ERR_NETWORK",
755
- "ERR_FR_TOO_MANY_REDIRECTS",
756
- "ERR_DEPRECATED",
757
- "ERR_BAD_RESPONSE",
758
- "ERR_BAD_REQUEST",
759
- "ERR_CANCELED",
760
- "ERR_NOT_SUPPORT",
761
- "ERR_INVALID_URL"
762
- // eslint-disable-next-line func-names
763
- ].forEach((code) => {
764
- descriptors[code] = { value: code };
765
- });
766
- Object.defineProperties(AxiosError$1, descriptors);
767
- Object.defineProperty(prototype$1, "isAxiosError", { value: true });
768
- AxiosError$1.from = (error, code, config2, request, response, customProps) => {
769
- const axiosError = Object.create(prototype$1);
770
- utils$1.toFlatObject(error, axiosError, function filter2(obj) {
771
- return obj !== Error.prototype;
772
- }, (prop) => {
773
- return prop !== "isAxiosError";
774
- });
775
- const msg = error && error.message ? error.message : "Error";
776
- const errCode = code == null && error ? error.code : code;
777
- AxiosError$1.call(axiosError, msg, errCode, config2, request, response);
778
- if (error && axiosError.cause == null) {
779
- Object.defineProperty(axiosError, "cause", { value: error, configurable: true });
780
- }
781
- axiosError.name = error && error.name || "Error";
782
- customProps && Object.assign(axiosError, customProps);
783
- return axiosError;
1356
+ isIterable,
1357
+ isSafeIterable
784
1358
  };
785
- const httpAdapter = null;
786
- function isVisitable(thing) {
787
- return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
788
- }
789
- function removeBrackets(key) {
790
- return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key;
791
- }
792
- function renderKey(path, key, dots) {
793
- if (!path) return key;
794
- return path.concat(key).map(function each(token, i) {
795
- token = removeBrackets(token);
796
- return !dots && i ? "[" + token + "]" : token;
797
- }).join(dots ? "." : "");
798
- }
1359
+ const ignoreDuplicateOf = utils$1.toObjectSet([
1360
+ "age",
1361
+ "authorization",
1362
+ "content-length",
1363
+ "content-type",
1364
+ "etag",
1365
+ "expires",
1366
+ "from",
1367
+ "host",
1368
+ "if-modified-since",
1369
+ "if-unmodified-since",
1370
+ "last-modified",
1371
+ "location",
1372
+ "max-forwards",
1373
+ "proxy-authorization",
1374
+ "referer",
1375
+ "retry-after",
1376
+ "user-agent"
1377
+ ]);
1378
+ const parseHeaders = (rawHeaders) => {
1379
+ const parsed = {};
1380
+ let key;
1381
+ let val;
1382
+ let i;
1383
+ rawHeaders && rawHeaders.split("\n").forEach(function parser(line) {
1384
+ i = line.indexOf(":");
1385
+ key = line.substring(0, i).trim().toLowerCase();
1386
+ val = line.substring(i + 1).trim();
1387
+ if (!key || parsed[key] && ignoreDuplicateOf[key]) {
1388
+ return;
1389
+ }
1390
+ if (key === "set-cookie") {
1391
+ if (parsed[key]) {
1392
+ parsed[key].push(val);
1393
+ } else {
1394
+ parsed[key] = [val];
1395
+ }
1396
+ } else {
1397
+ parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
1398
+ }
1399
+ });
1400
+ return parsed;
1401
+ };
1402
+ function trimSPorHTAB(str2) {
1403
+ let start = 0;
1404
+ let end = str2.length;
1405
+ while (start < end) {
1406
+ const code = str2.charCodeAt(start);
1407
+ if (code !== 9 && code !== 32) {
1408
+ break;
1409
+ }
1410
+ start += 1;
1411
+ }
1412
+ while (end > start) {
1413
+ const code = str2.charCodeAt(end - 1);
1414
+ if (code !== 9 && code !== 32) {
1415
+ break;
1416
+ }
1417
+ end -= 1;
1418
+ }
1419
+ return start === 0 && end === str2.length ? str2 : str2.slice(start, end);
1420
+ }
1421
+ const INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+", "g");
1422
+ const INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+", "g");
1423
+ function sanitizeValue(value, invalidChars) {
1424
+ if (utils$1.isArray(value)) {
1425
+ return value.map((item) => sanitizeValue(item, invalidChars));
1426
+ }
1427
+ return trimSPorHTAB(String(value).replace(invalidChars, ""));
1428
+ }
1429
+ const sanitizeHeaderValue = (value) => sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS);
1430
+ const sanitizeByteStringHeaderValue = (value) => sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS);
1431
+ function toByteStringHeaderObject(headers) {
1432
+ const byteStringHeaders = /* @__PURE__ */ Object.create(null);
1433
+ utils$1.forEach(headers.toJSON(), (value, header) => {
1434
+ byteStringHeaders[header] = sanitizeByteStringHeaderValue(value);
1435
+ });
1436
+ return byteStringHeaders;
1437
+ }
1438
+ const $internals = Symbol("internals");
1439
+ function normalizeHeader(header) {
1440
+ return header && String(header).trim().toLowerCase();
1441
+ }
1442
+ function normalizeValue(value) {
1443
+ if (value === false || value == null) {
1444
+ return value;
1445
+ }
1446
+ return utils$1.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value));
1447
+ }
1448
+ function parseTokens(str2) {
1449
+ const tokens = /* @__PURE__ */ Object.create(null);
1450
+ const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1451
+ let match;
1452
+ while (match = tokensRE.exec(str2)) {
1453
+ tokens[match[1]] = match[2];
1454
+ }
1455
+ return tokens;
1456
+ }
1457
+ const isValidHeaderName = (str2) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str2.trim());
1458
+ function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) {
1459
+ if (utils$1.isFunction(filter2)) {
1460
+ return filter2.call(this, value, header);
1461
+ }
1462
+ if (isHeaderNameFilter) {
1463
+ value = header;
1464
+ }
1465
+ if (!utils$1.isString(value)) return;
1466
+ if (utils$1.isString(filter2)) {
1467
+ return value.indexOf(filter2) !== -1;
1468
+ }
1469
+ if (utils$1.isRegExp(filter2)) {
1470
+ return filter2.test(value);
1471
+ }
1472
+ }
1473
+ function formatHeader(header) {
1474
+ return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str2) => {
1475
+ return char.toUpperCase() + str2;
1476
+ });
1477
+ }
1478
+ function buildAccessors(obj, header) {
1479
+ const accessorName = utils$1.toCamelCase(" " + header);
1480
+ ["get", "set", "has"].forEach((methodName) => {
1481
+ Object.defineProperty(obj, methodName + accessorName, {
1482
+ // Null-proto descriptor so a polluted Object.prototype.get cannot turn
1483
+ // this data descriptor into an accessor descriptor on the way in.
1484
+ __proto__: null,
1485
+ value: function(arg1, arg2, arg3) {
1486
+ return this[methodName].call(this, header, arg1, arg2, arg3);
1487
+ },
1488
+ configurable: true
1489
+ });
1490
+ });
1491
+ }
1492
+ let AxiosHeaders$1 = class AxiosHeaders {
1493
+ constructor(headers) {
1494
+ headers && this.set(headers);
1495
+ }
1496
+ set(header, valueOrRewrite, rewrite) {
1497
+ const self2 = this;
1498
+ function setHeader(_value, _header, _rewrite) {
1499
+ const lHeader = normalizeHeader(_header);
1500
+ if (!lHeader) {
1501
+ return;
1502
+ }
1503
+ const key = utils$1.findKey(self2, lHeader);
1504
+ if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) {
1505
+ self2[key || _header] = normalizeValue(_value);
1506
+ }
1507
+ }
1508
+ const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1509
+ if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1510
+ setHeaders(header, valueOrRewrite);
1511
+ } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1512
+ setHeaders(parseHeaders(header), valueOrRewrite);
1513
+ } else if (utils$1.isObject(header) && utils$1.isSafeIterable(header)) {
1514
+ let obj = /* @__PURE__ */ Object.create(null), dest, key;
1515
+ for (const entry of header) {
1516
+ if (!utils$1.isArray(entry)) {
1517
+ throw new TypeError("Object iterator must return a key-value pair");
1518
+ }
1519
+ key = entry[0];
1520
+ if (utils$1.hasOwnProp(obj, key)) {
1521
+ dest = obj[key];
1522
+ obj[key] = utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]];
1523
+ } else {
1524
+ obj[key] = entry[1];
1525
+ }
1526
+ }
1527
+ setHeaders(obj, valueOrRewrite);
1528
+ } else {
1529
+ header != null && setHeader(valueOrRewrite, header, rewrite);
1530
+ }
1531
+ return this;
1532
+ }
1533
+ get(header, parser) {
1534
+ header = normalizeHeader(header);
1535
+ if (header) {
1536
+ const key = utils$1.findKey(this, header);
1537
+ if (key) {
1538
+ const value = this[key];
1539
+ if (!parser) {
1540
+ return value;
1541
+ }
1542
+ if (parser === true) {
1543
+ return parseTokens(value);
1544
+ }
1545
+ if (utils$1.isFunction(parser)) {
1546
+ return parser.call(this, value, key);
1547
+ }
1548
+ if (utils$1.isRegExp(parser)) {
1549
+ return parser.exec(value);
1550
+ }
1551
+ throw new TypeError("parser must be boolean|regexp|function");
1552
+ }
1553
+ }
1554
+ }
1555
+ has(header, matcher) {
1556
+ header = normalizeHeader(header);
1557
+ if (header) {
1558
+ const key = utils$1.findKey(this, header);
1559
+ return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1560
+ }
1561
+ return false;
1562
+ }
1563
+ delete(header, matcher) {
1564
+ const self2 = this;
1565
+ let deleted = false;
1566
+ function deleteHeader(_header) {
1567
+ _header = normalizeHeader(_header);
1568
+ if (_header) {
1569
+ const key = utils$1.findKey(self2, _header);
1570
+ if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
1571
+ delete self2[key];
1572
+ deleted = true;
1573
+ }
1574
+ }
1575
+ }
1576
+ if (utils$1.isArray(header)) {
1577
+ header.forEach(deleteHeader);
1578
+ } else {
1579
+ deleteHeader(header);
1580
+ }
1581
+ return deleted;
1582
+ }
1583
+ clear(matcher) {
1584
+ const keys = Object.keys(this);
1585
+ let i = keys.length;
1586
+ let deleted = false;
1587
+ while (i--) {
1588
+ const key = keys[i];
1589
+ if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
1590
+ delete this[key];
1591
+ deleted = true;
1592
+ }
1593
+ }
1594
+ return deleted;
1595
+ }
1596
+ normalize(format) {
1597
+ const self2 = this;
1598
+ const headers = {};
1599
+ utils$1.forEach(this, (value, header) => {
1600
+ const key = utils$1.findKey(headers, header);
1601
+ if (key) {
1602
+ self2[key] = normalizeValue(value);
1603
+ delete self2[header];
1604
+ return;
1605
+ }
1606
+ const normalized = format ? formatHeader(header) : String(header).trim();
1607
+ if (normalized !== header) {
1608
+ delete self2[header];
1609
+ }
1610
+ self2[normalized] = normalizeValue(value);
1611
+ headers[normalized] = true;
1612
+ });
1613
+ return this;
1614
+ }
1615
+ concat(...targets) {
1616
+ return this.constructor.concat(this, ...targets);
1617
+ }
1618
+ toJSON(asStrings) {
1619
+ const obj = /* @__PURE__ */ Object.create(null);
1620
+ utils$1.forEach(this, (value, header) => {
1621
+ value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value);
1622
+ });
1623
+ return obj;
1624
+ }
1625
+ [Symbol.iterator]() {
1626
+ return Object.entries(this.toJSON())[Symbol.iterator]();
1627
+ }
1628
+ toString() {
1629
+ return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n");
1630
+ }
1631
+ getSetCookie() {
1632
+ return this.get("set-cookie") || [];
1633
+ }
1634
+ get [Symbol.toStringTag]() {
1635
+ return "AxiosHeaders";
1636
+ }
1637
+ static from(thing) {
1638
+ return thing instanceof this ? thing : new this(thing);
1639
+ }
1640
+ static concat(first, ...targets) {
1641
+ const computed = new this(first);
1642
+ targets.forEach((target) => computed.set(target));
1643
+ return computed;
1644
+ }
1645
+ static accessor(header) {
1646
+ const internals = this[$internals] = this[$internals] = {
1647
+ accessors: {}
1648
+ };
1649
+ const accessors = internals.accessors;
1650
+ const prototype2 = this.prototype;
1651
+ function defineAccessor(_header) {
1652
+ const lHeader = normalizeHeader(_header);
1653
+ if (!accessors[lHeader]) {
1654
+ buildAccessors(prototype2, _header);
1655
+ accessors[lHeader] = true;
1656
+ }
1657
+ }
1658
+ utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1659
+ return this;
1660
+ }
1661
+ };
1662
+ AxiosHeaders$1.accessor([
1663
+ "Content-Type",
1664
+ "Content-Length",
1665
+ "Accept",
1666
+ "Accept-Encoding",
1667
+ "User-Agent",
1668
+ "Authorization"
1669
+ ]);
1670
+ utils$1.reduceDescriptors(AxiosHeaders$1.prototype, ({ value }, key) => {
1671
+ let mapped = key[0].toUpperCase() + key.slice(1);
1672
+ return {
1673
+ get: () => value,
1674
+ set(headerValue) {
1675
+ this[mapped] = headerValue;
1676
+ }
1677
+ };
1678
+ });
1679
+ utils$1.freezeMethods(AxiosHeaders$1);
1680
+ const REDACTED = "[REDACTED ****]";
1681
+ function hasOwnOrPrototypeToJSON(source) {
1682
+ if (utils$1.hasOwnProp(source, "toJSON")) {
1683
+ return true;
1684
+ }
1685
+ let prototype2 = Object.getPrototypeOf(source);
1686
+ while (prototype2 && prototype2 !== Object.prototype) {
1687
+ if (utils$1.hasOwnProp(prototype2, "toJSON")) {
1688
+ return true;
1689
+ }
1690
+ prototype2 = Object.getPrototypeOf(prototype2);
1691
+ }
1692
+ return false;
1693
+ }
1694
+ function redactConfig(config2, redactKeys) {
1695
+ const lowerKeys = new Set(redactKeys.map((k) => String(k).toLowerCase()));
1696
+ const seen = [];
1697
+ const visit = (source) => {
1698
+ if (source === null || typeof source !== "object") return source;
1699
+ if (utils$1.isBuffer(source)) return source;
1700
+ if (seen.indexOf(source) !== -1) return void 0;
1701
+ if (source instanceof AxiosHeaders$1) {
1702
+ source = source.toJSON();
1703
+ }
1704
+ seen.push(source);
1705
+ let result;
1706
+ if (utils$1.isArray(source)) {
1707
+ result = [];
1708
+ source.forEach((v, i) => {
1709
+ const reducedValue = visit(v);
1710
+ if (!utils$1.isUndefined(reducedValue)) {
1711
+ result[i] = reducedValue;
1712
+ }
1713
+ });
1714
+ } else {
1715
+ if (!utils$1.isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) {
1716
+ seen.pop();
1717
+ return source;
1718
+ }
1719
+ result = /* @__PURE__ */ Object.create(null);
1720
+ for (const [key, value] of Object.entries(source)) {
1721
+ const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value);
1722
+ if (!utils$1.isUndefined(reducedValue)) {
1723
+ result[key] = reducedValue;
1724
+ }
1725
+ }
1726
+ }
1727
+ seen.pop();
1728
+ return result;
1729
+ };
1730
+ return visit(config2);
1731
+ }
1732
+ let AxiosError$1 = class AxiosError extends Error {
1733
+ static from(error, code, config2, request, response, customProps) {
1734
+ const axiosError = new AxiosError(error.message, code || error.code, config2, request, response);
1735
+ Object.defineProperty(axiosError, "cause", {
1736
+ __proto__: null,
1737
+ value: error,
1738
+ writable: true,
1739
+ enumerable: false,
1740
+ configurable: true
1741
+ });
1742
+ axiosError.name = error.name;
1743
+ if (error.status != null && axiosError.status == null) {
1744
+ axiosError.status = error.status;
1745
+ }
1746
+ customProps && Object.assign(axiosError, customProps);
1747
+ return axiosError;
1748
+ }
1749
+ /**
1750
+ * Create an Error with the specified message, config, error code, request and response.
1751
+ *
1752
+ * @param {string} message The error message.
1753
+ * @param {string} [code] The error code (for example, 'ECONNABORTED').
1754
+ * @param {Object} [config] The config.
1755
+ * @param {Object} [request] The request.
1756
+ * @param {Object} [response] The response.
1757
+ *
1758
+ * @returns {Error} The created error.
1759
+ */
1760
+ constructor(message, code, config2, request, response) {
1761
+ super(message);
1762
+ Object.defineProperty(this, "message", {
1763
+ // Null-proto descriptor so a polluted Object.prototype.get cannot turn
1764
+ // this data descriptor into an accessor descriptor on the way in.
1765
+ __proto__: null,
1766
+ value: message,
1767
+ enumerable: true,
1768
+ writable: true,
1769
+ configurable: true
1770
+ });
1771
+ this.name = "AxiosError";
1772
+ this.isAxiosError = true;
1773
+ code && (this.code = code);
1774
+ config2 && (this.config = config2);
1775
+ request && (this.request = request);
1776
+ if (response) {
1777
+ this.response = response;
1778
+ this.status = response.status;
1779
+ }
1780
+ }
1781
+ toJSON() {
1782
+ const config2 = this.config;
1783
+ const redactKeys = config2 && utils$1.hasOwnProp(config2, "redact") ? config2.redact : void 0;
1784
+ const serializedConfig = utils$1.isArray(redactKeys) && redactKeys.length > 0 ? redactConfig(config2, redactKeys) : utils$1.toJSONObject(config2);
1785
+ return {
1786
+ // Standard
1787
+ message: this.message,
1788
+ name: this.name,
1789
+ // Microsoft
1790
+ description: this.description,
1791
+ number: this.number,
1792
+ // Mozilla
1793
+ fileName: this.fileName,
1794
+ lineNumber: this.lineNumber,
1795
+ columnNumber: this.columnNumber,
1796
+ stack: this.stack,
1797
+ // Axios
1798
+ config: serializedConfig,
1799
+ code: this.code,
1800
+ status: this.status
1801
+ };
1802
+ }
1803
+ };
1804
+ AxiosError$1.ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
1805
+ AxiosError$1.ERR_BAD_OPTION = "ERR_BAD_OPTION";
1806
+ AxiosError$1.ECONNABORTED = "ECONNABORTED";
1807
+ AxiosError$1.ETIMEDOUT = "ETIMEDOUT";
1808
+ AxiosError$1.ECONNREFUSED = "ECONNREFUSED";
1809
+ AxiosError$1.ERR_NETWORK = "ERR_NETWORK";
1810
+ AxiosError$1.ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
1811
+ AxiosError$1.ERR_DEPRECATED = "ERR_DEPRECATED";
1812
+ AxiosError$1.ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
1813
+ AxiosError$1.ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
1814
+ AxiosError$1.ERR_CANCELED = "ERR_CANCELED";
1815
+ AxiosError$1.ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";
1816
+ AxiosError$1.ERR_INVALID_URL = "ERR_INVALID_URL";
1817
+ AxiosError$1.ERR_FORM_DATA_DEPTH_EXCEEDED = "ERR_FORM_DATA_DEPTH_EXCEEDED";
1818
+ const httpAdapter = null;
1819
+ const DEFAULT_FORM_DATA_MAX_DEPTH = 100;
1820
+ function isVisitable(thing) {
1821
+ return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
1822
+ }
1823
+ function removeBrackets(key) {
1824
+ return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key;
1825
+ }
1826
+ function renderKey(path, key, dots) {
1827
+ if (!path) return key;
1828
+ return path.concat(key).map(function each(token, i) {
1829
+ token = removeBrackets(token);
1830
+ return !dots && i ? "[" + token + "]" : token;
1831
+ }).join(dots ? "." : "");
1832
+ }
799
1833
  function isFlatArray(arr) {
800
1834
  return utils$1.isArray(arr) && !arr.some(isVisitable);
801
1835
  }
@@ -807,19 +1841,26 @@ function toFormData$1(obj, formData, options) {
807
1841
  throw new TypeError("target must be an object");
808
1842
  }
809
1843
  formData = formData || new FormData();
810
- options = utils$1.toFlatObject(options, {
811
- metaTokens: true,
812
- dots: false,
813
- indexes: false
814
- }, false, function defined(option, source) {
815
- return !utils$1.isUndefined(source[option]);
816
- });
1844
+ options = utils$1.toFlatObject(
1845
+ options,
1846
+ {
1847
+ metaTokens: true,
1848
+ dots: false,
1849
+ indexes: false
1850
+ },
1851
+ false,
1852
+ function defined(option, source) {
1853
+ return !utils$1.isUndefined(source[option]);
1854
+ }
1855
+ );
817
1856
  const metaTokens = options.metaTokens;
818
1857
  const visitor = options.visitor || defaultVisitor;
819
1858
  const dots = options.dots;
820
1859
  const indexes = options.indexes;
821
1860
  const _Blob = options.Blob || typeof Blob !== "undefined" && Blob;
1861
+ const maxDepth = options.maxDepth === void 0 ? DEFAULT_FORM_DATA_MAX_DEPTH : options.maxDepth;
822
1862
  const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
1863
+ const stack = [];
823
1864
  if (!utils$1.isFunction(visitor)) {
824
1865
  throw new TypeError("visitor must be a function");
825
1866
  }
@@ -835,16 +1876,51 @@ function toFormData$1(obj, formData, options) {
835
1876
  throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");
836
1877
  }
837
1878
  if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
838
- return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
1879
+ if (useBlob && typeof _Blob === "function") {
1880
+ return new _Blob([value]);
1881
+ }
1882
+ if (typeof Buffer !== "undefined") {
1883
+ return Buffer.from(value);
1884
+ }
1885
+ throw new AxiosError$1("Blob is not supported. Use a Buffer instead.", AxiosError$1.ERR_NOT_SUPPORT);
839
1886
  }
840
1887
  return value;
841
1888
  }
1889
+ function throwIfMaxDepthExceeded(depth) {
1890
+ if (depth > maxDepth) {
1891
+ throw new AxiosError$1(
1892
+ "Object is too deeply nested (" + depth + " levels). Max depth: " + maxDepth,
1893
+ AxiosError$1.ERR_FORM_DATA_DEPTH_EXCEEDED
1894
+ );
1895
+ }
1896
+ }
1897
+ function stringifyWithDepthLimit(value, depth) {
1898
+ if (maxDepth === Infinity) {
1899
+ return JSON.stringify(value);
1900
+ }
1901
+ const ancestors = [];
1902
+ return JSON.stringify(value, function limitDepth(_key, currentValue) {
1903
+ if (!utils$1.isObject(currentValue)) {
1904
+ return currentValue;
1905
+ }
1906
+ while (ancestors.length && ancestors[ancestors.length - 1] !== this) {
1907
+ ancestors.pop();
1908
+ }
1909
+ ancestors.push(currentValue);
1910
+ throwIfMaxDepthExceeded(depth + ancestors.length - 1);
1911
+ return currentValue;
1912
+ });
1913
+ }
842
1914
  function defaultVisitor(value, key, path) {
843
1915
  let arr = value;
1916
+ if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
1917
+ formData.append(renderKey(path, key, dots), convertValue(value));
1918
+ return false;
1919
+ }
844
1920
  if (value && !path && typeof value === "object") {
845
1921
  if (utils$1.endsWith(key, "{}")) {
846
1922
  key = metaTokens ? key : key.slice(0, -2);
847
- value = JSON.stringify(value);
1923
+ value = stringifyWithDepthLimit(value, 1);
848
1924
  } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) {
849
1925
  key = removeBrackets(key);
850
1926
  arr.forEach(function each(el, index2) {
@@ -863,28 +1939,22 @@ function toFormData$1(obj, formData, options) {
863
1939
  formData.append(renderKey(path, key, dots), convertValue(value));
864
1940
  return false;
865
1941
  }
866
- const stack = [];
867
1942
  const exposedHelpers = Object.assign(predicates, {
868
1943
  defaultVisitor,
869
1944
  convertValue,
870
1945
  isVisitable
871
1946
  });
872
- function build(value, path) {
1947
+ function build(value, path, depth = 0) {
873
1948
  if (utils$1.isUndefined(value)) return;
1949
+ throwIfMaxDepthExceeded(depth);
874
1950
  if (stack.indexOf(value) !== -1) {
875
- throw Error("Circular reference detected in " + path.join("."));
1951
+ throw new Error("Circular reference detected in " + path.join("."));
876
1952
  }
877
1953
  stack.push(value);
878
1954
  utils$1.forEach(value, function each(el, key) {
879
- const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
880
- formData,
881
- el,
882
- utils$1.isString(key) ? key.trim() : key,
883
- path,
884
- exposedHelpers
885
- );
1955
+ const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
886
1956
  if (result === true) {
887
- build(el, path ? path.concat(key) : [key]);
1957
+ build(el, path ? path.concat(key) : [key], depth + 1);
888
1958
  }
889
1959
  });
890
1960
  stack.pop();
@@ -895,17 +1965,16 @@ function toFormData$1(obj, formData, options) {
895
1965
  build(obj);
896
1966
  return formData;
897
1967
  }
898
- function encode$1(str) {
1968
+ function encode$1(str2) {
899
1969
  const charMap = {
900
1970
  "!": "%21",
901
1971
  "'": "%27",
902
1972
  "(": "%28",
903
1973
  ")": "%29",
904
1974
  "~": "%7E",
905
- "%20": "+",
906
- "%00": "\0"
1975
+ "%20": "+"
907
1976
  };
908
- return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
1977
+ return encodeURIComponent(str2).replace(/[!'()~]|%20/g, function replacer(match) {
909
1978
  return charMap[match];
910
1979
  });
911
1980
  }
@@ -914,13 +1983,11 @@ function AxiosURLSearchParams(params, options) {
914
1983
  params && toFormData$1(params, this, options);
915
1984
  }
916
1985
  const prototype = AxiosURLSearchParams.prototype;
917
- prototype.append = function append(name, value) {
918
- this._pairs.push([name, value]);
1986
+ prototype.append = function append(name2, value) {
1987
+ this._pairs.push([name2, value]);
919
1988
  };
920
1989
  prototype.toString = function toString2(encoder) {
921
- const _encode = encoder ? function(value) {
922
- return encoder.call(this, value, encode$1);
923
- } : encode$1;
1990
+ const _encode = encoder ? (value) => encoder.call(this, value, encode$1) : encode$1;
924
1991
  return this._pairs.map(function each(pair) {
925
1992
  return _encode(pair[0]) + "=" + _encode(pair[1]);
926
1993
  }, "").join("&");
@@ -932,18 +1999,17 @@ function buildURL(url, params, options) {
932
1999
  if (!params) {
933
2000
  return url;
934
2001
  }
935
- const _encode = options && options.encode || encode;
936
- if (utils$1.isFunction(options)) {
937
- options = {
938
- serialize: options
939
- };
940
- }
941
- const serializeFn = options && options.serialize;
2002
+ url = url || "";
2003
+ const _options = utils$1.isFunction(options) ? {
2004
+ serialize: options
2005
+ } : options;
2006
+ const _encode = utils$1.getSafeProp(_options, "encode") || encode;
2007
+ const serializeFn = utils$1.getSafeProp(_options, "serialize");
942
2008
  let serializedParams;
943
2009
  if (serializeFn) {
944
- serializedParams = serializeFn(params, options);
2010
+ serializedParams = serializeFn(params, _options);
945
2011
  } else {
946
- serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, options).toString(_encode);
2012
+ serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, _options).toString(_encode);
947
2013
  }
948
2014
  if (serializedParams) {
949
2015
  const hashmarkIndex = url.indexOf("#");
@@ -963,6 +2029,7 @@ class InterceptorManager {
963
2029
  *
964
2030
  * @param {Function} fulfilled The function to handle `then` for a `Promise`
965
2031
  * @param {Function} rejected The function to handle `reject` for a `Promise`
2032
+ * @param {Object} options The options for the interceptor, synchronous and runWhen
966
2033
  *
967
2034
  * @return {Number} An ID used to remove interceptor later
968
2035
  */
@@ -980,7 +2047,7 @@ class InterceptorManager {
980
2047
  *
981
2048
  * @param {Number} id The ID that was returned by `use`
982
2049
  *
983
- * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
2050
+ * @returns {void}
984
2051
  */
985
2052
  eject(id) {
986
2053
  if (this.handlers[id]) {
@@ -1018,7 +2085,10 @@ class InterceptorManager {
1018
2085
  const transitionalDefaults = {
1019
2086
  silentJSONParsing: true,
1020
2087
  forcedJSONParsing: true,
1021
- clarifyTimeoutError: false
2088
+ clarifyTimeoutError: false,
2089
+ legacyInterceptorReqResOrdering: true,
2090
+ advertiseZstdAcceptEncoding: false,
2091
+ validateStatusUndefinedResolves: true
1022
2092
  };
1023
2093
  const URLSearchParams$1 = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams;
1024
2094
  const FormData$1 = typeof FormData !== "undefined" ? FormData : null;
@@ -1052,443 +2122,197 @@ const platform = {
1052
2122
  ...utils,
1053
2123
  ...platform$1
1054
2124
  };
1055
- function toURLEncodedForm(data, options) {
1056
- return toFormData$1(data, new platform.classes.URLSearchParams(), {
1057
- visitor: function(value, key, path, helpers) {
1058
- if (platform.isNode && utils$1.isBuffer(value)) {
1059
- this.append(key, value.toString("base64"));
1060
- return false;
1061
- }
1062
- return helpers.defaultVisitor.apply(this, arguments);
1063
- },
1064
- ...options
1065
- });
1066
- }
1067
- function parsePropPath(name) {
1068
- return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
1069
- return match[0] === "[]" ? "" : match[1] || match[0];
1070
- });
1071
- }
1072
- function arrayToObject(arr) {
1073
- const obj = {};
1074
- const keys = Object.keys(arr);
1075
- let i;
1076
- const len = keys.length;
1077
- let key;
1078
- for (i = 0; i < len; i++) {
1079
- key = keys[i];
1080
- obj[key] = arr[key];
1081
- }
1082
- return obj;
1083
- }
1084
- function formDataToJSON(formData) {
1085
- function buildPath(path, value, target, index2) {
1086
- let name = path[index2++];
1087
- if (name === "__proto__") return true;
1088
- const isNumericKey = Number.isFinite(+name);
1089
- const isLast = index2 >= path.length;
1090
- name = !name && utils$1.isArray(target) ? target.length : name;
1091
- if (isLast) {
1092
- if (utils$1.hasOwnProp(target, name)) {
1093
- target[name] = [target[name], value];
1094
- } else {
1095
- target[name] = value;
1096
- }
1097
- return !isNumericKey;
1098
- }
1099
- if (!target[name] || !utils$1.isObject(target[name])) {
1100
- target[name] = [];
1101
- }
1102
- const result = buildPath(path, value, target[name], index2);
1103
- if (result && utils$1.isArray(target[name])) {
1104
- target[name] = arrayToObject(target[name]);
1105
- }
1106
- return !isNumericKey;
1107
- }
1108
- if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
1109
- const obj = {};
1110
- utils$1.forEachEntry(formData, (name, value) => {
1111
- buildPath(parsePropPath(name), value, obj, 0);
1112
- });
1113
- return obj;
1114
- }
1115
- return null;
1116
- }
1117
- function stringifySafely(rawValue, parser, encoder) {
1118
- if (utils$1.isString(rawValue)) {
1119
- try {
1120
- (parser || JSON.parse)(rawValue);
1121
- return utils$1.trim(rawValue);
1122
- } catch (e) {
1123
- if (e.name !== "SyntaxError") {
1124
- throw e;
1125
- }
1126
- }
1127
- }
1128
- return (encoder || JSON.stringify)(rawValue);
1129
- }
1130
- const defaults = {
1131
- transitional: transitionalDefaults,
1132
- adapter: ["xhr", "http", "fetch"],
1133
- transformRequest: [function transformRequest(data, headers) {
1134
- const contentType = headers.getContentType() || "";
1135
- const hasJSONContentType = contentType.indexOf("application/json") > -1;
1136
- const isObjectPayload = utils$1.isObject(data);
1137
- if (isObjectPayload && utils$1.isHTMLForm(data)) {
1138
- data = new FormData(data);
1139
- }
1140
- const isFormData2 = utils$1.isFormData(data);
1141
- if (isFormData2) {
1142
- return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
1143
- }
1144
- 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)) {
1145
- return data;
1146
- }
1147
- if (utils$1.isArrayBufferView(data)) {
1148
- return data.buffer;
1149
- }
1150
- if (utils$1.isURLSearchParams(data)) {
1151
- headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
1152
- return data.toString();
1153
- }
1154
- let isFileList2;
1155
- if (isObjectPayload) {
1156
- if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
1157
- return toURLEncodedForm(data, this.formSerializer).toString();
1158
- }
1159
- if ((isFileList2 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
1160
- const _FormData = this.env && this.env.FormData;
1161
- return toFormData$1(
1162
- isFileList2 ? { "files[]": data } : data,
1163
- _FormData && new _FormData(),
1164
- this.formSerializer
1165
- );
1166
- }
1167
- }
1168
- if (isObjectPayload || hasJSONContentType) {
1169
- headers.setContentType("application/json", false);
1170
- return stringifySafely(data);
1171
- }
1172
- return data;
1173
- }],
1174
- transformResponse: [function transformResponse(data) {
1175
- const transitional2 = this.transitional || defaults.transitional;
1176
- const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing;
1177
- const JSONRequested = this.responseType === "json";
1178
- if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
1179
- return data;
1180
- }
1181
- if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
1182
- const silentJSONParsing = transitional2 && transitional2.silentJSONParsing;
1183
- const strictJSONParsing = !silentJSONParsing && JSONRequested;
1184
- try {
1185
- return JSON.parse(data, this.parseReviver);
1186
- } catch (e) {
1187
- if (strictJSONParsing) {
1188
- if (e.name === "SyntaxError") {
1189
- throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response);
1190
- }
1191
- throw e;
1192
- }
1193
- }
1194
- }
1195
- return data;
1196
- }],
1197
- /**
1198
- * A timeout in milliseconds to abort a request. If set to 0 (default) a
1199
- * timeout is not created.
1200
- */
1201
- timeout: 0,
1202
- xsrfCookieName: "XSRF-TOKEN",
1203
- xsrfHeaderName: "X-XSRF-TOKEN",
1204
- maxContentLength: -1,
1205
- maxBodyLength: -1,
1206
- env: {
1207
- FormData: platform.classes.FormData,
1208
- Blob: platform.classes.Blob
1209
- },
1210
- validateStatus: function validateStatus(status) {
1211
- return status >= 200 && status < 300;
1212
- },
1213
- headers: {
1214
- common: {
1215
- "Accept": "application/json, text/plain, */*",
1216
- "Content-Type": void 0
1217
- }
1218
- }
1219
- };
1220
- utils$1.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => {
1221
- defaults.headers[method] = {};
1222
- });
1223
- const ignoreDuplicateOf = utils$1.toObjectSet([
1224
- "age",
1225
- "authorization",
1226
- "content-length",
1227
- "content-type",
1228
- "etag",
1229
- "expires",
1230
- "from",
1231
- "host",
1232
- "if-modified-since",
1233
- "if-unmodified-since",
1234
- "last-modified",
1235
- "location",
1236
- "max-forwards",
1237
- "proxy-authorization",
1238
- "referer",
1239
- "retry-after",
1240
- "user-agent"
1241
- ]);
1242
- const parseHeaders = (rawHeaders) => {
1243
- const parsed = {};
1244
- let key;
1245
- let val;
1246
- let i;
1247
- rawHeaders && rawHeaders.split("\n").forEach(function parser(line) {
1248
- i = line.indexOf(":");
1249
- key = line.substring(0, i).trim().toLowerCase();
1250
- val = line.substring(i + 1).trim();
1251
- if (!key || parsed[key] && ignoreDuplicateOf[key]) {
1252
- return;
1253
- }
1254
- if (key === "set-cookie") {
1255
- if (parsed[key]) {
1256
- parsed[key].push(val);
1257
- } else {
1258
- parsed[key] = [val];
1259
- }
1260
- } else {
1261
- parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
1262
- }
1263
- });
1264
- return parsed;
1265
- };
1266
- const $internals = Symbol("internals");
1267
- function normalizeHeader(header) {
1268
- return header && String(header).trim().toLowerCase();
1269
- }
1270
- function normalizeValue(value) {
1271
- if (value === false || value == null) {
1272
- return value;
1273
- }
1274
- return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
1275
- }
1276
- function parseTokens(str) {
1277
- const tokens = /* @__PURE__ */ Object.create(null);
1278
- const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1279
- let match;
1280
- while (match = tokensRE.exec(str)) {
1281
- tokens[match[1]] = match[2];
1282
- }
1283
- return tokens;
1284
- }
1285
- const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
1286
- function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) {
1287
- if (utils$1.isFunction(filter2)) {
1288
- return filter2.call(this, value, header);
1289
- }
1290
- if (isHeaderNameFilter) {
1291
- value = header;
1292
- }
1293
- if (!utils$1.isString(value)) return;
1294
- if (utils$1.isString(filter2)) {
1295
- return value.indexOf(filter2) !== -1;
1296
- }
1297
- if (utils$1.isRegExp(filter2)) {
1298
- return filter2.test(value);
1299
- }
1300
- }
1301
- function formatHeader(header) {
1302
- return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1303
- return char.toUpperCase() + str;
1304
- });
1305
- }
1306
- function buildAccessors(obj, header) {
1307
- const accessorName = utils$1.toCamelCase(" " + header);
1308
- ["get", "set", "has"].forEach((methodName) => {
1309
- Object.defineProperty(obj, methodName + accessorName, {
1310
- value: function(arg1, arg2, arg3) {
1311
- return this[methodName].call(this, header, arg1, arg2, arg3);
1312
- },
1313
- configurable: true
1314
- });
1315
- });
1316
- }
1317
- let AxiosHeaders$1 = class AxiosHeaders {
1318
- constructor(headers) {
1319
- headers && this.set(headers);
1320
- }
1321
- set(header, valueOrRewrite, rewrite) {
1322
- const self2 = this;
1323
- function setHeader(_value, _header, _rewrite) {
1324
- const lHeader = normalizeHeader(_header);
1325
- if (!lHeader) {
1326
- throw new Error("header name must be a non-empty string");
1327
- }
1328
- const key = utils$1.findKey(self2, lHeader);
1329
- if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) {
1330
- self2[key || _header] = normalizeValue(_value);
1331
- }
1332
- }
1333
- const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1334
- if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1335
- setHeaders(header, valueOrRewrite);
1336
- } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1337
- setHeaders(parseHeaders(header), valueOrRewrite);
1338
- } else if (utils$1.isObject(header) && utils$1.isIterable(header)) {
1339
- let obj = {}, dest, key;
1340
- for (const entry of header) {
1341
- if (!utils$1.isArray(entry)) {
1342
- throw TypeError("Object iterator must return a key-value pair");
1343
- }
1344
- obj[key = entry[0]] = (dest = obj[key]) ? utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1];
2125
+ function toURLEncodedForm(data, options) {
2126
+ return toFormData$1(data, new platform.classes.URLSearchParams(), {
2127
+ visitor: function(value, key, path, helpers) {
2128
+ if (platform.isNode && utils$1.isBuffer(value)) {
2129
+ this.append(key, value.toString("base64"));
2130
+ return false;
1345
2131
  }
1346
- setHeaders(obj, valueOrRewrite);
1347
- } else {
1348
- header != null && setHeader(valueOrRewrite, header, rewrite);
1349
- }
1350
- return this;
2132
+ return helpers.defaultVisitor.apply(this, arguments);
2133
+ },
2134
+ ...options
2135
+ });
2136
+ }
2137
+ const MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH;
2138
+ function throwIfDepthExceeded(index2) {
2139
+ if (index2 > MAX_DEPTH) {
2140
+ throw new AxiosError$1(
2141
+ "FormData field is too deeply nested (" + index2 + " levels). Max depth: " + MAX_DEPTH,
2142
+ AxiosError$1.ERR_FORM_DATA_DEPTH_EXCEEDED
2143
+ );
1351
2144
  }
1352
- get(header, parser) {
1353
- header = normalizeHeader(header);
1354
- if (header) {
1355
- const key = utils$1.findKey(this, header);
1356
- if (key) {
1357
- const value = this[key];
1358
- if (!parser) {
1359
- return value;
1360
- }
1361
- if (parser === true) {
1362
- return parseTokens(value);
1363
- }
1364
- if (utils$1.isFunction(parser)) {
1365
- return parser.call(this, value, key);
1366
- }
1367
- if (utils$1.isRegExp(parser)) {
1368
- return parser.exec(value);
1369
- }
1370
- throw new TypeError("parser must be boolean|regexp|function");
1371
- }
1372
- }
2145
+ }
2146
+ function parsePropPath(name2) {
2147
+ const path = [];
2148
+ const pattern = /\w+|\[(\w*)]/g;
2149
+ let match;
2150
+ while ((match = pattern.exec(name2)) !== null) {
2151
+ throwIfDepthExceeded(path.length);
2152
+ path.push(match[0] === "[]" ? "" : match[1] || match[0]);
1373
2153
  }
1374
- has(header, matcher) {
1375
- header = normalizeHeader(header);
1376
- if (header) {
1377
- const key = utils$1.findKey(this, header);
1378
- return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1379
- }
1380
- return false;
2154
+ return path;
2155
+ }
2156
+ function arrayToObject(arr) {
2157
+ const obj = {};
2158
+ const keys = Object.keys(arr);
2159
+ let i;
2160
+ const len = keys.length;
2161
+ let key;
2162
+ for (i = 0; i < len; i++) {
2163
+ key = keys[i];
2164
+ obj[key] = arr[key];
1381
2165
  }
1382
- delete(header, matcher) {
1383
- const self2 = this;
1384
- let deleted = false;
1385
- function deleteHeader(_header) {
1386
- _header = normalizeHeader(_header);
1387
- if (_header) {
1388
- const key = utils$1.findKey(self2, _header);
1389
- if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
1390
- delete self2[key];
1391
- deleted = true;
1392
- }
2166
+ return obj;
2167
+ }
2168
+ function formDataToJSON(formData) {
2169
+ function buildPath(path, value, target, index2) {
2170
+ throwIfDepthExceeded(index2);
2171
+ let name2 = path[index2++];
2172
+ if (name2 === "__proto__") return true;
2173
+ const isNumericKey = Number.isFinite(+name2);
2174
+ const isLast = index2 >= path.length;
2175
+ name2 = !name2 && utils$1.isArray(target) ? target.length : name2;
2176
+ if (isLast) {
2177
+ if (utils$1.hasOwnProp(target, name2)) {
2178
+ target[name2] = utils$1.isArray(target[name2]) ? target[name2].concat(value) : [target[name2], value];
2179
+ } else {
2180
+ target[name2] = value;
1393
2181
  }
2182
+ return !isNumericKey;
1394
2183
  }
1395
- if (utils$1.isArray(header)) {
1396
- header.forEach(deleteHeader);
1397
- } else {
1398
- deleteHeader(header);
2184
+ if (!utils$1.hasOwnProp(target, name2) || !utils$1.isObject(target[name2])) {
2185
+ target[name2] = [];
1399
2186
  }
1400
- return deleted;
1401
- }
1402
- clear(matcher) {
1403
- const keys = Object.keys(this);
1404
- let i = keys.length;
1405
- let deleted = false;
1406
- while (i--) {
1407
- const key = keys[i];
1408
- if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
1409
- delete this[key];
1410
- deleted = true;
1411
- }
2187
+ const result = buildPath(path, value, target[name2], index2);
2188
+ if (result && utils$1.isArray(target[name2])) {
2189
+ target[name2] = arrayToObject(target[name2]);
1412
2190
  }
1413
- return deleted;
1414
- }
1415
- normalize(format) {
1416
- const self2 = this;
1417
- const headers = {};
1418
- utils$1.forEach(this, (value, header) => {
1419
- const key = utils$1.findKey(headers, header);
1420
- if (key) {
1421
- self2[key] = normalizeValue(value);
1422
- delete self2[header];
1423
- return;
1424
- }
1425
- const normalized = format ? formatHeader(header) : String(header).trim();
1426
- if (normalized !== header) {
1427
- delete self2[header];
1428
- }
1429
- self2[normalized] = normalizeValue(value);
1430
- headers[normalized] = true;
1431
- });
1432
- return this;
1433
- }
1434
- concat(...targets) {
1435
- return this.constructor.concat(this, ...targets);
2191
+ return !isNumericKey;
1436
2192
  }
1437
- toJSON(asStrings) {
1438
- const obj = /* @__PURE__ */ Object.create(null);
1439
- utils$1.forEach(this, (value, header) => {
1440
- value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value);
2193
+ if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
2194
+ const obj = {};
2195
+ utils$1.forEachEntry(formData, (name2, value) => {
2196
+ buildPath(parsePropPath(name2), value, obj, 0);
1441
2197
  });
1442
2198
  return obj;
1443
2199
  }
1444
- [Symbol.iterator]() {
1445
- return Object.entries(this.toJSON())[Symbol.iterator]();
1446
- }
1447
- toString() {
1448
- return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n");
1449
- }
1450
- getSetCookie() {
1451
- return this.get("set-cookie") || [];
1452
- }
1453
- get [Symbol.toStringTag]() {
1454
- return "AxiosHeaders";
1455
- }
1456
- static from(thing) {
1457
- return thing instanceof this ? thing : new this(thing);
1458
- }
1459
- static concat(first, ...targets) {
1460
- const computed = new this(first);
1461
- targets.forEach((target) => computed.set(target));
1462
- return computed;
2200
+ return null;
2201
+ }
2202
+ const own = (obj, key) => obj != null && utils$1.hasOwnProp(obj, key) ? obj[key] : void 0;
2203
+ function stringifySafely(rawValue, parser, encoder) {
2204
+ if (utils$1.isString(rawValue)) {
2205
+ try {
2206
+ (parser || JSON.parse)(rawValue);
2207
+ return utils$1.trim(rawValue);
2208
+ } catch (e) {
2209
+ if (e.name !== "SyntaxError") {
2210
+ throw e;
2211
+ }
2212
+ }
1463
2213
  }
1464
- static accessor(header) {
1465
- const internals = this[$internals] = this[$internals] = {
1466
- accessors: {}
1467
- };
1468
- const accessors = internals.accessors;
1469
- const prototype2 = this.prototype;
1470
- function defineAccessor(_header) {
1471
- const lHeader = normalizeHeader(_header);
1472
- if (!accessors[lHeader]) {
1473
- buildAccessors(prototype2, _header);
1474
- accessors[lHeader] = true;
2214
+ return (encoder || JSON.stringify)(rawValue);
2215
+ }
2216
+ const defaults = {
2217
+ transitional: transitionalDefaults,
2218
+ adapter: ["xhr", "http", "fetch"],
2219
+ transformRequest: [
2220
+ function transformRequest(data, headers) {
2221
+ const contentType = headers.getContentType() || "";
2222
+ const hasJSONContentType = contentType.indexOf("application/json") > -1;
2223
+ const isObjectPayload = utils$1.isObject(data);
2224
+ if (isObjectPayload && utils$1.isHTMLForm(data)) {
2225
+ data = new FormData(data);
2226
+ }
2227
+ const isFormData2 = utils$1.isFormData(data);
2228
+ if (isFormData2) {
2229
+ return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
2230
+ }
2231
+ 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)) {
2232
+ return data;
2233
+ }
2234
+ if (utils$1.isArrayBufferView(data)) {
2235
+ return data.buffer;
2236
+ }
2237
+ if (utils$1.isURLSearchParams(data)) {
2238
+ headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
2239
+ return data.toString();
2240
+ }
2241
+ let isFileList2;
2242
+ if (isObjectPayload) {
2243
+ const formSerializer = own(this, "formSerializer");
2244
+ if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
2245
+ return toURLEncodedForm(data, formSerializer).toString();
2246
+ }
2247
+ if ((isFileList2 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
2248
+ const env = own(this, "env");
2249
+ const _FormData = env && env.FormData;
2250
+ return toFormData$1(
2251
+ isFileList2 ? { "files[]": data } : data,
2252
+ _FormData && new _FormData(),
2253
+ formSerializer
2254
+ );
2255
+ }
2256
+ }
2257
+ if (isObjectPayload || hasJSONContentType) {
2258
+ headers.setContentType("application/json", false);
2259
+ return stringifySafely(data);
1475
2260
  }
2261
+ return data;
2262
+ }
2263
+ ],
2264
+ transformResponse: [
2265
+ function transformResponse(data) {
2266
+ const transitional2 = own(this, "transitional") || defaults.transitional;
2267
+ const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing;
2268
+ const responseType = own(this, "responseType");
2269
+ const JSONRequested = responseType === "json";
2270
+ if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
2271
+ return data;
2272
+ }
2273
+ if (data && utils$1.isString(data) && (forcedJSONParsing && !responseType || JSONRequested)) {
2274
+ const silentJSONParsing = transitional2 && transitional2.silentJSONParsing;
2275
+ const strictJSONParsing = !silentJSONParsing && JSONRequested;
2276
+ try {
2277
+ return JSON.parse(data, own(this, "parseReviver"));
2278
+ } catch (e) {
2279
+ if (strictJSONParsing) {
2280
+ if (e.name === "SyntaxError") {
2281
+ throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, own(this, "response"));
2282
+ }
2283
+ throw e;
2284
+ }
2285
+ }
2286
+ }
2287
+ return data;
2288
+ }
2289
+ ],
2290
+ /**
2291
+ * A timeout in milliseconds to abort a request. If set to 0 (default) a
2292
+ * timeout is not created.
2293
+ */
2294
+ timeout: 0,
2295
+ xsrfCookieName: "XSRF-TOKEN",
2296
+ xsrfHeaderName: "X-XSRF-TOKEN",
2297
+ maxContentLength: -1,
2298
+ maxBodyLength: -1,
2299
+ env: {
2300
+ FormData: platform.classes.FormData,
2301
+ Blob: platform.classes.Blob
2302
+ },
2303
+ validateStatus: function validateStatus(status) {
2304
+ return status >= 200 && status < 300;
2305
+ },
2306
+ headers: {
2307
+ common: {
2308
+ Accept: "application/json, text/plain, */*",
2309
+ "Content-Type": void 0
1476
2310
  }
1477
- utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1478
- return this;
1479
2311
  }
1480
2312
  };
1481
- AxiosHeaders$1.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]);
1482
- utils$1.reduceDescriptors(AxiosHeaders$1.prototype, ({ value }, key) => {
1483
- let mapped = key[0].toUpperCase() + key.slice(1);
1484
- return {
1485
- get: () => value,
1486
- set(headerValue) {
1487
- this[mapped] = headerValue;
1488
- }
1489
- };
2313
+ utils$1.forEach(["delete", "get", "head", "post", "put", "patch", "query"], (method) => {
2314
+ defaults.headers[method] = {};
1490
2315
  });
1491
- utils$1.freezeMethods(AxiosHeaders$1);
1492
2316
  function transformData(fns, response) {
1493
2317
  const config2 = this || defaults;
1494
2318
  const context = response || config2;
@@ -1503,13 +2327,22 @@ function transformData(fns, response) {
1503
2327
  function isCancel$1(value) {
1504
2328
  return !!(value && value.__CANCEL__);
1505
2329
  }
1506
- function CanceledError$1(message, config2, request) {
1507
- AxiosError$1.call(this, message == null ? "canceled" : message, AxiosError$1.ERR_CANCELED, config2, request);
1508
- this.name = "CanceledError";
1509
- }
1510
- utils$1.inherits(CanceledError$1, AxiosError$1, {
1511
- __CANCEL__: true
1512
- });
2330
+ let CanceledError$1 = class CanceledError extends AxiosError$1 {
2331
+ /**
2332
+ * A `CanceledError` is an object that is thrown when an operation is canceled.
2333
+ *
2334
+ * @param {string=} message The message.
2335
+ * @param {Object=} config The config.
2336
+ * @param {Object=} request The request.
2337
+ *
2338
+ * @returns {CanceledError} The created error.
2339
+ */
2340
+ constructor(message, config2, request) {
2341
+ super(message == null ? "canceled" : message, AxiosError$1.ERR_CANCELED, config2, request);
2342
+ this.name = "CanceledError";
2343
+ this.__CANCEL__ = true;
2344
+ }
2345
+ };
1513
2346
  function settle(resolve, reject, response) {
1514
2347
  const validateStatus2 = response.config.validateStatus;
1515
2348
  if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
@@ -1517,7 +2350,7 @@ function settle(resolve, reject, response) {
1517
2350
  } else {
1518
2351
  reject(new AxiosError$1(
1519
2352
  "Request failed with status code " + response.status,
1520
- [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
2353
+ response.status >= 400 && response.status < 500 ? AxiosError$1.ERR_BAD_REQUEST : AxiosError$1.ERR_BAD_RESPONSE,
1521
2354
  response.config,
1522
2355
  response.request,
1523
2356
  response
@@ -1525,7 +2358,7 @@ function settle(resolve, reject, response) {
1525
2358
  }
1526
2359
  }
1527
2360
  function parseProtocol(url) {
1528
- const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
2361
+ const match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url);
1529
2362
  return match && match[1] || "";
1530
2363
  }
1531
2364
  function speedometer(samplesCount, min) {
@@ -1597,19 +2430,22 @@ const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
1597
2430
  let bytesNotified = 0;
1598
2431
  const _speedometer = speedometer(50, 250);
1599
2432
  return throttle((e) => {
1600
- const loaded = e.loaded;
2433
+ if (!e || typeof e.loaded !== "number") {
2434
+ return;
2435
+ }
2436
+ const rawLoaded = e.loaded;
1601
2437
  const total = e.lengthComputable ? e.total : void 0;
1602
- const progressBytes = loaded - bytesNotified;
2438
+ const loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded;
2439
+ const progressBytes = Math.max(0, loaded - bytesNotified);
1603
2440
  const rate = _speedometer(progressBytes);
1604
- const inRange = loaded <= total;
1605
- bytesNotified = loaded;
2441
+ bytesNotified = Math.max(bytesNotified, loaded);
1606
2442
  const data = {
1607
2443
  loaded,
1608
2444
  total,
1609
2445
  progress: total ? loaded / total : void 0,
1610
2446
  bytes: progressBytes,
1611
2447
  rate: rate ? rate : void 0,
1612
- estimated: rate && total && inRange ? (total - loaded) / rate : void 0,
2448
+ estimated: rate && total ? (total - loaded) / rate : void 0,
1613
2449
  event: e,
1614
2450
  lengthComputable: total != null,
1615
2451
  [isDownloadStream ? "download" : "upload"]: true
@@ -1619,11 +2455,14 @@ const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
1619
2455
  };
1620
2456
  const progressEventDecorator = (total, throttled) => {
1621
2457
  const lengthComputable = total != null;
1622
- return [(loaded) => throttled[0]({
1623
- lengthComputable,
1624
- total,
1625
- loaded
1626
- }), throttled[1]];
2458
+ return [
2459
+ (loaded) => throttled[0]({
2460
+ lengthComputable,
2461
+ total,
2462
+ loaded
2463
+ }),
2464
+ throttled[1]
2465
+ ];
1627
2466
  };
1628
2467
  const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
1629
2468
  const isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url) => {
@@ -1636,20 +2475,44 @@ const isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origi
1636
2475
  const cookies = platform.hasStandardBrowserEnv ? (
1637
2476
  // Standard browser envs support document.cookie
1638
2477
  {
1639
- write(name, value, expires, path, domain, secure) {
1640
- const cookie = [name + "=" + encodeURIComponent(value)];
1641
- utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString());
1642
- utils$1.isString(path) && cookie.push("path=" + path);
1643
- utils$1.isString(domain) && cookie.push("domain=" + domain);
1644
- secure === true && cookie.push("secure");
2478
+ write(name2, value, expires, path, domain, secure, sameSite) {
2479
+ if (typeof document === "undefined") return;
2480
+ const cookie = [`${name2}=${encodeURIComponent(value)}`];
2481
+ if (utils$1.isNumber(expires)) {
2482
+ cookie.push(`expires=${new Date(expires).toUTCString()}`);
2483
+ }
2484
+ if (utils$1.isString(path)) {
2485
+ cookie.push(`path=${path}`);
2486
+ }
2487
+ if (utils$1.isString(domain)) {
2488
+ cookie.push(`domain=${domain}`);
2489
+ }
2490
+ if (secure === true) {
2491
+ cookie.push("secure");
2492
+ }
2493
+ if (utils$1.isString(sameSite)) {
2494
+ cookie.push(`SameSite=${sameSite}`);
2495
+ }
1645
2496
  document.cookie = cookie.join("; ");
1646
2497
  },
1647
- read(name) {
1648
- const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
1649
- return match ? decodeURIComponent(match[3]) : null;
2498
+ read(name2) {
2499
+ if (typeof document === "undefined") return null;
2500
+ const cookies2 = document.cookie.split(";");
2501
+ for (let i = 0; i < cookies2.length; i++) {
2502
+ const cookie = cookies2[i].replace(/^\s+/, "");
2503
+ const eq = cookie.indexOf("=");
2504
+ if (eq !== -1 && cookie.slice(0, eq) === name2) {
2505
+ try {
2506
+ return decodeURIComponent(cookie.slice(eq + 1));
2507
+ } catch (e) {
2508
+ return cookie.slice(eq + 1);
2509
+ }
2510
+ }
2511
+ }
2512
+ return null;
1650
2513
  },
1651
- remove(name) {
1652
- this.write(name, "", Date.now() - 864e5);
2514
+ remove(name2) {
2515
+ this.write(name2, "", Date.now() - 864e5, "/");
1653
2516
  }
1654
2517
  }
1655
2518
  ) : (
@@ -1665,22 +2528,58 @@ const cookies = platform.hasStandardBrowserEnv ? (
1665
2528
  }
1666
2529
  );
1667
2530
  function isAbsoluteURL(url) {
2531
+ if (typeof url !== "string") {
2532
+ return false;
2533
+ }
1668
2534
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
1669
2535
  }
1670
2536
  function combineURLs(baseURL, relativeURL) {
1671
2537
  return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
1672
2538
  }
1673
- function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
2539
+ const malformedHttpProtocol = /^https?:(?!\/\/)/i;
2540
+ const httpProtocolControlCharacters = /[\t\n\r]/g;
2541
+ function stripLeadingC0ControlOrSpace(url) {
2542
+ let i = 0;
2543
+ while (i < url.length && url.charCodeAt(i) <= 32) {
2544
+ i++;
2545
+ }
2546
+ return url.slice(i);
2547
+ }
2548
+ function normalizeURLForProtocolCheck(url) {
2549
+ return stripLeadingC0ControlOrSpace(url).replace(httpProtocolControlCharacters, "");
2550
+ }
2551
+ function assertValidHttpProtocolURL(url, config2) {
2552
+ if (typeof url === "string" && malformedHttpProtocol.test(normalizeURLForProtocolCheck(url))) {
2553
+ throw new AxiosError$1(
2554
+ 'Invalid URL: missing "//" after protocol',
2555
+ AxiosError$1.ERR_INVALID_URL,
2556
+ config2
2557
+ );
2558
+ }
2559
+ }
2560
+ function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls, config2) {
2561
+ assertValidHttpProtocolURL(requestedURL, config2);
1674
2562
  let isRelativeUrl = !isAbsoluteURL(requestedURL);
1675
- if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
2563
+ if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) {
2564
+ assertValidHttpProtocolURL(baseURL, config2);
1676
2565
  return combineURLs(baseURL, requestedURL);
1677
2566
  }
1678
2567
  return requestedURL;
1679
2568
  }
1680
2569
  const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
1681
2570
  function mergeConfig$1(config1, config2) {
2571
+ config1 = config1 || {};
1682
2572
  config2 = config2 || {};
1683
- const config3 = {};
2573
+ const config3 = /* @__PURE__ */ Object.create(null);
2574
+ Object.defineProperty(config3, "hasOwnProperty", {
2575
+ // Null-proto descriptor so a polluted Object.prototype.get cannot turn
2576
+ // this data descriptor into an accessor descriptor on the way in.
2577
+ __proto__: null,
2578
+ value: Object.prototype.hasOwnProperty,
2579
+ enumerable: false,
2580
+ writable: true,
2581
+ configurable: true
2582
+ });
1684
2583
  function getMergedValue(target, source, prop, caseless) {
1685
2584
  if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
1686
2585
  return utils$1.merge.call({ caseless }, target, source);
@@ -1710,10 +2609,27 @@ function mergeConfig$1(config1, config2) {
1710
2609
  return getMergedValue(void 0, a);
1711
2610
  }
1712
2611
  }
2612
+ function getMergedTransitionalOption(prop) {
2613
+ const transitional2 = utils$1.hasOwnProp(config2, "transitional") ? config2.transitional : void 0;
2614
+ if (!utils$1.isUndefined(transitional2)) {
2615
+ if (utils$1.isPlainObject(transitional2)) {
2616
+ if (utils$1.hasOwnProp(transitional2, prop)) {
2617
+ return transitional2[prop];
2618
+ }
2619
+ } else {
2620
+ return void 0;
2621
+ }
2622
+ }
2623
+ const transitional1 = utils$1.hasOwnProp(config1, "transitional") ? config1.transitional : void 0;
2624
+ if (utils$1.isPlainObject(transitional1) && utils$1.hasOwnProp(transitional1, prop)) {
2625
+ return transitional1[prop];
2626
+ }
2627
+ return void 0;
2628
+ }
1713
2629
  function mergeDirectKeys(a, b, prop) {
1714
- if (prop in config2) {
2630
+ if (utils$1.hasOwnProp(config2, prop)) {
1715
2631
  return getMergedValue(a, b);
1716
- } else if (prop in config1) {
2632
+ } else if (utils$1.hasOwnProp(config1, prop)) {
1717
2633
  return getMergedValue(void 0, a);
1718
2634
  }
1719
2635
  }
@@ -1744,44 +2660,87 @@ function mergeConfig$1(config1, config2) {
1744
2660
  httpsAgent: defaultToConfig2,
1745
2661
  cancelToken: defaultToConfig2,
1746
2662
  socketPath: defaultToConfig2,
2663
+ allowedSocketPaths: defaultToConfig2,
1747
2664
  responseEncoding: defaultToConfig2,
1748
2665
  validateStatus: mergeDirectKeys,
1749
2666
  headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
1750
2667
  };
1751
2668
  utils$1.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) {
1752
- const merge2 = mergeMap[prop] || mergeDeepProperties;
1753
- const configValue = merge2(config1[prop], config2[prop], prop);
2669
+ if (prop === "__proto__" || prop === "constructor" || prop === "prototype") return;
2670
+ const merge2 = utils$1.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
2671
+ const a = utils$1.hasOwnProp(config1, prop) ? config1[prop] : void 0;
2672
+ const b = utils$1.hasOwnProp(config2, prop) ? config2[prop] : void 0;
2673
+ const configValue = merge2(a, b, prop);
1754
2674
  utils$1.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config3[prop] = configValue);
1755
2675
  });
2676
+ if (utils$1.hasOwnProp(config2, "validateStatus") && utils$1.isUndefined(config2.validateStatus) && getMergedTransitionalOption("validateStatusUndefinedResolves") === false) {
2677
+ if (utils$1.hasOwnProp(config1, "validateStatus")) {
2678
+ config3.validateStatus = getMergedValue(void 0, config1.validateStatus);
2679
+ } else {
2680
+ delete config3.validateStatus;
2681
+ }
2682
+ }
1756
2683
  return config3;
1757
2684
  }
1758
- const resolveConfig = (config2) => {
2685
+ const FORM_DATA_CONTENT_HEADERS = ["content-type", "content-length"];
2686
+ function setFormDataHeaders(headers, formHeaders, policy) {
2687
+ if (policy !== "content-only") {
2688
+ headers.set(formHeaders);
2689
+ return;
2690
+ }
2691
+ Object.entries(formHeaders || {}).forEach(([key, val]) => {
2692
+ if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {
2693
+ headers.set(key, val);
2694
+ }
2695
+ });
2696
+ }
2697
+ const encodeUTF8$1 = (str2) => encodeURIComponent(str2).replace(
2698
+ /%([0-9A-F]{2})/gi,
2699
+ (_, hex) => String.fromCharCode(parseInt(hex, 16))
2700
+ );
2701
+ function resolveConfig(config2) {
1759
2702
  const newConfig = mergeConfig$1({}, config2);
1760
- let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
2703
+ const own2 = (key) => utils$1.hasOwnProp(newConfig, key) ? newConfig[key] : void 0;
2704
+ const data = own2("data");
2705
+ let withXSRFToken = own2("withXSRFToken");
2706
+ const xsrfHeaderName = own2("xsrfHeaderName");
2707
+ const xsrfCookieName = own2("xsrfCookieName");
2708
+ let headers = own2("headers");
2709
+ const auth = own2("auth");
2710
+ const baseURL = own2("baseURL");
2711
+ const allowAbsoluteUrls = own2("allowAbsoluteUrls");
2712
+ const url = own2("url");
1761
2713
  newConfig.headers = headers = AxiosHeaders$1.from(headers);
1762
- newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config2.params, config2.paramsSerializer);
2714
+ newConfig.url = buildURL(
2715
+ buildFullPath(baseURL, url, allowAbsoluteUrls, newConfig),
2716
+ own2("params"),
2717
+ own2("paramsSerializer")
2718
+ );
1763
2719
  if (auth) {
1764
- headers.set(
1765
- "Authorization",
1766
- "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : ""))
1767
- );
2720
+ const username = utils$1.getSafeProp(auth, "username") || "";
2721
+ const password = utils$1.getSafeProp(auth, "password") || "";
2722
+ try {
2723
+ headers.set(
2724
+ "Authorization",
2725
+ "Basic " + btoa(username + ":" + (password ? encodeUTF8$1(password) : ""))
2726
+ );
2727
+ } catch (e) {
2728
+ throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_OPTION_VALUE, config2);
2729
+ }
1768
2730
  }
1769
2731
  if (utils$1.isFormData(data)) {
1770
- if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
2732
+ if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv || utils$1.isReactNative(data)) {
1771
2733
  headers.setContentType(void 0);
1772
2734
  } else if (utils$1.isFunction(data.getHeaders)) {
1773
- const formHeaders = data.getHeaders();
1774
- const allowedHeaders = ["content-type", "content-length"];
1775
- Object.entries(formHeaders).forEach(([key, val]) => {
1776
- if (allowedHeaders.includes(key.toLowerCase())) {
1777
- headers.set(key, val);
1778
- }
1779
- });
2735
+ setFormDataHeaders(headers, data.getHeaders(), own2("formDataHeaderPolicy"));
1780
2736
  }
1781
2737
  }
1782
2738
  if (platform.hasStandardBrowserEnv) {
1783
- withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
1784
- if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(newConfig.url)) {
2739
+ if (utils$1.isFunction(withXSRFToken)) {
2740
+ withXSRFToken = withXSRFToken(newConfig);
2741
+ }
2742
+ const shouldSendXSRF = withXSRFToken === true || withXSRFToken == null && isURLSameOrigin(newConfig.url);
2743
+ if (shouldSendXSRF) {
1785
2744
  const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
1786
2745
  if (xsrfValue) {
1787
2746
  headers.set(xsrfHeaderName, xsrfValue);
@@ -1789,7 +2748,7 @@ const resolveConfig = (config2) => {
1789
2748
  }
1790
2749
  }
1791
2750
  return newConfig;
1792
- };
2751
+ }
1793
2752
  const isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
1794
2753
  const xhrAdapter = isXHRAdapterSupported && function(config2) {
1795
2754
  return new Promise(function dispatchXhrRequest(resolve, reject) {
@@ -1825,13 +2784,17 @@ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1825
2784
  config: config2,
1826
2785
  request
1827
2786
  };
1828
- settle(function _resolve(value) {
1829
- resolve(value);
1830
- done();
1831
- }, function _reject(err) {
1832
- reject(err);
1833
- done();
1834
- }, response);
2787
+ settle(
2788
+ function _resolve(value) {
2789
+ resolve(value);
2790
+ done();
2791
+ },
2792
+ function _reject(err) {
2793
+ reject(err);
2794
+ done();
2795
+ },
2796
+ response
2797
+ );
1835
2798
  request = null;
1836
2799
  }
1837
2800
  if ("onloadend" in request) {
@@ -1841,7 +2804,7 @@ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1841
2804
  if (!request || request.readyState !== 4) {
1842
2805
  return;
1843
2806
  }
1844
- if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
2807
+ if (request.status === 0 && !(request.responseURL && request.responseURL.startsWith("file:"))) {
1845
2808
  return;
1846
2809
  }
1847
2810
  setTimeout(onloadend);
@@ -1852,6 +2815,7 @@ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1852
2815
  return;
1853
2816
  }
1854
2817
  reject(new AxiosError$1("Request aborted", AxiosError$1.ECONNABORTED, config2, request));
2818
+ done();
1855
2819
  request = null;
1856
2820
  };
1857
2821
  request.onerror = function handleError(event) {
@@ -1859,6 +2823,7 @@ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1859
2823
  const err = new AxiosError$1(msg, AxiosError$1.ERR_NETWORK, config2, request);
1860
2824
  err.event = event || null;
1861
2825
  reject(err);
2826
+ done();
1862
2827
  request = null;
1863
2828
  };
1864
2829
  request.ontimeout = function handleTimeout() {
@@ -1867,17 +2832,20 @@ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1867
2832
  if (_config.timeoutErrorMessage) {
1868
2833
  timeoutErrorMessage = _config.timeoutErrorMessage;
1869
2834
  }
1870
- reject(new AxiosError$1(
1871
- timeoutErrorMessage,
1872
- transitional2.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
1873
- config2,
1874
- request
1875
- ));
2835
+ reject(
2836
+ new AxiosError$1(
2837
+ timeoutErrorMessage,
2838
+ transitional2.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
2839
+ config2,
2840
+ request
2841
+ )
2842
+ );
2843
+ done();
1876
2844
  request = null;
1877
2845
  };
1878
2846
  requestData === void 0 && requestHeaders.setContentType(null);
1879
2847
  if ("setRequestHeader" in request) {
1880
- utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
2848
+ utils$1.forEach(toByteStringHeaderObject(requestHeaders), function setRequestHeader(val, key) {
1881
2849
  request.setRequestHeader(key, val);
1882
2850
  });
1883
2851
  }
@@ -1903,6 +2871,7 @@ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1903
2871
  }
1904
2872
  reject(!cancel || cancel.type ? new CanceledError$1(null, config2, request) : cancel);
1905
2873
  request.abort();
2874
+ done();
1906
2875
  request = null;
1907
2876
  };
1908
2877
  _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
@@ -1911,45 +2880,56 @@ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1911
2880
  }
1912
2881
  }
1913
2882
  const protocol = parseProtocol(_config.url);
1914
- if (protocol && platform.protocols.indexOf(protocol) === -1) {
1915
- reject(new AxiosError$1("Unsupported protocol " + protocol + ":", AxiosError$1.ERR_BAD_REQUEST, config2));
2883
+ if (protocol && !platform.protocols.includes(protocol)) {
2884
+ reject(
2885
+ new AxiosError$1(
2886
+ "Unsupported protocol " + protocol + ":",
2887
+ AxiosError$1.ERR_BAD_REQUEST,
2888
+ config2
2889
+ )
2890
+ );
2891
+ done();
1916
2892
  return;
1917
2893
  }
1918
2894
  request.send(requestData || null);
1919
2895
  });
1920
2896
  };
1921
2897
  const composeSignals = (signals, timeout) => {
1922
- const { length } = signals = signals ? signals.filter(Boolean) : [];
1923
- if (timeout || length) {
1924
- let controller2 = new AbortController();
1925
- let aborted;
1926
- const onabort = function(reason) {
1927
- if (!aborted) {
1928
- aborted = true;
1929
- unsubscribe();
1930
- const err = reason instanceof Error ? reason : this.reason;
1931
- controller2.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err));
1932
- }
1933
- };
1934
- let timer = timeout && setTimeout(() => {
1935
- timer = null;
1936
- onabort(new AxiosError$1(`timeout ${timeout} of ms exceeded`, AxiosError$1.ETIMEDOUT));
1937
- }, timeout);
1938
- const unsubscribe = () => {
1939
- if (signals) {
1940
- timer && clearTimeout(timer);
1941
- timer = null;
1942
- signals.forEach((signal2) => {
1943
- signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
1944
- });
1945
- signals = null;
1946
- }
1947
- };
1948
- signals.forEach((signal2) => signal2.addEventListener("abort", onabort));
1949
- const { signal } = controller2;
1950
- signal.unsubscribe = () => utils$1.asap(unsubscribe);
1951
- return signal;
2898
+ signals = signals ? signals.filter(Boolean) : [];
2899
+ if (!timeout && !signals.length) {
2900
+ return;
1952
2901
  }
2902
+ const controller2 = new AbortController();
2903
+ let aborted = false;
2904
+ const onabort = function(reason) {
2905
+ if (!aborted) {
2906
+ aborted = true;
2907
+ unsubscribe();
2908
+ const err = reason instanceof Error ? reason : this.reason;
2909
+ controller2.abort(
2910
+ err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err)
2911
+ );
2912
+ }
2913
+ };
2914
+ let timer = timeout && setTimeout(() => {
2915
+ timer = null;
2916
+ onabort(new AxiosError$1(`timeout of ${timeout}ms exceeded`, AxiosError$1.ETIMEDOUT));
2917
+ }, timeout);
2918
+ const unsubscribe = () => {
2919
+ if (!signals) {
2920
+ return;
2921
+ }
2922
+ timer && clearTimeout(timer);
2923
+ timer = null;
2924
+ signals.forEach((signal2) => {
2925
+ signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
2926
+ });
2927
+ signals = null;
2928
+ };
2929
+ signals.forEach((signal2) => signal2.addEventListener("abort", onabort, { once: true }));
2930
+ const { signal } = controller2;
2931
+ signal.unsubscribe = () => utils$1.asap(unsubscribe);
2932
+ return signal;
1953
2933
  };
1954
2934
  const streamChunk = function* (chunk, chunkSize) {
1955
2935
  let len = chunk.byteLength;
@@ -1998,44 +2978,127 @@ const trackStream = (stream, chunkSize, onProgress, onFinish) => {
1998
2978
  onFinish && onFinish(e);
1999
2979
  }
2000
2980
  };
2001
- return new ReadableStream({
2002
- async pull(controller2) {
2003
- try {
2004
- const { done: done2, value } = await iterator2.next();
2005
- if (done2) {
2006
- _onFinish();
2007
- controller2.close();
2008
- return;
2009
- }
2010
- let len = value.byteLength;
2011
- if (onProgress) {
2012
- let loadedBytes = bytes += len;
2013
- onProgress(loadedBytes);
2981
+ return new ReadableStream(
2982
+ {
2983
+ async pull(controller2) {
2984
+ try {
2985
+ const { done: done2, value } = await iterator2.next();
2986
+ if (done2) {
2987
+ _onFinish();
2988
+ controller2.close();
2989
+ return;
2990
+ }
2991
+ let len = value.byteLength;
2992
+ if (onProgress) {
2993
+ let loadedBytes = bytes += len;
2994
+ onProgress(loadedBytes);
2995
+ }
2996
+ controller2.enqueue(new Uint8Array(value));
2997
+ } catch (err) {
2998
+ _onFinish(err);
2999
+ throw err;
2014
3000
  }
2015
- controller2.enqueue(new Uint8Array(value));
2016
- } catch (err) {
2017
- _onFinish(err);
2018
- throw err;
3001
+ },
3002
+ cancel(reason) {
3003
+ _onFinish(reason);
3004
+ return iterator2.return();
2019
3005
  }
2020
3006
  },
2021
- cancel(reason) {
2022
- _onFinish(reason);
2023
- return iterator2.return();
3007
+ {
3008
+ highWaterMark: 2
2024
3009
  }
2025
- }, {
2026
- highWaterMark: 2
2027
- });
3010
+ );
2028
3011
  };
3012
+ const isHexDigit = (charCode) => charCode >= 48 && charCode <= 57 || charCode >= 65 && charCode <= 70 || charCode >= 97 && charCode <= 102;
3013
+ const isPercentEncodedByte = (str2, i, len) => i + 2 < len && isHexDigit(str2.charCodeAt(i + 1)) && isHexDigit(str2.charCodeAt(i + 2));
3014
+ function estimateDataURLDecodedBytes(url) {
3015
+ if (!url || typeof url !== "string") return 0;
3016
+ if (!url.startsWith("data:")) return 0;
3017
+ const comma = url.indexOf(",");
3018
+ if (comma < 0) return 0;
3019
+ const meta = url.slice(5, comma);
3020
+ const body = url.slice(comma + 1);
3021
+ const isBase64 = /;base64/i.test(meta);
3022
+ if (isBase64) {
3023
+ let effectiveLen = body.length;
3024
+ const len = body.length;
3025
+ for (let i = 0; i < len; i++) {
3026
+ if (body.charCodeAt(i) === 37 && i + 2 < len) {
3027
+ const a = body.charCodeAt(i + 1);
3028
+ const b = body.charCodeAt(i + 2);
3029
+ const isHex = isHexDigit(a) && isHexDigit(b);
3030
+ if (isHex) {
3031
+ effectiveLen -= 2;
3032
+ i += 2;
3033
+ }
3034
+ }
3035
+ }
3036
+ let pad = 0;
3037
+ let idx = len - 1;
3038
+ const tailIsPct3D = (j) => j >= 2 && body.charCodeAt(j - 2) === 37 && // '%'
3039
+ body.charCodeAt(j - 1) === 51 && // '3'
3040
+ (body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100);
3041
+ if (idx >= 0) {
3042
+ if (body.charCodeAt(idx) === 61) {
3043
+ pad++;
3044
+ idx--;
3045
+ } else if (tailIsPct3D(idx)) {
3046
+ pad++;
3047
+ idx -= 3;
3048
+ }
3049
+ }
3050
+ if (pad === 1 && idx >= 0) {
3051
+ if (body.charCodeAt(idx) === 61) {
3052
+ pad++;
3053
+ } else if (tailIsPct3D(idx)) {
3054
+ pad++;
3055
+ }
3056
+ }
3057
+ const groups = Math.floor(effectiveLen / 4);
3058
+ const bytes2 = groups * 3 - (pad || 0);
3059
+ return bytes2 > 0 ? bytes2 : 0;
3060
+ }
3061
+ let bytes = 0;
3062
+ for (let i = 0, len = body.length; i < len; i++) {
3063
+ const c = body.charCodeAt(i);
3064
+ if (c === 37 && isPercentEncodedByte(body, i, len)) {
3065
+ bytes += 1;
3066
+ i += 2;
3067
+ } else if (c < 128) {
3068
+ bytes += 1;
3069
+ } else if (c < 2048) {
3070
+ bytes += 2;
3071
+ } else if (c >= 55296 && c <= 56319 && i + 1 < len) {
3072
+ const next = body.charCodeAt(i + 1);
3073
+ if (next >= 56320 && next <= 57343) {
3074
+ bytes += 4;
3075
+ i++;
3076
+ } else {
3077
+ bytes += 3;
3078
+ }
3079
+ } else {
3080
+ bytes += 3;
3081
+ }
3082
+ }
3083
+ return bytes;
3084
+ }
3085
+ const VERSION$1 = "1.18.1";
2029
3086
  const DEFAULT_CHUNK_SIZE = 64 * 1024;
2030
3087
  const { isFunction } = utils$1;
2031
- const globalFetchAPI = (({ Request, Response }) => ({
2032
- Request,
2033
- Response
2034
- }))(utils$1.global);
2035
- const {
2036
- ReadableStream: ReadableStream$1,
2037
- TextEncoder
2038
- } = utils$1.global;
3088
+ const encodeUTF8 = (str2) => encodeURIComponent(str2).replace(
3089
+ /%([0-9A-F]{2})/gi,
3090
+ (_, hex) => String.fromCharCode(parseInt(hex, 16))
3091
+ );
3092
+ const decodeURIComponentSafe = (value) => {
3093
+ if (!utils$1.isString(value)) {
3094
+ return value;
3095
+ }
3096
+ try {
3097
+ return decodeURIComponent(value);
3098
+ } catch (error) {
3099
+ return value;
3100
+ }
3101
+ };
2039
3102
  const test = (fn, ...args) => {
2040
3103
  try {
2041
3104
  return !!fn(...args);
@@ -2043,10 +3106,27 @@ const test = (fn, ...args) => {
2043
3106
  return false;
2044
3107
  }
2045
3108
  };
3109
+ const maybeWithAuthCredentials = (url) => {
3110
+ const protocolIndex = url.indexOf("://");
3111
+ let urlToCheck = url;
3112
+ if (protocolIndex !== -1) {
3113
+ urlToCheck = urlToCheck.slice(protocolIndex + 3);
3114
+ }
3115
+ return urlToCheck.includes("@") || urlToCheck.includes(":");
3116
+ };
2046
3117
  const factory = (env) => {
2047
- env = utils$1.merge.call({
2048
- skipUndefined: true
2049
- }, globalFetchAPI, env);
3118
+ const globalObject = utils$1.global !== void 0 && utils$1.global !== null ? utils$1.global : globalThis;
3119
+ const { ReadableStream: ReadableStream2, TextEncoder } = globalObject;
3120
+ env = utils$1.merge.call(
3121
+ {
3122
+ skipUndefined: true
3123
+ },
3124
+ {
3125
+ Request: globalObject.Request,
3126
+ Response: globalObject.Response
3127
+ },
3128
+ env
3129
+ );
2050
3130
  const { fetch: envFetch, Request, Response } = env;
2051
3131
  const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === "function";
2052
3132
  const isRequestSupported = isFunction(Request);
@@ -2054,18 +3134,22 @@ const factory = (env) => {
2054
3134
  if (!isFetchSupported) {
2055
3135
  return false;
2056
3136
  }
2057
- const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1);
2058
- const encodeText = isFetchSupported && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : async (str) => new Uint8Array(await new Request(str).arrayBuffer()));
3137
+ const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream2);
3138
+ const encodeText = isFetchSupported && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder) => (str2) => encoder.encode(str2))(new TextEncoder()) : async (str2) => new Uint8Array(await new Request(str2).arrayBuffer()));
2059
3139
  const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
2060
3140
  let duplexAccessed = false;
2061
- const hasContentType = new Request(platform.origin, {
2062
- body: new ReadableStream$1(),
3141
+ const request = new Request(platform.origin, {
3142
+ body: new ReadableStream2(),
2063
3143
  method: "POST",
2064
3144
  get duplex() {
2065
3145
  duplexAccessed = true;
2066
3146
  return "half";
2067
3147
  }
2068
- }).headers.has("Content-Type");
3148
+ });
3149
+ const hasContentType = request.headers.has("Content-Type");
3150
+ if (request.body != null) {
3151
+ request.body.cancel();
3152
+ }
2069
3153
  return duplexAccessed && !hasContentType;
2070
3154
  });
2071
3155
  const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils$1.isReadableStream(new Response("").body));
@@ -2079,7 +3163,11 @@ const factory = (env) => {
2079
3163
  if (method) {
2080
3164
  return method.call(res);
2081
3165
  }
2082
- throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config2);
3166
+ throw new AxiosError$1(
3167
+ `Response type '${type}' is not supported`,
3168
+ AxiosError$1.ERR_NOT_SUPPORT,
3169
+ config2
3170
+ );
2083
3171
  });
2084
3172
  });
2085
3173
  })();
@@ -2124,63 +3212,189 @@ const factory = (env) => {
2124
3212
  responseType,
2125
3213
  headers,
2126
3214
  withCredentials = "same-origin",
2127
- fetchOptions
3215
+ fetchOptions,
3216
+ maxContentLength,
3217
+ maxBodyLength
2128
3218
  } = resolveConfig(config2);
3219
+ const hasMaxContentLength = utils$1.isNumber(maxContentLength) && maxContentLength > -1;
3220
+ const hasMaxBodyLength = utils$1.isNumber(maxBodyLength) && maxBodyLength > -1;
3221
+ const own2 = (key) => utils$1.hasOwnProp(config2, key) ? config2[key] : void 0;
2129
3222
  let _fetch = envFetch || fetch;
2130
3223
  responseType = responseType ? (responseType + "").toLowerCase() : "text";
2131
- let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
3224
+ let composedSignal = composeSignals(
3225
+ [signal, cancelToken && cancelToken.toAbortSignal()],
3226
+ timeout
3227
+ );
2132
3228
  let request = null;
2133
3229
  const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
2134
3230
  composedSignal.unsubscribe();
2135
3231
  });
2136
3232
  let requestContentLength;
3233
+ let pendingBodyError = null;
3234
+ const maxBodyLengthError = () => new AxiosError$1(
3235
+ "Request body larger than maxBodyLength limit",
3236
+ AxiosError$1.ERR_BAD_REQUEST,
3237
+ config2,
3238
+ request
3239
+ );
2137
3240
  try {
2138
- if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
2139
- let _request = new Request(url, {
2140
- method: "POST",
2141
- body: data,
2142
- duplex: "half"
2143
- });
2144
- let contentTypeHeader;
2145
- if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
2146
- headers.setContentType(contentTypeHeader);
3241
+ let auth = void 0;
3242
+ const configAuth = own2("auth");
3243
+ if (configAuth) {
3244
+ const username = utils$1.getSafeProp(configAuth, "username") || "";
3245
+ const password = utils$1.getSafeProp(configAuth, "password") || "";
3246
+ auth = {
3247
+ username,
3248
+ password
3249
+ };
3250
+ }
3251
+ if (maybeWithAuthCredentials(url)) {
3252
+ const parsedURL = new URL(url, platform.origin);
3253
+ if (!auth && (parsedURL.username || parsedURL.password)) {
3254
+ const urlUsername = decodeURIComponentSafe(parsedURL.username);
3255
+ const urlPassword = decodeURIComponentSafe(parsedURL.password);
3256
+ auth = {
3257
+ username: urlUsername,
3258
+ password: urlPassword
3259
+ };
3260
+ }
3261
+ if (parsedURL.username || parsedURL.password) {
3262
+ parsedURL.username = "";
3263
+ parsedURL.password = "";
3264
+ url = parsedURL.href;
2147
3265
  }
2148
- if (_request.body) {
2149
- const [onProgress, flush] = progressEventDecorator(
2150
- requestContentLength,
2151
- progressEventReducer(asyncDecorator(onUploadProgress))
3266
+ }
3267
+ if (auth) {
3268
+ headers.delete("authorization");
3269
+ headers.set(
3270
+ "Authorization",
3271
+ "Basic " + btoa(encodeUTF8((auth.username || "") + ":" + (auth.password || "")))
3272
+ );
3273
+ }
3274
+ if (hasMaxContentLength && typeof url === "string" && url.startsWith("data:")) {
3275
+ const estimated = estimateDataURLDecodedBytes(url);
3276
+ if (estimated > maxContentLength) {
3277
+ throw new AxiosError$1(
3278
+ "maxContentLength size of " + maxContentLength + " exceeded",
3279
+ AxiosError$1.ERR_BAD_RESPONSE,
3280
+ config2,
3281
+ request
2152
3282
  );
2153
- data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
2154
3283
  }
2155
3284
  }
3285
+ if (hasMaxBodyLength && method !== "get" && method !== "head") {
3286
+ const outboundLength = await getBodyLength(data);
3287
+ if (typeof outboundLength === "number" && isFinite(outboundLength)) {
3288
+ requestContentLength = outboundLength;
3289
+ if (outboundLength > maxBodyLength) {
3290
+ throw maxBodyLengthError();
3291
+ }
3292
+ }
3293
+ }
3294
+ const mustEnforceStreamBody = hasMaxBodyLength && (utils$1.isReadableStream(data) || utils$1.isStream(data));
3295
+ const trackRequestStream = (stream, onProgress, flush) => trackStream(
3296
+ stream,
3297
+ DEFAULT_CHUNK_SIZE,
3298
+ (loadedBytes) => {
3299
+ if (hasMaxBodyLength && loadedBytes > maxBodyLength) {
3300
+ throw pendingBodyError = maxBodyLengthError();
3301
+ }
3302
+ onProgress && onProgress(loadedBytes);
3303
+ },
3304
+ flush
3305
+ );
3306
+ if (supportsRequestStream && method !== "get" && method !== "head" && (onUploadProgress || mustEnforceStreamBody)) {
3307
+ requestContentLength = requestContentLength == null ? await resolveBodyLength(headers, data) : requestContentLength;
3308
+ if (requestContentLength !== 0 || mustEnforceStreamBody) {
3309
+ let _request = new Request(url, {
3310
+ method: "POST",
3311
+ body: data,
3312
+ duplex: "half"
3313
+ });
3314
+ let contentTypeHeader;
3315
+ if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
3316
+ headers.setContentType(contentTypeHeader);
3317
+ }
3318
+ if (_request.body) {
3319
+ const [onProgress, flush] = onUploadProgress && progressEventDecorator(
3320
+ requestContentLength,
3321
+ progressEventReducer(asyncDecorator(onUploadProgress))
3322
+ ) || [];
3323
+ data = trackRequestStream(_request.body, onProgress, flush);
3324
+ }
3325
+ }
3326
+ } else if (mustEnforceStreamBody && !isRequestSupported && isReadableStreamSupported && method !== "get" && method !== "head") {
3327
+ data = trackRequestStream(data);
3328
+ } else if (mustEnforceStreamBody && isRequestSupported && !supportsRequestStream && method !== "get" && method !== "head") {
3329
+ throw new AxiosError$1(
3330
+ "Stream request bodies are not supported by the current fetch implementation",
3331
+ AxiosError$1.ERR_NOT_SUPPORT,
3332
+ config2,
3333
+ request
3334
+ );
3335
+ }
2156
3336
  if (!utils$1.isString(withCredentials)) {
2157
3337
  withCredentials = withCredentials ? "include" : "omit";
2158
3338
  }
2159
3339
  const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype;
3340
+ if (utils$1.isFormData(data)) {
3341
+ const contentType = headers.getContentType();
3342
+ if (contentType && /^multipart\/form-data/i.test(contentType) && !/boundary=/i.test(contentType)) {
3343
+ headers.delete("content-type");
3344
+ }
3345
+ }
3346
+ headers.set("User-Agent", "axios/" + VERSION$1, false);
2160
3347
  const resolvedOptions = {
2161
3348
  ...fetchOptions,
2162
3349
  signal: composedSignal,
2163
3350
  method: method.toUpperCase(),
2164
- headers: headers.normalize().toJSON(),
3351
+ headers: toByteStringHeaderObject(headers.normalize()),
2165
3352
  body: data,
2166
3353
  duplex: "half",
2167
3354
  credentials: isCredentialsSupported ? withCredentials : void 0
2168
3355
  };
2169
3356
  request = isRequestSupported && new Request(url, resolvedOptions);
2170
3357
  let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions));
3358
+ const responseHeaders = AxiosHeaders$1.from(response.headers);
3359
+ if (hasMaxContentLength) {
3360
+ const declaredLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
3361
+ if (declaredLength != null && declaredLength > maxContentLength) {
3362
+ throw new AxiosError$1(
3363
+ "maxContentLength size of " + maxContentLength + " exceeded",
3364
+ AxiosError$1.ERR_BAD_RESPONSE,
3365
+ config2,
3366
+ request
3367
+ );
3368
+ }
3369
+ }
2171
3370
  const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
2172
- if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
3371
+ if (supportsResponseStream && response.body && (onDownloadProgress || hasMaxContentLength || isStreamResponse && unsubscribe)) {
2173
3372
  const options = {};
2174
3373
  ["status", "statusText", "headers"].forEach((prop) => {
2175
3374
  options[prop] = response[prop];
2176
3375
  });
2177
- const responseContentLength = utils$1.toFiniteNumber(response.headers.get("content-length"));
3376
+ const responseContentLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
2178
3377
  const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
2179
3378
  responseContentLength,
2180
3379
  progressEventReducer(asyncDecorator(onDownloadProgress), true)
2181
3380
  ) || [];
3381
+ let bytesRead = 0;
3382
+ const onChunkProgress = (loadedBytes) => {
3383
+ if (hasMaxContentLength) {
3384
+ bytesRead = loadedBytes;
3385
+ if (bytesRead > maxContentLength) {
3386
+ throw new AxiosError$1(
3387
+ "maxContentLength size of " + maxContentLength + " exceeded",
3388
+ AxiosError$1.ERR_BAD_RESPONSE,
3389
+ config2,
3390
+ request
3391
+ );
3392
+ }
3393
+ }
3394
+ onProgress && onProgress(loadedBytes);
3395
+ };
2182
3396
  response = new Response(
2183
- trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
3397
+ trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => {
2184
3398
  flush && flush();
2185
3399
  unsubscribe && unsubscribe();
2186
3400
  }),
@@ -2188,7 +3402,30 @@ const factory = (env) => {
2188
3402
  );
2189
3403
  }
2190
3404
  responseType = responseType || "text";
2191
- let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || "text"](response, config2);
3405
+ let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || "text"](
3406
+ response,
3407
+ config2
3408
+ );
3409
+ if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) {
3410
+ let materializedSize;
3411
+ if (responseData != null) {
3412
+ if (typeof responseData.byteLength === "number") {
3413
+ materializedSize = responseData.byteLength;
3414
+ } else if (typeof responseData.size === "number") {
3415
+ materializedSize = responseData.size;
3416
+ } else if (typeof responseData === "string") {
3417
+ materializedSize = typeof TextEncoder === "function" ? new TextEncoder().encode(responseData).byteLength : responseData.length;
3418
+ }
3419
+ }
3420
+ if (typeof materializedSize === "number" && materializedSize > maxContentLength) {
3421
+ throw new AxiosError$1(
3422
+ "maxContentLength size of " + maxContentLength + " exceeded",
3423
+ AxiosError$1.ERR_BAD_RESPONSE,
3424
+ config2,
3425
+ request
3426
+ );
3427
+ }
3428
+ }
2192
3429
  !isStreamResponse && unsubscribe && unsubscribe();
2193
3430
  return await new Promise((resolve, reject) => {
2194
3431
  settle(resolve, reject, {
@@ -2202,27 +3439,55 @@ const factory = (env) => {
2202
3439
  });
2203
3440
  } catch (err) {
2204
3441
  unsubscribe && unsubscribe();
3442
+ if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError$1) {
3443
+ const canceledError = composedSignal.reason;
3444
+ canceledError.config = config2;
3445
+ request && (canceledError.request = request);
3446
+ if (err !== canceledError) {
3447
+ Object.defineProperty(canceledError, "cause", {
3448
+ __proto__: null,
3449
+ value: err,
3450
+ writable: true,
3451
+ enumerable: false,
3452
+ configurable: true
3453
+ });
3454
+ }
3455
+ throw canceledError;
3456
+ }
3457
+ if (pendingBodyError) {
3458
+ request && !pendingBodyError.request && (pendingBodyError.request = request);
3459
+ throw pendingBodyError;
3460
+ }
3461
+ if (err instanceof AxiosError$1) {
3462
+ request && !err.request && (err.request = request);
3463
+ throw err;
3464
+ }
2205
3465
  if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) {
2206
- throw Object.assign(
2207
- new AxiosError$1("Network Error", AxiosError$1.ERR_NETWORK, config2, request),
2208
- {
2209
- cause: err.cause || err
2210
- }
3466
+ const networkError = new AxiosError$1(
3467
+ "Network Error",
3468
+ AxiosError$1.ERR_NETWORK,
3469
+ config2,
3470
+ request,
3471
+ err && err.response
2211
3472
  );
3473
+ Object.defineProperty(networkError, "cause", {
3474
+ __proto__: null,
3475
+ value: err.cause || err,
3476
+ writable: true,
3477
+ enumerable: false,
3478
+ configurable: true
3479
+ });
3480
+ throw networkError;
2212
3481
  }
2213
- throw AxiosError$1.from(err, err && err.code, config2, request);
3482
+ throw AxiosError$1.from(err, err && err.code, config2, request, err && err.response);
2214
3483
  }
2215
3484
  };
2216
3485
  };
2217
3486
  const seedCache = /* @__PURE__ */ new Map();
2218
3487
  const getFetch = (config2) => {
2219
- let env = config2 ? config2.env : {};
3488
+ let env = config2 && config2.env || {};
2220
3489
  const { fetch: fetch2, Request, Response } = env;
2221
- const seeds = [
2222
- Request,
2223
- Response,
2224
- fetch2
2225
- ];
3490
+ const seeds = [Request, Response, fetch2];
2226
3491
  let len = seeds.length, i = len, seed, target, map = seedCache;
2227
3492
  while (i--) {
2228
3493
  seed = seeds[i];
@@ -2243,48 +3508,57 @@ const knownAdapters = {
2243
3508
  utils$1.forEach(knownAdapters, (fn, value) => {
2244
3509
  if (fn) {
2245
3510
  try {
2246
- Object.defineProperty(fn, "name", { value });
3511
+ Object.defineProperty(fn, "name", { __proto__: null, value });
2247
3512
  } catch (e) {
2248
3513
  }
2249
- Object.defineProperty(fn, "adapterName", { value });
3514
+ Object.defineProperty(fn, "adapterName", { __proto__: null, value });
2250
3515
  }
2251
3516
  });
2252
3517
  const renderReason = (reason) => `- ${reason}`;
2253
3518
  const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
2254
- const adapters = {
2255
- getAdapter: (adapters2, config2) => {
2256
- adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2];
2257
- const { length } = adapters2;
2258
- let nameOrAdapter;
2259
- let adapter;
2260
- const rejectedReasons = {};
2261
- for (let i = 0; i < length; i++) {
2262
- nameOrAdapter = adapters2[i];
2263
- let id;
2264
- adapter = nameOrAdapter;
2265
- if (!isResolvedHandle(nameOrAdapter)) {
2266
- adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
2267
- if (adapter === void 0) {
2268
- throw new AxiosError$1(`Unknown adapter '${id}'`);
2269
- }
2270
- }
2271
- if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config2)))) {
2272
- break;
3519
+ function getAdapter$1(adapters2, config2) {
3520
+ adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2];
3521
+ const { length } = adapters2;
3522
+ let nameOrAdapter;
3523
+ let adapter;
3524
+ const rejectedReasons = {};
3525
+ for (let i = 0; i < length; i++) {
3526
+ nameOrAdapter = adapters2[i];
3527
+ let id;
3528
+ adapter = nameOrAdapter;
3529
+ if (!isResolvedHandle(nameOrAdapter)) {
3530
+ adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
3531
+ if (adapter === void 0) {
3532
+ throw new AxiosError$1(`Unknown adapter '${id}'`);
2273
3533
  }
2274
- rejectedReasons[id || "#" + i] = adapter;
2275
3534
  }
2276
- if (!adapter) {
2277
- const reasons = Object.entries(rejectedReasons).map(
2278
- ([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build")
2279
- );
2280
- let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified";
2281
- throw new AxiosError$1(
2282
- `There is no suitable adapter to dispatch the request ` + s,
2283
- "ERR_NOT_SUPPORT"
2284
- );
3535
+ if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config2)))) {
3536
+ break;
2285
3537
  }
2286
- return adapter;
2287
- },
3538
+ rejectedReasons[id || "#" + i] = adapter;
3539
+ }
3540
+ if (!adapter) {
3541
+ const reasons = Object.entries(rejectedReasons).map(
3542
+ ([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build")
3543
+ );
3544
+ let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified";
3545
+ throw new AxiosError$1(
3546
+ `There is no suitable adapter to dispatch the request ` + s,
3547
+ AxiosError$1.ERR_NOT_SUPPORT
3548
+ );
3549
+ }
3550
+ return adapter;
3551
+ }
3552
+ const adapters = {
3553
+ /**
3554
+ * Resolve an adapter from a list of adapter names or functions.
3555
+ * @type {Function}
3556
+ */
3557
+ getAdapter: getAdapter$1,
3558
+ /**
3559
+ * Exposes all known adapters
3560
+ * @type {Object<string, Function|Object>}
3561
+ */
2288
3562
  adapters: knownAdapters
2289
3563
  };
2290
3564
  function throwIfCancellationRequested(config2) {
@@ -2298,39 +3572,44 @@ function throwIfCancellationRequested(config2) {
2298
3572
  function dispatchRequest(config2) {
2299
3573
  throwIfCancellationRequested(config2);
2300
3574
  config2.headers = AxiosHeaders$1.from(config2.headers);
2301
- config2.data = transformData.call(
2302
- config2,
2303
- config2.transformRequest
2304
- );
3575
+ config2.data = transformData.call(config2, config2.transformRequest);
2305
3576
  if (["post", "put", "patch"].indexOf(config2.method) !== -1) {
2306
3577
  config2.headers.setContentType("application/x-www-form-urlencoded", false);
2307
3578
  }
2308
3579
  const adapter = adapters.getAdapter(config2.adapter || defaults.adapter, config2);
2309
- return adapter(config2).then(function onAdapterResolution(response) {
2310
- throwIfCancellationRequested(config2);
2311
- response.data = transformData.call(
2312
- config2,
2313
- config2.transformResponse,
2314
- response
2315
- );
2316
- response.headers = AxiosHeaders$1.from(response.headers);
2317
- return response;
2318
- }, function onAdapterRejection(reason) {
2319
- if (!isCancel$1(reason)) {
3580
+ return adapter(config2).then(
3581
+ function onAdapterResolution(response) {
2320
3582
  throwIfCancellationRequested(config2);
2321
- if (reason && reason.response) {
2322
- reason.response.data = transformData.call(
2323
- config2,
2324
- config2.transformResponse,
2325
- reason.response
2326
- );
2327
- reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
3583
+ config2.response = response;
3584
+ try {
3585
+ response.data = transformData.call(config2, config2.transformResponse, response);
3586
+ } finally {
3587
+ delete config2.response;
3588
+ }
3589
+ response.headers = AxiosHeaders$1.from(response.headers);
3590
+ return response;
3591
+ },
3592
+ function onAdapterRejection(reason) {
3593
+ if (!isCancel$1(reason)) {
3594
+ throwIfCancellationRequested(config2);
3595
+ if (reason && reason.response) {
3596
+ config2.response = reason.response;
3597
+ try {
3598
+ reason.response.data = transformData.call(
3599
+ config2,
3600
+ config2.transformResponse,
3601
+ reason.response
3602
+ );
3603
+ } finally {
3604
+ delete config2.response;
3605
+ }
3606
+ reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
3607
+ }
2328
3608
  }
3609
+ return Promise.reject(reason);
2329
3610
  }
2330
- return Promise.reject(reason);
2331
- });
3611
+ );
2332
3612
  }
2333
- const VERSION$1 = "1.12.2";
2334
3613
  const validators$1 = {};
2335
3614
  ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => {
2336
3615
  validators$1[type] = function validator2(thing) {
@@ -2367,20 +3646,23 @@ validators$1.spelling = function spelling(correctSpelling) {
2367
3646
  return true;
2368
3647
  };
2369
3648
  };
2370
- function assertOptions(options, schema, allowUnknown) {
2371
- if (typeof options !== "object") {
3649
+ function assertOptions(options, schema2, allowUnknown) {
3650
+ if (typeof options !== "object" || options === null) {
2372
3651
  throw new AxiosError$1("options must be an object", AxiosError$1.ERR_BAD_OPTION_VALUE);
2373
3652
  }
2374
3653
  const keys = Object.keys(options);
2375
3654
  let i = keys.length;
2376
3655
  while (i-- > 0) {
2377
3656
  const opt = keys[i];
2378
- const validator2 = schema[opt];
3657
+ const validator2 = Object.prototype.hasOwnProperty.call(schema2, opt) ? schema2[opt] : void 0;
2379
3658
  if (validator2) {
2380
3659
  const value = options[opt];
2381
3660
  const result = value === void 0 || validator2(value, opt, options);
2382
3661
  if (result !== true) {
2383
- throw new AxiosError$1("option " + opt + " must be " + result, AxiosError$1.ERR_BAD_OPTION_VALUE);
3662
+ throw new AxiosError$1(
3663
+ "option " + opt + " must be " + result,
3664
+ AxiosError$1.ERR_BAD_OPTION_VALUE
3665
+ );
2384
3666
  }
2385
3667
  continue;
2386
3668
  }
@@ -2417,12 +3699,23 @@ let Axios$1 = class Axios {
2417
3699
  if (err instanceof Error) {
2418
3700
  let dummy = {};
2419
3701
  Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
2420
- const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : "";
3702
+ const stack = (() => {
3703
+ if (!dummy.stack) {
3704
+ return "";
3705
+ }
3706
+ const firstNewlineIndex = dummy.stack.indexOf("\n");
3707
+ return firstNewlineIndex === -1 ? "" : dummy.stack.slice(firstNewlineIndex + 1);
3708
+ })();
2421
3709
  try {
2422
3710
  if (!err.stack) {
2423
3711
  err.stack = stack;
2424
- } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) {
2425
- err.stack += "\n" + stack;
3712
+ } else if (stack) {
3713
+ const firstNewlineIndex = stack.indexOf("\n");
3714
+ const secondNewlineIndex = firstNewlineIndex === -1 ? -1 : stack.indexOf("\n", firstNewlineIndex + 1);
3715
+ const stackWithoutTwoTopLines = secondNewlineIndex === -1 ? "" : stack.slice(secondNewlineIndex + 1);
3716
+ if (!String(err.stack).endsWith(stackWithoutTwoTopLines)) {
3717
+ err.stack += "\n" + stack;
3718
+ }
2426
3719
  }
2427
3720
  } catch (e) {
2428
3721
  }
@@ -2440,11 +3733,18 @@ let Axios$1 = class Axios {
2440
3733
  config2 = mergeConfig$1(this.defaults, config2);
2441
3734
  const { transitional: transitional2, paramsSerializer, headers } = config2;
2442
3735
  if (transitional2 !== void 0) {
2443
- validator.assertOptions(transitional2, {
2444
- silentJSONParsing: validators.transitional(validators.boolean),
2445
- forcedJSONParsing: validators.transitional(validators.boolean),
2446
- clarifyTimeoutError: validators.transitional(validators.boolean)
2447
- }, false);
3736
+ validator.assertOptions(
3737
+ transitional2,
3738
+ {
3739
+ silentJSONParsing: validators.transitional(validators.boolean),
3740
+ forcedJSONParsing: validators.transitional(validators.boolean),
3741
+ clarifyTimeoutError: validators.transitional(validators.boolean),
3742
+ legacyInterceptorReqResOrdering: validators.transitional(validators.boolean),
3743
+ advertiseZstdAcceptEncoding: validators.transitional(validators.boolean),
3744
+ validateStatusUndefinedResolves: validators.transitional(validators.boolean)
3745
+ },
3746
+ false
3747
+ );
2448
3748
  }
2449
3749
  if (paramsSerializer != null) {
2450
3750
  if (utils$1.isFunction(paramsSerializer)) {
@@ -2452,10 +3752,14 @@ let Axios$1 = class Axios {
2452
3752
  serialize: paramsSerializer
2453
3753
  };
2454
3754
  } else {
2455
- validator.assertOptions(paramsSerializer, {
2456
- encode: validators.function,
2457
- serialize: validators.function
2458
- }, true);
3755
+ validator.assertOptions(
3756
+ paramsSerializer,
3757
+ {
3758
+ encode: validators.function,
3759
+ serialize: validators.function
3760
+ },
3761
+ true
3762
+ );
2459
3763
  }
2460
3764
  }
2461
3765
  if (config2.allowAbsoluteUrls !== void 0) ;
@@ -2464,21 +3768,19 @@ let Axios$1 = class Axios {
2464
3768
  } else {
2465
3769
  config2.allowAbsoluteUrls = true;
2466
3770
  }
2467
- validator.assertOptions(config2, {
2468
- baseUrl: validators.spelling("baseURL"),
2469
- withXsrfToken: validators.spelling("withXSRFToken")
2470
- }, true);
2471
- config2.method = (config2.method || this.defaults.method || "get").toLowerCase();
2472
- let contextHeaders = headers && utils$1.merge(
2473
- headers.common,
2474
- headers[config2.method]
2475
- );
2476
- headers && utils$1.forEach(
2477
- ["delete", "get", "head", "post", "put", "patch", "common"],
2478
- (method) => {
2479
- delete headers[method];
2480
- }
3771
+ validator.assertOptions(
3772
+ config2,
3773
+ {
3774
+ baseUrl: validators.spelling("baseURL"),
3775
+ withXsrfToken: validators.spelling("withXSRFToken")
3776
+ },
3777
+ true
2481
3778
  );
3779
+ config2.method = (config2.method || this.defaults.method || "get").toLowerCase();
3780
+ let contextHeaders = headers && utils$1.merge(headers.common, headers[config2.method]);
3781
+ headers && utils$1.forEach(["delete", "get", "head", "post", "put", "patch", "query", "common"], (method) => {
3782
+ delete headers[method];
3783
+ });
2482
3784
  config2.headers = AxiosHeaders$1.concat(contextHeaders, headers);
2483
3785
  const requestInterceptorChain = [];
2484
3786
  let synchronousRequestInterceptors = true;
@@ -2487,7 +3789,13 @@ let Axios$1 = class Axios {
2487
3789
  return;
2488
3790
  }
2489
3791
  synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
2490
- requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
3792
+ const transitional3 = config2.transitional || transitionalDefaults;
3793
+ const legacyInterceptorReqResOrdering = transitional3 && transitional3.legacyInterceptorReqResOrdering;
3794
+ if (legacyInterceptorReqResOrdering) {
3795
+ requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
3796
+ } else {
3797
+ requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
3798
+ }
2491
3799
  });
2492
3800
  const responseInterceptorChain = [];
2493
3801
  this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
@@ -2533,34 +3841,40 @@ let Axios$1 = class Axios {
2533
3841
  }
2534
3842
  getUri(config2) {
2535
3843
  config2 = mergeConfig$1(this.defaults, config2);
2536
- const fullPath = buildFullPath(config2.baseURL, config2.url, config2.allowAbsoluteUrls);
3844
+ const fullPath = buildFullPath(config2.baseURL, config2.url, config2.allowAbsoluteUrls, config2);
2537
3845
  return buildURL(fullPath, config2.params, config2.paramsSerializer);
2538
3846
  }
2539
3847
  };
2540
3848
  utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) {
2541
3849
  Axios$1.prototype[method] = function(url, config2) {
2542
- return this.request(mergeConfig$1(config2 || {}, {
2543
- method,
2544
- url,
2545
- data: (config2 || {}).data
2546
- }));
3850
+ return this.request(
3851
+ mergeConfig$1(config2 || {}, {
3852
+ method,
3853
+ url,
3854
+ data: config2 && utils$1.hasOwnProp(config2, "data") ? config2.data : void 0
3855
+ })
3856
+ );
2547
3857
  };
2548
3858
  });
2549
- utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
3859
+ utils$1.forEach(["post", "put", "patch", "query"], function forEachMethodWithData(method) {
2550
3860
  function generateHTTPMethod(isForm) {
2551
3861
  return function httpMethod(url, data, config2) {
2552
- return this.request(mergeConfig$1(config2 || {}, {
2553
- method,
2554
- headers: isForm ? {
2555
- "Content-Type": "multipart/form-data"
2556
- } : {},
2557
- url,
2558
- data
2559
- }));
3862
+ return this.request(
3863
+ mergeConfig$1(config2 || {}, {
3864
+ method,
3865
+ headers: isForm ? {
3866
+ "Content-Type": "multipart/form-data"
3867
+ } : {},
3868
+ url,
3869
+ data
3870
+ })
3871
+ );
2560
3872
  };
2561
3873
  }
2562
3874
  Axios$1.prototype[method] = generateHTTPMethod();
2563
- Axios$1.prototype[method + "Form"] = generateHTTPMethod(true);
3875
+ if (method !== "query") {
3876
+ Axios$1.prototype[method + "Form"] = generateHTTPMethod(true);
3877
+ }
2564
3878
  });
2565
3879
  let CancelToken$1 = class CancelToken {
2566
3880
  constructor(executor) {
@@ -2728,7 +4042,13 @@ const HttpStatusCode$1 = {
2728
4042
  InsufficientStorage: 507,
2729
4043
  LoopDetected: 508,
2730
4044
  NotExtended: 510,
2731
- NetworkAuthenticationRequired: 511
4045
+ NetworkAuthenticationRequired: 511,
4046
+ WebServerIsDown: 521,
4047
+ ConnectionTimedOut: 522,
4048
+ OriginIsUnreachable: 523,
4049
+ TimeoutOccurred: 524,
4050
+ SslHandshakeFailed: 525,
4051
+ InvalidSslCertificate: 526
2732
4052
  };
2733
4053
  Object.entries(HttpStatusCode$1).forEach(([key, value]) => {
2734
4054
  HttpStatusCode$1[value] = key;
@@ -2738,7 +4058,7 @@ function createInstance(defaultConfig) {
2738
4058
  const instance = bind(Axios$1.prototype.request, context);
2739
4059
  utils$1.extend(instance, Axios$1.prototype, context, { allOwnKeys: true });
2740
4060
  utils$1.extend(instance, context, null, { allOwnKeys: true });
2741
- instance.create = function create(instanceConfig) {
4061
+ instance.create = function create2(instanceConfig) {
2742
4062
  return createInstance(mergeConfig$1(defaultConfig, instanceConfig));
2743
4063
  };
2744
4064
  return instance;
@@ -2752,8 +4072,8 @@ axios.VERSION = VERSION$1;
2752
4072
  axios.toFormData = toFormData$1;
2753
4073
  axios.AxiosError = AxiosError$1;
2754
4074
  axios.Cancel = axios.CanceledError;
2755
- axios.all = function all(promises) {
2756
- return Promise.all(promises);
4075
+ axios.all = function all(promises2) {
4076
+ return Promise.all(promises2);
2757
4077
  };
2758
4078
  axios.spread = spread$1;
2759
4079
  axios.isAxiosError = isAxiosError$1;
@@ -2765,8 +4085,8 @@ axios.HttpStatusCode = HttpStatusCode$1;
2765
4085
  axios.default = axios;
2766
4086
  const {
2767
4087
  Axios: Axios2,
2768
- AxiosError,
2769
- CanceledError,
4088
+ AxiosError: AxiosError2,
4089
+ CanceledError: CanceledError2,
2770
4090
  isCancel,
2771
4091
  CancelToken: CancelToken2,
2772
4092
  VERSION,
@@ -2779,7 +4099,8 @@ const {
2779
4099
  HttpStatusCode,
2780
4100
  formToJSON,
2781
4101
  getAdapter,
2782
- mergeConfig
4102
+ mergeConfig,
4103
+ create
2783
4104
  } = axios;
2784
4105
  const service = ({ strapi }) => {
2785
4106
  return {
@@ -2810,29 +4131,6 @@ const service = ({ strapi }) => {
2810
4131
  async getUsuarios(sanitizedQueryParams) {
2811
4132
  return await strapi.documents("plugin::users-permissions.user").findMany(sanitizedQueryParams);
2812
4133
  },
2813
- async getImagenes() {
2814
- const existingFolders = await strapi.documents("plugin::upload.folder").findMany({
2815
- filters: {
2816
- name: "Generated"
2817
- }
2818
- });
2819
- if (existingFolders) {
2820
- return await strapi.documents("plugin::upload.file").findMany({
2821
- filters: {
2822
- folder: {
2823
- id: {
2824
- $eq: existingFolders[0].id
2825
- }
2826
- }
2827
- },
2828
- sort: ["createdAt:desc"]
2829
- });
2830
- }
2831
- return [];
2832
- },
2833
- async eliminarImagen(sanitizedQueryParams) {
2834
- return await strapi.documents("plugin::upload.file").delete(sanitizedQueryParams);
2835
- },
2836
4134
  // ───────────────────────────────
2837
4135
  // 📥 Proxy File Download (bypasses browser CORS)
2838
4136
  // ───────────────────────────────
@@ -2870,27 +4168,7 @@ const service = ({ strapi }) => {
2870
4168
  // 🏞️ Internal File Upload Helper
2871
4169
  // ───────────────────────────────
2872
4170
  async _uploadGeneratedFile(file, filename, mimeType, folderName = "Generated") {
2873
- const existingFolders = await strapi.documents("plugin::upload.folder").findMany({
2874
- filters: { name: folderName }
2875
- });
2876
- let folderId;
2877
- if (!existingFolders || existingFolders.length === 0) {
2878
- const lastFolder = await strapi.documents("plugin::upload.folder").findMany({
2879
- sort: { pathId: "desc" },
2880
- limit: 1
2881
- });
2882
- const pathId = Array.isArray(lastFolder) && lastFolder.length > 0 ? lastFolder[0].pathId + 1 : 1;
2883
- const createdFolder = await strapi.documents("plugin::upload.folder").create({
2884
- data: {
2885
- name: folderName,
2886
- path: `/${folderName.toLowerCase()}`,
2887
- pathId
2888
- }
2889
- });
2890
- folderId = createdFolder.id;
2891
- } else {
2892
- folderId = existingFolders[0].id;
2893
- }
4171
+ const folderId = await ensureFolder(strapi, folderName);
2894
4172
  let fileSize = 0;
2895
4173
  if (typeof file === "string") {
2896
4174
  const stats = fs.statSync(file);
@@ -3125,15 +4403,7 @@ const service = ({ strapi }) => {
3125
4403
  output_format: "image/png"
3126
4404
  };
3127
4405
  const promptText = JSON.stringify(promptJson);
3128
- const generatedBase64Image = await this._callGeminiImageGeneration(
3129
- promptText,
3130
- aspectRatio || "16:9",
3131
- // Use provided aspectRatio or default
3132
- imageSize || "1K",
3133
- // Use provided imageSize or default
3134
- []
3135
- // No reference images for article generation
3136
- );
4406
+ const generatedBase64Image = await strapi.plugin("strapi-content-generator-gemini").service("image-studio").generateForArticle(promptText, aspectRatio || "16:9", imageSize || "1K");
3137
4407
  const buffer = Buffer.from(generatedBase64Image, "base64");
3138
4408
  const uploadedFile = await this._uploadGeneratedFile(buffer, `article-${articleId}.png`, "image/png");
3139
4409
  const articleModel = await strapi.getModel("api::articulo.articulo");
@@ -3156,134 +4426,10 @@ const service = ({ strapi }) => {
3156
4426
  throw new Error("Error al generar la imagen para el artículo.");
3157
4427
  }
3158
4428
  },
3159
- // ───────────────────────────────
3160
- // 🖼️ Internal Image Generation Helper
3161
- // Imagen 4 cuando no hay imágenes de referencia (mejor calidad y adherencia al prompt)
3162
- // Gemini 2.5 Flash como fallback cuando se proporcionan imágenes de referencia
3163
- // ───────────────────────────────
3164
- async _callGeminiImageGeneration(promptText, aspectRatio, imageSizeLabel, referenceImages) {
3165
- const ai = await this.geminiConfig();
3166
- const cleanPrompt = promptText.replace(/\r\n/g, " ").replace(/\n/g, " ").replace(/\s+/g, " ").trim();
3167
- if (referenceImages.length === 0) {
3168
- const response = await ai.models.generateImages({
3169
- model: "imagen-4.0-generate-001",
3170
- prompt: cleanPrompt,
3171
- config: {
3172
- numberOfImages: 1,
3173
- aspectRatio,
3174
- outputMimeType: "image/png"
3175
- }
3176
- });
3177
- const imageBytes = response.generatedImages?.[0]?.image?.imageBytes;
3178
- if (!imageBytes) {
3179
- throw new Error("Imagen 4 no devolvió imagen. Verifica el prompt o el modelo.");
3180
- }
3181
- return imageBytes;
3182
- }
3183
- const imageParts = referenceImages.map((img) => ({
3184
- inlineData: {
3185
- mimeType: img.mimeType,
3186
- data: img.buffer.toString("base64")
3187
- }
3188
- }));
3189
- const result = await ai.models.generateContent({
3190
- model: "gemini-2.5-flash-image",
3191
- contents: [{ text: cleanPrompt }, ...imageParts],
3192
- config: {
3193
- responseModalities: [Modality.IMAGE],
3194
- imageConfig: { aspectRatio, imageSize: imageSizeLabel }
3195
- }
3196
- });
3197
- const parts = result?.candidates?.[0]?.content?.parts;
3198
- if (!Array.isArray(parts)) {
3199
- throw new Error("Respuesta inválida del modelo (parts no encontrado)");
3200
- }
3201
- const imagePart = parts.find(
3202
- (p) => p?.inlineData?.data && typeof p.inlineData.data === "string" && p.inlineData.mimeType?.startsWith("image/")
3203
- );
3204
- if (!imagePart) {
3205
- throw new Error("No se encontró ninguna imagen en la respuesta del modelo");
3206
- }
3207
- return imagePart.inlineData.data;
3208
- },
3209
- // ───────────────────────────────
3210
- // 🖼️ Generate Image (Standalone)
3211
- // ───────────────────────────────
3212
- async generateImage(ctx) {
3213
- const { prompt, aspectRatio, imageSize } = ctx.request.body;
3214
- if (!prompt) {
3215
- throw new Error("Se requiere 'prompt' para generar el contenido visual.");
3216
- }
3217
- const promptJson = {
3218
- label: `standalone-image-${Date.now()}`,
3219
- task: "generate_image",
3220
- canvas: {
3221
- resolution: imageSize || "1K",
3222
- aspect_ratio: aspectRatio || "16:9"
3223
- },
3224
- style: {
3225
- type: "architectural software engineering visualization",
3226
- aesthetic: "high-end technical 3D render / octane style",
3227
- background: "view of a bright white minimalist architectural gallery, sun-drenched space, white polished floors and tall glass windows",
3228
- lighting: "intense natural daylight, soft global illumination, clean diffused light with subtle volumetric rays from windows"
3229
- },
3230
- concept_brief: prompt,
3231
- subject: [
3232
- "apply the concept brief above as the main subject — rendered as a sophisticated 3D holographic or architectural structure floating inside the gallery",
3233
- "materials: frosted glass, white matte ceramic, polished metal accents",
3234
- "brand accent colors red #E4002B and teal #00C7B1 on glowing energy filaments, highlights, and data connections",
3235
- "the structure casts a sharp, clean reflection on the white polished gallery floor",
3236
- "STRICTLY NO people, NO humans, NO hands, NO chairs",
3237
- "STRICTLY NO text, NO labels, NO words, NO letters, NO numbers, NO logos",
3238
- "high-end 3D render, architectural photography style, 4k quality"
3239
- ],
3240
- camera: {
3241
- perspective: "three-quarter wide shot, slightly elevated, showing both the subject and the gallery environment",
3242
- depth_of_field: "main subject in sharp focus, gallery background beautifully blurred"
3243
- },
3244
- render: {
3245
- engine: "Octane or Cinema 4D",
3246
- effects: "bloom on glowing elements, ray-traced reflections on the white polished floor, subsurface scattering on frosted glass, volumetric light rays from gallery windows",
3247
- quality: "masterpiece, hyper-detailed"
3248
- },
3249
- output_format: "image/png"
3250
- };
3251
- const basePrompt = JSON.stringify(promptJson);
3252
- const files = ctx.request.files ?? {};
3253
- const referenceImages = Object.entries(files).filter(([key]) => key.startsWith("referenceImages")).map(([, file]) => file);
3254
- if (referenceImages.length > 5) {
3255
- throw new Error("Máximo 5 imágenes de referencia permitidas.");
3256
- }
3257
- const imageBuffers = referenceImages.map((file) => {
3258
- const typedFile = file;
3259
- return {
3260
- buffer: typedFile.buffer ?? fs.readFileSync(typedFile.filepath),
3261
- mimeType: typedFile.mimetype
3262
- };
3263
- });
3264
- try {
3265
- const generatedBase64Image = await this._callGeminiImageGeneration(
3266
- basePrompt,
3267
- aspectRatio || "16:9",
3268
- imageSize || "1K",
3269
- imageBuffers
3270
- );
3271
- const buffer = Buffer.from(generatedBase64Image, "base64");
3272
- const filename = `generated-image-${Date.now()}.png`;
3273
- const uploadedFile = await this._uploadGeneratedFile(buffer, filename, "image/png");
3274
- return {
3275
- message: `Imagen generada y subida correctamente.`,
3276
- file: uploadedFile
3277
- };
3278
- } catch (err) {
3279
- console.error("🚀 ~ generateImage ~ err:", err);
3280
- throw new Error(`Error al generar la imagen.`);
3281
- }
3282
- },
3283
4429
  // 🎞️ Internal Veo Video Generation / Extension Helper
3284
4430
  async _callVeoVideoGeneration(promptText, aspectRatio, durationSeconds, sceneRefs, previousVideo) {
3285
4431
  const ai = await this.geminiConfig();
3286
- const cleanPrompt = promptText.replace(/\s+/g, " ").trim();
4432
+ const cleanPrompt2 = promptText.replace(/\s+/g, " ").trim();
3287
4433
  const referenceImages = sceneRefs.map((img) => ({
3288
4434
  image: {
3289
4435
  imageBytes: img.buffer.toString("base64"),
@@ -3300,7 +4446,7 @@ const service = ({ strapi }) => {
3300
4446
  };
3301
4447
  const operationParams = {
3302
4448
  model: "veo-3.1-generate-preview",
3303
- prompt: cleanPrompt,
4449
+ prompt: cleanPrompt2,
3304
4450
  config: config2
3305
4451
  };
3306
4452
  if (previousVideo) {
@@ -3532,13 +4678,15 @@ ${hashtags}`,
3532
4678
  };
3533
4679
  };
3534
4680
  const services = {
3535
- service
4681
+ service,
4682
+ "image-studio": imageStudio$1,
4683
+ templates: templates$1
3536
4684
  };
3537
4685
  const index = {
3538
4686
  register,
3539
4687
  bootstrap,
3540
4688
  destroy,
3541
- config: config$1,
4689
+ config: config$2,
3542
4690
  controllers,
3543
4691
  routes,
3544
4692
  services,