@interware/content-generator 0.4.3 → 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-oubMDdAZ.mjs → App-DPVBu7QB.mjs} +37 -712
  3. package/dist/_chunks/{App-DmCOiKrV.js → App-DVTFrZvf.js} +31 -706
  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-DwDV99gW.js → getTranslation-D88uLXGd.js} +1 -1
  11. package/dist/_chunks/{getTranslation-B0tfTODk.mjs → getTranslation-DfxaP_TC.mjs} +1 -1
  12. package/dist/_chunks/{index-PnmqwUfI.mjs → index-CqDdi211.mjs} +25 -7
  13. package/dist/_chunks/{index-CTnsB_jp.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 +2439 -1247
  120. package/dist/server/index.mjs +2446 -1253
  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 +1 -5
  127. package/dist/server/src/controllers/image-studio.d.ts +23 -0
  128. package/dist/server/src/controllers/index.d.ts +129 -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 +231 -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 +28 -57
  141. package/dist/server/src/services/service.d.ts +1 -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-APrsjya3.js +0 -262
  151. package/dist/_chunks/Settings-BevnW4cE.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 -11
  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,38 +136,14 @@ 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);
145
+ async downloadFile(ctx) {
146
+ await pluginService().downloadFile(ctx);
110
147
  },
111
148
  async generateVideo(ctx) {
112
149
  ctx.body = await pluginService().generateVideo(ctx);
@@ -116,186 +153,719 @@ const controller = ({ strapi }) => {
116
153
  },
117
154
  async publishToFacebook(ctx) {
118
155
  ctx.body = await pluginService().publishToFacebook(ctx);
119
- },
120
- async get(ctx) {
121
- const pluginStore = strapi.store({
122
- type: "plugin",
123
- name: "strapi-content-generator-gemini"
124
- });
125
- const googleGenAI = await pluginStore.get({ key: "GOOGLE_GEN_AI" });
126
- const clientURL = await pluginStore.get({ key: "CLIENT_URL" });
127
- const previewSecret = await pluginStore.get({ key: "PREVIEW_SECRET" });
128
- ctx.body = { googleGenAI, clientURL, previewSecret };
129
- },
130
- async set(ctx) {
131
- const { key1, key2, key3 } = ctx.request.body;
132
- const pluginStore = strapi.store({
133
- type: "plugin",
134
- name: "strapi-content-generator-gemini"
135
- });
136
- await pluginStore.set({ key: "GOOGLE_GEN_AI", value: key1 });
137
- await pluginStore.set({ key: "CLIENT_URL", value: key2 });
138
- await pluginStore.set({ key: "PREVIEW_SECRET", value: key3 });
139
- ctx.body = { ok: true };
140
156
  }
141
157
  };
142
158
  };
143
- 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
+ });
144
178
  return {
179
+ /** Devuelve si cada credencial está guardada y sus últimos 4 caracteres, nunca el valor. */
145
180
  async get(ctx) {
146
- const pluginStore = strapi.store({
147
- type: "plugin",
148
- name: "strapi-content-generator-gemini"
149
- });
150
- const googleGenAI = await pluginStore.get({ key: "GOOGLE_GEN_AI" });
151
- const linkedInAccessToken = await pluginStore.get({ key: "LINKEDIN_ACCESS_TOKEN" });
152
- const linkedInOrganizationId = await pluginStore.get({ key: "LINKEDIN_ORGANIZATION_ID" });
153
- const facebookClientToken = await pluginStore.get({ key: "FACEBOOK_CLIENT_TOKEN" });
154
- const facebookPageId = await pluginStore.get({ key: "FACEBOOK_PAGE_ID" });
155
- 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);
156
186
  },
187
+ /** Escribe solo las credenciales conocidas que llegan como texto no vacío. */
157
188
  async set(ctx) {
158
- const { googleGenAI, linkedInAccessToken, linkedInOrganizationId, facebookClientToken, facebookPageId } = ctx.request.body;
159
- const pluginStore = strapi.store({
160
- type: "plugin",
161
- name: "strapi-content-generator-gemini"
162
- });
163
- await pluginStore.set({ key: "GOOGLE_GEN_AI", value: googleGenAI });
164
- await pluginStore.set({ key: "LINKEDIN_ACCESS_TOKEN", value: linkedInAccessToken });
165
- await pluginStore.set({ key: "LINKEDIN_ORGANIZATION_ID", value: linkedInOrganizationId });
166
- await pluginStore.set({ key: "FACEBOOK_CLIENT_TOKEN", value: facebookClientToken });
167
- 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
+ }
168
197
  ctx.body = { ok: true };
169
198
  }
170
199
  };
171
200
  };
172
- const controllers = {
173
- controller,
174
- 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
175
215
  };
176
- const middlewares = {};
177
- const policies = {};
178
- const admin = [
179
- {
180
- method: "GET",
181
- path: "/posts",
182
- handler: "controller.getArticles",
183
- config: {
184
- policies: [],
185
- 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);
186
324
  }
187
325
  },
188
- {
189
- method: "GET",
190
- path: "/categories",
191
- handler: "controller.getCategories",
192
- config: {
193
- policies: [],
194
- auth: false
195
- }
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;
196
344
  },
197
- {
198
- method: "GET",
199
- path: "/users",
200
- handler: "controller.getUsers",
201
- config: {
202
- policies: [],
203
- auth: false
204
- }
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;
205
359
  },
206
- {
207
- method: "GET",
208
- path: "/images",
209
- handler: "controller.getImages",
210
- config: {
211
- policies: [],
212
- auth: false
213
- }
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);
214
370
  },
215
- {
216
- method: "DELETE",
217
- path: "/delete-image",
218
- handler: "controller.deleteImage",
219
- config: {
220
- policies: [],
221
- 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.");
222
451
  }
223
- },
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 = [
224
474
  {
225
- method: "POST",
226
- path: "/generate-article",
227
- handler: "controller.generateArticle",
228
- config: {
229
- policies: [],
230
- auth: false
231
- }
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
+ ]
232
490
  },
233
491
  {
234
- method: "POST",
235
- path: "/generate-image",
236
- handler: "controller.generateImageForArticle",
237
- config: {
238
- policies: [],
239
- auth: false
240
- }
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
+ ]
241
509
  },
242
510
  {
243
- method: "POST",
244
- path: "/generate-image-with-config",
245
- handler: "controller.generateImage",
246
- config: {
247
- policies: [],
248
- auth: false
249
- }
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
+ ]
250
530
  },
251
531
  {
252
- method: "POST",
253
- path: "/generate-video-with-scenes",
254
- handler: "controller.generateVideo",
255
- config: {
256
- policies: [],
257
- auth: false
258
- }
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
+ ]
259
549
  },
260
550
  {
261
- method: "POST",
262
- path: "/publish-linkedin",
263
- handler: "controller.publishToLinkedIn",
264
- config: {
265
- policies: [],
266
- auth: false
267
- }
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
+ ]
268
568
  },
269
569
  {
270
- method: "POST",
271
- path: "/publish-facebook",
272
- handler: "controller.publishToFacebook",
273
- config: {
274
- policies: [],
275
- auth: false
276
- }
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
+ ]
277
587
  }
278
588
  ];
279
- const contentApi = [
280
- {
281
- method: "GET",
282
- path: "/config",
283
- handler: "config.get",
284
- config: {
285
- policies: [],
286
- 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);
287
601
  }
288
- },
289
- {
290
- method: "POST",
291
- path: "/config",
292
- handler: "config.set",
293
- config: {
294
- policies: [],
295
- 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.");
296
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] }
297
837
  }
298
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 = [];
299
869
  const routes = {
300
870
  "content-api": {
301
871
  type: "content-api",
@@ -314,9 +884,26 @@ function bind(fn, thisArg) {
314
884
  const { toString } = Object.prototype;
315
885
  const { getPrototypeOf } = Object;
316
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;
317
904
  const kindOf = /* @__PURE__ */ ((cache) => (thing) => {
318
- const str = toString.call(thing);
319
- 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());
320
907
  })(/* @__PURE__ */ Object.create(null));
321
908
  const kindOfTest = (type) => {
322
909
  type = type.toLowerCase();
@@ -344,11 +931,14 @@ const isNumber = typeOfTest("number");
344
931
  const isObject = (thing) => thing !== null && typeof thing === "object";
345
932
  const isBoolean = (thing) => thing === true || thing === false;
346
933
  const isPlainObject = (val) => {
347
- if (kindOf(val) !== "object") {
934
+ if (!isObject(val)) {
348
935
  return false;
349
936
  }
350
937
  const prototype2 = getPrototypeOf(val);
351
- 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);
352
942
  };
353
943
  const isEmptyObject = (val) => {
354
944
  if (!isObject(val) || isBuffer(val)) {
@@ -362,17 +952,42 @@ const isEmptyObject = (val) => {
362
952
  };
363
953
  const isDate = kindOfTest("Date");
364
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";
365
959
  const isBlob = kindOfTest("Blob");
366
960
  const isFileList = kindOfTest("FileList");
367
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;
368
971
  const isFormData = (thing) => {
369
- let kind;
370
- return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction$1(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
371
- 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]";
372
980
  };
373
981
  const isURLSearchParams = kindOfTest("URLSearchParams");
374
- const [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
375
- 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
+ };
376
991
  function forEach(obj, fn, { allOwnKeys = false } = {}) {
377
992
  if (obj === null || typeof obj === "undefined") {
378
993
  return;
@@ -420,13 +1035,17 @@ const _global = (() => {
420
1035
  return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
421
1036
  })();
422
1037
  const isContextDefined = (context) => !isUndefined(context) && context !== _global;
423
- function merge() {
1038
+ function merge(...objs) {
424
1039
  const { caseless, skipUndefined } = isContextDefined(this) && this || {};
425
1040
  const result = {};
426
1041
  const assignValue = (val, key) => {
427
- const targetKey = caseless && findKey(result, key) || key;
428
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
429
- 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);
430
1049
  } else if (isPlainObject(val)) {
431
1050
  result[targetKey] = merge({}, val);
432
1051
  } else if (isArray(val)) {
@@ -435,19 +1054,51 @@ function merge() {
435
1054
  result[targetKey] = val;
436
1055
  }
437
1056
  };
438
- for (let i = 0, l = arguments.length; i < l; i++) {
439
- 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
+ }
440
1073
  }
441
1074
  return result;
442
1075
  }
443
1076
  const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
444
- forEach(b, (val, key) => {
445
- if (thisArg && isFunction$1(val)) {
446
- a[key] = bind(val, thisArg);
447
- } else {
448
- a[key] = val;
449
- }
450
- }, { 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
+ );
451
1102
  return a;
452
1103
  };
453
1104
  const stripBOM = (content) => {
@@ -456,10 +1107,17 @@ const stripBOM = (content) => {
456
1107
  }
457
1108
  return content;
458
1109
  };
459
- const inherits = (constructor, superConstructor, props, descriptors2) => {
460
- constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
461
- 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
+ });
462
1119
  Object.defineProperty(constructor, "super", {
1120
+ __proto__: null,
463
1121
  value: superConstructor.prototype
464
1122
  });
465
1123
  props && Object.assign(constructor.prototype, props);
@@ -485,13 +1143,13 @@ const toFlatObject = (sourceObj, destObj, filter2, propFilter) => {
485
1143
  } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype);
486
1144
  return destObj;
487
1145
  };
488
- const endsWith = (str, searchString, position) => {
489
- str = String(str);
490
- if (position === void 0 || position > str.length) {
491
- 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;
492
1150
  }
493
1151
  position -= searchString.length;
494
- const lastIndex = str.indexOf(searchString, position);
1152
+ const lastIndex = str2.indexOf(searchString, position);
495
1153
  return lastIndex !== -1 && lastIndex === position;
496
1154
  };
497
1155
  const toArray = (thing) => {
@@ -519,42 +1177,39 @@ const forEachEntry = (obj, fn) => {
519
1177
  fn.call(obj, pair[0], pair[1]);
520
1178
  }
521
1179
  };
522
- const matchAll = (regExp, str) => {
1180
+ const matchAll = (regExp, str2) => {
523
1181
  let matches;
524
1182
  const arr = [];
525
- while ((matches = regExp.exec(str)) !== null) {
1183
+ while ((matches = regExp.exec(str2)) !== null) {
526
1184
  arr.push(matches);
527
1185
  }
528
1186
  return arr;
529
1187
  };
530
1188
  const isHTMLForm = kindOfTest("HTMLFormElement");
531
- const toCamelCase = (str) => {
532
- return str.toLowerCase().replace(
533
- /[-_\s]([a-z\d])(\w*)/g,
534
- function replacer(m, p1, p2) {
535
- return p1.toUpperCase() + p2;
536
- }
537
- );
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
+ });
538
1193
  };
539
- const hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
1194
+ const { propertyIsEnumerable } = Object.prototype;
540
1195
  const isRegExp = kindOfTest("RegExp");
541
1196
  const reduceDescriptors = (obj, reducer) => {
542
- const descriptors2 = Object.getOwnPropertyDescriptors(obj);
1197
+ const descriptors = Object.getOwnPropertyDescriptors(obj);
543
1198
  const reducedDescriptors = {};
544
- forEach(descriptors2, (descriptor, name) => {
1199
+ forEach(descriptors, (descriptor, name2) => {
545
1200
  let ret;
546
- if ((ret = reducer(descriptor, name, obj)) !== false) {
547
- reducedDescriptors[name] = ret || descriptor;
1201
+ if ((ret = reducer(descriptor, name2, obj)) !== false) {
1202
+ reducedDescriptors[name2] = ret || descriptor;
548
1203
  }
549
1204
  });
550
1205
  Object.defineProperties(obj, reducedDescriptors);
551
1206
  };
552
1207
  const freezeMethods = (obj) => {
553
- reduceDescriptors(obj, (descriptor, name) => {
554
- 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)) {
555
1210
  return false;
556
1211
  }
557
- const value = obj[name];
1212
+ const value = obj[name2];
558
1213
  if (!isFunction$1(value)) return;
559
1214
  descriptor.enumerable = false;
560
1215
  if ("writable" in descriptor) {
@@ -563,7 +1218,7 @@ const freezeMethods = (obj) => {
563
1218
  }
564
1219
  if (!descriptor.set) {
565
1220
  descriptor.set = () => {
566
- throw Error("Can not rewrite read-only method '" + name + "'");
1221
+ throw Error("Can not rewrite read-only method '" + name2 + "'");
567
1222
  };
568
1223
  }
569
1224
  });
@@ -587,29 +1242,29 @@ function isSpecCompliantForm(thing) {
587
1242
  return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
588
1243
  }
589
1244
  const toJSONObject = (obj) => {
590
- const stack = new Array(10);
591
- const visit = (source, i) => {
1245
+ const visited = /* @__PURE__ */ new WeakSet();
1246
+ const visit = (source) => {
592
1247
  if (isObject(source)) {
593
- if (stack.indexOf(source) >= 0) {
1248
+ if (visited.has(source)) {
594
1249
  return;
595
1250
  }
596
1251
  if (isBuffer(source)) {
597
1252
  return source;
598
1253
  }
599
1254
  if (!("toJSON" in source)) {
600
- stack[i] = source;
1255
+ visited.add(source);
601
1256
  const target = isArray(source) ? [] : {};
602
1257
  forEach(source, (value, key) => {
603
- const reducedValue = visit(value, i + 1);
1258
+ const reducedValue = visit(value);
604
1259
  !isUndefined(reducedValue) && (target[key] = reducedValue);
605
1260
  });
606
- stack[i] = void 0;
1261
+ visited.delete(source);
607
1262
  return target;
608
1263
  }
609
1264
  }
610
1265
  return source;
611
1266
  };
612
- return visit(obj, 0);
1267
+ return visit(obj);
613
1268
  };
614
1269
  const isAsyncFn = kindOfTest("AsyncFunction");
615
1270
  const isThenable = (thing) => thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
@@ -618,22 +1273,24 @@ const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
618
1273
  return setImmediate;
619
1274
  }
620
1275
  return postMessageSupported ? ((token, callbacks) => {
621
- _global.addEventListener("message", ({ source, data }) => {
622
- if (source === _global && data === token) {
623
- callbacks.length && callbacks.shift()();
624
- }
625
- }, 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
+ );
626
1285
  return (cb) => {
627
1286
  callbacks.push(cb);
628
1287
  _global.postMessage(token, "*");
629
1288
  };
630
1289
  })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
631
- })(
632
- typeof setImmediate === "function",
633
- isFunction$1(_global.postMessage)
634
- );
1290
+ })(typeof setImmediate === "function", isFunction$1(_global.postMessage));
635
1291
  const asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate;
636
1292
  const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]);
1293
+ const isSafeIterable = (thing) => thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing);
637
1294
  const utils$1 = {
638
1295
  isArray,
639
1296
  isArrayBuffer,
@@ -653,6 +1310,8 @@ const utils$1 = {
653
1310
  isUndefined,
654
1311
  isDate,
655
1312
  isFile,
1313
+ isReactNativeBlob,
1314
+ isReactNative,
656
1315
  isBlob,
657
1316
  isRegExp,
658
1317
  isFunction: isFunction$1,
@@ -677,6 +1336,8 @@ const utils$1 = {
677
1336
  hasOwnProperty,
678
1337
  hasOwnProp: hasOwnProperty,
679
1338
  // an alias to avoid ESLint no-prototype-builtins detection
1339
+ hasOwnInPrototypeChain,
1340
+ getSafeProp,
680
1341
  reduceDescriptors,
681
1342
  freezeMethods,
682
1343
  toObjectSet,
@@ -692,102 +1353,487 @@ const utils$1 = {
692
1353
  isThenable,
693
1354
  setImmediate: _setImmediate,
694
1355
  asap,
695
- isIterable
696
- };
697
- function AxiosError$1(message, code, config2, request, response) {
698
- Error.call(this);
699
- if (Error.captureStackTrace) {
700
- Error.captureStackTrace(this, this.constructor);
701
- } else {
702
- this.stack = new Error().stack;
703
- }
704
- this.message = message;
705
- this.name = "AxiosError";
706
- code && (this.code = code);
707
- config2 && (this.config = config2);
708
- request && (this.request = request);
709
- if (response) {
710
- this.response = response;
711
- this.status = response.status ? response.status : null;
712
- }
713
- }
714
- utils$1.inherits(AxiosError$1, Error, {
715
- toJSON: function toJSON() {
716
- return {
717
- // Standard
718
- message: this.message,
719
- name: this.name,
720
- // Microsoft
721
- description: this.description,
722
- number: this.number,
723
- // Mozilla
724
- fileName: this.fileName,
725
- lineNumber: this.lineNumber,
726
- columnNumber: this.columnNumber,
727
- stack: this.stack,
728
- // Axios
729
- config: utils$1.toJSONObject(this.config),
730
- code: this.code,
731
- status: this.status
732
- };
733
- }
734
- });
735
- const prototype$1 = AxiosError$1.prototype;
736
- const descriptors = {};
737
- [
738
- "ERR_BAD_OPTION_VALUE",
739
- "ERR_BAD_OPTION",
740
- "ECONNABORTED",
741
- "ETIMEDOUT",
742
- "ERR_NETWORK",
743
- "ERR_FR_TOO_MANY_REDIRECTS",
744
- "ERR_DEPRECATED",
745
- "ERR_BAD_RESPONSE",
746
- "ERR_BAD_REQUEST",
747
- "ERR_CANCELED",
748
- "ERR_NOT_SUPPORT",
749
- "ERR_INVALID_URL"
750
- // eslint-disable-next-line func-names
751
- ].forEach((code) => {
752
- descriptors[code] = { value: code };
753
- });
754
- Object.defineProperties(AxiosError$1, descriptors);
755
- Object.defineProperty(prototype$1, "isAxiosError", { value: true });
756
- AxiosError$1.from = (error, code, config2, request, response, customProps) => {
757
- const axiosError = Object.create(prototype$1);
758
- utils$1.toFlatObject(error, axiosError, function filter2(obj) {
759
- return obj !== Error.prototype;
760
- }, (prop) => {
761
- return prop !== "isAxiosError";
762
- });
763
- const msg = error && error.message ? error.message : "Error";
764
- const errCode = code == null && error ? error.code : code;
765
- AxiosError$1.call(axiosError, msg, errCode, config2, request, response);
766
- if (error && axiosError.cause == null) {
767
- Object.defineProperty(axiosError, "cause", { value: error, configurable: true });
768
- }
769
- axiosError.name = error && error.name || "Error";
770
- customProps && Object.assign(axiosError, customProps);
771
- return axiosError;
1356
+ isIterable,
1357
+ isSafeIterable
772
1358
  };
773
- const httpAdapter = null;
774
- function isVisitable(thing) {
775
- return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
776
- }
777
- function removeBrackets(key) {
778
- return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key;
779
- }
780
- function renderKey(path, key, dots) {
781
- if (!path) return key;
782
- return path.concat(key).map(function each(token, i) {
783
- token = removeBrackets(token);
784
- return !dots && i ? "[" + token + "]" : token;
785
- }).join(dots ? "." : "");
786
- }
787
- function isFlatArray(arr) {
788
- return utils$1.isArray(arr) && !arr.some(isVisitable);
789
- }
790
- const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
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
+ }
1833
+ function isFlatArray(arr) {
1834
+ return utils$1.isArray(arr) && !arr.some(isVisitable);
1835
+ }
1836
+ const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
791
1837
  return /^is[A-Z]/.test(prop);
792
1838
  });
793
1839
  function toFormData$1(obj, formData, options) {
@@ -795,19 +1841,26 @@ function toFormData$1(obj, formData, options) {
795
1841
  throw new TypeError("target must be an object");
796
1842
  }
797
1843
  formData = formData || new FormData();
798
- options = utils$1.toFlatObject(options, {
799
- metaTokens: true,
800
- dots: false,
801
- indexes: false
802
- }, false, function defined(option, source) {
803
- return !utils$1.isUndefined(source[option]);
804
- });
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
+ );
805
1856
  const metaTokens = options.metaTokens;
806
1857
  const visitor = options.visitor || defaultVisitor;
807
1858
  const dots = options.dots;
808
1859
  const indexes = options.indexes;
809
1860
  const _Blob = options.Blob || typeof Blob !== "undefined" && Blob;
1861
+ const maxDepth = options.maxDepth === void 0 ? DEFAULT_FORM_DATA_MAX_DEPTH : options.maxDepth;
810
1862
  const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
1863
+ const stack = [];
811
1864
  if (!utils$1.isFunction(visitor)) {
812
1865
  throw new TypeError("visitor must be a function");
813
1866
  }
@@ -823,16 +1876,51 @@ function toFormData$1(obj, formData, options) {
823
1876
  throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");
824
1877
  }
825
1878
  if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
826
- 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);
827
1886
  }
828
1887
  return value;
829
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
+ }
830
1914
  function defaultVisitor(value, key, path) {
831
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
+ }
832
1920
  if (value && !path && typeof value === "object") {
833
1921
  if (utils$1.endsWith(key, "{}")) {
834
1922
  key = metaTokens ? key : key.slice(0, -2);
835
- value = JSON.stringify(value);
1923
+ value = stringifyWithDepthLimit(value, 1);
836
1924
  } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) {
837
1925
  key = removeBrackets(key);
838
1926
  arr.forEach(function each(el, index2) {
@@ -851,28 +1939,22 @@ function toFormData$1(obj, formData, options) {
851
1939
  formData.append(renderKey(path, key, dots), convertValue(value));
852
1940
  return false;
853
1941
  }
854
- const stack = [];
855
1942
  const exposedHelpers = Object.assign(predicates, {
856
1943
  defaultVisitor,
857
1944
  convertValue,
858
1945
  isVisitable
859
1946
  });
860
- function build(value, path) {
1947
+ function build(value, path, depth = 0) {
861
1948
  if (utils$1.isUndefined(value)) return;
1949
+ throwIfMaxDepthExceeded(depth);
862
1950
  if (stack.indexOf(value) !== -1) {
863
- throw Error("Circular reference detected in " + path.join("."));
1951
+ throw new Error("Circular reference detected in " + path.join("."));
864
1952
  }
865
1953
  stack.push(value);
866
1954
  utils$1.forEach(value, function each(el, key) {
867
- const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
868
- formData,
869
- el,
870
- utils$1.isString(key) ? key.trim() : key,
871
- path,
872
- exposedHelpers
873
- );
1955
+ const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
874
1956
  if (result === true) {
875
- build(el, path ? path.concat(key) : [key]);
1957
+ build(el, path ? path.concat(key) : [key], depth + 1);
876
1958
  }
877
1959
  });
878
1960
  stack.pop();
@@ -883,17 +1965,16 @@ function toFormData$1(obj, formData, options) {
883
1965
  build(obj);
884
1966
  return formData;
885
1967
  }
886
- function encode$1(str) {
1968
+ function encode$1(str2) {
887
1969
  const charMap = {
888
1970
  "!": "%21",
889
1971
  "'": "%27",
890
1972
  "(": "%28",
891
1973
  ")": "%29",
892
1974
  "~": "%7E",
893
- "%20": "+",
894
- "%00": "\0"
1975
+ "%20": "+"
895
1976
  };
896
- return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
1977
+ return encodeURIComponent(str2).replace(/[!'()~]|%20/g, function replacer(match) {
897
1978
  return charMap[match];
898
1979
  });
899
1980
  }
@@ -902,13 +1983,11 @@ function AxiosURLSearchParams(params, options) {
902
1983
  params && toFormData$1(params, this, options);
903
1984
  }
904
1985
  const prototype = AxiosURLSearchParams.prototype;
905
- prototype.append = function append(name, value) {
906
- this._pairs.push([name, value]);
1986
+ prototype.append = function append(name2, value) {
1987
+ this._pairs.push([name2, value]);
907
1988
  };
908
1989
  prototype.toString = function toString2(encoder) {
909
- const _encode = encoder ? function(value) {
910
- return encoder.call(this, value, encode$1);
911
- } : encode$1;
1990
+ const _encode = encoder ? (value) => encoder.call(this, value, encode$1) : encode$1;
912
1991
  return this._pairs.map(function each(pair) {
913
1992
  return _encode(pair[0]) + "=" + _encode(pair[1]);
914
1993
  }, "").join("&");
@@ -920,18 +1999,17 @@ function buildURL(url, params, options) {
920
1999
  if (!params) {
921
2000
  return url;
922
2001
  }
923
- const _encode = options && options.encode || encode;
924
- if (utils$1.isFunction(options)) {
925
- options = {
926
- serialize: options
927
- };
928
- }
929
- 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");
930
2008
  let serializedParams;
931
2009
  if (serializeFn) {
932
- serializedParams = serializeFn(params, options);
2010
+ serializedParams = serializeFn(params, _options);
933
2011
  } else {
934
- 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);
935
2013
  }
936
2014
  if (serializedParams) {
937
2015
  const hashmarkIndex = url.indexOf("#");
@@ -951,6 +2029,7 @@ class InterceptorManager {
951
2029
  *
952
2030
  * @param {Function} fulfilled The function to handle `then` for a `Promise`
953
2031
  * @param {Function} rejected The function to handle `reject` for a `Promise`
2032
+ * @param {Object} options The options for the interceptor, synchronous and runWhen
954
2033
  *
955
2034
  * @return {Number} An ID used to remove interceptor later
956
2035
  */
@@ -968,7 +2047,7 @@ class InterceptorManager {
968
2047
  *
969
2048
  * @param {Number} id The ID that was returned by `use`
970
2049
  *
971
- * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
2050
+ * @returns {void}
972
2051
  */
973
2052
  eject(id) {
974
2053
  if (this.handlers[id]) {
@@ -1006,7 +2085,10 @@ class InterceptorManager {
1006
2085
  const transitionalDefaults = {
1007
2086
  silentJSONParsing: true,
1008
2087
  forcedJSONParsing: true,
1009
- clarifyTimeoutError: false
2088
+ clarifyTimeoutError: false,
2089
+ legacyInterceptorReqResOrdering: true,
2090
+ advertiseZstdAcceptEncoding: false,
2091
+ validateStatusUndefinedResolves: true
1010
2092
  };
1011
2093
  const URLSearchParams$1 = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams;
1012
2094
  const FormData$1 = typeof FormData !== "undefined" ? FormData : null;
@@ -1047,436 +2129,190 @@ function toURLEncodedForm(data, options) {
1047
2129
  this.append(key, value.toString("base64"));
1048
2130
  return false;
1049
2131
  }
1050
- return helpers.defaultVisitor.apply(this, arguments);
1051
- },
1052
- ...options
1053
- });
1054
- }
1055
- function parsePropPath(name) {
1056
- return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
1057
- return match[0] === "[]" ? "" : match[1] || match[0];
1058
- });
1059
- }
1060
- function arrayToObject(arr) {
1061
- const obj = {};
1062
- const keys = Object.keys(arr);
1063
- let i;
1064
- const len = keys.length;
1065
- let key;
1066
- for (i = 0; i < len; i++) {
1067
- key = keys[i];
1068
- obj[key] = arr[key];
1069
- }
1070
- return obj;
1071
- }
1072
- function formDataToJSON(formData) {
1073
- function buildPath(path, value, target, index2) {
1074
- let name = path[index2++];
1075
- if (name === "__proto__") return true;
1076
- const isNumericKey = Number.isFinite(+name);
1077
- const isLast = index2 >= path.length;
1078
- name = !name && utils$1.isArray(target) ? target.length : name;
1079
- if (isLast) {
1080
- if (utils$1.hasOwnProp(target, name)) {
1081
- target[name] = [target[name], value];
1082
- } else {
1083
- target[name] = value;
1084
- }
1085
- return !isNumericKey;
1086
- }
1087
- if (!target[name] || !utils$1.isObject(target[name])) {
1088
- target[name] = [];
1089
- }
1090
- const result = buildPath(path, value, target[name], index2);
1091
- if (result && utils$1.isArray(target[name])) {
1092
- target[name] = arrayToObject(target[name]);
1093
- }
1094
- return !isNumericKey;
1095
- }
1096
- if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
1097
- const obj = {};
1098
- utils$1.forEachEntry(formData, (name, value) => {
1099
- buildPath(parsePropPath(name), value, obj, 0);
1100
- });
1101
- return obj;
1102
- }
1103
- return null;
1104
- }
1105
- function stringifySafely(rawValue, parser, encoder) {
1106
- if (utils$1.isString(rawValue)) {
1107
- try {
1108
- (parser || JSON.parse)(rawValue);
1109
- return utils$1.trim(rawValue);
1110
- } catch (e) {
1111
- if (e.name !== "SyntaxError") {
1112
- throw e;
1113
- }
1114
- }
1115
- }
1116
- return (encoder || JSON.stringify)(rawValue);
1117
- }
1118
- const defaults = {
1119
- transitional: transitionalDefaults,
1120
- adapter: ["xhr", "http", "fetch"],
1121
- transformRequest: [function transformRequest(data, headers) {
1122
- const contentType = headers.getContentType() || "";
1123
- const hasJSONContentType = contentType.indexOf("application/json") > -1;
1124
- const isObjectPayload = utils$1.isObject(data);
1125
- if (isObjectPayload && utils$1.isHTMLForm(data)) {
1126
- data = new FormData(data);
1127
- }
1128
- const isFormData2 = utils$1.isFormData(data);
1129
- if (isFormData2) {
1130
- return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
1131
- }
1132
- 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)) {
1133
- return data;
1134
- }
1135
- if (utils$1.isArrayBufferView(data)) {
1136
- return data.buffer;
1137
- }
1138
- if (utils$1.isURLSearchParams(data)) {
1139
- headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
1140
- return data.toString();
1141
- }
1142
- let isFileList2;
1143
- if (isObjectPayload) {
1144
- if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
1145
- return toURLEncodedForm(data, this.formSerializer).toString();
1146
- }
1147
- if ((isFileList2 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
1148
- const _FormData = this.env && this.env.FormData;
1149
- return toFormData$1(
1150
- isFileList2 ? { "files[]": data } : data,
1151
- _FormData && new _FormData(),
1152
- this.formSerializer
1153
- );
1154
- }
1155
- }
1156
- if (isObjectPayload || hasJSONContentType) {
1157
- headers.setContentType("application/json", false);
1158
- return stringifySafely(data);
1159
- }
1160
- return data;
1161
- }],
1162
- transformResponse: [function transformResponse(data) {
1163
- const transitional2 = this.transitional || defaults.transitional;
1164
- const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing;
1165
- const JSONRequested = this.responseType === "json";
1166
- if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
1167
- return data;
1168
- }
1169
- if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
1170
- const silentJSONParsing = transitional2 && transitional2.silentJSONParsing;
1171
- const strictJSONParsing = !silentJSONParsing && JSONRequested;
1172
- try {
1173
- return JSON.parse(data, this.parseReviver);
1174
- } catch (e) {
1175
- if (strictJSONParsing) {
1176
- if (e.name === "SyntaxError") {
1177
- throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response);
1178
- }
1179
- throw e;
1180
- }
1181
- }
1182
- }
1183
- return data;
1184
- }],
1185
- /**
1186
- * A timeout in milliseconds to abort a request. If set to 0 (default) a
1187
- * timeout is not created.
1188
- */
1189
- timeout: 0,
1190
- xsrfCookieName: "XSRF-TOKEN",
1191
- xsrfHeaderName: "X-XSRF-TOKEN",
1192
- maxContentLength: -1,
1193
- maxBodyLength: -1,
1194
- env: {
1195
- FormData: platform.classes.FormData,
1196
- Blob: platform.classes.Blob
1197
- },
1198
- validateStatus: function validateStatus(status) {
1199
- return status >= 200 && status < 300;
1200
- },
1201
- headers: {
1202
- common: {
1203
- "Accept": "application/json, text/plain, */*",
1204
- "Content-Type": void 0
1205
- }
1206
- }
1207
- };
1208
- utils$1.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => {
1209
- defaults.headers[method] = {};
1210
- });
1211
- const ignoreDuplicateOf = utils$1.toObjectSet([
1212
- "age",
1213
- "authorization",
1214
- "content-length",
1215
- "content-type",
1216
- "etag",
1217
- "expires",
1218
- "from",
1219
- "host",
1220
- "if-modified-since",
1221
- "if-unmodified-since",
1222
- "last-modified",
1223
- "location",
1224
- "max-forwards",
1225
- "proxy-authorization",
1226
- "referer",
1227
- "retry-after",
1228
- "user-agent"
1229
- ]);
1230
- const parseHeaders = (rawHeaders) => {
1231
- const parsed = {};
1232
- let key;
1233
- let val;
1234
- let i;
1235
- rawHeaders && rawHeaders.split("\n").forEach(function parser(line) {
1236
- i = line.indexOf(":");
1237
- key = line.substring(0, i).trim().toLowerCase();
1238
- val = line.substring(i + 1).trim();
1239
- if (!key || parsed[key] && ignoreDuplicateOf[key]) {
1240
- return;
1241
- }
1242
- if (key === "set-cookie") {
1243
- if (parsed[key]) {
1244
- parsed[key].push(val);
1245
- } else {
1246
- parsed[key] = [val];
1247
- }
1248
- } else {
1249
- parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
1250
- }
1251
- });
1252
- return parsed;
1253
- };
1254
- const $internals = Symbol("internals");
1255
- function normalizeHeader(header) {
1256
- return header && String(header).trim().toLowerCase();
1257
- }
1258
- function normalizeValue(value) {
1259
- if (value === false || value == null) {
1260
- return value;
1261
- }
1262
- return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
1263
- }
1264
- function parseTokens(str) {
1265
- const tokens = /* @__PURE__ */ Object.create(null);
1266
- const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1267
- let match;
1268
- while (match = tokensRE.exec(str)) {
1269
- tokens[match[1]] = match[2];
1270
- }
1271
- return tokens;
1272
- }
1273
- const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
1274
- function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) {
1275
- if (utils$1.isFunction(filter2)) {
1276
- return filter2.call(this, value, header);
1277
- }
1278
- if (isHeaderNameFilter) {
1279
- value = header;
1280
- }
1281
- if (!utils$1.isString(value)) return;
1282
- if (utils$1.isString(filter2)) {
1283
- return value.indexOf(filter2) !== -1;
1284
- }
1285
- if (utils$1.isRegExp(filter2)) {
1286
- return filter2.test(value);
1287
- }
1288
- }
1289
- function formatHeader(header) {
1290
- return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1291
- return char.toUpperCase() + str;
1292
- });
1293
- }
1294
- function buildAccessors(obj, header) {
1295
- const accessorName = utils$1.toCamelCase(" " + header);
1296
- ["get", "set", "has"].forEach((methodName) => {
1297
- Object.defineProperty(obj, methodName + accessorName, {
1298
- value: function(arg1, arg2, arg3) {
1299
- return this[methodName].call(this, header, arg1, arg2, arg3);
1300
- },
1301
- configurable: true
1302
- });
1303
- });
1304
- }
1305
- let AxiosHeaders$1 = class AxiosHeaders {
1306
- constructor(headers) {
1307
- headers && this.set(headers);
1308
- }
1309
- set(header, valueOrRewrite, rewrite) {
1310
- const self2 = this;
1311
- function setHeader(_value, _header, _rewrite) {
1312
- const lHeader = normalizeHeader(_header);
1313
- if (!lHeader) {
1314
- throw new Error("header name must be a non-empty string");
1315
- }
1316
- const key = utils$1.findKey(self2, lHeader);
1317
- if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) {
1318
- self2[key || _header] = normalizeValue(_value);
1319
- }
1320
- }
1321
- const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1322
- if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1323
- setHeaders(header, valueOrRewrite);
1324
- } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1325
- setHeaders(parseHeaders(header), valueOrRewrite);
1326
- } else if (utils$1.isObject(header) && utils$1.isIterable(header)) {
1327
- let obj = {}, dest, key;
1328
- for (const entry of header) {
1329
- if (!utils$1.isArray(entry)) {
1330
- throw TypeError("Object iterator must return a key-value pair");
1331
- }
1332
- obj[key = entry[0]] = (dest = obj[key]) ? utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1];
1333
- }
1334
- setHeaders(obj, valueOrRewrite);
1335
- } else {
1336
- header != null && setHeader(valueOrRewrite, header, rewrite);
1337
- }
1338
- 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
+ );
1339
2144
  }
1340
- get(header, parser) {
1341
- header = normalizeHeader(header);
1342
- if (header) {
1343
- const key = utils$1.findKey(this, header);
1344
- if (key) {
1345
- const value = this[key];
1346
- if (!parser) {
1347
- return value;
1348
- }
1349
- if (parser === true) {
1350
- return parseTokens(value);
1351
- }
1352
- if (utils$1.isFunction(parser)) {
1353
- return parser.call(this, value, key);
1354
- }
1355
- if (utils$1.isRegExp(parser)) {
1356
- return parser.exec(value);
1357
- }
1358
- throw new TypeError("parser must be boolean|regexp|function");
1359
- }
1360
- }
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]);
1361
2153
  }
1362
- has(header, matcher) {
1363
- header = normalizeHeader(header);
1364
- if (header) {
1365
- const key = utils$1.findKey(this, header);
1366
- return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1367
- }
1368
- 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];
1369
2165
  }
1370
- delete(header, matcher) {
1371
- const self2 = this;
1372
- let deleted = false;
1373
- function deleteHeader(_header) {
1374
- _header = normalizeHeader(_header);
1375
- if (_header) {
1376
- const key = utils$1.findKey(self2, _header);
1377
- if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
1378
- delete self2[key];
1379
- deleted = true;
1380
- }
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;
1381
2181
  }
2182
+ return !isNumericKey;
1382
2183
  }
1383
- if (utils$1.isArray(header)) {
1384
- header.forEach(deleteHeader);
1385
- } else {
1386
- deleteHeader(header);
2184
+ if (!utils$1.hasOwnProp(target, name2) || !utils$1.isObject(target[name2])) {
2185
+ target[name2] = [];
1387
2186
  }
1388
- return deleted;
1389
- }
1390
- clear(matcher) {
1391
- const keys = Object.keys(this);
1392
- let i = keys.length;
1393
- let deleted = false;
1394
- while (i--) {
1395
- const key = keys[i];
1396
- if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
1397
- delete this[key];
1398
- deleted = true;
1399
- }
2187
+ const result = buildPath(path, value, target[name2], index2);
2188
+ if (result && utils$1.isArray(target[name2])) {
2189
+ target[name2] = arrayToObject(target[name2]);
1400
2190
  }
1401
- return deleted;
1402
- }
1403
- normalize(format) {
1404
- const self2 = this;
1405
- const headers = {};
1406
- utils$1.forEach(this, (value, header) => {
1407
- const key = utils$1.findKey(headers, header);
1408
- if (key) {
1409
- self2[key] = normalizeValue(value);
1410
- delete self2[header];
1411
- return;
1412
- }
1413
- const normalized = format ? formatHeader(header) : String(header).trim();
1414
- if (normalized !== header) {
1415
- delete self2[header];
1416
- }
1417
- self2[normalized] = normalizeValue(value);
1418
- headers[normalized] = true;
1419
- });
1420
- return this;
1421
- }
1422
- concat(...targets) {
1423
- return this.constructor.concat(this, ...targets);
2191
+ return !isNumericKey;
1424
2192
  }
1425
- toJSON(asStrings) {
1426
- const obj = /* @__PURE__ */ Object.create(null);
1427
- utils$1.forEach(this, (value, header) => {
1428
- 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);
1429
2197
  });
1430
2198
  return obj;
1431
2199
  }
1432
- [Symbol.iterator]() {
1433
- return Object.entries(this.toJSON())[Symbol.iterator]();
1434
- }
1435
- toString() {
1436
- return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n");
1437
- }
1438
- getSetCookie() {
1439
- return this.get("set-cookie") || [];
1440
- }
1441
- get [Symbol.toStringTag]() {
1442
- return "AxiosHeaders";
1443
- }
1444
- static from(thing) {
1445
- return thing instanceof this ? thing : new this(thing);
1446
- }
1447
- static concat(first, ...targets) {
1448
- const computed = new this(first);
1449
- targets.forEach((target) => computed.set(target));
1450
- 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
+ }
1451
2213
  }
1452
- static accessor(header) {
1453
- const internals = this[$internals] = this[$internals] = {
1454
- accessors: {}
1455
- };
1456
- const accessors = internals.accessors;
1457
- const prototype2 = this.prototype;
1458
- function defineAccessor(_header) {
1459
- const lHeader = normalizeHeader(_header);
1460
- if (!accessors[lHeader]) {
1461
- buildAccessors(prototype2, _header);
1462
- 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);
1463
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
1464
2310
  }
1465
- utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1466
- return this;
1467
2311
  }
1468
2312
  };
1469
- AxiosHeaders$1.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]);
1470
- utils$1.reduceDescriptors(AxiosHeaders$1.prototype, ({ value }, key) => {
1471
- let mapped = key[0].toUpperCase() + key.slice(1);
1472
- return {
1473
- get: () => value,
1474
- set(headerValue) {
1475
- this[mapped] = headerValue;
1476
- }
1477
- };
2313
+ utils$1.forEach(["delete", "get", "head", "post", "put", "patch", "query"], (method) => {
2314
+ defaults.headers[method] = {};
1478
2315
  });
1479
- utils$1.freezeMethods(AxiosHeaders$1);
1480
2316
  function transformData(fns, response) {
1481
2317
  const config2 = this || defaults;
1482
2318
  const context = response || config2;
@@ -1491,13 +2327,22 @@ function transformData(fns, response) {
1491
2327
  function isCancel$1(value) {
1492
2328
  return !!(value && value.__CANCEL__);
1493
2329
  }
1494
- function CanceledError$1(message, config2, request) {
1495
- AxiosError$1.call(this, message == null ? "canceled" : message, AxiosError$1.ERR_CANCELED, config2, request);
1496
- this.name = "CanceledError";
1497
- }
1498
- utils$1.inherits(CanceledError$1, AxiosError$1, {
1499
- __CANCEL__: true
1500
- });
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
+ };
1501
2346
  function settle(resolve, reject, response) {
1502
2347
  const validateStatus2 = response.config.validateStatus;
1503
2348
  if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
@@ -1505,7 +2350,7 @@ function settle(resolve, reject, response) {
1505
2350
  } else {
1506
2351
  reject(new AxiosError$1(
1507
2352
  "Request failed with status code " + response.status,
1508
- [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,
1509
2354
  response.config,
1510
2355
  response.request,
1511
2356
  response
@@ -1513,7 +2358,7 @@ function settle(resolve, reject, response) {
1513
2358
  }
1514
2359
  }
1515
2360
  function parseProtocol(url) {
1516
- const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
2361
+ const match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url);
1517
2362
  return match && match[1] || "";
1518
2363
  }
1519
2364
  function speedometer(samplesCount, min) {
@@ -1585,19 +2430,22 @@ const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
1585
2430
  let bytesNotified = 0;
1586
2431
  const _speedometer = speedometer(50, 250);
1587
2432
  return throttle((e) => {
1588
- const loaded = e.loaded;
2433
+ if (!e || typeof e.loaded !== "number") {
2434
+ return;
2435
+ }
2436
+ const rawLoaded = e.loaded;
1589
2437
  const total = e.lengthComputable ? e.total : void 0;
1590
- const progressBytes = loaded - bytesNotified;
2438
+ const loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded;
2439
+ const progressBytes = Math.max(0, loaded - bytesNotified);
1591
2440
  const rate = _speedometer(progressBytes);
1592
- const inRange = loaded <= total;
1593
- bytesNotified = loaded;
2441
+ bytesNotified = Math.max(bytesNotified, loaded);
1594
2442
  const data = {
1595
2443
  loaded,
1596
2444
  total,
1597
2445
  progress: total ? loaded / total : void 0,
1598
2446
  bytes: progressBytes,
1599
2447
  rate: rate ? rate : void 0,
1600
- estimated: rate && total && inRange ? (total - loaded) / rate : void 0,
2448
+ estimated: rate && total ? (total - loaded) / rate : void 0,
1601
2449
  event: e,
1602
2450
  lengthComputable: total != null,
1603
2451
  [isDownloadStream ? "download" : "upload"]: true
@@ -1607,11 +2455,14 @@ const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
1607
2455
  };
1608
2456
  const progressEventDecorator = (total, throttled) => {
1609
2457
  const lengthComputable = total != null;
1610
- return [(loaded) => throttled[0]({
1611
- lengthComputable,
1612
- total,
1613
- loaded
1614
- }), throttled[1]];
2458
+ return [
2459
+ (loaded) => throttled[0]({
2460
+ lengthComputable,
2461
+ total,
2462
+ loaded
2463
+ }),
2464
+ throttled[1]
2465
+ ];
1615
2466
  };
1616
2467
  const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
1617
2468
  const isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url) => {
@@ -1624,20 +2475,44 @@ const isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origi
1624
2475
  const cookies = platform.hasStandardBrowserEnv ? (
1625
2476
  // Standard browser envs support document.cookie
1626
2477
  {
1627
- write(name, value, expires, path, domain, secure) {
1628
- const cookie = [name + "=" + encodeURIComponent(value)];
1629
- utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString());
1630
- utils$1.isString(path) && cookie.push("path=" + path);
1631
- utils$1.isString(domain) && cookie.push("domain=" + domain);
1632
- 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
+ }
1633
2496
  document.cookie = cookie.join("; ");
1634
2497
  },
1635
- read(name) {
1636
- const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
1637
- 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;
1638
2513
  },
1639
- remove(name) {
1640
- this.write(name, "", Date.now() - 864e5);
2514
+ remove(name2) {
2515
+ this.write(name2, "", Date.now() - 864e5, "/");
1641
2516
  }
1642
2517
  }
1643
2518
  ) : (
@@ -1653,22 +2528,58 @@ const cookies = platform.hasStandardBrowserEnv ? (
1653
2528
  }
1654
2529
  );
1655
2530
  function isAbsoluteURL(url) {
2531
+ if (typeof url !== "string") {
2532
+ return false;
2533
+ }
1656
2534
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
1657
2535
  }
1658
2536
  function combineURLs(baseURL, relativeURL) {
1659
2537
  return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
1660
2538
  }
1661
- 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);
1662
2562
  let isRelativeUrl = !isAbsoluteURL(requestedURL);
1663
- if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
2563
+ if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) {
2564
+ assertValidHttpProtocolURL(baseURL, config2);
1664
2565
  return combineURLs(baseURL, requestedURL);
1665
2566
  }
1666
2567
  return requestedURL;
1667
2568
  }
1668
2569
  const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
1669
2570
  function mergeConfig$1(config1, config2) {
2571
+ config1 = config1 || {};
1670
2572
  config2 = config2 || {};
1671
- 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
+ });
1672
2583
  function getMergedValue(target, source, prop, caseless) {
1673
2584
  if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
1674
2585
  return utils$1.merge.call({ caseless }, target, source);
@@ -1698,10 +2609,27 @@ function mergeConfig$1(config1, config2) {
1698
2609
  return getMergedValue(void 0, a);
1699
2610
  }
1700
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
+ }
1701
2629
  function mergeDirectKeys(a, b, prop) {
1702
- if (prop in config2) {
2630
+ if (utils$1.hasOwnProp(config2, prop)) {
1703
2631
  return getMergedValue(a, b);
1704
- } else if (prop in config1) {
2632
+ } else if (utils$1.hasOwnProp(config1, prop)) {
1705
2633
  return getMergedValue(void 0, a);
1706
2634
  }
1707
2635
  }
@@ -1732,44 +2660,87 @@ function mergeConfig$1(config1, config2) {
1732
2660
  httpsAgent: defaultToConfig2,
1733
2661
  cancelToken: defaultToConfig2,
1734
2662
  socketPath: defaultToConfig2,
2663
+ allowedSocketPaths: defaultToConfig2,
1735
2664
  responseEncoding: defaultToConfig2,
1736
2665
  validateStatus: mergeDirectKeys,
1737
2666
  headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
1738
2667
  };
1739
2668
  utils$1.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) {
1740
- const merge2 = mergeMap[prop] || mergeDeepProperties;
1741
- 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);
1742
2674
  utils$1.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config3[prop] = configValue);
1743
2675
  });
1744
- return config3;
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
+ }
2683
+ return config3;
2684
+ }
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
+ });
1745
2696
  }
1746
- const resolveConfig = (config2) => {
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) {
1747
2702
  const newConfig = mergeConfig$1({}, config2);
1748
- 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");
1749
2713
  newConfig.headers = headers = AxiosHeaders$1.from(headers);
1750
- 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
+ );
1751
2719
  if (auth) {
1752
- headers.set(
1753
- "Authorization",
1754
- "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : ""))
1755
- );
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
+ }
1756
2730
  }
1757
2731
  if (utils$1.isFormData(data)) {
1758
- if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
2732
+ if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv || utils$1.isReactNative(data)) {
1759
2733
  headers.setContentType(void 0);
1760
2734
  } else if (utils$1.isFunction(data.getHeaders)) {
1761
- const formHeaders = data.getHeaders();
1762
- const allowedHeaders = ["content-type", "content-length"];
1763
- Object.entries(formHeaders).forEach(([key, val]) => {
1764
- if (allowedHeaders.includes(key.toLowerCase())) {
1765
- headers.set(key, val);
1766
- }
1767
- });
2735
+ setFormDataHeaders(headers, data.getHeaders(), own2("formDataHeaderPolicy"));
1768
2736
  }
1769
2737
  }
1770
2738
  if (platform.hasStandardBrowserEnv) {
1771
- withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
1772
- 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) {
1773
2744
  const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
1774
2745
  if (xsrfValue) {
1775
2746
  headers.set(xsrfHeaderName, xsrfValue);
@@ -1777,7 +2748,7 @@ const resolveConfig = (config2) => {
1777
2748
  }
1778
2749
  }
1779
2750
  return newConfig;
1780
- };
2751
+ }
1781
2752
  const isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
1782
2753
  const xhrAdapter = isXHRAdapterSupported && function(config2) {
1783
2754
  return new Promise(function dispatchXhrRequest(resolve, reject) {
@@ -1813,13 +2784,17 @@ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1813
2784
  config: config2,
1814
2785
  request
1815
2786
  };
1816
- settle(function _resolve(value) {
1817
- resolve(value);
1818
- done();
1819
- }, function _reject(err) {
1820
- reject(err);
1821
- done();
1822
- }, 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
+ );
1823
2798
  request = null;
1824
2799
  }
1825
2800
  if ("onloadend" in request) {
@@ -1829,7 +2804,7 @@ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1829
2804
  if (!request || request.readyState !== 4) {
1830
2805
  return;
1831
2806
  }
1832
- if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
2807
+ if (request.status === 0 && !(request.responseURL && request.responseURL.startsWith("file:"))) {
1833
2808
  return;
1834
2809
  }
1835
2810
  setTimeout(onloadend);
@@ -1840,6 +2815,7 @@ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1840
2815
  return;
1841
2816
  }
1842
2817
  reject(new AxiosError$1("Request aborted", AxiosError$1.ECONNABORTED, config2, request));
2818
+ done();
1843
2819
  request = null;
1844
2820
  };
1845
2821
  request.onerror = function handleError(event) {
@@ -1847,6 +2823,7 @@ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1847
2823
  const err = new AxiosError$1(msg, AxiosError$1.ERR_NETWORK, config2, request);
1848
2824
  err.event = event || null;
1849
2825
  reject(err);
2826
+ done();
1850
2827
  request = null;
1851
2828
  };
1852
2829
  request.ontimeout = function handleTimeout() {
@@ -1855,17 +2832,20 @@ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1855
2832
  if (_config.timeoutErrorMessage) {
1856
2833
  timeoutErrorMessage = _config.timeoutErrorMessage;
1857
2834
  }
1858
- reject(new AxiosError$1(
1859
- timeoutErrorMessage,
1860
- transitional2.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
1861
- config2,
1862
- request
1863
- ));
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();
1864
2844
  request = null;
1865
2845
  };
1866
2846
  requestData === void 0 && requestHeaders.setContentType(null);
1867
2847
  if ("setRequestHeader" in request) {
1868
- utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
2848
+ utils$1.forEach(toByteStringHeaderObject(requestHeaders), function setRequestHeader(val, key) {
1869
2849
  request.setRequestHeader(key, val);
1870
2850
  });
1871
2851
  }
@@ -1891,6 +2871,7 @@ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1891
2871
  }
1892
2872
  reject(!cancel || cancel.type ? new CanceledError$1(null, config2, request) : cancel);
1893
2873
  request.abort();
2874
+ done();
1894
2875
  request = null;
1895
2876
  };
1896
2877
  _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
@@ -1899,45 +2880,56 @@ const xhrAdapter = isXHRAdapterSupported && function(config2) {
1899
2880
  }
1900
2881
  }
1901
2882
  const protocol = parseProtocol(_config.url);
1902
- if (protocol && platform.protocols.indexOf(protocol) === -1) {
1903
- 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();
1904
2892
  return;
1905
2893
  }
1906
2894
  request.send(requestData || null);
1907
2895
  });
1908
2896
  };
1909
2897
  const composeSignals = (signals, timeout) => {
1910
- const { length } = signals = signals ? signals.filter(Boolean) : [];
1911
- if (timeout || length) {
1912
- let controller2 = new AbortController();
1913
- let aborted;
1914
- const onabort = function(reason) {
1915
- if (!aborted) {
1916
- aborted = true;
1917
- unsubscribe();
1918
- const err = reason instanceof Error ? reason : this.reason;
1919
- controller2.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err));
1920
- }
1921
- };
1922
- let timer = timeout && setTimeout(() => {
1923
- timer = null;
1924
- onabort(new AxiosError$1(`timeout ${timeout} of ms exceeded`, AxiosError$1.ETIMEDOUT));
1925
- }, timeout);
1926
- const unsubscribe = () => {
1927
- if (signals) {
1928
- timer && clearTimeout(timer);
1929
- timer = null;
1930
- signals.forEach((signal2) => {
1931
- signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
1932
- });
1933
- signals = null;
1934
- }
1935
- };
1936
- signals.forEach((signal2) => signal2.addEventListener("abort", onabort));
1937
- const { signal } = controller2;
1938
- signal.unsubscribe = () => utils$1.asap(unsubscribe);
1939
- return signal;
2898
+ signals = signals ? signals.filter(Boolean) : [];
2899
+ if (!timeout && !signals.length) {
2900
+ return;
1940
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;
1941
2933
  };
1942
2934
  const streamChunk = function* (chunk, chunkSize) {
1943
2935
  let len = chunk.byteLength;
@@ -1986,44 +2978,127 @@ const trackStream = (stream, chunkSize, onProgress, onFinish) => {
1986
2978
  onFinish && onFinish(e);
1987
2979
  }
1988
2980
  };
1989
- return new ReadableStream({
1990
- async pull(controller2) {
1991
- try {
1992
- const { done: done2, value } = await iterator2.next();
1993
- if (done2) {
1994
- _onFinish();
1995
- controller2.close();
1996
- return;
1997
- }
1998
- let len = value.byteLength;
1999
- if (onProgress) {
2000
- let loadedBytes = bytes += len;
2001
- 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;
2002
3000
  }
2003
- controller2.enqueue(new Uint8Array(value));
2004
- } catch (err) {
2005
- _onFinish(err);
2006
- throw err;
3001
+ },
3002
+ cancel(reason) {
3003
+ _onFinish(reason);
3004
+ return iterator2.return();
2007
3005
  }
2008
3006
  },
2009
- cancel(reason) {
2010
- _onFinish(reason);
2011
- return iterator2.return();
3007
+ {
3008
+ highWaterMark: 2
2012
3009
  }
2013
- }, {
2014
- highWaterMark: 2
2015
- });
3010
+ );
2016
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";
2017
3086
  const DEFAULT_CHUNK_SIZE = 64 * 1024;
2018
3087
  const { isFunction } = utils$1;
2019
- const globalFetchAPI = (({ Request, Response }) => ({
2020
- Request,
2021
- Response
2022
- }))(utils$1.global);
2023
- const {
2024
- ReadableStream: ReadableStream$1,
2025
- TextEncoder
2026
- } = 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
+ };
2027
3102
  const test = (fn, ...args) => {
2028
3103
  try {
2029
3104
  return !!fn(...args);
@@ -2031,10 +3106,27 @@ const test = (fn, ...args) => {
2031
3106
  return false;
2032
3107
  }
2033
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
+ };
2034
3117
  const factory = (env) => {
2035
- env = utils$1.merge.call({
2036
- skipUndefined: true
2037
- }, 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
+ );
2038
3130
  const { fetch: envFetch, Request, Response } = env;
2039
3131
  const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === "function";
2040
3132
  const isRequestSupported = isFunction(Request);
@@ -2042,18 +3134,22 @@ const factory = (env) => {
2042
3134
  if (!isFetchSupported) {
2043
3135
  return false;
2044
3136
  }
2045
- const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1);
2046
- 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()));
2047
3139
  const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
2048
3140
  let duplexAccessed = false;
2049
- const hasContentType = new Request(platform.origin, {
2050
- body: new ReadableStream$1(),
3141
+ const request = new Request(platform.origin, {
3142
+ body: new ReadableStream2(),
2051
3143
  method: "POST",
2052
3144
  get duplex() {
2053
3145
  duplexAccessed = true;
2054
3146
  return "half";
2055
3147
  }
2056
- }).headers.has("Content-Type");
3148
+ });
3149
+ const hasContentType = request.headers.has("Content-Type");
3150
+ if (request.body != null) {
3151
+ request.body.cancel();
3152
+ }
2057
3153
  return duplexAccessed && !hasContentType;
2058
3154
  });
2059
3155
  const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils$1.isReadableStream(new Response("").body));
@@ -2067,7 +3163,11 @@ const factory = (env) => {
2067
3163
  if (method) {
2068
3164
  return method.call(res);
2069
3165
  }
2070
- 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
+ );
2071
3171
  });
2072
3172
  });
2073
3173
  })();
@@ -2112,63 +3212,189 @@ const factory = (env) => {
2112
3212
  responseType,
2113
3213
  headers,
2114
3214
  withCredentials = "same-origin",
2115
- fetchOptions
3215
+ fetchOptions,
3216
+ maxContentLength,
3217
+ maxBodyLength
2116
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;
2117
3222
  let _fetch = envFetch || fetch;
2118
3223
  responseType = responseType ? (responseType + "").toLowerCase() : "text";
2119
- let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
3224
+ let composedSignal = composeSignals(
3225
+ [signal, cancelToken && cancelToken.toAbortSignal()],
3226
+ timeout
3227
+ );
2120
3228
  let request = null;
2121
3229
  const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
2122
3230
  composedSignal.unsubscribe();
2123
3231
  });
2124
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
+ );
2125
3240
  try {
2126
- if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
2127
- let _request = new Request(url, {
2128
- method: "POST",
2129
- body: data,
2130
- duplex: "half"
2131
- });
2132
- let contentTypeHeader;
2133
- if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
2134
- 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;
2135
3265
  }
2136
- if (_request.body) {
2137
- const [onProgress, flush] = progressEventDecorator(
2138
- requestContentLength,
2139
- 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
2140
3282
  );
2141
- data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
2142
3283
  }
2143
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
+ }
2144
3336
  if (!utils$1.isString(withCredentials)) {
2145
3337
  withCredentials = withCredentials ? "include" : "omit";
2146
3338
  }
2147
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);
2148
3347
  const resolvedOptions = {
2149
3348
  ...fetchOptions,
2150
3349
  signal: composedSignal,
2151
3350
  method: method.toUpperCase(),
2152
- headers: headers.normalize().toJSON(),
3351
+ headers: toByteStringHeaderObject(headers.normalize()),
2153
3352
  body: data,
2154
3353
  duplex: "half",
2155
3354
  credentials: isCredentialsSupported ? withCredentials : void 0
2156
3355
  };
2157
3356
  request = isRequestSupported && new Request(url, resolvedOptions);
2158
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
+ }
2159
3370
  const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
2160
- if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
3371
+ if (supportsResponseStream && response.body && (onDownloadProgress || hasMaxContentLength || isStreamResponse && unsubscribe)) {
2161
3372
  const options = {};
2162
3373
  ["status", "statusText", "headers"].forEach((prop) => {
2163
3374
  options[prop] = response[prop];
2164
3375
  });
2165
- const responseContentLength = utils$1.toFiniteNumber(response.headers.get("content-length"));
3376
+ const responseContentLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
2166
3377
  const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
2167
3378
  responseContentLength,
2168
3379
  progressEventReducer(asyncDecorator(onDownloadProgress), true)
2169
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
+ };
2170
3396
  response = new Response(
2171
- trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
3397
+ trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => {
2172
3398
  flush && flush();
2173
3399
  unsubscribe && unsubscribe();
2174
3400
  }),
@@ -2176,7 +3402,30 @@ const factory = (env) => {
2176
3402
  );
2177
3403
  }
2178
3404
  responseType = responseType || "text";
2179
- 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
+ }
2180
3429
  !isStreamResponse && unsubscribe && unsubscribe();
2181
3430
  return await new Promise((resolve, reject) => {
2182
3431
  settle(resolve, reject, {
@@ -2190,27 +3439,55 @@ const factory = (env) => {
2190
3439
  });
2191
3440
  } catch (err) {
2192
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
+ }
2193
3465
  if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) {
2194
- throw Object.assign(
2195
- new AxiosError$1("Network Error", AxiosError$1.ERR_NETWORK, config2, request),
2196
- {
2197
- cause: err.cause || err
2198
- }
3466
+ const networkError = new AxiosError$1(
3467
+ "Network Error",
3468
+ AxiosError$1.ERR_NETWORK,
3469
+ config2,
3470
+ request,
3471
+ err && err.response
2199
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;
2200
3481
  }
2201
- throw AxiosError$1.from(err, err && err.code, config2, request);
3482
+ throw AxiosError$1.from(err, err && err.code, config2, request, err && err.response);
2202
3483
  }
2203
3484
  };
2204
3485
  };
2205
3486
  const seedCache = /* @__PURE__ */ new Map();
2206
3487
  const getFetch = (config2) => {
2207
- let env = config2 ? config2.env : {};
3488
+ let env = config2 && config2.env || {};
2208
3489
  const { fetch: fetch2, Request, Response } = env;
2209
- const seeds = [
2210
- Request,
2211
- Response,
2212
- fetch2
2213
- ];
3490
+ const seeds = [Request, Response, fetch2];
2214
3491
  let len = seeds.length, i = len, seed, target, map = seedCache;
2215
3492
  while (i--) {
2216
3493
  seed = seeds[i];
@@ -2231,48 +3508,57 @@ const knownAdapters = {
2231
3508
  utils$1.forEach(knownAdapters, (fn, value) => {
2232
3509
  if (fn) {
2233
3510
  try {
2234
- Object.defineProperty(fn, "name", { value });
3511
+ Object.defineProperty(fn, "name", { __proto__: null, value });
2235
3512
  } catch (e) {
2236
3513
  }
2237
- Object.defineProperty(fn, "adapterName", { value });
3514
+ Object.defineProperty(fn, "adapterName", { __proto__: null, value });
2238
3515
  }
2239
3516
  });
2240
3517
  const renderReason = (reason) => `- ${reason}`;
2241
3518
  const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
2242
- const adapters = {
2243
- getAdapter: (adapters2, config2) => {
2244
- adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2];
2245
- const { length } = adapters2;
2246
- let nameOrAdapter;
2247
- let adapter;
2248
- const rejectedReasons = {};
2249
- for (let i = 0; i < length; i++) {
2250
- nameOrAdapter = adapters2[i];
2251
- let id;
2252
- adapter = nameOrAdapter;
2253
- if (!isResolvedHandle(nameOrAdapter)) {
2254
- adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
2255
- if (adapter === void 0) {
2256
- throw new AxiosError$1(`Unknown adapter '${id}'`);
2257
- }
2258
- }
2259
- if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config2)))) {
2260
- 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}'`);
2261
3533
  }
2262
- rejectedReasons[id || "#" + i] = adapter;
2263
3534
  }
2264
- if (!adapter) {
2265
- const reasons = Object.entries(rejectedReasons).map(
2266
- ([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build")
2267
- );
2268
- let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified";
2269
- throw new AxiosError$1(
2270
- `There is no suitable adapter to dispatch the request ` + s,
2271
- "ERR_NOT_SUPPORT"
2272
- );
3535
+ if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config2)))) {
3536
+ break;
2273
3537
  }
2274
- return adapter;
2275
- },
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
+ */
2276
3562
  adapters: knownAdapters
2277
3563
  };
2278
3564
  function throwIfCancellationRequested(config2) {
@@ -2286,39 +3572,44 @@ function throwIfCancellationRequested(config2) {
2286
3572
  function dispatchRequest(config2) {
2287
3573
  throwIfCancellationRequested(config2);
2288
3574
  config2.headers = AxiosHeaders$1.from(config2.headers);
2289
- config2.data = transformData.call(
2290
- config2,
2291
- config2.transformRequest
2292
- );
3575
+ config2.data = transformData.call(config2, config2.transformRequest);
2293
3576
  if (["post", "put", "patch"].indexOf(config2.method) !== -1) {
2294
3577
  config2.headers.setContentType("application/x-www-form-urlencoded", false);
2295
3578
  }
2296
3579
  const adapter = adapters.getAdapter(config2.adapter || defaults.adapter, config2);
2297
- return adapter(config2).then(function onAdapterResolution(response) {
2298
- throwIfCancellationRequested(config2);
2299
- response.data = transformData.call(
2300
- config2,
2301
- config2.transformResponse,
2302
- response
2303
- );
2304
- response.headers = AxiosHeaders$1.from(response.headers);
2305
- return response;
2306
- }, function onAdapterRejection(reason) {
2307
- if (!isCancel$1(reason)) {
3580
+ return adapter(config2).then(
3581
+ function onAdapterResolution(response) {
2308
3582
  throwIfCancellationRequested(config2);
2309
- if (reason && reason.response) {
2310
- reason.response.data = transformData.call(
2311
- config2,
2312
- config2.transformResponse,
2313
- reason.response
2314
- );
2315
- 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
+ }
2316
3608
  }
3609
+ return Promise.reject(reason);
2317
3610
  }
2318
- return Promise.reject(reason);
2319
- });
3611
+ );
2320
3612
  }
2321
- const VERSION$1 = "1.12.2";
2322
3613
  const validators$1 = {};
2323
3614
  ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => {
2324
3615
  validators$1[type] = function validator2(thing) {
@@ -2355,20 +3646,23 @@ validators$1.spelling = function spelling(correctSpelling) {
2355
3646
  return true;
2356
3647
  };
2357
3648
  };
2358
- function assertOptions(options, schema, allowUnknown) {
2359
- if (typeof options !== "object") {
3649
+ function assertOptions(options, schema2, allowUnknown) {
3650
+ if (typeof options !== "object" || options === null) {
2360
3651
  throw new AxiosError$1("options must be an object", AxiosError$1.ERR_BAD_OPTION_VALUE);
2361
3652
  }
2362
3653
  const keys = Object.keys(options);
2363
3654
  let i = keys.length;
2364
3655
  while (i-- > 0) {
2365
3656
  const opt = keys[i];
2366
- const validator2 = schema[opt];
3657
+ const validator2 = Object.prototype.hasOwnProperty.call(schema2, opt) ? schema2[opt] : void 0;
2367
3658
  if (validator2) {
2368
3659
  const value = options[opt];
2369
3660
  const result = value === void 0 || validator2(value, opt, options);
2370
3661
  if (result !== true) {
2371
- 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
+ );
2372
3666
  }
2373
3667
  continue;
2374
3668
  }
@@ -2405,12 +3699,23 @@ let Axios$1 = class Axios {
2405
3699
  if (err instanceof Error) {
2406
3700
  let dummy = {};
2407
3701
  Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
2408
- 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
+ })();
2409
3709
  try {
2410
3710
  if (!err.stack) {
2411
3711
  err.stack = stack;
2412
- } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) {
2413
- 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
+ }
2414
3719
  }
2415
3720
  } catch (e) {
2416
3721
  }
@@ -2428,11 +3733,18 @@ let Axios$1 = class Axios {
2428
3733
  config2 = mergeConfig$1(this.defaults, config2);
2429
3734
  const { transitional: transitional2, paramsSerializer, headers } = config2;
2430
3735
  if (transitional2 !== void 0) {
2431
- validator.assertOptions(transitional2, {
2432
- silentJSONParsing: validators.transitional(validators.boolean),
2433
- forcedJSONParsing: validators.transitional(validators.boolean),
2434
- clarifyTimeoutError: validators.transitional(validators.boolean)
2435
- }, 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
+ );
2436
3748
  }
2437
3749
  if (paramsSerializer != null) {
2438
3750
  if (utils$1.isFunction(paramsSerializer)) {
@@ -2440,10 +3752,14 @@ let Axios$1 = class Axios {
2440
3752
  serialize: paramsSerializer
2441
3753
  };
2442
3754
  } else {
2443
- validator.assertOptions(paramsSerializer, {
2444
- encode: validators.function,
2445
- serialize: validators.function
2446
- }, true);
3755
+ validator.assertOptions(
3756
+ paramsSerializer,
3757
+ {
3758
+ encode: validators.function,
3759
+ serialize: validators.function
3760
+ },
3761
+ true
3762
+ );
2447
3763
  }
2448
3764
  }
2449
3765
  if (config2.allowAbsoluteUrls !== void 0) ;
@@ -2452,21 +3768,19 @@ let Axios$1 = class Axios {
2452
3768
  } else {
2453
3769
  config2.allowAbsoluteUrls = true;
2454
3770
  }
2455
- validator.assertOptions(config2, {
2456
- baseUrl: validators.spelling("baseURL"),
2457
- withXsrfToken: validators.spelling("withXSRFToken")
2458
- }, true);
2459
- config2.method = (config2.method || this.defaults.method || "get").toLowerCase();
2460
- let contextHeaders = headers && utils$1.merge(
2461
- headers.common,
2462
- headers[config2.method]
2463
- );
2464
- headers && utils$1.forEach(
2465
- ["delete", "get", "head", "post", "put", "patch", "common"],
2466
- (method) => {
2467
- delete headers[method];
2468
- }
3771
+ validator.assertOptions(
3772
+ config2,
3773
+ {
3774
+ baseUrl: validators.spelling("baseURL"),
3775
+ withXsrfToken: validators.spelling("withXSRFToken")
3776
+ },
3777
+ true
2469
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
+ });
2470
3784
  config2.headers = AxiosHeaders$1.concat(contextHeaders, headers);
2471
3785
  const requestInterceptorChain = [];
2472
3786
  let synchronousRequestInterceptors = true;
@@ -2475,7 +3789,13 @@ let Axios$1 = class Axios {
2475
3789
  return;
2476
3790
  }
2477
3791
  synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
2478
- 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
+ }
2479
3799
  });
2480
3800
  const responseInterceptorChain = [];
2481
3801
  this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
@@ -2521,34 +3841,40 @@ let Axios$1 = class Axios {
2521
3841
  }
2522
3842
  getUri(config2) {
2523
3843
  config2 = mergeConfig$1(this.defaults, config2);
2524
- const fullPath = buildFullPath(config2.baseURL, config2.url, config2.allowAbsoluteUrls);
3844
+ const fullPath = buildFullPath(config2.baseURL, config2.url, config2.allowAbsoluteUrls, config2);
2525
3845
  return buildURL(fullPath, config2.params, config2.paramsSerializer);
2526
3846
  }
2527
3847
  };
2528
3848
  utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) {
2529
3849
  Axios$1.prototype[method] = function(url, config2) {
2530
- return this.request(mergeConfig$1(config2 || {}, {
2531
- method,
2532
- url,
2533
- data: (config2 || {}).data
2534
- }));
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
+ );
2535
3857
  };
2536
3858
  });
2537
- utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
3859
+ utils$1.forEach(["post", "put", "patch", "query"], function forEachMethodWithData(method) {
2538
3860
  function generateHTTPMethod(isForm) {
2539
3861
  return function httpMethod(url, data, config2) {
2540
- return this.request(mergeConfig$1(config2 || {}, {
2541
- method,
2542
- headers: isForm ? {
2543
- "Content-Type": "multipart/form-data"
2544
- } : {},
2545
- url,
2546
- data
2547
- }));
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
+ );
2548
3872
  };
2549
3873
  }
2550
3874
  Axios$1.prototype[method] = generateHTTPMethod();
2551
- Axios$1.prototype[method + "Form"] = generateHTTPMethod(true);
3875
+ if (method !== "query") {
3876
+ Axios$1.prototype[method + "Form"] = generateHTTPMethod(true);
3877
+ }
2552
3878
  });
2553
3879
  let CancelToken$1 = class CancelToken {
2554
3880
  constructor(executor) {
@@ -2716,7 +4042,13 @@ const HttpStatusCode$1 = {
2716
4042
  InsufficientStorage: 507,
2717
4043
  LoopDetected: 508,
2718
4044
  NotExtended: 510,
2719
- NetworkAuthenticationRequired: 511
4045
+ NetworkAuthenticationRequired: 511,
4046
+ WebServerIsDown: 521,
4047
+ ConnectionTimedOut: 522,
4048
+ OriginIsUnreachable: 523,
4049
+ TimeoutOccurred: 524,
4050
+ SslHandshakeFailed: 525,
4051
+ InvalidSslCertificate: 526
2720
4052
  };
2721
4053
  Object.entries(HttpStatusCode$1).forEach(([key, value]) => {
2722
4054
  HttpStatusCode$1[value] = key;
@@ -2726,7 +4058,7 @@ function createInstance(defaultConfig) {
2726
4058
  const instance = bind(Axios$1.prototype.request, context);
2727
4059
  utils$1.extend(instance, Axios$1.prototype, context, { allOwnKeys: true });
2728
4060
  utils$1.extend(instance, context, null, { allOwnKeys: true });
2729
- instance.create = function create(instanceConfig) {
4061
+ instance.create = function create2(instanceConfig) {
2730
4062
  return createInstance(mergeConfig$1(defaultConfig, instanceConfig));
2731
4063
  };
2732
4064
  return instance;
@@ -2740,8 +4072,8 @@ axios.VERSION = VERSION$1;
2740
4072
  axios.toFormData = toFormData$1;
2741
4073
  axios.AxiosError = AxiosError$1;
2742
4074
  axios.Cancel = axios.CanceledError;
2743
- axios.all = function all(promises) {
2744
- return Promise.all(promises);
4075
+ axios.all = function all(promises2) {
4076
+ return Promise.all(promises2);
2745
4077
  };
2746
4078
  axios.spread = spread$1;
2747
4079
  axios.isAxiosError = isAxiosError$1;
@@ -2753,8 +4085,8 @@ axios.HttpStatusCode = HttpStatusCode$1;
2753
4085
  axios.default = axios;
2754
4086
  const {
2755
4087
  Axios: Axios2,
2756
- AxiosError,
2757
- CanceledError,
4088
+ AxiosError: AxiosError2,
4089
+ CanceledError: CanceledError2,
2758
4090
  isCancel,
2759
4091
  CancelToken: CancelToken2,
2760
4092
  VERSION,
@@ -2767,7 +4099,8 @@ const {
2767
4099
  HttpStatusCode,
2768
4100
  formToJSON,
2769
4101
  getAdapter,
2770
- mergeConfig
4102
+ mergeConfig,
4103
+ create
2771
4104
  } = axios;
2772
4105
  const service = ({ strapi }) => {
2773
4106
  return {
@@ -2798,54 +4131,44 @@ const service = ({ strapi }) => {
2798
4131
  async getUsuarios(sanitizedQueryParams) {
2799
4132
  return await strapi.documents("plugin::users-permissions.user").findMany(sanitizedQueryParams);
2800
4133
  },
2801
- async getImagenes() {
2802
- const existingFolders = await strapi.documents("plugin::upload.folder").findMany({
2803
- filters: {
2804
- name: "Generated"
4134
+ // ───────────────────────────────
4135
+ // 📥 Proxy File Download (bypasses browser CORS)
4136
+ // ───────────────────────────────
4137
+ async downloadFile(ctx) {
4138
+ const { url } = ctx.request.body;
4139
+ if (!url) {
4140
+ ctx.status = 400;
4141
+ ctx.body = { error: "Se requiere el parámetro 'url'." };
4142
+ return;
4143
+ }
4144
+ let parsedUrl;
4145
+ try {
4146
+ parsedUrl = new URL(url);
4147
+ const allowedHosts = [
4148
+ "web-cms-interware.s3.us-east-1.amazonaws.com",
4149
+ "api.interware.com.mx",
4150
+ ...process.env.NODE_ENV === "development" ? ["localhost"] : []
4151
+ ];
4152
+ if (!allowedHosts.includes(parsedUrl.hostname)) {
4153
+ ctx.status = 403;
4154
+ ctx.body = { error: "URL no permitida." };
4155
+ return;
2805
4156
  }
2806
- });
2807
- if (existingFolders) {
2808
- return await strapi.documents("plugin::upload.file").findMany({
2809
- filters: {
2810
- folder: {
2811
- id: {
2812
- $eq: existingFolders[0].id
2813
- }
2814
- }
2815
- },
2816
- sort: ["createdAt:desc"]
2817
- });
4157
+ } catch {
4158
+ ctx.status = 400;
4159
+ ctx.body = { error: "URL inválida." };
4160
+ return;
2818
4161
  }
2819
- return [];
2820
- },
2821
- async eliminarImagen(sanitizedQueryParams) {
2822
- return await strapi.documents("plugin::upload.file").delete(sanitizedQueryParams);
4162
+ const response = await axios.get(url, { responseType: "arraybuffer" });
4163
+ const base64 = Buffer.from(response.data).toString("base64");
4164
+ const contentType = response.headers["content-type"] || "application/octet-stream";
4165
+ ctx.body = { base64, contentType };
2823
4166
  },
2824
4167
  // ───────────────────────────────
2825
4168
  // 🏞️ Internal File Upload Helper
2826
4169
  // ───────────────────────────────
2827
4170
  async _uploadGeneratedFile(file, filename, mimeType, folderName = "Generated") {
2828
- const existingFolders = await strapi.documents("plugin::upload.folder").findMany({
2829
- filters: { name: folderName }
2830
- });
2831
- let folderId;
2832
- if (!existingFolders || existingFolders.length === 0) {
2833
- const lastFolder = await strapi.documents("plugin::upload.folder").findMany({
2834
- sort: { pathId: "desc" },
2835
- limit: 1
2836
- });
2837
- const pathId = Array.isArray(lastFolder) && lastFolder.length > 0 ? lastFolder[0].pathId + 1 : 1;
2838
- const createdFolder = await strapi.documents("plugin::upload.folder").create({
2839
- data: {
2840
- name: folderName,
2841
- path: `/${folderName.toLowerCase()}`,
2842
- pathId
2843
- }
2844
- });
2845
- folderId = createdFolder.id;
2846
- } else {
2847
- folderId = existingFolders[0].id;
2848
- }
4171
+ const folderId = await ensureFolder(strapi, folderName);
2849
4172
  let fileSize = 0;
2850
4173
  if (typeof file === "string") {
2851
4174
  const stats = fs.statSync(file);
@@ -3080,15 +4403,7 @@ const service = ({ strapi }) => {
3080
4403
  output_format: "image/png"
3081
4404
  };
3082
4405
  const promptText = JSON.stringify(promptJson);
3083
- const generatedBase64Image = await this._callGeminiImageGeneration(
3084
- promptText,
3085
- aspectRatio || "16:9",
3086
- // Use provided aspectRatio or default
3087
- imageSize || "1K",
3088
- // Use provided imageSize or default
3089
- []
3090
- // No reference images for article generation
3091
- );
4406
+ const generatedBase64Image = await strapi.plugin("strapi-content-generator-gemini").service("image-studio").generateForArticle(promptText, aspectRatio || "16:9", imageSize || "1K");
3092
4407
  const buffer = Buffer.from(generatedBase64Image, "base64");
3093
4408
  const uploadedFile = await this._uploadGeneratedFile(buffer, `article-${articleId}.png`, "image/png");
3094
4409
  const articleModel = await strapi.getModel("api::articulo.articulo");
@@ -3111,134 +4426,10 @@ const service = ({ strapi }) => {
3111
4426
  throw new Error("Error al generar la imagen para el artículo.");
3112
4427
  }
3113
4428
  },
3114
- // ───────────────────────────────
3115
- // 🖼️ Internal Image Generation Helper
3116
- // Imagen 4 cuando no hay imágenes de referencia (mejor calidad y adherencia al prompt)
3117
- // Gemini 2.5 Flash como fallback cuando se proporcionan imágenes de referencia
3118
- // ───────────────────────────────
3119
- async _callGeminiImageGeneration(promptText, aspectRatio, imageSizeLabel, referenceImages) {
3120
- const ai = await this.geminiConfig();
3121
- const cleanPrompt = promptText.replace(/\r\n/g, " ").replace(/\n/g, " ").replace(/\s+/g, " ").trim();
3122
- if (referenceImages.length === 0) {
3123
- const response = await ai.models.generateImages({
3124
- model: "imagen-4.0-generate-001",
3125
- prompt: cleanPrompt,
3126
- config: {
3127
- numberOfImages: 1,
3128
- aspectRatio,
3129
- outputMimeType: "image/png"
3130
- }
3131
- });
3132
- const imageBytes = response.generatedImages?.[0]?.image?.imageBytes;
3133
- if (!imageBytes) {
3134
- throw new Error("Imagen 4 no devolvió imagen. Verifica el prompt o el modelo.");
3135
- }
3136
- return imageBytes;
3137
- }
3138
- const imageParts = referenceImages.map((img) => ({
3139
- inlineData: {
3140
- mimeType: img.mimeType,
3141
- data: img.buffer.toString("base64")
3142
- }
3143
- }));
3144
- const result = await ai.models.generateContent({
3145
- model: "gemini-2.5-flash-image",
3146
- contents: [{ text: cleanPrompt }, ...imageParts],
3147
- config: {
3148
- responseModalities: [Modality.IMAGE],
3149
- imageConfig: { aspectRatio, imageSize: imageSizeLabel }
3150
- }
3151
- });
3152
- const parts = result?.candidates?.[0]?.content?.parts;
3153
- if (!Array.isArray(parts)) {
3154
- throw new Error("Respuesta inválida del modelo (parts no encontrado)");
3155
- }
3156
- const imagePart = parts.find(
3157
- (p) => p?.inlineData?.data && typeof p.inlineData.data === "string" && p.inlineData.mimeType?.startsWith("image/")
3158
- );
3159
- if (!imagePart) {
3160
- throw new Error("No se encontró ninguna imagen en la respuesta del modelo");
3161
- }
3162
- return imagePart.inlineData.data;
3163
- },
3164
- // ───────────────────────────────
3165
- // 🖼️ Generate Image (Standalone)
3166
- // ───────────────────────────────
3167
- async generateImage(ctx) {
3168
- const { prompt, aspectRatio, imageSize } = ctx.request.body;
3169
- if (!prompt) {
3170
- throw new Error("Se requiere 'prompt' para generar el contenido visual.");
3171
- }
3172
- const promptJson = {
3173
- label: `standalone-image-${Date.now()}`,
3174
- task: "generate_image",
3175
- canvas: {
3176
- resolution: imageSize || "1K",
3177
- aspect_ratio: aspectRatio || "16:9"
3178
- },
3179
- style: {
3180
- type: "architectural software engineering visualization",
3181
- aesthetic: "high-end technical 3D render / octane style",
3182
- background: "view of a bright white minimalist architectural gallery, sun-drenched space, white polished floors and tall glass windows",
3183
- lighting: "intense natural daylight, soft global illumination, clean diffused light with subtle volumetric rays from windows"
3184
- },
3185
- concept_brief: prompt,
3186
- subject: [
3187
- "apply the concept brief above as the main subject — rendered as a sophisticated 3D holographic or architectural structure floating inside the gallery",
3188
- "materials: frosted glass, white matte ceramic, polished metal accents",
3189
- "brand accent colors red #E4002B and teal #00C7B1 on glowing energy filaments, highlights, and data connections",
3190
- "the structure casts a sharp, clean reflection on the white polished gallery floor",
3191
- "STRICTLY NO people, NO humans, NO hands, NO chairs",
3192
- "STRICTLY NO text, NO labels, NO words, NO letters, NO numbers, NO logos",
3193
- "high-end 3D render, architectural photography style, 4k quality"
3194
- ],
3195
- camera: {
3196
- perspective: "three-quarter wide shot, slightly elevated, showing both the subject and the gallery environment",
3197
- depth_of_field: "main subject in sharp focus, gallery background beautifully blurred"
3198
- },
3199
- render: {
3200
- engine: "Octane or Cinema 4D",
3201
- effects: "bloom on glowing elements, ray-traced reflections on the white polished floor, subsurface scattering on frosted glass, volumetric light rays from gallery windows",
3202
- quality: "masterpiece, hyper-detailed"
3203
- },
3204
- output_format: "image/png"
3205
- };
3206
- const basePrompt = JSON.stringify(promptJson);
3207
- const files = ctx.request.files ?? {};
3208
- const referenceImages = Object.entries(files).filter(([key]) => key.startsWith("referenceImages")).map(([, file]) => file);
3209
- if (referenceImages.length > 5) {
3210
- throw new Error("Máximo 5 imágenes de referencia permitidas.");
3211
- }
3212
- const imageBuffers = referenceImages.map((file) => {
3213
- const typedFile = file;
3214
- return {
3215
- buffer: typedFile.buffer ?? fs.readFileSync(typedFile.filepath),
3216
- mimeType: typedFile.mimetype
3217
- };
3218
- });
3219
- try {
3220
- const generatedBase64Image = await this._callGeminiImageGeneration(
3221
- basePrompt,
3222
- aspectRatio || "16:9",
3223
- imageSize || "1K",
3224
- imageBuffers
3225
- );
3226
- const buffer = Buffer.from(generatedBase64Image, "base64");
3227
- const filename = `generated-image-${Date.now()}.png`;
3228
- const uploadedFile = await this._uploadGeneratedFile(buffer, filename, "image/png");
3229
- return {
3230
- message: `Imagen generada y subida correctamente.`,
3231
- file: uploadedFile
3232
- };
3233
- } catch (err) {
3234
- console.error("🚀 ~ generateImage ~ err:", err);
3235
- throw new Error(`Error al generar la imagen.`);
3236
- }
3237
- },
3238
4429
  // 🎞️ Internal Veo Video Generation / Extension Helper
3239
4430
  async _callVeoVideoGeneration(promptText, aspectRatio, durationSeconds, sceneRefs, previousVideo) {
3240
4431
  const ai = await this.geminiConfig();
3241
- const cleanPrompt = promptText.replace(/\s+/g, " ").trim();
4432
+ const cleanPrompt2 = promptText.replace(/\s+/g, " ").trim();
3242
4433
  const referenceImages = sceneRefs.map((img) => ({
3243
4434
  image: {
3244
4435
  imageBytes: img.buffer.toString("base64"),
@@ -3255,7 +4446,7 @@ const service = ({ strapi }) => {
3255
4446
  };
3256
4447
  const operationParams = {
3257
4448
  model: "veo-3.1-generate-preview",
3258
- prompt: cleanPrompt,
4449
+ prompt: cleanPrompt2,
3259
4450
  config: config2
3260
4451
  };
3261
4452
  if (previousVideo) {
@@ -3487,13 +4678,15 @@ ${hashtags}`,
3487
4678
  };
3488
4679
  };
3489
4680
  const services = {
3490
- service
4681
+ service,
4682
+ "image-studio": imageStudio$1,
4683
+ templates: templates$1
3491
4684
  };
3492
4685
  const index = {
3493
4686
  register,
3494
4687
  bootstrap,
3495
4688
  destroy,
3496
- config: config$1,
4689
+ config: config$2,
3497
4690
  controllers,
3498
4691
  routes,
3499
4692
  services,