@praxisui/files-upload 10.0.0-rc.70 → 10.0.0-rc.72

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.
@@ -1,5 +1,5 @@
1
1
  import * as i0 from '@angular/core';
2
- import { Injectable, inject, signal, InjectionToken, Inject, Component, Optional, EventEmitter, ViewChild, Output, Input, ChangeDetectionStrategy, ENVIRONMENT_INITIALIZER } from '@angular/core';
2
+ import { Optional, Injectable, inject, signal, InjectionToken, Inject, Component, EventEmitter, ViewChild, Output, Input, ChangeDetectionStrategy, ENVIRONMENT_INITIALIZER } from '@angular/core';
3
3
  import { ActivatedRoute } from '@angular/router';
4
4
  import * as i18 from '@angular/common';
5
5
  import { CommonModule } from '@angular/common';
@@ -21,19 +21,19 @@ import * as i7 from '@angular/material/select';
21
21
  import { MatSelectModule } from '@angular/material/select';
22
22
  import * as i1 from '@angular/common/http';
23
23
  import { HttpHeaders, HttpEventType, HttpResponse, HttpErrorResponse } from '@angular/common/http';
24
- import * as i1$2 from '@praxisui/core';
25
- import { providePraxisI18n, PraxisI18nService, PraxisIconButtonComponent, ComponentKeyService, ASYNC_CONFIG_STORAGE, PraxisIconDirective, ComponentMetadataRegistry } from '@praxisui/core';
24
+ import * as i2 from '@praxisui/core';
25
+ import { isPraxisContextualHeaderName, providePraxisI18n, PraxisI18nService, PraxisIconButtonComponent, isSafePraxisFileId, buildHeaders, API_URL, ComponentKeyService, ASYNC_CONFIG_STORAGE, PraxisIconDirective, normalizePraxisStoredFileMetadata, resolvePraxisFileOperationOptions, buildApiUrl, PRAXIS_FILE_UPLOAD_PORT, ComponentMetadataRegistry } from '@praxisui/core';
26
26
  import * as i3 from '@angular/material/tabs';
27
27
  import { MatTabsModule } from '@angular/material/tabs';
28
28
  import * as i6 from '@angular/material/checkbox';
29
29
  import { MatCheckboxModule } from '@angular/material/checkbox';
30
30
  import * as i9 from '@angular/material/tooltip';
31
31
  import { MatTooltipModule } from '@angular/material/tooltip';
32
- import * as i2 from '@angular/material/snack-bar';
32
+ import * as i2$1 from '@angular/material/snack-bar';
33
33
  import { MatSnackBarModule } from '@angular/material/snack-bar';
34
34
  import { toObservable, takeUntilDestroyed } from '@angular/core/rxjs-interop';
35
- import { of, throwError, BehaviorSubject, map as map$1, startWith, combineLatest, retry, debounceTime, from, Subscription } from 'rxjs';
36
- import * as i1$3 from '@praxisui/settings-panel';
35
+ import { of, throwError, BehaviorSubject, map as map$1, startWith, combineLatest, retry, timer, debounceTime, from, EMPTY, Subscription } from 'rxjs';
36
+ import * as i1$2 from '@praxisui/settings-panel';
37
37
  import { SETTINGS_PANEL_DATA } from '@praxisui/settings-panel';
38
38
  import { map, catchError, take, concatMap, toArray, tap, filter, defaultIfEmpty } from 'rxjs/operators';
39
39
  import { TemplatePortal } from '@angular/cdk/portal';
@@ -52,16 +52,13 @@ function getPrimaryErrorItem(error) {
52
52
  if (!error) {
53
53
  return undefined;
54
54
  }
55
- if (isStructuredErrorItem(error) && !isErrorEnvelope(error)) {
56
- return error;
57
- }
58
- if (!isErrorEnvelope(error)) {
59
- return undefined;
60
- }
61
- const structured = error.errors?.[0];
55
+ const structured = isErrorEnvelope(error) ? error.errors?.[0] : undefined;
62
56
  if (structured) {
63
57
  return structured;
64
58
  }
59
+ if (isStructuredErrorItem(error)) {
60
+ return error;
61
+ }
65
62
  return undefined;
66
63
  }
67
64
 
@@ -92,6 +89,8 @@ var ScanStatus;
92
89
  ScanStatus["CLEAN"] = "CLEAN";
93
90
  ScanStatus["INFECTED"] = "INFECTED";
94
91
  ScanStatus["FAILED"] = "FAILED";
92
+ ScanStatus["UNAVAILABLE"] = "UNAVAILABLE";
93
+ ScanStatus["SKIPPED"] = "SKIPPED";
95
94
  })(ScanStatus || (ScanStatus = {}));
96
95
 
97
96
  /** Result status for each file in a bulk upload operation. */
@@ -107,13 +106,17 @@ var BulkUploadResultStatus;
107
106
  */
108
107
  class ConfigService {
109
108
  http;
109
+ runtimeContext;
110
110
  cache = new Map();
111
- constructor(http) {
111
+ constructor(http, runtimeContext) {
112
112
  this.http = http;
113
+ this.runtimeContext = runtimeContext;
113
114
  }
114
115
  buildCacheKey(baseUrl, headers) {
115
- const headerKey = JSON.stringify(headers);
116
- return `${baseUrl}|${headerKey}`;
116
+ const normalizedEntries = Array.from(headers.entries())
117
+ .sort(([a], [b]) => a.localeCompare(b))
118
+ .map(([lowerKey, entry]) => [lowerKey, entry.value]);
119
+ return `${baseUrl}|${JSON.stringify(normalizedEntries)}`;
117
120
  }
118
121
  /**
119
122
  * Fetches the effective configuration from the server.
@@ -121,22 +124,52 @@ class ConfigService {
121
124
  * @param headersProvider Optional callback providing additional headers such as tenant/user.
122
125
  */
123
126
  getEffectiveConfig(baseUrl = '/api/files', headersProvider) {
127
+ const cleanBase = (baseUrl ?? '').trim().replace(/\/+$/, '') || '/api/files';
124
128
  const now = Date.now();
125
- const headersObj = headersProvider ? headersProvider() : {};
126
- const key = this.buildCacheKey(baseUrl, headersObj);
129
+ const hasEnterpriseContext = Boolean(this.runtimeContext
130
+ && (this.runtimeContext.effectiveContext
131
+ || this.runtimeContext.snapshot
132
+ || this.runtimeContext.isSwitching
133
+ || this.runtimeContext.lifecycleState() !== 'idle'));
134
+ const headerEntries = new Map();
135
+ const applySource = (source, excludeContextual) => {
136
+ if (!source) {
137
+ return;
138
+ }
139
+ for (const [name, raw] of Object.entries(source)) {
140
+ if (excludeContextual && isPraxisContextualHeaderName(name)) {
141
+ continue;
142
+ }
143
+ if (typeof raw === 'string' && raw.trim()) {
144
+ headerEntries.set(name.toLowerCase(), { name, value: raw.trim() });
145
+ }
146
+ }
147
+ };
148
+ if (hasEnterpriseContext && this.runtimeContext?.effectiveRequestHeaders) {
149
+ applySource(this.runtimeContext.effectiveRequestHeaders(), false);
150
+ }
151
+ applySource(headersProvider ? headersProvider() : undefined, hasEnterpriseContext);
152
+ const key = this.buildCacheKey(cleanBase, headerEntries);
127
153
  const entry = this.cache.get(key);
128
154
  if (entry && now - entry.timestamp < 60_000) {
129
155
  return of(entry.data);
130
156
  }
131
- const url = `${baseUrl}/config`;
157
+ const url = `${cleanBase}/config`;
158
+ let headers = new HttpHeaders();
159
+ for (const item of headerEntries.values()) {
160
+ headers = headers.set(item.name, item.value);
161
+ }
132
162
  if (entry?.etag) {
133
- headersObj['If-None-Match'] = entry.etag;
163
+ headers = headers.set('If-None-Match', entry.etag);
164
+ }
165
+ if (this.runtimeContext) {
166
+ headers = this.runtimeContext.applyHeaders(headers);
134
167
  }
135
- const headers = new HttpHeaders(headersObj);
136
168
  return this.http
137
169
  .get(url, {
138
170
  observe: 'response',
139
171
  headers,
172
+ withCredentials: true,
140
173
  })
141
174
  .pipe(map((resp) => {
142
175
  const etag = resp.headers.get('ETag') || undefined;
@@ -158,13 +191,15 @@ class ConfigService {
158
191
  return throwError(() => err);
159
192
  }));
160
193
  }
161
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: ConfigService, deps: [{ token: i1.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable });
194
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: ConfigService, deps: [{ token: i1.HttpClient }, { token: i2.EnterpriseRuntimeContextService, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
162
195
  static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: ConfigService, providedIn: 'root' });
163
196
  }
164
197
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: ConfigService, decorators: [{
165
198
  type: Injectable,
166
199
  args: [{ providedIn: 'root' }]
167
- }], ctorParameters: () => [{ type: i1.HttpClient }] });
200
+ }], ctorParameters: () => [{ type: i1.HttpClient }, { type: i2.EnterpriseRuntimeContextService, decorators: [{
201
+ type: Optional
202
+ }] }] });
168
203
 
169
204
  /**
170
205
  * Angular composable that retrieves the effective upload configuration
@@ -210,56 +245,75 @@ function useEffectiveUploadConfig(baseUrl, headersProvider) {
210
245
  const DEFAULT_CATALOG = {
211
246
  [ErrorCode.FILE_TOO_LARGE]: {
212
247
  title: 'Arquivo muito grande',
248
+ titleEn: 'File too large',
213
249
  category: 'validacao',
214
250
  phase: 'pre-upload',
215
251
  severity: 'error',
252
+ retriable: false,
216
253
  userAction: 'Reduza o tamanho ou aumente o limite permitido.',
254
+ userActionEn: 'Reduce the file size or choose a smaller file within the allowed limit.',
217
255
  },
218
256
  [ErrorCode.INVALID_FILE_TYPE]: {
219
257
  title: 'Tipo de arquivo inválido',
258
+ titleEn: 'Invalid file type',
220
259
  category: 'validacao',
221
260
  phase: 'pre-upload',
222
261
  severity: 'error',
262
+ retriable: false,
223
263
  userAction: 'Ajuste a extensão/MIME conforme a política.',
264
+ userActionEn: 'Choose a file whose extension and MIME type match the active policy.',
224
265
  },
225
266
  [ErrorCode.FMT_UNSUPPORTED]: {
226
267
  title: 'Formato não suportado',
268
+ titleEn: 'Unsupported format',
227
269
  category: 'validacao',
228
270
  phase: 'analise',
229
271
  severity: 'error',
272
+ retriable: false,
230
273
  },
231
274
  [ErrorCode.FMT_MAGIC_MISMATCH]: {
232
275
  title: 'Conteúdo incompatível',
276
+ titleEn: 'Incompatible content',
233
277
  category: 'validacao',
234
278
  phase: 'analise',
235
279
  severity: 'error',
280
+ retriable: false,
236
281
  },
237
282
  [ErrorCode.FMT_CORRUPTED]: {
238
283
  title: 'Arquivo corrompido',
284
+ titleEn: 'Corrupted file',
239
285
  category: 'validacao',
240
286
  phase: 'analise',
241
287
  severity: 'error',
288
+ retriable: false,
242
289
  },
243
290
  [ErrorCode.SEC_DANGEROUS_TYPE]: {
244
291
  title: 'Tipo perigoso bloqueado',
292
+ titleEn: 'Dangerous file type blocked',
245
293
  category: 'seguranca',
246
294
  phase: 'pre-upload',
247
295
  severity: 'error',
296
+ retriable: false,
248
297
  },
249
298
  [ErrorCode.SEC_VIRUS_DETECTED]: {
250
299
  title: 'Vírus detectado',
300
+ titleEn: 'Virus detected',
251
301
  category: 'seguranca',
252
302
  phase: 'analise',
253
303
  severity: 'error',
304
+ retriable: false,
254
305
  },
255
306
  [ErrorCode.SEC_MALICIOUS_CONTENT]: {
256
307
  title: 'Malware detectado',
308
+ titleEn: 'Malware detected',
257
309
  category: 'seguranca',
258
310
  phase: 'analise',
259
311
  severity: 'error',
312
+ retriable: false,
260
313
  },
261
314
  [ErrorCode.SYS_STORAGE_ERROR]: {
262
315
  title: 'Erro de armazenamento',
316
+ titleEn: 'Storage error',
263
317
  category: 'armazenamento',
264
318
  phase: 'armazenamento',
265
319
  severity: 'error',
@@ -267,6 +321,7 @@ const DEFAULT_CATALOG = {
267
321
  },
268
322
  [ErrorCode.RATE_LIMIT_EXCEEDED]: {
269
323
  title: 'Limite de taxa excedido',
324
+ titleEn: 'Rate limit exceeded',
270
325
  category: 'limites',
271
326
  phase: 'operacional',
272
327
  severity: 'warn',
@@ -274,6 +329,7 @@ const DEFAULT_CATALOG = {
274
329
  },
275
330
  [ErrorCode.SYS_RATE_LIMIT]: {
276
331
  title: 'Limite de requisições excedido',
332
+ titleEn: 'Request limit exceeded',
277
333
  category: 'limites',
278
334
  phase: 'operacional',
279
335
  severity: 'warn',
@@ -281,12 +337,15 @@ const DEFAULT_CATALOG = {
281
337
  },
282
338
  [ErrorCode.QUOTA_EXCEEDED]: {
283
339
  title: 'Cota excedida',
340
+ titleEn: 'Quota exceeded',
284
341
  category: 'limites',
285
342
  phase: 'operacional',
286
343
  severity: 'warn',
344
+ retriable: false,
287
345
  },
288
346
  [ErrorCode.INTERNAL_ERROR]: {
289
347
  title: 'Erro interno',
348
+ titleEn: 'Internal error',
290
349
  category: 'operacional',
291
350
  phase: 'operacional',
292
351
  severity: 'error',
@@ -294,103 +353,195 @@ const DEFAULT_CATALOG = {
294
353
  },
295
354
  [ErrorCode.UNAUTHORIZED]: {
296
355
  title: 'Não autorizado',
356
+ titleEn: 'Unauthorized',
297
357
  category: 'operacional',
298
358
  phase: 'operacional',
299
359
  severity: 'error',
360
+ retriable: false,
300
361
  },
301
362
  [ErrorCode.NOT_FOUND]: {
302
363
  title: 'Não encontrado',
364
+ titleEn: 'Not found',
303
365
  category: 'operacional',
304
366
  phase: 'operacional',
305
367
  severity: 'warn',
368
+ retriable: false,
306
369
  },
307
370
  // Alias de mensagens de config (strings do backend fora do enum)
308
- INVALID_TYPE: { title: 'Tipo de arquivo inválido', category: 'validacao', phase: 'pre-upload', severity: 'error' },
309
- UNSUPPORTED_FILE_TYPE: { title: 'Tipo não suportado', category: 'validacao', phase: 'analise', severity: 'error' },
310
- MAGIC_NUMBER_MISMATCH: { title: 'Assinatura incompatível', category: 'validacao', phase: 'analise', severity: 'error' },
311
- CORRUPTED_FILE: { title: 'Arquivo corrompido', category: 'validacao', phase: 'analise', severity: 'error' },
312
- DANGEROUS_FILE_TYPE: { title: 'Tipo perigoso bloqueado', category: 'seguranca', phase: 'pre-upload', severity: 'error' },
313
- DANGEROUS_EXECUTABLE: { title: 'Executável bloqueado', category: 'seguranca', phase: 'analise', severity: 'error' },
314
- MALWARE_DETECTED: { title: 'Malware detectado', category: 'seguranca', phase: 'analise', severity: 'error' },
315
- VIRUS_DETECTED: { title: 'Vírus detectado', category: 'seguranca', phase: 'analise', severity: 'error' },
316
- FILE_STORE_ERROR: { title: 'Erro ao armazenar arquivo', category: 'armazenamento', phase: 'armazenamento', severity: 'error', retriable: true },
317
- FILE_STORAGE_FAILED: { title: 'Falha ao armazenar arquivo', category: 'armazenamento', phase: 'armazenamento', severity: 'error', retriable: true },
318
- VIRUS_SCAN_ERROR: { title: 'Erro no antivírus', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: true },
319
- VIRUS_SCAN_FAILED: { title: 'Antivírus falhou', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: true },
320
- VIRUS_SCAN_UNAVAILABLE: { title: 'Antivírus indisponível', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: true },
321
- IO_ERROR: { title: 'Erro de entrada/saída', category: 'rede', phase: 'operacional', severity: 'error', retriable: true },
322
- UPLOAD_TIMEOUT: { title: 'Tempo esgotado no upload', category: 'operacional', phase: 'operacional', severity: 'warn', retriable: true },
323
- BULK_UPLOAD_TIMEOUT: { title: 'Tempo esgotado no upload em lote', category: 'operacional', phase: 'lote', severity: 'warn', retriable: true },
324
- BULK_UPLOAD_CANCELLED: { title: 'Upload em lote cancelado', category: 'operacional', phase: 'lote', severity: 'warn' },
325
- MIME_TYPE_MISMATCH: { title: 'MIME não corresponde', category: 'validacao', phase: 'analise', severity: 'error' },
326
- FILE_STRUCTURE_ERROR: { title: 'Estrutura inválida', category: 'validacao', phase: 'analise', severity: 'error' },
327
- STRUCTURE_VALIDATION_FAILED: { title: 'Validação de estrutura falhou', category: 'validacao', phase: 'analise', severity: 'error' },
328
- EMPTY_FILE: { title: 'Arquivo vazio', category: 'validacao', phase: 'pre-upload', severity: 'error' },
329
- INVALID_JSON_OPTIONS: { title: 'JSON de opções inválido', category: 'config', phase: 'operacional', severity: 'error' },
330
- OPCOES_JSON_INVALIDAS: { title: 'JSON de opções inválido', category: 'config', phase: 'operacional', severity: 'error', userAction: 'Corrija a sintaxe do JSON enviado no campo options.' },
331
- EMPTY_FILENAME: { title: 'Nome do arquivo obrigatório', category: 'validacao', phase: 'pre-upload', severity: 'error' },
332
- FILE_ANALYSIS_ERROR: { title: 'Erro na análise do arquivo', category: 'operacional', phase: 'analise', severity: 'error', retriable: true },
333
- CONFIGURATION_ERROR: { title: 'Erro de configuração', category: 'config', phase: 'operacional', severity: 'error' },
334
- SECURITY_VIOLATION: { title: 'Violação de segurança', category: 'seguranca', phase: 'pre-upload', severity: 'error' },
335
- CONFLICT_POLICY_ERROR: { title: 'Erro de política de conflito', category: 'conflito', phase: 'operacional', severity: 'error' },
336
- CONFLICT_POLICY_SKIP: { title: 'Arquivo ignorado por política', category: 'conflito', phase: 'operacional', severity: 'info' },
337
- FILE_EXISTS: { title: 'Arquivo já existe', category: 'conflito', phase: 'operacional', severity: 'warn' },
338
- PATH_TRAVERSAL: { title: 'Path traversal detectado', category: 'seguranca', phase: 'pre-upload', severity: 'error' },
339
- INSUFFICIENT_STORAGE: { title: 'Sem espaço em disco', category: 'armazenamento', phase: 'armazenamento', severity: 'error' },
340
- SIGNATURE_MISMATCH: { title: 'Assinatura não corresponde', category: 'validacao', phase: 'analise', severity: 'error' },
341
- SUSPICIOUS_STRUCTURE: { title: 'Estrutura suspeita', category: 'seguranca', phase: 'analise', severity: 'warn' },
342
- INVALID_FILE_SIZE_CONFIG: { title: 'Configuração de tamanho inválida', category: 'config', phase: 'operacional', severity: 'error' },
343
- USER_CANCELLED: { title: 'Upload cancelado pelo usuário', category: 'operacional', phase: 'operacional', severity: 'info' },
344
- SYSTEM_POLICY_BLOCKED: { title: 'Bloqueado por política do sistema', category: 'operacional', phase: 'operacional', severity: 'error' },
345
- SUSPICIOUS_EXTENSION_BLOCKED: { title: 'Extensão suspeita bloqueada', category: 'seguranca', phase: 'pre-upload', severity: 'warn' },
346
- DANGEROUS_SCRIPT: { title: 'Script perigoso detectado', category: 'seguranca', phase: 'analise', severity: 'error' },
347
- BATCH_SIZE_EXCEEDED: { title: 'Quantidade por lote excedida', category: 'validacao', phase: 'pre-upload', severity: 'error' },
348
- EMBEDDED_EXECUTABLE: { title: 'Executável incorporado', category: 'seguranca', phase: 'analise', severity: 'warn' },
349
- INVALID_PATH: { title: 'Caminho inválido', category: 'validacao', phase: 'pre-upload', severity: 'error' },
350
- FAILED_TO_ANALYZE: { title: 'Falha ao analisar', category: 'operacional', phase: 'analise', severity: 'error', retriable: true },
351
- ZIP_BOMB_DETECTED: { title: 'Possível zip bomb', category: 'seguranca', phase: 'analise', severity: 'error' },
352
- UNKNOWN_ERROR: { title: 'Erro desconhecido', category: 'operacional', phase: 'operacional', severity: 'error', retriable: true },
371
+ INVALID_TYPE: { title: 'Tipo de arquivo inválido', titleEn: 'Invalid file type', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
372
+ UNSUPPORTED_FILE_TYPE: { title: 'Tipo não suportado', titleEn: 'Unsupported file type', category: 'validacao', phase: 'analise', severity: 'error', retriable: false },
373
+ MAGIC_NUMBER_MISMATCH: { title: 'Assinatura incompatível', titleEn: 'Incompatible signature', category: 'validacao', phase: 'analise', severity: 'error', retriable: false },
374
+ CORRUPTED_FILE: { title: 'Arquivo corrompido', titleEn: 'Corrupted file', category: 'validacao', phase: 'analise', severity: 'error', retriable: false },
375
+ DANGEROUS_FILE_TYPE: { title: 'Tipo perigoso bloqueado', titleEn: 'Dangerous file type blocked', category: 'seguranca', phase: 'pre-upload', severity: 'error', retriable: false },
376
+ DANGEROUS_EXECUTABLE: { title: 'Executável bloqueado', titleEn: 'Executable blocked', category: 'seguranca', phase: 'analise', severity: 'error', retriable: false },
377
+ MALWARE_DETECTED: { title: 'Malware detectado', titleEn: 'Malware detected', category: 'seguranca', phase: 'analise', severity: 'error', retriable: false },
378
+ VIRUS_DETECTED: { title: 'Vírus detectado', titleEn: 'Virus detected', category: 'seguranca', phase: 'analise', severity: 'error', retriable: false },
379
+ FILE_STORE_ERROR: { title: 'Erro ao armazenar arquivo', titleEn: 'Error storing file', category: 'armazenamento', phase: 'armazenamento', severity: 'error', retriable: true },
380
+ FILE_STORAGE_FAILED: { title: 'Falha ao armazenar arquivo', titleEn: 'Failed to store file', category: 'armazenamento', phase: 'armazenamento', severity: 'error', retriable: true },
381
+ VIRUS_SCAN_ERROR: { title: 'Erro no antivírus', titleEn: 'Antivirus error', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: true },
382
+ VIRUS_SCAN_FAILED: { title: 'Antivírus falhou', titleEn: 'Antivirus scan failed', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: true },
383
+ VIRUS_SCAN_UNAVAILABLE: { title: 'Antivírus indisponível', titleEn: 'Antivirus unavailable', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: true },
384
+ IO_ERROR: { title: 'Erro de entrada/saída', titleEn: 'Input/output error', category: 'rede', phase: 'operacional', severity: 'error', retriable: true },
385
+ UPLOAD_TIMEOUT: { title: 'Tempo esgotado no upload', titleEn: 'Upload timed out', category: 'operacional', phase: 'operacional', severity: 'warn', retriable: true },
386
+ BULK_UPLOAD_TIMEOUT: { title: 'Tempo esgotado no upload em lote', titleEn: 'Bulk upload timed out', category: 'operacional', phase: 'lote', severity: 'warn', retriable: true },
387
+ BULK_UPLOAD_CANCELLED: { title: 'Upload em lote cancelado', titleEn: 'Bulk upload cancelled', category: 'operacional', phase: 'lote', severity: 'warn', retriable: false },
388
+ MIME_TYPE_MISMATCH: { title: 'MIME não corresponde', titleEn: 'MIME mismatch', category: 'validacao', phase: 'analise', severity: 'error', retriable: false },
389
+ FILE_STRUCTURE_ERROR: { title: 'Estrutura inválida', titleEn: 'Invalid file structure', category: 'validacao', phase: 'analise', severity: 'error', retriable: false },
390
+ STRUCTURE_VALIDATION_FAILED: { title: 'Validação de estrutura falhou', titleEn: 'Structure validation failed', category: 'validacao', phase: 'analise', severity: 'error', retriable: false },
391
+ EMPTY_FILE: { title: 'Arquivo vazio', titleEn: 'Empty file', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
392
+ INVALID_JSON_OPTIONS: { title: 'JSON de opções inválido', titleEn: 'Invalid JSON options', category: 'config', phase: 'operacional', severity: 'error', retriable: false },
393
+ OPCOES_JSON_INVALIDAS: {
394
+ title: 'JSON de opções inválido',
395
+ titleEn: 'Invalid JSON options',
396
+ category: 'config',
397
+ phase: 'operacional',
398
+ severity: 'error',
399
+ retriable: false,
400
+ userAction: 'Corrija a sintaxe do JSON enviado no campo options.',
401
+ userActionEn: 'Fix the JSON syntax provided in the options field.',
402
+ },
403
+ CAMPO_OBRIGATORIO_AUSENTE: { title: 'Campo obrigatório ausente', titleEn: 'Required field missing', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
404
+ ARGUMENTO_INVALIDO: { title: 'Argumento inválido', titleEn: 'Invalid argument', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
405
+ EMPTY_FILENAME: { title: 'Nome do arquivo obrigatório', titleEn: 'File name required', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
406
+ FILE_ANALYSIS_ERROR: { title: 'Erro na análise do arquivo', titleEn: 'File analysis error', category: 'operacional', phase: 'analise', severity: 'error', retriable: true },
407
+ CONFIGURATION_ERROR: { title: 'Erro de configuração', titleEn: 'Configuration error', category: 'config', phase: 'operacional', severity: 'error', retriable: false },
408
+ SECURITY_VIOLATION: { title: 'Violação de segurança', titleEn: 'Security violation', category: 'seguranca', phase: 'pre-upload', severity: 'error', retriable: false },
409
+ CONFLICT_POLICY_ERROR: { title: 'Erro de política de conflito', titleEn: 'Conflict policy error', category: 'conflito', phase: 'operacional', severity: 'error', retriable: false },
410
+ CONFLICT_POLICY_SKIP: { title: 'Arquivo ignorado por política', titleEn: 'File skipped by conflict policy', category: 'conflito', phase: 'operacional', severity: 'info', retriable: false },
411
+ FILE_EXISTS: { title: 'Arquivo já existe', titleEn: 'File already exists', category: 'conflito', phase: 'operacional', severity: 'warn', retriable: false },
412
+ PATH_TRAVERSAL: { title: 'Path traversal detectado', titleEn: 'Path traversal detected', category: 'seguranca', phase: 'pre-upload', severity: 'error', retriable: false },
413
+ INSUFFICIENT_STORAGE: { title: 'Sem espaço em disco', titleEn: 'Insufficient storage', category: 'armazenamento', phase: 'armazenamento', severity: 'error', retriable: false },
414
+ SIGNATURE_MISMATCH: { title: 'Assinatura não corresponde', titleEn: 'Signature mismatch', category: 'validacao', phase: 'analise', severity: 'error', retriable: false },
415
+ SUSPICIOUS_STRUCTURE: { title: 'Estrutura suspeita', titleEn: 'Suspicious structure', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: false },
416
+ INVALID_FILE_SIZE_CONFIG: { title: 'Configuração de tamanho inválida', titleEn: 'Invalid size configuration', category: 'config', phase: 'operacional', severity: 'error', retriable: false },
417
+ USER_CANCELLED: { title: 'Upload cancelado pelo usuário', titleEn: 'Upload cancelled by user', category: 'operacional', phase: 'operacional', severity: 'info', retriable: false },
418
+ SYSTEM_POLICY_BLOCKED: { title: 'Bloqueado por política do sistema', titleEn: 'Blocked by system policy', category: 'operacional', phase: 'operacional', severity: 'error', retriable: false },
419
+ SUSPICIOUS_EXTENSION_BLOCKED: { title: 'Extensão suspeita bloqueada', titleEn: 'Suspicious extension blocked', category: 'seguranca', phase: 'pre-upload', severity: 'warn', retriable: false },
420
+ DANGEROUS_SCRIPT: { title: 'Script perigoso detectado', titleEn: 'Dangerous script detected', category: 'seguranca', phase: 'analise', severity: 'error', retriable: false },
421
+ BATCH_SIZE_EXCEEDED: { title: 'Quantidade por lote excedida', titleEn: 'Batch limit exceeded', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
422
+ EMBEDDED_EXECUTABLE: { title: 'Executável incorporado', titleEn: 'Embedded executable detected', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: false },
423
+ INVALID_PATH: { title: 'Caminho inválido', titleEn: 'Invalid path', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
424
+ FAILED_TO_ANALYZE: { title: 'Falha ao analisar', titleEn: 'Analysis failed', category: 'operacional', phase: 'analise', severity: 'error', retriable: true },
425
+ ZIP_BOMB_DETECTED: { title: 'Possível zip bomb', titleEn: 'Zip bomb detected', category: 'seguranca', phase: 'analise', severity: 'error', retriable: false },
426
+ UNKNOWN_ERROR: { title: 'Erro desconhecido', titleEn: 'Unknown error', category: 'operacional', phase: 'operacional', severity: 'error', retriable: true },
353
427
  // Aliases PT-BR adicionais para os códigos específicos do backend
354
- ARQUIVO_VAZIO: { title: 'Arquivo vazio', category: 'validacao', phase: 'pre-upload', severity: 'error' },
355
- ASSINATURA_INVALIDA: { title: 'Assinatura não corresponde', category: 'validacao', phase: 'analise', severity: 'error' },
356
- ARQUIVO_EXECUTAVEL_PERIGOSO: { title: 'Executável bloqueado', category: 'seguranca', phase: 'analise', severity: 'error' },
357
- SCRIPT_PERIGOSO: { title: 'Script perigoso detectado', category: 'seguranca', phase: 'analise', severity: 'error' },
358
- ARQUIVO_CORROMPIDO: { title: 'Arquivo corrompido', category: 'validacao', phase: 'analise', severity: 'error' },
359
- ESTRUTURA_SUSPEITA: { title: 'Estrutura suspeita', category: 'seguranca', phase: 'analise', severity: 'warn' },
360
- MAGIC_NUMBER_INCOMPATIVEL: { title: 'Assinatura incompatível', category: 'validacao', phase: 'analise', severity: 'error' },
361
- TIPO_ARQUIVO_PERIGOSO: { title: 'Tipo perigoso bloqueado', category: 'seguranca', phase: 'pre-upload', severity: 'error' },
362
- SCANNER_VIRUS_INDISPONIVEL: { title: 'Antivírus indisponível', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: true },
363
- EXTENSAO_SUSPEITA_BLOQUEADA: { title: 'Extensão suspeita bloqueada', category: 'seguranca', phase: 'pre-upload', severity: 'warn' },
364
- TIPO_NAO_SUPORTADO: { title: 'Tipo não suportado', category: 'validacao', phase: 'analise', severity: 'error' },
365
- NOME_ARQUIVO_INVALIDO: { title: 'Nome de arquivo inválido', category: 'validacao', phase: 'pre-upload', severity: 'error' },
366
- TEMPO_ESGOTADO_UPLOAD: { title: 'Tempo esgotado no upload', category: 'operacional', phase: 'operacional', severity: 'warn', retriable: true },
367
- TEMPO_ESGOTADO_UPLOAD_LOTE: { title: 'Tempo esgotado no upload em lote', category: 'operacional', phase: 'lote', severity: 'warn', retriable: true },
368
- ERRO_IO: { title: 'Erro de entrada/saída', category: 'rede', phase: 'operacional', severity: 'error', retriable: true },
369
- ESPAÇO_INSUFICIENTE: { title: 'Sem espaço em disco', category: 'armazenamento', phase: 'armazenamento', severity: 'error' },
370
- UPLOAD_LOTE_CANCELADO: { title: 'Upload em lote cancelado', category: 'operacional', phase: 'lote', severity: 'warn' },
371
- UPLOAD_CANCELADO_USUARIO: { title: 'Upload cancelado pelo usuário', category: 'operacional', phase: 'operacional', severity: 'info' },
372
- TAMANHO_LOTE_EXCEDIDO: { title: 'Quantidade por lote excedida', category: 'validacao', phase: 'pre-upload', severity: 'error' },
373
- TIPO_MIME_INCOMPATIVEL: { title: 'MIME não corresponde', category: 'validacao', phase: 'analise', severity: 'error' },
374
- VIOLACAO_SEGURANCA: { title: 'Violação de segurança', category: 'seguranca', phase: 'pre-upload', severity: 'error' },
375
- ERRO_DESCONHECIDO: { title: 'Erro interno do sistema', category: 'operacional', phase: 'operacional', severity: 'error' },
376
- BLOQUEADO_POLITICA_SISTEMA: { title: 'Bloqueado por política do sistema', category: 'operacional', phase: 'operacional', severity: 'error' },
377
- FALHA_ESCANEAMENTO_VIRUS: { title: 'Antivírus falhou', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: true },
378
- FALHA_VALIDACAO_ESTRUTURA: { title: 'Validação de estrutura falhou', category: 'validacao', phase: 'analise', severity: 'error' },
379
- CONFIGURACAO_TAMANHO_INVALIDA: { title: 'Configuração de tamanho inválida', category: 'config', phase: 'operacional', severity: 'error' },
380
- FALHA_ARMAZENAMENTO: { title: 'Falha ao armazenar arquivo', category: 'armazenamento', phase: 'armazenamento', severity: 'error', retriable: true },
381
- ERRO_ARMAZENAMENTO_ARQUIVO: { title: 'Erro ao armazenar arquivo', category: 'armazenamento', phase: 'armazenamento', severity: 'error', retriable: true },
382
- NOME_ARQUIVO_VAZIO: { title: 'Nome do arquivo obrigatório', category: 'validacao', phase: 'pre-upload', severity: 'error' },
383
- ERRO_ANALISE_ARQUIVO: { title: 'Erro na análise do arquivo', category: 'operacional', phase: 'analise', severity: 'error', retriable: true },
384
- ERRO_ESTRUTURA_ARQUIVO: { title: 'Erro na estrutura do arquivo', category: 'validacao', phase: 'analise', severity: 'error' },
385
- CAMINHO_INVALIDO: { title: 'Caminho inválido', category: 'validacao', phase: 'pre-upload', severity: 'error' },
386
- ERRO_CONFIGURACAO: { title: 'Erro de configuração', category: 'config', phase: 'operacional', severity: 'error' },
387
- ERRO_ESCANEAMENTO_VIRUS: { title: 'Erro no antivírus', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: true },
388
- FALHA_ANALISE_ARQUIVO: { title: 'Falha ao analisar', category: 'operacional', phase: 'analise', severity: 'error', retriable: true },
389
- ERRO_POLITICA_CONFLITO: { title: 'Erro de política de conflito', category: 'conflito', phase: 'operacional', severity: 'error' },
390
- POLITICA_CONFLITO_IGNORAR: { title: 'Arquivo ignorado por política', category: 'conflito', phase: 'operacional', severity: 'info' },
428
+ ARQUIVO_VAZIO: { title: 'Arquivo vazio', titleEn: 'Empty file', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
429
+ ASSINATURA_INVALIDA: { title: 'Assinatura não corresponde', titleEn: 'Signature mismatch', category: 'validacao', phase: 'analise', severity: 'error', retriable: false },
430
+ ARQUIVO_EXECUTAVEL_PERIGOSO: { title: 'Executável bloqueado', titleEn: 'Executable blocked', category: 'seguranca', phase: 'analise', severity: 'error', retriable: false },
431
+ SCRIPT_PERIGOSO: { title: 'Script perigoso detectado', titleEn: 'Dangerous script detected', category: 'seguranca', phase: 'analise', severity: 'error', retriable: false },
432
+ ARQUIVO_CORROMPIDO: { title: 'Arquivo corrompido', titleEn: 'Corrupted file', category: 'validacao', phase: 'analise', severity: 'error', retriable: false },
433
+ ESTRUTURA_SUSPEITA: { title: 'Estrutura suspeita', titleEn: 'Suspicious structure', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: false },
434
+ ZIP_BOMB_DETECTADO: { title: 'Possível zip bomb', titleEn: 'Zip bomb detected', category: 'seguranca', phase: 'analise', severity: 'error', retriable: false },
435
+ EXECUTAVEL_INCORPORADO: { title: 'Executável incorporado', titleEn: 'Embedded executable detected', category: 'seguranca', phase: 'analise', severity: 'error', retriable: false },
436
+ MALWARE_DETECTADO: { title: 'Malware detectado', titleEn: 'Malware detected', category: 'seguranca', phase: 'analise', severity: 'error', retriable: false },
437
+ VIRUS_DETECTADO: { title: 'Vírus detectado', titleEn: 'Virus detected', category: 'seguranca', phase: 'analise', severity: 'error', retriable: false },
438
+ MAGIC_NUMBER_INCOMPATIVEL: { title: 'Assinatura incompatível', titleEn: 'Incompatible signature', category: 'validacao', phase: 'analise', severity: 'error', retriable: false },
439
+ TIPO_ARQUIVO_PERIGOSO: { title: 'Tipo perigoso bloqueado', titleEn: 'Dangerous file type blocked', category: 'seguranca', phase: 'pre-upload', severity: 'error', retriable: false },
440
+ SCANNER_VIRUS_INDISPONIVEL: { title: 'Antivírus indisponível', titleEn: 'Antivirus unavailable', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: true },
441
+ EXTENSAO_SUSPEITA_BLOQUEADA: { title: 'Extensão suspeita bloqueada', titleEn: 'Suspicious extension blocked', category: 'seguranca', phase: 'pre-upload', severity: 'warn', retriable: false },
442
+ TIPO_NAO_SUPORTADO: { title: 'Tipo não suportado', titleEn: 'Unsupported file type', category: 'validacao', phase: 'analise', severity: 'error', retriable: false },
443
+ NOME_ARQUIVO_INVALIDO: { title: 'Nome de arquivo inválido', titleEn: 'Invalid file name', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
444
+ TEMPO_ESGOTADO_UPLOAD: { title: 'Tempo esgotado no upload', titleEn: 'Upload timed out', category: 'operacional', phase: 'operacional', severity: 'warn', retriable: true },
445
+ TEMPO_ESGOTADO_UPLOAD_LOTE: { title: 'Tempo esgotado no upload em lote', titleEn: 'Bulk upload timed out', category: 'operacional', phase: 'lote', severity: 'warn', retriable: true },
446
+ ERRO_IO: { title: 'Erro de entrada/saída', titleEn: 'Input/output error', category: 'rede', phase: 'operacional', severity: 'error', retriable: true },
447
+ ESPAÇO_INSUFICIENTE: { title: 'Sem espaço em disco', titleEn: 'Insufficient storage', category: 'armazenamento', phase: 'armazenamento', severity: 'error', retriable: false },
448
+ ESPACO_INSUFICIENTE: { title: 'Sem espaço em disco', titleEn: 'Insufficient storage', category: 'armazenamento', phase: 'armazenamento', severity: 'error', retriable: false },
449
+ UPLOAD_LOTE_CANCELADO: { title: 'Upload em lote cancelado', titleEn: 'Bulk upload cancelled', category: 'operacional', phase: 'lote', severity: 'warn', retriable: false },
450
+ UPLOAD_CANCELADO_USUARIO: { title: 'Upload cancelado pelo usuário', titleEn: 'Upload cancelled by user', category: 'operacional', phase: 'operacional', severity: 'info', retriable: false },
451
+ TAMANHO_LOTE_EXCEDIDO: { title: 'Quantidade por lote excedida', titleEn: 'Batch limit exceeded', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
452
+ TIPO_MIME_INCOMPATIVEL: { title: 'MIME não corresponde', titleEn: 'MIME mismatch', category: 'validacao', phase: 'analise', severity: 'error', retriable: false },
453
+ VIOLACAO_SEGURANCA: { title: 'Violação de segurança', titleEn: 'Security violation', category: 'seguranca', phase: 'pre-upload', severity: 'error', retriable: false },
454
+ LIMITE_TAXA_EXCEDIDO: { title: 'Limite de taxa excedido', titleEn: 'Rate limit exceeded', category: 'limites', phase: 'operacional', severity: 'warn', retriable: true },
455
+ COTA_EXCEDIDA: { title: 'Cota excedida', titleEn: 'Quota exceeded', category: 'limites', phase: 'operacional', severity: 'warn', retriable: false },
456
+ ARQUIVO_NAO_ENCONTRADO: { title: 'Arquivo não encontrado', titleEn: 'File not found', category: 'operacional', phase: 'operacional', severity: 'warn', retriable: false },
457
+ ACESSO_NEGADO: { title: 'Acesso negado', titleEn: 'Access denied', category: 'seguranca', phase: 'operacional', severity: 'error', retriable: false },
458
+ ERRO_DESCONHECIDO: { title: 'Erro interno do sistema', titleEn: 'Internal system error', category: 'operacional', phase: 'operacional', severity: 'error', retriable: true },
459
+ BLOQUEADO_POLITICA_SISTEMA: { title: 'Bloqueado por política do sistema', titleEn: 'Blocked by system policy', category: 'operacional', phase: 'operacional', severity: 'error', retriable: false },
460
+ FALHA_ESCANEAMENTO_VIRUS: { title: 'Antivírus falhou', titleEn: 'Antivirus scan failed', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: true },
461
+ FALHA_VALIDACAO_ESTRUTURA: { title: 'Validação de estrutura falhou', titleEn: 'Structure validation failed', category: 'validacao', phase: 'analise', severity: 'error', retriable: false },
462
+ CONFIGURACAO_TAMANHO_INVALIDA: { title: 'Configuração de tamanho inválida', titleEn: 'Invalid size configuration', category: 'config', phase: 'operacional', severity: 'error', retriable: false },
463
+ FALHA_ARMAZENAMENTO: { title: 'Falha ao armazenar arquivo', titleEn: 'Failed to store file', category: 'armazenamento', phase: 'armazenamento', severity: 'error', retriable: true },
464
+ ERRO_ARMAZENAMENTO_ARQUIVO: { title: 'Erro ao armazenar arquivo', titleEn: 'Error storing file', category: 'armazenamento', phase: 'armazenamento', severity: 'error', retriable: true },
465
+ NOME_ARQUIVO_VAZIO: { title: 'Nome do arquivo obrigatório', titleEn: 'File name required', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
466
+ ERRO_ANALISE_ARQUIVO: { title: 'Erro na análise do arquivo', titleEn: 'File analysis error', category: 'operacional', phase: 'analise', severity: 'error', retriable: true },
467
+ ERRO_ESTRUTURA_ARQUIVO: { title: 'Erro na estrutura do arquivo', titleEn: 'Invalid file structure', category: 'validacao', phase: 'analise', severity: 'error', retriable: false },
468
+ CAMINHO_INVALIDO: { title: 'Caminho inválido', titleEn: 'Invalid path', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
469
+ ERRO_CONFIGURACAO: { title: 'Erro de configuração', titleEn: 'Configuration error', category: 'config', phase: 'operacional', severity: 'error', retriable: false },
470
+ ERRO_ESCANEAMENTO_VIRUS: { title: 'Erro no antivírus', titleEn: 'Antivirus error', category: 'seguranca', phase: 'analise', severity: 'warn', retriable: true },
471
+ FALHA_ANALISE_ARQUIVO: { title: 'Falha ao analisar', titleEn: 'Analysis failed', category: 'operacional', phase: 'analise', severity: 'error', retriable: true },
472
+ ERRO_POLITICA_CONFLITO: { title: 'Erro de política de conflito', titleEn: 'Conflict policy error', category: 'conflito', phase: 'operacional', severity: 'error', retriable: false },
473
+ POLITICA_CONFLITO_IGNORAR: { title: 'Arquivo ignorado por política', titleEn: 'File skipped by conflict policy', category: 'conflito', phase: 'operacional', severity: 'info', retriable: false },
474
+ ARQUIVO_MUITO_GRANDE: { title: 'Arquivo muito grande', titleEn: 'File too large', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
475
+ ARQUIVO_JA_EXISTE: { title: 'Arquivo já existe', titleEn: 'File already exists', category: 'conflito', phase: 'operacional', severity: 'warn', retriable: false },
476
+ TIPO_ARQUIVO_INVALIDO: { title: 'Tipo de arquivo inválido', titleEn: 'Invalid file type', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
477
+ TIPO_MIDIA_NAO_SUPORTADO: { title: 'Tipo de mídia não suportado', titleEn: 'Unsupported media type', category: 'validacao', phase: 'pre-upload', severity: 'error', retriable: false },
478
+ NAO_AUTORIZADO: { title: 'Autenticação necessária', titleEn: 'Authentication required', category: 'operacional', phase: 'operacional', severity: 'error', retriable: false },
479
+ ERRO_INTERNO: { title: 'Erro interno do servidor', titleEn: 'Internal server error', category: 'operacional', phase: 'operacional', severity: 'error', retriable: true },
480
+ ARQUIVO_SOB_RETENCAO: {
481
+ title: 'Arquivo sob retenção',
482
+ titleEn: 'File under retention hold',
483
+ category: 'conflito',
484
+ phase: 'operacional',
485
+ severity: 'warn',
486
+ retriable: false,
487
+ userAction: 'Aguarde a liberação da retenção ou conclusão da aprovação antes de excluir.',
488
+ userActionEn: 'Wait for the retention hold or pending approval to be released before deleting.',
489
+ },
490
+ CONFLITO_ESTADO: {
491
+ title: 'Conflito de estado do arquivo',
492
+ titleEn: 'File lifecycle conflict',
493
+ category: 'conflito',
494
+ phase: 'operacional',
495
+ severity: 'warn',
496
+ retriable: false,
497
+ userAction: 'Atualize os metadados do arquivo antes de tentar outra transição.',
498
+ userActionEn: 'Refresh the file metadata before attempting another lifecycle transition.',
499
+ },
500
+ EXCLUSAO_ATIVO_BLOQUEADA: {
501
+ title: 'Exclusão de arquivo confirmado bloqueada',
502
+ titleEn: 'Active file deletion blocked',
503
+ category: 'seguranca',
504
+ phase: 'operacional',
505
+ severity: 'error',
506
+ retriable: false,
507
+ userAction: 'Arquivos confirmados não podem ser excluídos pela política vigente.',
508
+ userActionEn: 'Confirmed files cannot be deleted under the current server policy.',
509
+ },
510
+ NO_FILES_PROVIDED: {
511
+ title: 'Nenhum arquivo enviado',
512
+ titleEn: 'No files provided',
513
+ category: 'validacao',
514
+ phase: 'pre-upload',
515
+ severity: 'error',
516
+ retriable: false,
517
+ userAction: 'Selecione ao menos um arquivo antes de enviar.',
518
+ userActionEn: 'Select at least one file before submitting.',
519
+ },
520
+ INVALID_OPTIONS_FORMAT: {
521
+ title: 'Formato de opções inválido',
522
+ titleEn: 'Invalid options format',
523
+ category: 'config',
524
+ phase: 'operacional',
525
+ severity: 'error',
526
+ retriable: false,
527
+ userAction: 'Verifique a formatação JSON do parâmetro options.',
528
+ userActionEn: 'Check the JSON format of the options parameter.',
529
+ },
391
530
  };
392
- function getErrorMeta(code) {
393
- return DEFAULT_CATALOG[code] ?? { title: code };
531
+ function getErrorMeta(code, locale) {
532
+ const entry = DEFAULT_CATALOG[code];
533
+ if (!entry) {
534
+ return { title: code };
535
+ }
536
+ const isEnglish = (locale ?? '').trim().toLowerCase().startsWith('en');
537
+ if (!isEnglish) {
538
+ return entry;
539
+ }
540
+ return {
541
+ ...entry,
542
+ title: entry.titleEn || entry.title,
543
+ ...(entry.userActionEn ? { userAction: entry.userActionEn } : {}),
544
+ };
394
545
  }
395
546
 
396
547
  const FILES_UPLOAD_EN_US = {
@@ -667,6 +818,84 @@ const FILES_UPLOAD_EN_US = {
667
818
  'praxis.filesUpload.errors.LIMITE_TAXA_EXCEDIDO': 'Rate limit exceeded.',
668
819
  'praxis.filesUpload.errors.COTA_EXCEDIDA': 'Quota exceeded.',
669
820
  'praxis.filesUpload.errors.ARQUIVO_JA_EXISTE': 'File already exists.',
821
+ 'praxis.filesUpload.errors.SCANNER_VIRUS_INDISPONIVEL': 'Antivirus scanner is currently unavailable. Please retry shortly.',
822
+ 'praxis.filesUpload.errors.MALWARE_DETECTADO': 'Malware detected in file.',
823
+ 'praxis.filesUpload.errors.VIRUS_DETECTADO': 'Virus detected in file.',
824
+ 'praxis.filesUpload.errors.ESTRUTURA_SUSPEITA': 'Suspicious document structure detected.',
825
+ 'praxis.filesUpload.errors.ARQUIVO_CORROMPIDO': 'Corrupted or unreadable file.',
826
+ 'praxis.filesUpload.errors.ZIP_BOMB_DETECTADO': 'Compressed archive exceeds safe extraction limits.',
827
+ 'praxis.filesUpload.errors.EXECUTAVEL_INCORPORADO': 'Embedded executable content detected.',
828
+ 'praxis.filesUpload.errors.TIPO_MIME_INCOMPATIVEL': 'File MIME type does not match its content.',
829
+ 'praxis.filesUpload.errors.ASSINATURA_INVALIDA': 'File signature does not match declared format.',
830
+ 'praxis.filesUpload.errors.MAGIC_NUMBER_INCOMPATIVEL': 'Binary content does not match declared extension.',
831
+ 'praxis.filesUpload.errors.ARQUIVO_VAZIO': 'Uploaded file is empty.',
832
+ 'praxis.filesUpload.errors.TIPO_NAO_SUPORTADO': 'Unsupported file type.',
833
+ 'praxis.filesUpload.errors.CAMINHO_INVALIDO': 'Invalid file path.',
834
+ 'praxis.filesUpload.errors.NOME_ARQUIVO_INVALIDO': 'Invalid file name.',
835
+ 'praxis.filesUpload.errors.ARQUIVO_EXECUTAVEL_PERIGOSO': 'Executable file blocked by security policy.',
836
+ 'praxis.filesUpload.errors.SCRIPT_PERIGOSO': 'Potentially dangerous script detected in file.',
837
+ 'praxis.filesUpload.errors.TIPO_ARQUIVO_PERIGOSO': 'Dangerous file type blocked by security policy.',
838
+ 'praxis.filesUpload.errors.EXTENSAO_SUSPEITA_BLOQUEADA': 'Suspicious file extension blocked by security policy.',
839
+ 'praxis.filesUpload.errors.VIOLACAO_SEGURANCA': 'File blocked due to security policy violation.',
840
+ 'praxis.filesUpload.errors.TEMPO_ESGOTADO_UPLOAD': 'File upload timed out.',
841
+ 'praxis.filesUpload.errors.TEMPO_ESGOTADO_UPLOAD_LOTE': 'Batch upload timed out.',
842
+ 'praxis.filesUpload.errors.ERRO_IO': 'Input/output error during upload.',
843
+ 'praxis.filesUpload.errors.ESPAÇO_INSUFICIENTE': 'Insufficient server storage.',
844
+ 'praxis.filesUpload.errors.ESPACO_INSUFICIENTE': 'Insufficient server storage.',
845
+ 'praxis.filesUpload.errors.ARQUIVO_NAO_ENCONTRADO': 'File not found.',
846
+ 'praxis.filesUpload.errors.ACESSO_NEGADO': 'You do not have permission to access or modify this file.',
847
+ 'praxis.filesUpload.errors.INVALID_TYPE': 'Invalid file type.',
848
+ 'praxis.filesUpload.errors.UNSUPPORTED_FILE_TYPE': 'Unsupported file type.',
849
+ 'praxis.filesUpload.errors.MAGIC_NUMBER_MISMATCH': 'File signature does not match extension.',
850
+ 'praxis.filesUpload.errors.CORRUPTED_FILE': 'Corrupted or unreadable file.',
851
+ 'praxis.filesUpload.errors.DANGEROUS_FILE_TYPE': 'Dangerous file type blocked by policy.',
852
+ 'praxis.filesUpload.errors.DANGEROUS_EXECUTABLE': 'Executable file blocked by security policy.',
853
+ 'praxis.filesUpload.errors.MALWARE_DETECTED': 'Malware detected in file.',
854
+ 'praxis.filesUpload.errors.VIRUS_DETECTED': 'Virus detected in file.',
855
+ 'praxis.filesUpload.errors.FILE_STORE_ERROR': 'Error storing file.',
856
+ 'praxis.filesUpload.errors.FILE_STORAGE_FAILED': 'Failed to store file.',
857
+ 'praxis.filesUpload.errors.VIRUS_SCAN_ERROR': 'Antivirus scanner error.',
858
+ 'praxis.filesUpload.errors.VIRUS_SCAN_FAILED': 'Antivirus scan failed.',
859
+ 'praxis.filesUpload.errors.VIRUS_SCAN_UNAVAILABLE': 'Antivirus scanner is currently unavailable.',
860
+ 'praxis.filesUpload.errors.IO_ERROR': 'Input/output error during upload.',
861
+ 'praxis.filesUpload.errors.MIME_TYPE_MISMATCH': 'File MIME type does not match content.',
862
+ 'praxis.filesUpload.errors.FILE_STRUCTURE_ERROR': 'Invalid file structure.',
863
+ 'praxis.filesUpload.errors.STRUCTURE_VALIDATION_FAILED': 'File structure validation failed.',
864
+ 'praxis.filesUpload.errors.EMPTY_FILE': 'Uploaded file is empty.',
865
+ 'praxis.filesUpload.errors.FILE_ANALYSIS_ERROR': 'Error analyzing uploaded file.',
866
+ 'praxis.filesUpload.errors.CONFIGURATION_ERROR': 'Upload configuration error.',
867
+ 'praxis.filesUpload.errors.SECURITY_VIOLATION': 'Blocked due to security policy violation.',
868
+ 'praxis.filesUpload.errors.CONFLICT_POLICY_ERROR': 'Conflict policy error.',
869
+ 'praxis.filesUpload.errors.CONFLICT_POLICY_SKIP': 'File skipped by conflict policy.',
870
+ 'praxis.filesUpload.errors.INVALID_FILE_SIZE_CONFIG': 'Invalid file size configuration.',
871
+ 'praxis.filesUpload.errors.SYSTEM_POLICY_BLOCKED': 'Blocked by system policy.',
872
+ 'praxis.filesUpload.errors.SUSPICIOUS_EXTENSION_BLOCKED': 'Suspicious extension blocked by policy.',
873
+ 'praxis.filesUpload.errors.DANGEROUS_SCRIPT': 'Dangerous script detected in file.',
874
+ 'praxis.filesUpload.errors.BATCH_SIZE_EXCEEDED': 'Batch file count limit exceeded.',
875
+ 'praxis.filesUpload.errors.EMBEDDED_EXECUTABLE': 'Embedded executable content detected.',
876
+ 'praxis.filesUpload.errors.INVALID_PATH': 'Invalid file path.',
877
+ 'praxis.filesUpload.errors.FAILED_TO_ANALYZE': 'Failed to analyze file.',
878
+ 'praxis.filesUpload.errors.ZIP_BOMB_DETECTED': 'Compressed archive exceeds safe extraction limits.',
879
+ 'praxis.filesUpload.errors.SIGNATURE_MISMATCH': 'File signature does not match content.',
880
+ 'praxis.filesUpload.errors.SUSPICIOUS_STRUCTURE': 'Suspicious file structure detected.',
881
+ 'praxis.filesUpload.errors.BLOQUEADO_POLITICA_SISTEMA': 'Blocked by system policy.',
882
+ 'praxis.filesUpload.errors.FALHA_ESCANEAMENTO_VIRUS': 'Antivirus scan failed.',
883
+ 'praxis.filesUpload.errors.FALHA_VALIDACAO_ESTRUTURA': 'File structure validation failed.',
884
+ 'praxis.filesUpload.errors.CONFIGURACAO_TAMANHO_INVALIDA': 'Invalid size configuration.',
885
+ 'praxis.filesUpload.errors.FALHA_ARMAZENAMENTO': 'Failed to store file.',
886
+ 'praxis.filesUpload.errors.ERRO_ARMAZENAMENTO_ARQUIVO': 'Error storing file.',
887
+ 'praxis.filesUpload.errors.NOME_ARQUIVO_VAZIO': 'File name is required.',
888
+ 'praxis.filesUpload.errors.ERRO_ANALISE_ARQUIVO': 'Error analyzing file.',
889
+ 'praxis.filesUpload.errors.ERRO_ESTRUTURA_ARQUIVO': 'Invalid file structure.',
890
+ 'praxis.filesUpload.errors.ERRO_CONFIGURACAO': 'Configuration error.',
891
+ 'praxis.filesUpload.errors.ERRO_ESCANEAMENTO_VIRUS': 'Antivirus scanner error.',
892
+ 'praxis.filesUpload.errors.FALHA_ANALISE_ARQUIVO': 'Failed to analyze file.',
893
+ 'praxis.filesUpload.errors.ERRO_POLITICA_CONFLITO': 'Conflict policy error.',
894
+ 'praxis.filesUpload.errors.POLITICA_CONFLITO_IGNORAR': 'File skipped by conflict policy.',
895
+ 'praxis.filesUpload.errors.ERRO_DESCONHECIDO': 'Unknown internal error.',
896
+ 'praxis.filesUpload.errors.UPLOAD_LOTE_CANCELADO': 'Batch upload cancelled.',
897
+ 'praxis.filesUpload.errors.UPLOAD_CANCELADO_USUARIO': 'Upload cancelled by user.',
898
+ 'praxis.filesUpload.errors.TAMANHO_LOTE_EXCEDIDO': 'Batch file count limit exceeded.',
670
899
  'praxis.filesUpload.errors.INVALID_JSON_OPTIONS': 'Invalid JSON options.',
671
900
  'praxis.filesUpload.errors.EMPTY_FILENAME': 'File name is required.',
672
901
  'praxis.filesUpload.errors.FILE_EXISTS': 'File already exists.',
@@ -677,6 +906,11 @@ const FILES_UPLOAD_EN_US = {
677
906
  'praxis.filesUpload.errors.BULK_UPLOAD_CANCELLED': 'Bulk upload cancelled.',
678
907
  'praxis.filesUpload.errors.USER_CANCELLED': 'Upload cancelled by user.',
679
908
  'praxis.filesUpload.errors.UNKNOWN_ERROR': 'Unknown error.',
909
+ 'praxis.filesUpload.errors.ARQUIVO_SOB_RETENCAO': 'This file is protected by a retention hold or pending approval policy.',
910
+ 'praxis.filesUpload.errors.CONFLITO_ESTADO': 'The current file lifecycle status does not allow this operation.',
911
+ 'praxis.filesUpload.errors.EXCLUSAO_ATIVO_BLOQUEADA': 'The configured server policy forbids deleting confirmed files.',
912
+ 'praxis.filesUpload.errors.NO_FILES_PROVIDED': 'No files were provided for upload.',
913
+ 'praxis.filesUpload.errors.INVALID_OPTIONS_FORMAT': 'Invalid format in the options parameter.',
680
914
  'praxis.filesUpload.fieldPendingSummary': 'Files ready to upload',
681
915
  'praxis.filesUpload.fieldSelectedSummary': 'Selected file',
682
916
  'praxis.filesUpload.fieldSelectedPlural': 'files attached',
@@ -984,7 +1218,85 @@ const FILES_UPLOAD_PT_BR = {
984
1218
  'praxis.filesUpload.errors.LIMITE_TAXA_EXCEDIDO': 'Limite de taxa excedido.',
985
1219
  'praxis.filesUpload.errors.COTA_EXCEDIDA': 'Cota excedida.',
986
1220
  'praxis.filesUpload.errors.ARQUIVO_JA_EXISTE': 'Arquivo já existe.',
1221
+ 'praxis.filesUpload.errors.SCANNER_VIRUS_INDISPONIVEL': 'Scanner antivírus indisponível no momento. Tente novamente em instantes.',
1222
+ 'praxis.filesUpload.errors.MALWARE_DETECTADO': 'Malware detectado no arquivo.',
1223
+ 'praxis.filesUpload.errors.VIRUS_DETECTADO': 'Vírus detectado no arquivo.',
1224
+ 'praxis.filesUpload.errors.ESTRUTURA_SUSPEITA': 'Estrutura suspeita detectada no documento.',
1225
+ 'praxis.filesUpload.errors.ARQUIVO_CORROMPIDO': 'Arquivo corrompido ou ilegível.',
1226
+ 'praxis.filesUpload.errors.ZIP_BOMB_DETECTADO': 'Arquivo compactado excede limites seguros de extração.',
1227
+ 'praxis.filesUpload.errors.EXECUTAVEL_INCORPORADO': 'Conteúdo executável incorporado detectado.',
1228
+ 'praxis.filesUpload.errors.TIPO_MIME_INCOMPATIVEL': 'Tipo MIME incompatível com o conteúdo do arquivo.',
1229
+ 'praxis.filesUpload.errors.ASSINATURA_INVALIDA': 'Assinatura do arquivo incompatível com o formato declarado.',
1230
+ 'praxis.filesUpload.errors.MAGIC_NUMBER_INCOMPATIVEL': 'Conteúdo binário incompatível com a extensão declarada.',
1231
+ 'praxis.filesUpload.errors.ARQUIVO_VAZIO': 'O arquivo enviado está vazio.',
1232
+ 'praxis.filesUpload.errors.TIPO_NAO_SUPORTADO': 'Tipo de arquivo não suportado.',
1233
+ 'praxis.filesUpload.errors.CAMINHO_INVALIDO': 'Caminho do arquivo inválido.',
1234
+ 'praxis.filesUpload.errors.NOME_ARQUIVO_INVALIDO': 'Nome do arquivo inválido.',
1235
+ 'praxis.filesUpload.errors.ARQUIVO_EXECUTAVEL_PERIGOSO': 'Arquivo executável bloqueado pela política de segurança.',
1236
+ 'praxis.filesUpload.errors.SCRIPT_PERIGOSO': 'Script potencialmente perigoso detectado no arquivo.',
1237
+ 'praxis.filesUpload.errors.TIPO_ARQUIVO_PERIGOSO': 'Tipo de arquivo bloqueado pela política de segurança.',
1238
+ 'praxis.filesUpload.errors.EXTENSAO_SUSPEITA_BLOQUEADA': 'Extensão suspeita bloqueada pela política de segurança.',
1239
+ 'praxis.filesUpload.errors.VIOLACAO_SEGURANCA': 'Arquivo bloqueado por violação de segurança.',
1240
+ 'praxis.filesUpload.errors.TEMPO_ESGOTADO_UPLOAD': 'Tempo esgotado durante o envio do arquivo.',
1241
+ 'praxis.filesUpload.errors.TEMPO_ESGOTADO_UPLOAD_LOTE': 'Tempo esgotado durante o envio em lote.',
1242
+ 'praxis.filesUpload.errors.ERRO_IO': 'Falha de entrada/saída durante o envio.',
1243
+ 'praxis.filesUpload.errors.ESPAÇO_INSUFICIENTE': 'Espaço insuficiente no servidor.',
1244
+ 'praxis.filesUpload.errors.ESPACO_INSUFICIENTE': 'Espaço insuficiente no servidor.',
1245
+ 'praxis.filesUpload.errors.ARQUIVO_NAO_ENCONTRADO': 'Arquivo não encontrado.',
1246
+ 'praxis.filesUpload.errors.ACESSO_NEGADO': 'Sem permissão para acessar ou modificar este arquivo.',
987
1247
  // Outros possíveis códigos mapeados no catálogo
1248
+ 'praxis.filesUpload.errors.INVALID_TYPE': 'Tipo de arquivo inválido.',
1249
+ 'praxis.filesUpload.errors.UNSUPPORTED_FILE_TYPE': 'Tipo de arquivo não suportado.',
1250
+ 'praxis.filesUpload.errors.MAGIC_NUMBER_MISMATCH': 'Assinatura incompatível com a extensão declarada.',
1251
+ 'praxis.filesUpload.errors.CORRUPTED_FILE': 'Arquivo corrompido.',
1252
+ 'praxis.filesUpload.errors.DANGEROUS_FILE_TYPE': 'Tipo perigoso bloqueado.',
1253
+ 'praxis.filesUpload.errors.DANGEROUS_EXECUTABLE': 'Executável bloqueado pela política de segurança.',
1254
+ 'praxis.filesUpload.errors.MALWARE_DETECTED': 'Malware detectado no arquivo.',
1255
+ 'praxis.filesUpload.errors.VIRUS_DETECTED': 'Vírus detectado no arquivo.',
1256
+ 'praxis.filesUpload.errors.FILE_STORE_ERROR': 'Erro ao armazenar arquivo.',
1257
+ 'praxis.filesUpload.errors.FILE_STORAGE_FAILED': 'Falha ao armazenar arquivo.',
1258
+ 'praxis.filesUpload.errors.VIRUS_SCAN_ERROR': 'Erro no scanner antivírus.',
1259
+ 'praxis.filesUpload.errors.VIRUS_SCAN_FAILED': 'Falha na verificação antivírus.',
1260
+ 'praxis.filesUpload.errors.VIRUS_SCAN_UNAVAILABLE': 'Scanner antivírus indisponível no momento.',
1261
+ 'praxis.filesUpload.errors.IO_ERROR': 'Erro de leitura/escrita durante o envio.',
1262
+ 'praxis.filesUpload.errors.MIME_TYPE_MISMATCH': 'Tipo MIME incompatível com o conteúdo.',
1263
+ 'praxis.filesUpload.errors.FILE_STRUCTURE_ERROR': 'Estrutura de arquivo inválida.',
1264
+ 'praxis.filesUpload.errors.STRUCTURE_VALIDATION_FAILED': 'Validação de estrutura falhou.',
1265
+ 'praxis.filesUpload.errors.EMPTY_FILE': 'O arquivo enviado está vazio.',
1266
+ 'praxis.filesUpload.errors.FILE_ANALYSIS_ERROR': 'Erro na análise do arquivo.',
1267
+ 'praxis.filesUpload.errors.CONFIGURATION_ERROR': 'Erro de configuração.',
1268
+ 'praxis.filesUpload.errors.SECURITY_VIOLATION': 'Arquivo bloqueado por violação de segurança.',
1269
+ 'praxis.filesUpload.errors.CONFLICT_POLICY_ERROR': 'Erro de política de conflito.',
1270
+ 'praxis.filesUpload.errors.CONFLICT_POLICY_SKIP': 'Arquivo ignorado pela política de conflito.',
1271
+ 'praxis.filesUpload.errors.INVALID_FILE_SIZE_CONFIG': 'Configuração de tamanho inválida.',
1272
+ 'praxis.filesUpload.errors.SYSTEM_POLICY_BLOCKED': 'Bloqueado por política do sistema.',
1273
+ 'praxis.filesUpload.errors.SUSPICIOUS_EXTENSION_BLOCKED': 'Extensão suspeita bloqueada.',
1274
+ 'praxis.filesUpload.errors.DANGEROUS_SCRIPT': 'Script perigoso detectado.',
1275
+ 'praxis.filesUpload.errors.BATCH_SIZE_EXCEEDED': 'Quantidade por lote excedida.',
1276
+ 'praxis.filesUpload.errors.EMBEDDED_EXECUTABLE': 'Executável incorporado detectado.',
1277
+ 'praxis.filesUpload.errors.INVALID_PATH': 'Caminho inválido.',
1278
+ 'praxis.filesUpload.errors.FAILED_TO_ANALYZE': 'Falha ao analisar arquivo.',
1279
+ 'praxis.filesUpload.errors.ZIP_BOMB_DETECTED': 'Arquivo compactado excede limites seguros.',
1280
+ 'praxis.filesUpload.errors.SIGNATURE_MISMATCH': 'Assinatura incompatível.',
1281
+ 'praxis.filesUpload.errors.SUSPICIOUS_STRUCTURE': 'Estrutura suspeita detectada.',
1282
+ 'praxis.filesUpload.errors.BLOQUEADO_POLITICA_SISTEMA': 'Bloqueado por política do sistema.',
1283
+ 'praxis.filesUpload.errors.FALHA_ESCANEAMENTO_VIRUS': 'Falha no escaneamento antivírus.',
1284
+ 'praxis.filesUpload.errors.FALHA_VALIDACAO_ESTRUTURA': 'Validação de estrutura falhou.',
1285
+ 'praxis.filesUpload.errors.CONFIGURACAO_TAMANHO_INVALIDA': 'Configuração de tamanho inválida.',
1286
+ 'praxis.filesUpload.errors.FALHA_ARMAZENAMENTO': 'Falha ao armazenar arquivo.',
1287
+ 'praxis.filesUpload.errors.ERRO_ARMAZENAMENTO_ARQUIVO': 'Erro ao armazenar arquivo.',
1288
+ 'praxis.filesUpload.errors.NOME_ARQUIVO_VAZIO': 'Nome do arquivo obrigatório.',
1289
+ 'praxis.filesUpload.errors.ERRO_ANALISE_ARQUIVO': 'Erro na análise do arquivo.',
1290
+ 'praxis.filesUpload.errors.ERRO_ESTRUTURA_ARQUIVO': 'Erro na estrutura do arquivo.',
1291
+ 'praxis.filesUpload.errors.ERRO_CONFIGURACAO': 'Erro de configuração.',
1292
+ 'praxis.filesUpload.errors.ERRO_ESCANEAMENTO_VIRUS': 'Erro no antivírus.',
1293
+ 'praxis.filesUpload.errors.FALHA_ANALISE_ARQUIVO': 'Falha ao analisar arquivo.',
1294
+ 'praxis.filesUpload.errors.ERRO_POLITICA_CONFLITO': 'Erro de política de conflito.',
1295
+ 'praxis.filesUpload.errors.POLITICA_CONFLITO_IGNORAR': 'Arquivo ignorado pela política de conflito.',
1296
+ 'praxis.filesUpload.errors.ERRO_DESCONHECIDO': 'Erro desconhecido no servidor.',
1297
+ 'praxis.filesUpload.errors.UPLOAD_LOTE_CANCELADO': 'Upload em lote cancelado.',
1298
+ 'praxis.filesUpload.errors.UPLOAD_CANCELADO_USUARIO': 'Upload cancelado pelo usuário.',
1299
+ 'praxis.filesUpload.errors.TAMANHO_LOTE_EXCEDIDO': 'Quantidade por lote excedida.',
988
1300
  'praxis.filesUpload.errors.INVALID_JSON_OPTIONS': 'JSON de opções inválido.',
989
1301
  'praxis.filesUpload.errors.EMPTY_FILENAME': 'Nome do arquivo obrigatório.',
990
1302
  'praxis.filesUpload.errors.FILE_EXISTS': 'Arquivo já existe.',
@@ -995,6 +1307,11 @@ const FILES_UPLOAD_PT_BR = {
995
1307
  'praxis.filesUpload.errors.BULK_UPLOAD_CANCELLED': 'Upload em lote cancelado.',
996
1308
  'praxis.filesUpload.errors.USER_CANCELLED': 'Upload cancelado pelo usuário.',
997
1309
  'praxis.filesUpload.errors.UNKNOWN_ERROR': 'Erro desconhecido.',
1310
+ 'praxis.filesUpload.errors.ARQUIVO_SOB_RETENCAO': 'O arquivo está protegido por política de retenção ou aprovação pendente.',
1311
+ 'praxis.filesUpload.errors.CONFLITO_ESTADO': 'O estado atual do arquivo não permite esta operação.',
1312
+ 'praxis.filesUpload.errors.EXCLUSAO_ATIVO_BLOQUEADA': 'A política configurada não permite excluir arquivos confirmados.',
1313
+ 'praxis.filesUpload.errors.NO_FILES_PROVIDED': 'Nenhum arquivo foi selecionado para envio.',
1314
+ 'praxis.filesUpload.errors.INVALID_OPTIONS_FORMAT': 'Formato inválido no campo de opções.',
998
1315
  'praxis.filesUpload.fieldPendingSummary': 'Arquivos prontos para envio',
999
1316
  'praxis.filesUpload.fieldSelectedSummary': 'Arquivo selecionado',
1000
1317
  'praxis.filesUpload.fieldSelectedPlural': 'arquivos vinculados',
@@ -1570,7 +1887,7 @@ class PraxisFilesUploadConfigEditor {
1570
1887
  }
1571
1888
  return risks;
1572
1889
  }
1573
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: PraxisFilesUploadConfigEditor, deps: [{ token: i1$1.FormBuilder }, { token: SETTINGS_PANEL_DATA }, { token: i2.MatSnackBar }, { token: i0.DestroyRef }], target: i0.ɵɵFactoryTarget.Component });
1890
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: PraxisFilesUploadConfigEditor, deps: [{ token: i1$1.FormBuilder }, { token: SETTINGS_PANEL_DATA }, { token: i2$1.MatSnackBar }, { token: i0.DestroyRef }], target: i0.ɵɵFactoryTarget.Component });
1574
1891
  static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.14", type: PraxisFilesUploadConfigEditor, isStandalone: true, selector: "praxis-files-upload-config-editor", providers: [providePraxisFilesUploadI18n()], ngImport: i0, template: `
1575
1892
  <div class="editor-layout">
1576
1893
  <aside class="summary-panel" [attr.aria-label]="tx('editor.summary.ariaLabel', 'Executive summary for the current configuration')">
@@ -2995,7 +3312,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.14", ngImpo
2995
3312
  }], ctorParameters: () => [{ type: i1$1.FormBuilder }, { type: undefined, decorators: [{
2996
3313
  type: Inject,
2997
3314
  args: [SETTINGS_PANEL_DATA]
2998
- }] }, { type: i2.MatSnackBar }, { type: i0.DestroyRef }] });
3315
+ }] }, { type: i2$1.MatSnackBar }, { type: i0.DestroyRef }] });
2999
3316
 
3000
3317
  function toError(key, info) {
3001
3318
  return { [key]: info };
@@ -3129,8 +3446,19 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.14", ngImpo
3129
3446
 
3130
3447
  class FilesApiClient {
3131
3448
  http;
3132
- constructor(http) {
3449
+ runtimeContext;
3450
+ apiUrlConfig;
3451
+ constructor(http, runtimeContext, apiUrlConfig = null) {
3133
3452
  this.http = http;
3453
+ this.runtimeContext = runtimeContext;
3454
+ this.apiUrlConfig = apiUrlConfig;
3455
+ }
3456
+ /** Consulta configuração efetiva de upload do backend. */
3457
+ getConfig(baseUrl, withCredentials = true, requestOptions) {
3458
+ return this.http.get(`${this.normalizeBaseUrl(baseUrl)}/config`, {
3459
+ headers: this.buildHeaders(requestOptions),
3460
+ withCredentials,
3461
+ });
3134
3462
  }
3135
3463
  /** Upload de um único arquivo com metadata/conflictPolicy e options JSON. */
3136
3464
  upload(baseUrl, file, options = {}) {
@@ -3143,11 +3471,72 @@ class FilesApiClient {
3143
3471
  if (options.conflictPolicy)
3144
3472
  formData.append('conflictPolicy', options.conflictPolicy);
3145
3473
  return this.http
3146
- .post(`${baseUrl}/upload`, formData, {
3474
+ .post(`${this.normalizeBaseUrl(baseUrl)}/upload`, formData, {
3475
+ headers: this.stripContentTypeHeader(this.buildHeaders(options)),
3147
3476
  reportProgress: true,
3148
3477
  observe: 'events',
3478
+ withCredentials: options.withCredentials ?? true,
3149
3479
  })
3150
- .pipe(retry(options.retryCount ?? 0));
3480
+ .pipe(retry({
3481
+ count: options.retryCount ?? 0,
3482
+ delay: (error, retryCount) => isTransientUploadHttpError(error)
3483
+ ? timer(computeUploadRetryDelayMs(error, retryCount))
3484
+ : throwError(() => error),
3485
+ }));
3486
+ }
3487
+ /** Consulta metadados públicos de um arquivo enviado. */
3488
+ getMetadata(baseUrl, fileId, withCredentials = true, requestOptions) {
3489
+ if (!isSafePraxisFileId(fileId)) {
3490
+ return throwError(() => new Error('Invalid fileId.'));
3491
+ }
3492
+ return this.http.get(`${this.normalizeBaseUrl(baseUrl)}/${encodeURIComponent(fileId.trim())}`, {
3493
+ headers: this.buildHeaders(requestOptions),
3494
+ withCredentials,
3495
+ });
3496
+ }
3497
+ /** Confirma ciclo de vida do arquivo (`STAGED` -> `ACTIVE`). */
3498
+ confirm(baseUrl, fileId, withCredentials = true, requestOptions) {
3499
+ if (!isSafePraxisFileId(fileId)) {
3500
+ return throwError(() => new Error('Invalid fileId.'));
3501
+ }
3502
+ return this.http.post(`${this.normalizeBaseUrl(baseUrl)}/${encodeURIComponent(fileId.trim())}/confirm`, null, {
3503
+ headers: this.buildHeaders(requestOptions),
3504
+ withCredentials,
3505
+ });
3506
+ }
3507
+ /** Remove arquivo e marca metadados como `DELETED`. */
3508
+ delete(baseUrl, fileId, withCredentials = true, requestOptions) {
3509
+ if (!isSafePraxisFileId(fileId)) {
3510
+ return throwError(() => new Error('Invalid fileId.'));
3511
+ }
3512
+ return this.http.delete(`${this.normalizeBaseUrl(baseUrl)}/${encodeURIComponent(fileId.trim())}`, {
3513
+ headers: this.buildHeaders(requestOptions),
3514
+ withCredentials,
3515
+ });
3516
+ }
3517
+ /** Retorna URL segura para download ou visualização inline (`/content`). */
3518
+ getContentUrl(baseUrl, fileId, disposition = 'attachment') {
3519
+ if (!isSafePraxisFileId(fileId)) {
3520
+ return '';
3521
+ }
3522
+ const safeDisposition = disposition === 'inline' ? 'inline' : 'attachment';
3523
+ return `${this.normalizeBaseUrl(baseUrl)}/${encodeURIComponent(fileId.trim())}/content?disposition=${safeDisposition}`;
3524
+ }
3525
+ /** Baixa conteúdo binário do arquivo (`/content`). */
3526
+ getContent(baseUrl, fileId, disposition = 'attachment', withCredentials = true, requestOptions) {
3527
+ const url = this.getContentUrl(baseUrl, fileId, disposition);
3528
+ if (!url) {
3529
+ return throwError(() => new Error('Invalid fileId.'));
3530
+ }
3531
+ return this.http.get(url, {
3532
+ headers: this.buildHeaders(requestOptions),
3533
+ responseType: 'blob',
3534
+ withCredentials,
3535
+ });
3536
+ }
3537
+ /** Baixa conteúdo binário autenticado (`/content`) para preview seguro via Blob. */
3538
+ fetchContentBlob(baseUrl, fileId, disposition = 'inline', withCredentials = true, requestOptions) {
3539
+ return this.getContent(baseUrl, fileId, disposition, withCredentials, requestOptions);
3151
3540
  }
3152
3541
  /** Upload múltiplo com arrays de metadata/conflictPolicy e options JSON. */
3153
3542
  bulkUpload(baseUrl, files, options = {}) {
@@ -3170,24 +3559,187 @@ class FilesApiClient {
3170
3559
  formData.append('conflictPolicy', JSON.stringify(policies));
3171
3560
  }
3172
3561
  return this.http
3173
- .post(`${baseUrl}/bulk`, formData, {
3562
+ .post(`${this.normalizeBaseUrl(baseUrl)}/bulk`, formData, {
3563
+ headers: this.stripContentTypeHeader(this.buildHeaders(options)),
3174
3564
  reportProgress: true,
3175
3565
  observe: 'events',
3566
+ withCredentials: options.withCredentials ?? true,
3176
3567
  })
3177
- .pipe(retry(options.retryCount ?? 0));
3568
+ .pipe(retry({
3569
+ count: options.retryCount ?? 0,
3570
+ delay: (error, retryCount) => isTransientUploadHttpError(error)
3571
+ ? timer(computeUploadRetryDelayMs(error, retryCount))
3572
+ : throwError(() => error),
3573
+ }));
3178
3574
  }
3179
- presign(baseUrl, fileName) {
3575
+ presign(baseUrl, fileName, withCredentials = true, requestOptions) {
3180
3576
  // Backend: POST /upload/presign?filename=...
3181
- const url = `${baseUrl}/upload/presign?filename=${encodeURIComponent(fileName)}`;
3182
- return this.http.post(url, null, { observe: 'body' });
3577
+ const url = `${this.normalizeBaseUrl(baseUrl)}/upload/presign?filename=${encodeURIComponent(fileName)}`;
3578
+ return this.http.post(url, null, {
3579
+ headers: this.buildHeaders(requestOptions),
3580
+ observe: 'body',
3581
+ withCredentials,
3582
+ });
3183
3583
  }
3184
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: FilesApiClient, deps: [{ token: i1.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable });
3584
+ normalizeBaseUrl(baseUrl) {
3585
+ const trimmed = (baseUrl ?? '').trim().replace(/\/+$/, '');
3586
+ return trimmed || '/api/files';
3587
+ }
3588
+ buildHeaders(requestOptions) {
3589
+ const headerEntries = new Map();
3590
+ const apiKey = requestOptions?.apiUrlKey?.trim();
3591
+ const entry = (apiKey ? this.apiUrlConfig?.[apiKey] : undefined)
3592
+ || this.apiUrlConfig?.['files']
3593
+ || this.apiUrlConfig?.['default'];
3594
+ if (requestOptions?.preserveExplicitContextHeaders) {
3595
+ this.applyRecordToMap(headerEntries, this.readBaseHeaders(), true);
3596
+ this.applyHttpHeadersToMap(headerEntries, buildHeaders(entry || {}), true);
3597
+ this.applyRecordToMap(headerEntries, requestOptions.headers, false);
3598
+ return this.toHttpHeaders(headerEntries);
3599
+ }
3600
+ this.applyRecordToMap(headerEntries, this.readBaseHeaders(), false);
3601
+ this.applyHttpHeadersToMap(headerEntries, buildHeaders(entry || {}), false);
3602
+ this.applyRecordToMap(headerEntries, requestOptions?.headers, false);
3603
+ let headers = this.toHttpHeaders(headerEntries) ?? new HttpHeaders();
3604
+ if (this.runtimeContext) {
3605
+ headers = this.runtimeContext.applyHeaders(headers);
3606
+ }
3607
+ return headers.keys().length > 0 ? headers : undefined;
3608
+ }
3609
+ stripContentTypeHeader(headers) {
3610
+ if (!headers) {
3611
+ return undefined;
3612
+ }
3613
+ let next = headers;
3614
+ for (const key of headers.keys()) {
3615
+ if (key.toLowerCase() === 'content-type') {
3616
+ next = next.delete(key);
3617
+ }
3618
+ }
3619
+ return next.keys().length > 0 ? next : undefined;
3620
+ }
3621
+ readBaseHeaders() {
3622
+ const shouldUseEnterpriseContext = Boolean(this.runtimeContext
3623
+ && (this.runtimeContext.effectiveContext
3624
+ || this.runtimeContext.snapshot
3625
+ || this.runtimeContext.isSwitching
3626
+ || this.runtimeContext.lifecycleState() !== 'idle'));
3627
+ if (shouldUseEnterpriseContext && this.runtimeContext?.effectiveRequestHeaders) {
3628
+ return this.runtimeContext.effectiveRequestHeaders();
3629
+ }
3630
+ try {
3631
+ const factory = globalThis
3632
+ .PAX_FETCH_HEADERS;
3633
+ const result = factory?.();
3634
+ return result && typeof result === 'object' ? result : undefined;
3635
+ }
3636
+ catch {
3637
+ return undefined;
3638
+ }
3639
+ }
3640
+ applyHttpHeadersToMap(target, source, excludeContextual) {
3641
+ if (!source) {
3642
+ return;
3643
+ }
3644
+ for (const key of source.keys()) {
3645
+ if (excludeContextual && isPraxisContextualHeaderName(key)) {
3646
+ continue;
3647
+ }
3648
+ const values = source.getAll(key);
3649
+ if (values && values.length > 0) {
3650
+ target.set(key.toLowerCase(), {
3651
+ name: key,
3652
+ value: values.length === 1 ? values[0] : values,
3653
+ });
3654
+ }
3655
+ }
3656
+ }
3657
+ applyRecordToMap(target, source, excludeContextual) {
3658
+ if (!source) {
3659
+ return;
3660
+ }
3661
+ for (const [name, raw] of Object.entries(source)) {
3662
+ if (excludeContextual && isPraxisContextualHeaderName(name)) {
3663
+ continue;
3664
+ }
3665
+ if (typeof raw === 'string' && raw.trim()) {
3666
+ target.set(name.toLowerCase(), { name, value: raw });
3667
+ }
3668
+ }
3669
+ }
3670
+ toHttpHeaders(entries) {
3671
+ if (entries.size === 0) {
3672
+ return undefined;
3673
+ }
3674
+ let headers = new HttpHeaders();
3675
+ for (const entry of entries.values()) {
3676
+ headers = headers.set(entry.name, entry.value);
3677
+ }
3678
+ return headers;
3679
+ }
3680
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: FilesApiClient, deps: [{ token: i1.HttpClient }, { token: i2.EnterpriseRuntimeContextService, optional: true }, { token: API_URL, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
3185
3681
  static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: FilesApiClient, providedIn: 'root' });
3186
3682
  }
3187
3683
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: FilesApiClient, decorators: [{
3188
3684
  type: Injectable,
3189
3685
  args: [{ providedIn: 'root' }]
3190
- }], ctorParameters: () => [{ type: i1.HttpClient }] });
3686
+ }], ctorParameters: () => [{ type: i1.HttpClient }, { type: i2.EnterpriseRuntimeContextService, decorators: [{
3687
+ type: Optional
3688
+ }] }, { type: undefined, decorators: [{
3689
+ type: Optional
3690
+ }, {
3691
+ type: Inject,
3692
+ args: [API_URL]
3693
+ }] }] });
3694
+ function isTransientUploadHttpError(error) {
3695
+ const status = error?.status;
3696
+ if (typeof status !== 'number') {
3697
+ return false;
3698
+ }
3699
+ if (status === 429) {
3700
+ const code = extractUploadErrorCode(error);
3701
+ if (code === 'COTA_EXCEDIDA' || code === 'QUOTA_EXCEEDED') {
3702
+ return false;
3703
+ }
3704
+ return true;
3705
+ }
3706
+ return status === 0 || status === 408 || status >= 500;
3707
+ }
3708
+ function extractUploadErrorCode(error) {
3709
+ const body = error?.error;
3710
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
3711
+ return '';
3712
+ }
3713
+ const record = body;
3714
+ const errors = record['errors'];
3715
+ if (Array.isArray(errors) && errors.length > 0 && errors[0] && typeof errors[0] === 'object') {
3716
+ const firstCode = errors[0]['code'];
3717
+ if (typeof firstCode === 'string' && firstCode.trim()) {
3718
+ return firstCode.trim().toUpperCase();
3719
+ }
3720
+ }
3721
+ const direct = record['code'] ?? record['errorCode'];
3722
+ return typeof direct === 'string' ? direct.trim().toUpperCase() : '';
3723
+ }
3724
+ function computeUploadRetryDelayMs(error, retryAttempt) {
3725
+ const headers = error?.headers;
3726
+ const rawRetryAfter = headers?.get?.('Retry-After')?.trim();
3727
+ if (rawRetryAfter) {
3728
+ if (/^\d+$/.test(rawRetryAfter)) {
3729
+ const secs = Number(rawRetryAfter);
3730
+ if (Number.isFinite(secs) && secs >= 0) {
3731
+ return Math.min(60_000, Math.max(500, secs * 1000));
3732
+ }
3733
+ }
3734
+ const parsedMs = Date.parse(rawRetryAfter);
3735
+ if (Number.isFinite(parsedMs)) {
3736
+ const deltaMs = Math.max(0, parsedMs - Date.now());
3737
+ return Math.min(60_000, Math.max(500, deltaMs));
3738
+ }
3739
+ }
3740
+ const attempt = Number.isFinite(retryAttempt) && retryAttempt > 0 ? retryAttempt : 1;
3741
+ return Math.min(60_000, 500 * attempt);
3742
+ }
3191
3743
 
3192
3744
  class PresignedUploaderService {
3193
3745
  http;
@@ -3266,6 +3818,33 @@ const DEFAULT_MESSAGES = {
3266
3818
  ARQUIVO_MUITO_GRANDE: 'Arquivo muito grande.',
3267
3819
  TIPO_ARQUIVO_INVALIDO: 'Tipo de arquivo inválido.',
3268
3820
  TIPO_MIDIA_NAO_SUPORTADO: 'Tipo de mídia não suportado.',
3821
+ TIPO_NAO_SUPORTADO: 'Tipo de arquivo não suportado.',
3822
+ TIPO_MIME_INCOMPATIVEL: 'O tipo MIME do conteúdo não corresponde ao arquivo enviado.',
3823
+ ASSINATURA_INVALIDA: 'Assinatura do arquivo incompatível com o formato declarado.',
3824
+ MAGIC_NUMBER_INCOMPATIVEL: 'Conteúdo binário incompatível com a extensão declarada.',
3825
+ ESTRUTURA_SUSPEITA: 'Estrutura suspeita detectada no documento.',
3826
+ ARQUIVO_CORROMPIDO: 'Arquivo corrompido ou ilegível.',
3827
+ ZIP_BOMB_DETECTADO: 'Arquivo compactado excede limites seguros de extração.',
3828
+ EXECUTAVEL_INCORPORADO: 'Conteúdo executável incorporado detectado.',
3829
+ PATH_TRAVERSAL: 'Caminho de arquivo inválido detectado.',
3830
+ ARQUIVO_VAZIO: 'O arquivo enviado está vazio.',
3831
+ CAMINHO_INVALIDO: 'Caminho do arquivo inválido.',
3832
+ NOME_ARQUIVO_INVALIDO: 'Nome do arquivo inválido.',
3833
+ ARQUIVO_EXECUTAVEL_PERIGOSO: 'Arquivo executável bloqueado pela política de segurança.',
3834
+ SCRIPT_PERIGOSO: 'Script potencialmente perigoso detectado no arquivo.',
3835
+ TIPO_ARQUIVO_PERIGOSO: 'Tipo de arquivo bloqueado pela política de segurança.',
3836
+ EXTENSAO_SUSPEITA_BLOQUEADA: 'Extensão suspeita bloqueada pela política de segurança.',
3837
+ VIOLACAO_SEGURANCA: 'Arquivo bloqueado por violação de segurança.',
3838
+ SCANNER_VIRUS_INDISPONIVEL: 'Scanner antivírus indisponível no momento. Tente novamente em instantes.',
3839
+ MALWARE_DETECTADO: 'Malware detectado no arquivo.',
3840
+ VIRUS_DETECTADO: 'Vírus detectado no arquivo.',
3841
+ TEMPO_ESGOTADO_UPLOAD: 'Tempo esgotado durante o envio do arquivo.',
3842
+ TEMPO_ESGOTADO_UPLOAD_LOTE: 'Tempo esgotado durante o envio em lote.',
3843
+ ERRO_IO: 'Falha de leitura/escrita durante o envio do arquivo.',
3844
+ ESPAÇO_INSUFICIENTE: 'Armazenamento temporário insuficiente no servidor.',
3845
+ ESPACO_INSUFICIENTE: 'Armazenamento temporário insuficiente no servidor.',
3846
+ ARQUIVO_NAO_ENCONTRADO: 'Arquivo não encontrado.',
3847
+ ACESSO_NEGADO: 'Sem permissão para acessar ou modificar este arquivo.',
3269
3848
  CAMPO_OBRIGATORIO_AUSENTE: 'Campo obrigatório ausente.',
3270
3849
  OPCOES_JSON_INVALIDAS: 'JSON de opções inválido.',
3271
3850
  ARGUMENTO_INVALIDO: 'Argumento inválido.',
@@ -3274,6 +3853,11 @@ const DEFAULT_MESSAGES = {
3274
3853
  LIMITE_TAXA_EXCEDIDO: 'Limite de taxa excedido.',
3275
3854
  COTA_EXCEDIDA: 'Cota excedida.',
3276
3855
  ARQUIVO_JA_EXISTE: 'Arquivo já existe.',
3856
+ ARQUIVO_SOB_RETENCAO: 'O arquivo está protegido por política de retenção ou aprovação pendente.',
3857
+ CONFLITO_ESTADO: 'O estado atual do arquivo não permite esta operação.',
3858
+ EXCLUSAO_ATIVO_BLOQUEADA: 'A política configurada não permite excluir arquivos confirmados.',
3859
+ NO_FILES_PROVIDED: 'Nenhum arquivo foi selecionado para envio.',
3860
+ INVALID_OPTIONS_FORMAT: 'Formato inválido no campo de opções.',
3277
3861
  };
3278
3862
  class ErrorMapperService {
3279
3863
  i18n;
@@ -3287,46 +3871,64 @@ class ErrorMapperService {
3287
3871
  map(error, headers) {
3288
3872
  const primary = getPrimaryErrorItem(error);
3289
3873
  const code = String(primary?.code || 'UNKNOWN_ERROR');
3874
+ const locale = this.i18n?.getLocale?.() ?? 'pt-BR';
3875
+ const isEnglish = locale.trim().toLowerCase().startsWith('en');
3290
3876
  const translatedMessage = resolvePraxisFilesUploadText(this.i18n, `errors.${code}`, '', undefined, this.legacyTranslate);
3291
- const defaultMessage = DEFAULT_MESSAGES[code] ??
3292
- primary?.message ??
3293
- (isErrorEnvelope(error) ? error.message : undefined) ??
3294
- 'Erro desconhecido.';
3877
+ const catalogDictionary = (isEnglish ? FILES_UPLOAD_EN_US : FILES_UPLOAD_PT_BR);
3878
+ const dictionaryMessage = catalogDictionary[`praxis.filesUpload.errors.${code}`];
3879
+ const primaryMessage = primary?.message?.trim() ? primary.message : undefined;
3880
+ const envelopeMessage = isErrorEnvelope(error) && error.message?.trim() ? error.message : undefined;
3881
+ const defaultMessage = (isEnglish ? dictionaryMessage : DEFAULT_MESSAGES[code] ?? dictionaryMessage) ??
3882
+ primaryMessage ??
3883
+ envelopeMessage ??
3884
+ (isEnglish ? 'Unknown error.' : 'Erro desconhecido.');
3295
3885
  const configuredMessage = this.customMessages?.[code];
3296
3886
  const message = configuredMessage ??
3297
3887
  (translatedMessage || defaultMessage);
3298
3888
  // metadados do catálogo
3299
- const meta = getErrorMeta(code);
3889
+ const meta = getErrorMeta(code, locale);
3890
+ const resolvedTitle = resolvePraxisFilesUploadText(this.i18n, `errorTitles.${code}`, meta.title, undefined, this.legacyTranslate);
3891
+ const resolvedUserAction = meta.userAction
3892
+ ? resolvePraxisFilesUploadText(this.i18n, `errorActions.${code}`, meta.userAction, undefined, this.legacyTranslate)
3893
+ : undefined;
3300
3894
  const mapped = {
3301
3895
  message,
3302
- title: meta.title,
3896
+ title: resolvedTitle,
3303
3897
  severity: meta.severity,
3304
3898
  category: meta.category,
3305
3899
  phase: meta.phase,
3306
- userAction: meta.userAction,
3900
+ userAction: resolvedUserAction,
3901
+ ...(meta.retriable !== undefined ? { retriable: meta.retriable } : {}),
3307
3902
  };
3903
+ const retryAfterSeconds = parseRetryAfterHeader(headers?.get('Retry-After'));
3904
+ if (retryAfterSeconds !== undefined) {
3905
+ mapped.retryAfterSeconds = retryAfterSeconds;
3906
+ }
3308
3907
  const isRateLimit = code === 'LIMITE_TAXA_EXCEDIDO' ||
3309
3908
  code === 'RATE_LIMIT_EXCEEDED' ||
3310
3909
  code === 'SYS_RATE_LIMIT';
3311
3910
  if (isRateLimit) {
3312
- const limit = Number(headers?.get('X-RateLimit-Limit'));
3313
- const remaining = Number(headers?.get('X-RateLimit-Remaining'));
3314
- const resetEpochSeconds = Number(headers?.get('X-RateLimit-Reset'));
3315
- if (!Number.isNaN(limit) &&
3316
- !Number.isNaN(remaining) &&
3317
- !Number.isNaN(resetEpochSeconds)) {
3318
- mapped.rateLimit = { limit, remaining, resetEpochSeconds };
3911
+ const limit = parseFiniteHeaderNumber(headers?.get('X-RateLimit-Limit'));
3912
+ const remaining = parseFiniteHeaderNumber(headers?.get('X-RateLimit-Remaining'));
3913
+ const rawReset = parseFiniteHeaderNumber(headers?.get('X-RateLimit-Reset'));
3914
+ if (limit !== undefined && remaining !== undefined && rawReset !== undefined) {
3915
+ mapped.rateLimit = {
3916
+ limit,
3917
+ remaining,
3918
+ resetEpochSeconds: normalizeResetEpochSeconds(rawReset),
3919
+ ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}),
3920
+ };
3319
3921
  }
3320
3922
  }
3321
3923
  return mapped;
3322
3924
  }
3323
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: ErrorMapperService, deps: [{ token: i1$2.PraxisI18nService }, { token: FILES_UPLOAD_ERROR_MESSAGES, optional: true }, { token: TRANSLATE_LIKE, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
3925
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: ErrorMapperService, deps: [{ token: i2.PraxisI18nService }, { token: FILES_UPLOAD_ERROR_MESSAGES, optional: true }, { token: TRANSLATE_LIKE, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
3324
3926
  static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: ErrorMapperService, providedIn: 'root' });
3325
3927
  }
3326
3928
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: ErrorMapperService, decorators: [{
3327
3929
  type: Injectable,
3328
3930
  args: [{ providedIn: 'root' }]
3329
- }], ctorParameters: () => [{ type: i1$2.PraxisI18nService }, { type: undefined, decorators: [{
3931
+ }], ctorParameters: () => [{ type: i2.PraxisI18nService }, { type: undefined, decorators: [{
3330
3932
  type: Optional
3331
3933
  }, {
3332
3934
  type: Inject,
@@ -3337,6 +3939,38 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.14", ngImpo
3337
3939
  type: Inject,
3338
3940
  args: [TRANSLATE_LIKE]
3339
3941
  }] }] });
3942
+ function parseRetryAfterHeader(raw) {
3943
+ const trimmed = raw?.trim();
3944
+ if (!trimmed) {
3945
+ return undefined;
3946
+ }
3947
+ if (/^\d+$/.test(trimmed)) {
3948
+ const num = Number(trimmed);
3949
+ return Number.isFinite(num) && num >= 0 ? num : undefined;
3950
+ }
3951
+ const parsedDateMs = Date.parse(trimmed);
3952
+ if (Number.isFinite(parsedDateMs)) {
3953
+ return Math.max(0, Math.ceil((parsedDateMs - Date.now()) / 1000));
3954
+ }
3955
+ return undefined;
3956
+ }
3957
+ function parseFiniteHeaderNumber(raw) {
3958
+ const trimmed = raw?.trim();
3959
+ if (!trimmed) {
3960
+ return undefined;
3961
+ }
3962
+ const num = Number(trimmed);
3963
+ return Number.isFinite(num) && num >= 0 ? num : undefined;
3964
+ }
3965
+ function normalizeResetEpochSeconds(rawReset) {
3966
+ if (rawReset > 1e12) {
3967
+ return Math.floor(rawReset / 1000);
3968
+ }
3969
+ if (rawReset < 1e9) {
3970
+ return Math.floor(Date.now() / 1000) + Math.max(0, Math.floor(rawReset));
3971
+ }
3972
+ return Math.floor(rawReset);
3973
+ }
3340
3974
 
3341
3975
  let nextPraxisFilesUploadA11yId = 0;
3342
3976
  class PraxisFilesUpload {
@@ -4125,6 +4759,10 @@ class PraxisFilesUpload {
4125
4759
  if (event.type === HttpEventType.Response) {
4126
4760
  const resp = event.body;
4127
4761
  const meta = this.mapUploadResponseToFileMetadata(resp);
4762
+ if (!meta || !meta.id) {
4763
+ this.handleError(new Error('Upload response missing a valid fileId.'));
4764
+ return;
4765
+ }
4128
4766
  this.finishUpload(true, meta);
4129
4767
  }
4130
4768
  else {
@@ -4389,6 +5027,7 @@ class PraxisFilesUpload {
4389
5027
  loaded: event.loaded,
4390
5028
  total: event.total,
4391
5029
  });
5030
+ this.cdr.markForCheck();
4392
5031
  }
4393
5032
  }
4394
5033
  handleError(err) {
@@ -4422,6 +5061,7 @@ class PraxisFilesUpload {
4422
5061
  this.errorMessage = normalizedError.message;
4423
5062
  this.error.emit(normalizedError);
4424
5063
  }
5064
+ this.cdr.markForCheck();
4425
5065
  }
4426
5066
  finishUpload(success, meta, results) {
4427
5067
  this.uploading = false;
@@ -4473,14 +5113,47 @@ class PraxisFilesUpload {
4473
5113
  if (!payload) {
4474
5114
  return undefined;
4475
5115
  }
5116
+ const nestedMeta = payload.metadata;
5117
+ const rawStatusValue = payload.status
5118
+ ?? (typeof nestedMeta?.['status'] === 'string' ? nestedMeta['status'] : undefined);
5119
+ const rawStatus = typeof rawStatusValue === 'string' ? rawStatusValue.trim().toUpperCase() : '';
5120
+ const normalizedStatus = rawStatus === 'STAGED'
5121
+ || rawStatus === 'PENDING_APPROVAL'
5122
+ || rawStatus === 'ACTIVE'
5123
+ || rawStatus === 'DELETED'
5124
+ ? rawStatus
5125
+ : undefined;
5126
+ const rawScanStatusValue = payload.scanStatus
5127
+ ?? (typeof nestedMeta?.['scanStatus'] === 'string' ? nestedMeta['scanStatus'] : undefined);
5128
+ const rawScanUpper = typeof rawScanStatusValue === 'string' ? rawScanStatusValue.trim().toUpperCase() : '';
5129
+ const scanStatus = !rawScanUpper
5130
+ ? ScanStatus.PENDING
5131
+ : rawScanUpper === 'ERROR'
5132
+ ? ScanStatus.FAILED
5133
+ : rawScanUpper === ScanStatus.CLEAN
5134
+ || rawScanUpper === ScanStatus.SCANNING
5135
+ || rawScanUpper === ScanStatus.INFECTED
5136
+ || rawScanUpper === ScanStatus.FAILED
5137
+ || rawScanUpper === ScanStatus.UNAVAILABLE
5138
+ || rawScanUpper === ScanStatus.SKIPPED
5139
+ || rawScanUpper === ScanStatus.PENDING
5140
+ ? rawScanUpper
5141
+ : ScanStatus.UNAVAILABLE;
5142
+ const tenantId = payload.tenantId
5143
+ ?? (typeof nestedMeta?.['tenantId'] === 'string' ? nestedMeta['tenantId'] : '');
5144
+ const safeId = isSafePraxisFileId(payload.fileId) ? payload.fileId.trim() : '';
4476
5145
  return {
4477
- id: payload.fileId || '',
5146
+ id: safeId,
4478
5147
  fileName: payload.originalFilename,
5148
+ ...(payload.serverFilename !== undefined ? { serverFilename: payload.serverFilename } : {}),
4479
5149
  contentType: payload.mimeType || '',
4480
5150
  fileSize: payload.fileSize,
5151
+ ...(payload.checksumSha256 !== undefined ? { checksumSha256: payload.checksumSha256 } : {}),
4481
5152
  uploadedAt: payload.uploadTimestamp,
4482
- tenantId: '',
4483
- scanStatus: ScanStatus.PENDING,
5153
+ tenantId,
5154
+ ...(normalizedStatus ? { status: normalizedStatus } : {}),
5155
+ scanStatus,
5156
+ ...(nestedMeta ? { metadata: nestedMeta } : {}),
4484
5157
  };
4485
5158
  }
4486
5159
  primaryErrorCode(error) {
@@ -4633,7 +5306,7 @@ class PraxisFilesUpload {
4633
5306
  return acc[key];
4634
5307
  }, context);
4635
5308
  }
4636
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: PraxisFilesUpload, deps: [{ token: i1$3.SettingsPanelService }, { token: DragProximityService }, { token: i3$1.Overlay }, { token: i0.ViewContainerRef }, { token: i0.ChangeDetectorRef }, { token: ASYNC_CONFIG_STORAGE }, { token: i1$2.PraxisI18nService }, { token: FILES_UPLOAD_TEXTS, optional: true }, { token: TRANSLATE_LIKE, optional: true }, { token: ConfigService, optional: true }, { token: FilesApiClient, optional: true }, { token: PresignedUploaderService, optional: true }, { token: ErrorMapperService, optional: true }], target: i0.ɵɵFactoryTarget.Component });
5309
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: PraxisFilesUpload, deps: [{ token: i1$2.SettingsPanelService }, { token: DragProximityService }, { token: i3$1.Overlay }, { token: i0.ViewContainerRef }, { token: i0.ChangeDetectorRef }, { token: ASYNC_CONFIG_STORAGE }, { token: i2.PraxisI18nService }, { token: FILES_UPLOAD_TEXTS, optional: true }, { token: TRANSLATE_LIKE, optional: true }, { token: ConfigService, optional: true }, { token: FilesApiClient, optional: true }, { token: PresignedUploaderService, optional: true }, { token: ErrorMapperService, optional: true }], target: i0.ɵɵFactoryTarget.Component });
4637
5310
  static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.14", type: PraxisFilesUpload, isStandalone: true, selector: "praxis-files-upload", inputs: { config: "config", filesUploadId: "filesUploadId", componentInstanceId: "componentInstanceId", baseUrl: "baseUrl", displayMode: "displayMode", context: "context", enableCustomization: "enableCustomization" }, outputs: { uploadSuccess: "uploadSuccess", bulkComplete: "bulkComplete", error: "error", rateLimited: "rateLimited", uploadStart: "uploadStart", uploadProgress: "uploadProgress", retry: "retry", download: "download", copyLink: "copyLink", detailsOpened: "detailsOpened", detailsClosed: "detailsClosed", pendingStateChange: "pendingStateChange", proximityChange: "proximityChange", readinessChange: "readinessChange" }, providers: [providePraxisFilesUploadI18n()], viewQueries: [{ propertyName: "fileInput", first: true, predicate: ["fileInput"], descendants: true }, { propertyName: "hostRef", first: true, predicate: ["host"], descendants: true, static: true }, { propertyName: "overlayTmpl", first: true, predicate: ["proximityOverlayTmpl"], descendants: true }, { propertyName: "selectedOverlayTmpl", first: true, predicate: ["selectedOverlayTmpl"], descendants: true }], usesOnChanges: true, ngImport: i0, template: `
4638
5311
  <div
4639
5312
  class="praxis-files-upload"
@@ -5654,10 +6327,10 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.14", ngImpo
5654
6327
  <ng-content></ng-content>
5655
6328
  </div>
5656
6329
  `, styles: ["@charset \"UTF-8\";.praxis-files-upload{position:relative;container-type:inline-size}.praxis-files-upload .settings-btn{position:absolute;top:.5rem;right:.5rem}.praxis-files-upload .rate-limit-banner,.praxis-files-upload .quota-banner,.praxis-files-upload .error{margin:.5rem 0;padding:.5rem 1rem;border-radius:var(--md-sys-shape-corner-small, 4px)}.praxis-files-upload .rate-limit-banner{background:var(--md-sys-color-error-container);color:var(--md-sys-color-on-error-container)}.praxis-files-upload .quota-banner{background:var(--md-sys-color-tertiary-container);color:var(--md-sys-color-on-tertiary-container)}.praxis-files-upload .dropzone{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:2rem;border:2px dashed var(--md-sys-color-outline);border-radius:var(--md-sys-shape-corner-medium, 4px);background:var(--md-sys-color-surface-container-low);color:var(--md-sys-color-on-surface);text-align:center;transition:background-color .2s;width:100%;min-height:160px;margin:.5rem 0;gap:.5rem;position:relative}.praxis-files-upload .dropzone:hover{outline:none;background:var(--md-sys-color-surface-container-high);border-color:var(--md-sys-color-primary)}.praxis-files-upload .dropzone.dragover{background:var(--md-sys-color-surface-container-high);border-color:var(--md-sys-color-primary)}.praxis-files-upload .dropzone.disabled{opacity:.6;cursor:not-allowed;pointer-events:none}.praxis-files-upload .dropzone p{margin:0 0 .5rem}.praxis-files-upload .dropzone .dz-icon{font-size:40px;color:var(--md-sys-color-primary);margin-bottom:.25rem}.praxis-files-upload .dropzone .dz-title{font-weight:600}.praxis-files-upload .dropzone .dz-hint{margin:0;opacity:.8;font-size:.9rem}.praxis-files-upload .dropzone .field-actions{position:absolute;top:.25rem;right:.25rem;display:flex;gap:.25rem;pointer-events:auto}.praxis-files-upload .progress{margin-top:1rem}.praxis-files-upload .upload-policy-fields{display:grid;grid-template-columns:minmax(12rem,.8fr) minmax(16rem,1.2fr);align-items:start;gap:.75rem;margin-top:1rem}.praxis-files-upload .conflict-policy,.praxis-files-upload .metadata{width:100%;min-width:0}.praxis-files-upload .metadata textarea{resize:vertical}.praxis-files-upload .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);border:0}.praxis-files-upload .bulk-results{margin-top:1rem}.praxis-files-upload .bulk-results .bulk-summary{display:flex;gap:1rem;align-items:center;margin-bottom:.5rem}.praxis-files-upload .bulk-results .bulk-summary .stat{display:flex;align-items:center;gap:.35rem;padding:.25rem .5rem;border-radius:6px;background:var(--md-sys-color-surface-container-low)}.praxis-files-upload .bulk-results .bulk-summary .stat.success{color:var(--md-sys-color-on-primary-container);background:var(--md-sys-color-primary-container)}.praxis-files-upload .bulk-results .bulk-summary .stat.failed{color:var(--md-sys-color-on-error-container);background:var(--md-sys-color-error-container)}.praxis-files-upload .bulk-results .bulk-summary .stat .label{opacity:.9}.praxis-files-upload .bulk-results .bulk-summary .stat .value{font-weight:600}.praxis-files-upload .bulk-results .results-list{list-style:none;padding:0;margin:0;display:flex;flex-direction:column;gap:.5rem}.praxis-files-upload .bulk-results .result-item{display:flex;gap:.75rem;padding:.5rem .75rem;border:1px solid var(--md-sys-color-outline-variant);border-radius:8px;background:var(--md-sys-color-surface-container-lowest)}.praxis-files-upload .bulk-results .result-item.ok{border-color:var(--md-sys-color-primary)}.praxis-files-upload .bulk-results .result-item.err{border-color:var(--md-sys-color-error)}.praxis-files-upload .bulk-results .result-item .status-icon{align-self:flex-start;color:currentColor}.praxis-files-upload .bulk-results .result-item .main{flex:1;min-width:0}.praxis-files-upload .bulk-results .result-item .title{display:flex;align-items:center;gap:.5rem}.praxis-files-upload .bulk-results .result-item .name{font-weight:600}.praxis-files-upload .bulk-results .result-item .badge{font-size:.75rem;padding:.1rem .4rem;border-radius:999px;background:var(--md-sys-color-primary-container);color:var(--md-sys-color-on-primary-container)}.praxis-files-upload .bulk-results .result-item .badge.err{background:var(--md-sys-color-error-container);color:var(--md-sys-color-on-error-container)}.praxis-files-upload .bulk-results .result-item .meta,.praxis-files-upload .bulk-results .result-item .error{display:flex;flex-wrap:wrap;gap:.5rem 1rem;margin-top:.25rem}.praxis-files-upload .bulk-results .result-item .error .code{font-weight:600}.praxis-files-upload .bulk-results .result-item .extra{margin-top:.25rem}.praxis-files-upload .bulk-results .result-item .item-actions{display:flex;align-items:center;gap:.25rem}.praxis-files-upload .bulk-results .list-footer{margin-top:.5rem;display:flex;justify-content:center}.praxis-files-upload .proximity-overlay{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:.5rem;border:2px dashed var(--md-sys-color-outline);border-radius:var(--md-sys-shape-corner-medium, 4px);background:var(--md-sys-color-surface-container-high);color:var(--md-sys-color-on-surface);text-align:center;z-index:2;pointer-events:none}.praxis-files-upload .proximity-overlay .dz-icon{font-size:40px;color:var(--md-sys-color-primary)}.praxis-files-upload .proximity-overlay .dz-title{font-weight:600}.praxis-files-upload .proximity-overlay .dz-hint{opacity:.85}.praxis-files-upload .selected-overlay{background:var(--md-sys-color-surface);color:var(--md-sys-color-on-surface);border:1px solid var(--md-sys-color-outline-variant);border-radius:8px;box-shadow:var(--md-sys-elevation-level2, 0 2px 6px rgba(0, 0, 0, .15));max-height:260px;overflow:auto;padding:.5rem}.praxis-files-upload .selected-overlay .sel-header{position:sticky;top:0;z-index:1;background:var(--md-sys-color-surface);display:flex;align-items:center;gap:.5rem;padding-bottom:.25rem;margin-bottom:.25rem}.praxis-files-upload .selected-overlay .sel-header .title{font-weight:600}.praxis-files-upload .selected-overlay .sel-header .spacer{flex:1}.praxis-files-upload .selected-overlay .sel-list{list-style:none;margin:0;padding:0}.praxis-files-upload .selected-overlay .sel-list .sel-item{display:flex;align-items:center;gap:.75rem;padding:.5rem .75rem;border-bottom:1px solid var(--md-sys-color-outline-variant, #ccc);transition:background-color .12s ease}.praxis-files-upload .selected-overlay .sel-list .sel-item .file-icon{opacity:.9;color:var(--md-sys-color-primary, #1976d2)}.praxis-files-upload .selected-overlay .sel-list .sel-item .info{flex:1;min-width:0}.praxis-files-upload .selected-overlay .sel-list .sel-item .info .name{font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.praxis-files-upload .selected-overlay .sel-list .sel-item .info .meta{font-size:.8rem;opacity:.7}.praxis-files-upload .selected-overlay .sel-list .sel-item .remove-btn{color:var(--md-sys-color-error, #b00020)}.praxis-files-upload .selected-overlay .sel-list .sel-item .more-btn{margin-left:.25rem}.praxis-files-upload .selected-overlay .sel-list .sel-item:hover{background:var(--md-sys-color-surface-container-low)}@container (max-width: 640px){.praxis-files-upload .upload-policy-fields{grid-template-columns:minmax(0,1fr)}}@media(max-width:640px){.praxis-files-upload .upload-policy-fields{grid-template-columns:minmax(0,1fr)}}:host ::ng-deep .praxis-files-upload-overlay-panel{pointer-events:none}:host ::ng-deep .praxis-files-selected-overlay-panel{pointer-events:auto;z-index:3}\n"] }]
5657
- }], ctorParameters: () => [{ type: i1$3.SettingsPanelService }, { type: DragProximityService }, { type: i3$1.Overlay }, { type: i0.ViewContainerRef }, { type: i0.ChangeDetectorRef }, { type: undefined, decorators: [{
6330
+ }], ctorParameters: () => [{ type: i1$2.SettingsPanelService }, { type: DragProximityService }, { type: i3$1.Overlay }, { type: i0.ViewContainerRef }, { type: i0.ChangeDetectorRef }, { type: undefined, decorators: [{
5658
6331
  type: Inject,
5659
6332
  args: [ASYNC_CONFIG_STORAGE]
5660
- }] }, { type: i1$2.PraxisI18nService }, { type: undefined, decorators: [{
6333
+ }] }, { type: i2.PraxisI18nService }, { type: undefined, decorators: [{
5661
6334
  type: Optional
5662
6335
  }, {
5663
6336
  type: Inject,
@@ -6445,6 +7118,264 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.14", ngImpo
6445
7118
  args: ['pendingPanel']
6446
7119
  }] } });
6447
7120
 
7121
+ const PRAXIS_FILES_API_UPLOAD_PORT_OPTIONS = new InjectionToken('PRAXIS_FILES_API_UPLOAD_PORT_OPTIONS', {
7122
+ providedIn: 'root',
7123
+ factory: () => ({}),
7124
+ });
7125
+ class FilesApiUploadPortAdapter {
7126
+ client;
7127
+ apiUrlConfig;
7128
+ options;
7129
+ constructor(client, apiUrlConfig = null, options = null) {
7130
+ this.client = client;
7131
+ this.apiUrlConfig = apiUrlConfig;
7132
+ this.options = options;
7133
+ }
7134
+ upload(request) {
7135
+ const baseUrl = this.resolveBaseUrl(request.baseUrl);
7136
+ const mergedHeaders = this.mergeHeaders(this.options?.headers, request.headers, Boolean(request.preserveExplicitContextHeaders));
7137
+ return this.client
7138
+ .upload(baseUrl, request.file, {
7139
+ optionsJson: request.optionsJson,
7140
+ metadata: request.metadata ? { ...request.metadata } : undefined,
7141
+ conflictPolicy: request.conflictPolicy,
7142
+ withCredentials: this.withCredentials(),
7143
+ ...(mergedHeaders ? { headers: mergedHeaders } : {}),
7144
+ ...(request.preserveExplicitContextHeaders ? { preserveExplicitContextHeaders: true } : {}),
7145
+ ...(this.options?.apiUrlKey?.trim() ? { apiUrlKey: this.options.apiUrlKey.trim() } : {}),
7146
+ })
7147
+ .pipe(concatMap((event) => {
7148
+ if (event.type === HttpEventType.UploadProgress) {
7149
+ const total = typeof event.total === 'number' && event.total > 0 ? event.total : undefined;
7150
+ const percent = total !== undefined
7151
+ ? Math.min(100, Math.round((event.loaded / total) * 100))
7152
+ : undefined;
7153
+ return of({
7154
+ type: 'progress',
7155
+ loaded: event.loaded,
7156
+ ...(total !== undefined ? { total } : {}),
7157
+ ...(percent !== undefined ? { percent } : {}),
7158
+ });
7159
+ }
7160
+ if (event.type === HttpEventType.Response) {
7161
+ const normalized = normalizePraxisStoredFileMetadata(event.body);
7162
+ if (!isSafePraxisFileId(normalized.fileId)) {
7163
+ return throwError(() => new Error('Upload response missing a valid fileId.'));
7164
+ }
7165
+ return of({
7166
+ type: 'completed',
7167
+ file: normalized,
7168
+ });
7169
+ }
7170
+ return EMPTY;
7171
+ }));
7172
+ }
7173
+ getMetadata(fileId, baseUrlOrOptions) {
7174
+ const op = resolvePraxisFileOperationOptions(baseUrlOrOptions);
7175
+ return this.client
7176
+ .getMetadata(this.resolveBaseUrl(op.baseUrl), fileId, this.withCredentials(), this.toClientRequestOptions(op))
7177
+ .pipe(map((response) => {
7178
+ const normalized = normalizePraxisStoredFileMetadata(response);
7179
+ if (!isSafePraxisFileId(normalized.fileId)) {
7180
+ throw new Error('Metadata response missing a valid fileId.');
7181
+ }
7182
+ return normalized;
7183
+ }));
7184
+ }
7185
+ confirm(fileId, baseUrlOrOptions) {
7186
+ const op = resolvePraxisFileOperationOptions(baseUrlOrOptions);
7187
+ return this.client
7188
+ .confirm(this.resolveBaseUrl(op.baseUrl), fileId, this.withCredentials(), this.toClientRequestOptions(op))
7189
+ .pipe(map((response) => {
7190
+ const normalized = normalizePraxisStoredFileMetadata(response);
7191
+ if (!isSafePraxisFileId(normalized.fileId)) {
7192
+ throw new Error('Confirm response missing a valid fileId.');
7193
+ }
7194
+ return normalized;
7195
+ }));
7196
+ }
7197
+ delete(fileId, baseUrlOrOptions) {
7198
+ if (!isSafePraxisFileId(fileId)) {
7199
+ return throwError(() => new Error('Invalid fileId.'));
7200
+ }
7201
+ const op = resolvePraxisFileOperationOptions(baseUrlOrOptions);
7202
+ const normalizedId = fileId.trim();
7203
+ return this.client
7204
+ .delete(this.resolveBaseUrl(op.baseUrl), fileId, this.withCredentials(), this.toClientRequestOptions(op))
7205
+ .pipe(map((response) => {
7206
+ if (response === null || response === undefined) {
7207
+ return {
7208
+ fileId: normalizedId,
7209
+ originalFilename: '',
7210
+ mimeType: '',
7211
+ fileSize: 0,
7212
+ status: 'DELETED',
7213
+ scanStatus: 'SKIPPED',
7214
+ };
7215
+ }
7216
+ const normalized = normalizePraxisStoredFileMetadata(response);
7217
+ return normalized.fileId
7218
+ ? normalized
7219
+ : { ...normalized, fileId: normalizedId, status: 'DELETED' };
7220
+ }));
7221
+ }
7222
+ getContentUrl(fileId, disposition = 'attachment', baseUrl) {
7223
+ return this.client.getContentUrl(this.resolveBaseUrl(baseUrl), fileId, disposition);
7224
+ }
7225
+ fetchContentBlob(fileId, disposition = 'inline', baseUrlOrOptions) {
7226
+ const op = resolvePraxisFileOperationOptions(baseUrlOrOptions);
7227
+ return this.client.fetchContentBlob(this.resolveBaseUrl(op.baseUrl), fileId, disposition, this.withCredentials(), this.toClientRequestOptions(op));
7228
+ }
7229
+ getConfig(baseUrlOrOptions) {
7230
+ const op = resolvePraxisFileOperationOptions(baseUrlOrOptions);
7231
+ return this.client
7232
+ .getConfig(this.resolveBaseUrl(op.baseUrl), this.withCredentials(), this.toClientRequestOptions(op))
7233
+ .pipe(map((response) => {
7234
+ const record = response;
7235
+ const data = record?.['data'] && typeof record['data'] === 'object' && !Array.isArray(record['data'])
7236
+ ? record['data']
7237
+ : record && typeof record === 'object' && !Array.isArray(record)
7238
+ ? record
7239
+ : {};
7240
+ const opts = data['options'] && typeof data['options'] === 'object' && !Array.isArray(data['options'])
7241
+ ? data['options']
7242
+ : {};
7243
+ return {
7244
+ allowedExtensions: Array.isArray(opts['allowedExtensions'])
7245
+ ? opts['allowedExtensions'].filter((item) => typeof item === 'string')
7246
+ : undefined,
7247
+ acceptMimeTypes: Array.isArray(opts['acceptMimeTypes'])
7248
+ ? opts['acceptMimeTypes'].filter((item) => typeof item === 'string')
7249
+ : undefined,
7250
+ maxUploadSizeMb: typeof opts['maxUploadSizeMb'] === 'number' ? opts['maxUploadSizeMb'] : null,
7251
+ enableVirusScanning: typeof opts['enableVirusScanning'] === 'boolean'
7252
+ ? opts['enableVirusScanning']
7253
+ : undefined,
7254
+ };
7255
+ }));
7256
+ }
7257
+ resolveBaseUrl(requestBaseUrl) {
7258
+ const rawRequest = requestBaseUrl?.trim();
7259
+ if (rawRequest === '/') {
7260
+ return '/api/files';
7261
+ }
7262
+ const explicitRequest = rawRequest?.replace(/\/+$/, '');
7263
+ if (explicitRequest) {
7264
+ return explicitRequest;
7265
+ }
7266
+ const rawOption = this.options?.baseUrl?.trim();
7267
+ if (rawOption === '/') {
7268
+ return '/api/files';
7269
+ }
7270
+ const explicitOption = rawOption?.replace(/\/+$/, '');
7271
+ if (explicitOption) {
7272
+ return explicitOption;
7273
+ }
7274
+ const key = this.options?.apiUrlKey?.trim();
7275
+ if (key && this.apiUrlConfig?.[key]) {
7276
+ const configured = buildApiUrl(this.apiUrlConfig[key]).replace(/\/+$/, '');
7277
+ if (configured) {
7278
+ return appendFilesSegmentForConfiguredEntry(configured);
7279
+ }
7280
+ }
7281
+ if (this.apiUrlConfig?.['files']) {
7282
+ const filesUrl = buildApiUrl(this.apiUrlConfig['files']).replace(/\/+$/, '');
7283
+ if (filesUrl) {
7284
+ return appendFilesSegmentForConfiguredEntry(filesUrl);
7285
+ }
7286
+ }
7287
+ if (this.apiUrlConfig?.['default']) {
7288
+ const defaultUrl = buildApiUrl(this.apiUrlConfig['default']).replace(/\/+$/, '');
7289
+ if (defaultUrl) {
7290
+ if (/^https?:\/\/[^/]+$/i.test(defaultUrl)) {
7291
+ return `${defaultUrl}/api/files`;
7292
+ }
7293
+ return defaultUrl.endsWith('/files') ? defaultUrl : `${defaultUrl}/files`;
7294
+ }
7295
+ }
7296
+ return '/api/files';
7297
+ }
7298
+ withCredentials() {
7299
+ return this.options?.withCredentials ?? true;
7300
+ }
7301
+ toClientRequestOptions(op) {
7302
+ const mergedHeaders = this.mergeHeaders(this.options?.headers, op.headers, Boolean(op.preserveExplicitContextHeaders));
7303
+ return {
7304
+ ...(mergedHeaders ? { headers: mergedHeaders } : {}),
7305
+ ...(op.preserveExplicitContextHeaders ? { preserveExplicitContextHeaders: true } : {}),
7306
+ ...(this.options?.apiUrlKey?.trim() ? { apiUrlKey: this.options.apiUrlKey.trim() } : {}),
7307
+ };
7308
+ }
7309
+ mergeHeaders(base, override, excludeBaseContextual = false) {
7310
+ if (!base && !override) {
7311
+ return undefined;
7312
+ }
7313
+ const entries = new Map();
7314
+ if (base) {
7315
+ for (const [key, value] of Object.entries(base)) {
7316
+ if (excludeBaseContextual && isPraxisContextualHeaderName(key)) {
7317
+ continue;
7318
+ }
7319
+ if (typeof value === 'string' && value.trim()) {
7320
+ entries.set(key.toLowerCase(), { name: key, value: value.trim() });
7321
+ }
7322
+ }
7323
+ }
7324
+ if (override) {
7325
+ for (const [key, value] of Object.entries(override)) {
7326
+ if (typeof value === 'string' && value.trim()) {
7327
+ entries.set(key.toLowerCase(), { name: key, value: value.trim() });
7328
+ }
7329
+ }
7330
+ }
7331
+ if (entries.size === 0) {
7332
+ return undefined;
7333
+ }
7334
+ const merged = {};
7335
+ for (const entry of entries.values()) {
7336
+ merged[entry.name] = entry.value;
7337
+ }
7338
+ return merged;
7339
+ }
7340
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: FilesApiUploadPortAdapter, deps: [{ token: FilesApiClient }, { token: API_URL, optional: true }, { token: PRAXIS_FILES_API_UPLOAD_PORT_OPTIONS, optional: true }], target: i0.ɵɵFactoryTarget.Injectable });
7341
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: FilesApiUploadPortAdapter });
7342
+ }
7343
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.14", ngImport: i0, type: FilesApiUploadPortAdapter, decorators: [{
7344
+ type: Injectable
7345
+ }], ctorParameters: () => [{ type: FilesApiClient }, { type: undefined, decorators: [{
7346
+ type: Optional
7347
+ }, {
7348
+ type: Inject,
7349
+ args: [API_URL]
7350
+ }] }, { type: undefined, decorators: [{
7351
+ type: Optional
7352
+ }, {
7353
+ type: Inject,
7354
+ args: [PRAXIS_FILES_API_UPLOAD_PORT_OPTIONS]
7355
+ }] }] });
7356
+ function appendFilesSegmentForConfiguredEntry(url) {
7357
+ if (url.endsWith('/files')) {
7358
+ return url;
7359
+ }
7360
+ if (/^https?:\/\/[^/]+$/i.test(url)) {
7361
+ return `${url}/api/files`;
7362
+ }
7363
+ if (url === '/api' || url.endsWith('/api')) {
7364
+ return `${url}/files`;
7365
+ }
7366
+ return url;
7367
+ }
7368
+ function providePraxisFilesApiUploadPort(options = {}) {
7369
+ return [
7370
+ { provide: PRAXIS_FILES_API_UPLOAD_PORT_OPTIONS, useValue: options },
7371
+ FilesApiUploadPortAdapter,
7372
+ {
7373
+ provide: PRAXIS_FILE_UPLOAD_PORT,
7374
+ useExisting: FilesApiUploadPortAdapter,
7375
+ },
7376
+ ];
7377
+ }
7378
+
6448
7379
  class PraxisFilesUploadWidgetConfigEditor {
6449
7380
  inputs = null;
6450
7381
  widgetKey;
@@ -7260,4 +8191,4 @@ const PRAXIS_FILES_UPLOAD_AUTHORING_MANIFEST = {
7260
8191
  * Generated bundle index. Do not edit.
7261
8192
  */
7262
8193
 
7263
- export { BulkUploadResultStatus, ErrorCode, ErrorMapperService, FILES_UPLOAD_AI_CAPABILITIES, FILES_UPLOAD_EN_US, FILES_UPLOAD_ERROR_MESSAGES, FILES_UPLOAD_PT_BR, FILES_UPLOAD_TEXTS, FilesApiClient, PRAXIS_FILES_UPLOAD_AUTHORING_MANIFEST, PRAXIS_FILES_UPLOAD_COMPONENT_METADATA, PdxFilesUploadFieldComponent, PraxisFilesUpload, PraxisFilesUploadConfigEditor, PraxisFilesUploadWidgetConfigEditor, PresignedUploaderService, ScanStatus, TRANSLATE_LIKE, acceptValidator, createPraxisFilesUploadI18nConfig, getPrimaryErrorItem, isErrorEnvelope, maxBulkSizeValidator, maxFileSizeValidator, maxFilesPerBulkValidator, providePraxisFilesUploadI18n, providePraxisFilesUploadMetadata, resolvePraxisFilesUploadText };
8194
+ export { BulkUploadResultStatus, ErrorCode, ErrorMapperService, FILES_UPLOAD_AI_CAPABILITIES, FILES_UPLOAD_EN_US, FILES_UPLOAD_ERROR_MESSAGES, FILES_UPLOAD_PT_BR, FILES_UPLOAD_TEXTS, FilesApiClient, FilesApiUploadPortAdapter, PRAXIS_FILES_API_UPLOAD_PORT_OPTIONS, PRAXIS_FILES_UPLOAD_AUTHORING_MANIFEST, PRAXIS_FILES_UPLOAD_COMPONENT_METADATA, PdxFilesUploadFieldComponent, PraxisFilesUpload, PraxisFilesUploadConfigEditor, PraxisFilesUploadWidgetConfigEditor, PresignedUploaderService, ScanStatus, TRANSLATE_LIKE, acceptValidator, createPraxisFilesUploadI18nConfig, getPrimaryErrorItem, isErrorEnvelope, maxBulkSizeValidator, maxFileSizeValidator, maxFilesPerBulkValidator, providePraxisFilesApiUploadPort, providePraxisFilesUploadI18n, providePraxisFilesUploadMetadata, resolvePraxisFilesUploadText };