UNPKG

@uploadcare/file-uploader

Version:

Building blocks for Uploadcare products integration

1,562 lines (1,522 loc) 65.5 kB
import { BaseComponent } from '@symbiotejs/symbiote'; export { BaseComponent, Data, UID } from '@symbiotejs/symbiote'; import * as _uploadcare_upload_client from '@uploadcare/upload-client'; import { UploadcareFile, Metadata, UploadError, NetworkError, UploadcareGroup, FileFromOptions } from '@uploadcare/upload-client'; export { Metadata, NetworkError, UploadError, UploadcareError, UploadcareFile, UploadcareGroup } from '@uploadcare/upload-client'; import { TelemetryRequest } from '@uploadcare/quality-insights'; declare class A11y { private _destroyKeyUX; private readonly _scopedWindow; constructor(); registerBlock(scope: Block): void; destroy(): void; } type LocaleChangeCallback = () => void; declare class LocaleManager { private _blockInstance; private _localeName; private _callbacks; private _boundBlocks; constructor(blockInstance: Block); onLocaleChange(callback: LocaleChangeCallback): () => void; bindL10n(block: Block, key: string, resolver: LocaleChangeCallback): void; destroyL10nBindings(block: Block): void; destroy(): void; } declare class Modal extends Block { static styleAttrs: string[]; static StateConsumerScope: string; private _mouseDownTarget; handleModalOpen: ModalCb; handleModalClose: ModalCb; handleModalCloseAll: ModalCb; constructor(); _handleBackdropClick: () => void; _closeDialog: () => void; _handleDialogClose: () => void; _handleDialogMouseDown: (e: MouseEvent) => void; _handleDialogMouseUp: (e: MouseEvent) => void; show(): void; hide(): void; private _handleModalOpen; private _handleModalClose; private _handleModalCloseAll; initCallback(): void; destroyCallback(): void; } declare const ModalEvents: Readonly<{ readonly ADD: "modal:add"; readonly DELETE: "modal:delete"; readonly OPEN: "modal:open"; readonly CLOSE: "modal:close"; readonly CLOSE_ALL: "modal:closeAll"; readonly DESTROY: "modal:destroy"; }>; type ModalId = ActivityType; type ModalCb = (data: { id: ModalId; modal: Modal; }) => void; type ModalEventType = (typeof ModalEvents)[keyof typeof ModalEvents]; declare class ModalManager { private _modals; private _activeModals; private _subscribers; private _block; constructor(block: Block); private _debugPrint; /** * Register a modal with the manager * @param id Unique identifier for the modal * @param modal Modal component instance */ registerModal(id: ModalId, modal: Modal): void; /** Remove a modal by ID. */ deleteModal(id: ModalId): boolean; /** Open a modal by its ID. */ open(id: ModalId): boolean; /** Close a specific modal by ID. */ close(id: ModalId): boolean; /** Toggle a modal - open if closed, close if open. */ toggle(id: ModalId): boolean; /** True if there are any active modals. */ get hasActiveModals(): boolean; /** Close the most recently opened modal and return to the previous one. */ back(): boolean; /** Close all open modals. */ closeAll(): number; /** * Subscribe to modal events * @returns Unsubscribe function */ subscribe(event: ModalEventType, callback: ModalCb): () => void; /** Unsubscribe from modal events */ unsubscribe(event: ModalEventType, callback: ModalCb | undefined): void; /** Notify all subscribers of a modal event. */ private _notify; /** Destroy the modal manager, clean up resources */ destroy(): void; } type TelemetryState = TelemetryRequest & { eventTimestamp: number; }; type TelemetryEventBody = Partial<Pick<TelemetryState, 'payload' | 'config'>> & { modalId?: string; eventType?: EventKey; }; declare class TelemetryManager { private readonly _sessionId; private readonly _telemetryInstance; private readonly _block; private _config; private _initialized; private _lastPayload; private readonly _queue; constructor(block: Block); private _init; private _setConfig; private _formattingPayload; private _excludedEvents; sendEvent(body: TelemetryEventBody): void; sendEventError(error: unknown, context?: string): void; /** * Method to send telemetry event for Cloud Image Editor. */ sendEventCloudImageEditor(e: MouseEvent, tabId: string, options?: Record<string, unknown>): void; /** * Deeply compares two objects and returns true if they are equal, false otherwise. */ private _checkObj; private get _timestamp(); private get _solution(); private get _activity(); } declare class Block extends BaseComponent<any> { private __cfgProxy?; protected l10nProcessorSubs: Map<string, Set<{ remove: () => void; }>>; static StateConsumerScope: string | null; static styleAttrs: string[]; protected requireCtxName: boolean; activityType: ActivityType; init$: {}; l10n(str: string, variables?: Record<string, string | number>): string; private pluralize; protected bindL10n(key: string, resolver: () => void): void; constructor(); emit(type: Parameters<EventEmitter['emit']>[0], payload?: Parameters<EventEmitter['emit']>[1], options?: Parameters<EventEmitter['emit']>[2]): void; hasBlockInCtx(callback: (block: Block) => boolean): boolean; setOrAddState(prop: string, newVal: any): void; connectedCallback(): void; disconnectedCallback(): void; initCallback(): void; get testId(): string; get modalManager(): ModalManager | undefined; get telemetryManager(): TelemetryManager | { sendEvent: () => void; sendEventCloudImageEditor: () => void; sendEventError: () => void; }; protected get localeManager(): LocaleManager | null; protected get a11y(): A11y | null; protected get blocksRegistry(): Set<Block>; destroyCallback(): void; /** * Called when the last block is removed from the context. Note that inheritors must run their callback before that. */ protected destroyCtxCallback(): void; protected proxyUrl(url: string): Promise<string>; get cfg(): ConfigType; subConfigValue<T extends keyof ConfigType>(key: T, callback: (value: ConfigType[T]) => void): void; debugPrint(...args: unknown[]): void; static reg(name?: string): void; } declare const EventType: Readonly<{ readonly INIT_SOLUTION: "init-solution"; readonly CHANGE_CONFIG: "change-config"; readonly FILE_ADDED: "file-added"; readonly FILE_REMOVED: "file-removed"; readonly FILE_UPLOAD_START: "file-upload-start"; readonly FILE_UPLOAD_PROGRESS: "file-upload-progress"; readonly FILE_UPLOAD_SUCCESS: "file-upload-success"; readonly FILE_UPLOAD_FAILED: "file-upload-failed"; readonly FILE_URL_CHANGED: "file-url-changed"; readonly MODAL_OPEN: "modal-open"; readonly MODAL_CLOSE: "modal-close"; readonly DONE_CLICK: "done-click"; readonly UPLOAD_CLICK: "upload-click"; readonly ACTIVITY_CHANGE: "activity-change"; readonly COMMON_UPLOAD_START: "common-upload-start"; readonly COMMON_UPLOAD_PROGRESS: "common-upload-progress"; readonly COMMON_UPLOAD_SUCCESS: "common-upload-success"; readonly COMMON_UPLOAD_FAILED: "common-upload-failed"; readonly CHANGE: "change"; readonly GROUP_CREATED: "group-created"; }>; type EventKey = (typeof EventType)[keyof typeof EventType]; type EventPayload = { [EventType.FILE_ADDED]: OutputFileEntry<'idle'>; [EventType.FILE_REMOVED]: OutputFileEntry<'removed'>; [EventType.FILE_UPLOAD_START]: OutputFileEntry<'uploading'>; [EventType.FILE_UPLOAD_PROGRESS]: OutputFileEntry<'uploading'>; [EventType.FILE_UPLOAD_SUCCESS]: OutputFileEntry<'success'>; [EventType.FILE_UPLOAD_FAILED]: OutputFileEntry<'failed'>; [EventType.FILE_URL_CHANGED]: OutputFileEntry<'success'>; [EventType.MODAL_OPEN]: { modalId: ModalId; }; [EventType.MODAL_CLOSE]: { modalId: ModalId; hasActiveModals: boolean; }; [EventType.ACTIVITY_CHANGE]: { activity: ActivityType; }; [EventType.UPLOAD_CLICK]: void; [EventType.DONE_CLICK]: OutputCollectionState; [EventType.COMMON_UPLOAD_START]: OutputCollectionState<'uploading'>; [EventType.COMMON_UPLOAD_PROGRESS]: OutputCollectionState<'uploading'>; [EventType.COMMON_UPLOAD_SUCCESS]: OutputCollectionState<'success'>; [EventType.COMMON_UPLOAD_FAILED]: OutputCollectionState<'failed'>; [EventType.CHANGE]: OutputCollectionState; [EventType.GROUP_CREATED]: OutputCollectionState<'success', 'has-group'>; [EventType.INIT_SOLUTION]: void; [EventType.CHANGE_CONFIG]: void; }; declare class EventEmitter { private _timeoutStore; private _targets; private _debugPrint; constructor(debugPrint: (...args: unknown[]) => void); bindTarget(target: Block): void; unbindTarget(target: Block): void; private _dispatch; emit<T extends EventKey, TDebounce extends boolean | number | undefined = undefined>(type: T, payload?: TDebounce extends false | undefined ? EventPayload[T] : () => EventPayload[T], options?: { debounce?: TDebounce; }): void; } type EventMap = { [T in keyof EventPayload]: CustomEvent<EventPayload[T]>; }; type LocaleDefinition = Record<string, string>; type LocaleDefinitionResolver = () => Promise<LocaleDefinition>; declare const defineLocale: (localeName: string, definitionOrResolver: LocaleDefinition | LocaleDefinitionResolver) => void; declare function buildOutputCollectionState<TCollectionStatus extends OutputCollectionStatus, TGroupFlag extends GroupFlag = 'maybe-has-group'>(uploaderBlock: UploaderBlock): OutputCollectionState<TCollectionStatus, TGroupFlag>; type TypedSchema = Record<string, { type: unknown; value: unknown; nullable?: boolean; }>; type Constructor<T = any> = new (...args: any[]) => T; type ExtractType<T, V> = T extends StringConstructor ? string : T extends BooleanConstructor ? boolean : T extends NumberConstructor ? number : T extends ArrayConstructor ? V : T extends Constructor ? InstanceType<T> : T; type ExtractDataFromSchema<T extends TypedSchema> = { [K in keyof T]: ExtractType<T[K]['type'], T[K]['value']> | (T[K]['nullable'] extends true ? null : never); }; type ExtractKeysFromSchema<T extends TypedSchema> = Extract<keyof T, string>; declare class TypedData<T extends TypedSchema> { private __typedSchema; private __ctxId; private __schema; private __data; constructor(typedSchema: T, ctxName?: string); get uid(): string; setValue<K extends ExtractKeysFromSchema<T>>(prop: K, value: ExtractDataFromSchema<T>[K]): void; setMultipleValues(updObj: Partial<ExtractDataFromSchema<T>>): void; getValue<K extends ExtractKeysFromSchema<T>>(prop: K): ExtractDataFromSchema<T>[K]; subscribe<K extends ExtractKeysFromSchema<T>>(prop: K, handler: (newVal: ExtractDataFromSchema<T>[K]) => void): { remove: () => void; callback: Function; }; remove(): void; } declare const uploadEntrySchema: Readonly<{ file: Readonly<{ type: { new (fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File; prototype: File; }; value: null; nullable: true; }>; externalUrl: Readonly<{ type: StringConstructor; value: null; nullable: true; }>; fileName: Readonly<{ type: StringConstructor; value: null; nullable: true; }>; fileSize: Readonly<{ type: NumberConstructor; value: null; nullable: true; }>; lastModified: Readonly<{ type: NumberConstructor; value: number; }>; uploadProgress: Readonly<{ type: NumberConstructor; value: 0; }>; uuid: Readonly<{ type: StringConstructor; value: null; nullable: true; }>; isImage: Readonly<{ type: BooleanConstructor; value: false; }>; mimeType: Readonly<{ type: StringConstructor; value: null; nullable: true; }>; ctxName: Readonly<{ type: StringConstructor; value: null; nullable: true; }>; cdnUrl: Readonly<{ type: StringConstructor; value: null; nullable: true; }>; cdnUrlModifiers: Readonly<{ type: StringConstructor; value: null; nullable: true; }>; fileInfo: Readonly<{ type: typeof UploadcareFile; value: null; nullable: true; }>; isUploading: Readonly<{ type: BooleanConstructor; value: false; }>; abortController: Readonly<{ type: { new (): AbortController; prototype: AbortController; }; value: null; nullable: true; }>; thumbUrl: Readonly<{ type: StringConstructor; value: null; nullable: true; }>; silent: Readonly<{ type: BooleanConstructor; value: false; }>; source: Readonly<{ type: StringConstructor; value: null; nullable: true; }>; fullPath: Readonly<{ type: StringConstructor; value: null; nullable: true; }>; metadata: Readonly<{ type: ObjectConstructor; value: null; nullable: true; }>; errors: Readonly<{ type: ArrayConstructor; value: OutputErrorFile[]; }>; uploadError: Readonly<{ type: ErrorConstructor; value: null; nullable: true; }>; isRemoved: Readonly<{ type: BooleanConstructor; value: false; }>; isQueuedForUploading: Readonly<{ type: BooleanConstructor; value: false; }>; isValidationPending: Readonly<{ type: BooleanConstructor; value: false; }>; isQueuedForValidation: Readonly<{ type: BooleanConstructor; value: false; }>; }>; type UploadEntryData = ExtractDataFromSchema<typeof uploadEntrySchema>; type UploadEntryTypedData = TypedData<typeof uploadEntrySchema>; type UploadEntryKeys = ExtractKeysFromSchema<typeof uploadEntrySchema>; type FuncFileValidator = (outputEntry: OutputFileEntry, api: UploaderPublicApi, options?: { signal?: AbortSignal; }) => undefined | OutputErrorFile | Promise<undefined | OutputErrorFile>; type FileValidatorDescriptor = { runOn: 'add' | 'upload' | 'change'; validator: FuncFileValidator; }; type FileValidator = FileValidatorDescriptor | FuncFileValidator; type FuncCollectionValidator = (collection: ReturnType<typeof buildOutputCollectionState<OutputCollectionStatus>>, api: UploaderPublicApi) => undefined | OutputErrorCollection; declare class ValidationManager { private _blockInstance; private _uploadCollection; private _commonFileValidators; private _commonCollectionValidators; private _queue; private _runQueueDebounced; private _entryValidationState; constructor(blockInstance: UploaderBlock); runFileValidators(runOn: FileValidatorDescriptor['runOn'], entryIds?: string[]): void; runCollectionValidators(): void; cleanupValidationForEntry(entry: TypedData<typeof uploadEntrySchema>): void; private _runFileValidatorsForEntry; private _addCustomTypeToValidationError; private _getEntryValidationState; private _getValidatorDescriptors; private _getValidatorDescriptorsForEntry; } type CameraMode = 'photo' | 'video'; type CameraStatus = 'shot' | 'retake' | 'accept' | 'play' | 'stop' | 'pause' | 'resume'; declare class CameraSource extends UploaderBlock { couldBeCtxOwner: boolean; activityType: "camera"; private _unsubPermissions; private _capturing; private _chunks; private _mediaRecorder; private _stream; private _selectedAudioId; private _selectedCameraId; private _activeTab; private _options; private _canvas; private _ctx; private _cameraDevices; private _audioDevices; private _permissionResponses; constructor(); _chooseActionWithCamera: () => void; _updateTimer: () => void; _startTimer: () => void; _stopTimer: () => void; _startTimeline: () => void; _stopTimeline: () => void; _animationFrameId: number | null; _startRecording: () => void; private _stopRecording; /** This method is used to toggle recording pause/resume */ _toggleRecording: () => void; _toggleEnableAudio: () => void; /** * Previewing the video that was recorded on the camera */ private _previewVideo; _retake: () => void; _accept: () => void; _handlePhoto: (status: CameraStatus) => void; _handleVideo: (status: CameraStatus) => void; private _setCameraState; private _shot; private _handleActiveTab; private _createFile; _guessExtensionByMime(mime: string | undefined): string; /** * The send file to the server */ _toSend: (file: File) => void; private get _cameraModes(); private _setPermissionsState; _makeStreamInactive: () => boolean; _stopCapture: () => void; _capture: () => Promise<void>; _handlePermissionsChange: () => void; _permissionAccess: () => Promise<void>; _getPermission: () => void; _requestDeviceAccess: () => Promise<void>; _getDevices: () => Promise<void>; _onActivate: () => Promise<void>; _onDeactivate: () => Promise<void>; _handleCameraModes: (cameraModes: CameraMode[]) => void; initCallback(): void; _destroy(): void; destroyCallback(): Promise<void>; } /** * Config keys that can't be passed as attribute (because they are object or function) */ declare const complexConfigKeys: readonly ["metadata", "localeDefinitionOverride", "secureUploadsSignatureResolver", "secureDeliveryProxyUrlResolver", "iconHrefResolver", "fileValidators", "collectionValidators", "mediaRecorderOptions"]; /** Mapping of attribute names to state */ declare const attrStateMapping: Record<string, string>; declare class Config extends Block { requireCtxName: boolean; constructor(); private _flushValueToAttribute; private _flushValueToState; private _setValue; private _getValue; _assertSameValueDifferentReference(key: string, previousValue: unknown, nextValue: unknown): void; initCallback(): void; attributeChangedCallback(name: keyof typeof attrStateMapping, oldVal: string, newVal: string): void; } interface Config extends ConfigType { } type FilesViewMode = 'grid' | 'list'; declare class UploadList extends UploaderBlock { couldBeCtxOwner: boolean; historyTracked: boolean; activityType: "upload-list"; constructor(); private _throttledHandleCollectionUpdate; private _updateUploadsState; private _getHeaderText; get couldOpenActivity(): boolean; initCallback(): void; destroyCallback(): void; } declare const ExternalUploadSource: Readonly<{ readonly FACEBOOK: "facebook"; readonly DROPBOX: "dropbox"; readonly GDRIVE: "gdrive"; readonly GPHOTOS: "gphotos"; readonly FLICKR: "flickr"; readonly VK: "vk"; readonly EVERNOTE: "evernote"; readonly BOX: "box"; readonly ONEDRIVE: "onedrive"; readonly HUDDLE: "huddle"; }>; declare const UploadSource: Readonly<{ readonly FACEBOOK: "facebook"; readonly DROPBOX: "dropbox"; readonly GDRIVE: "gdrive"; readonly GPHOTOS: "gphotos"; readonly FLICKR: "flickr"; readonly VK: "vk"; readonly EVERNOTE: "evernote"; readonly BOX: "box"; readonly ONEDRIVE: "onedrive"; readonly HUDDLE: "huddle"; readonly MOBILE_VIDEO_CAMERA: "mobile-video-camera"; readonly MOBILE_PHOTO_CAMERA: "mobile-photo-camera"; readonly LOCAL: "local"; readonly DROP_AREA: "drop-area"; readonly CAMERA: "camera"; readonly EXTERNAL: "external"; readonly API: "js-api"; readonly URL: "url"; readonly DRAW: "draw"; }>; type SourceTypes = (typeof UploadSource)[keyof typeof UploadSource]; declare const CameraSourceTypes: Readonly<{ PHOTO: "photo"; VIDEO: "video"; }>; type ModeCameraType = (typeof CameraSourceTypes)[keyof typeof CameraSourceTypes]; type ApiAddFileCommonOptions = { silent?: boolean; fileName?: string; source?: string; }; declare class UploaderPublicApi { private _ctx; constructor(ctx: UploaderBlock); private get _uploadCollection(); get cfg(): ConfigType; get l10n(): (str: string, variables?: Record<string, string | number>) => string; /** * TODO: Probably we should not allow user to override `source` property */ addFileFromUrl: (url: string, { silent, fileName, source }?: ApiAddFileCommonOptions) => OutputFileEntry<"idle">; addFileFromUuid: (uuid: string, { silent, fileName, source }?: ApiAddFileCommonOptions) => OutputFileEntry<"idle">; addFileFromCdnUrl: (cdnUrl: string, { silent, fileName, source }?: ApiAddFileCommonOptions) => OutputFileEntry<"idle">; addFileFromObject: (file: File, { silent, fileName, source, fullPath, }?: ApiAddFileCommonOptions & { fullPath?: string; }) => OutputFileEntry<"idle">; removeFileByInternalId: (internalId: string) => void; removeAllFiles(): void; uploadAll: () => void; openSystemDialog: (options?: { captureCamera?: boolean; modeCamera?: ModeCameraType; }) => void; getOutputItem<TStatus extends OutputFileStatus>(entryId: string): OutputFileEntry<TStatus>; getOutputCollectionState<TStatus extends OutputCollectionStatus>(): ReturnType<typeof buildOutputCollectionState<TStatus>>; initFlow: (force?: boolean) => void; doneFlow: () => void; setCurrentActivity: <T extends ActivityType>(activityType: T, ...params: T extends keyof ActivityParamsMap ? [ActivityParamsMap[T]] : T extends RegisteredActivityType ? [undefined?] : [any?]) => void; getCurrentActivity: () => ActivityType; setModalState: (opened: boolean) => void; private get _sourceList(); } type MetadataCallback = (fileEntry: OutputFileEntry) => Promise<Metadata> | Metadata; type LocaleDefinitionOverride = Record<string, LocaleDefinition>; type SecureDeliveryProxyUrlResolver = (previewUrl: string, urlParts: { uuid: string; cdnUrlModifiers: string; fileName: string; }) => Promise<string> | string; type SecureUploadsSignatureAndExpire = { secureSignature: string; secureExpire: string; }; type SecureUploadsSignatureResolver = () => Promise<SecureUploadsSignatureAndExpire | null>; type IconHrefResolver = (iconName: string) => string; type FileValidators = FileValidator[]; type CollectionValidators = FuncCollectionValidator[]; type ConfigType = { /** * Your project’s Public Key. */ pubkey: string; /** * Allow multiple file uploads. */ multiple: boolean; /** * Minimum number of files to upload. */ multipleMin: number; /** * Maximum number of files to upload. */ multipleMax: number; /** * Require user confirmation before uploading. */ confirmUpload: boolean; /** * Allow only image files. */ imgOnly: boolean; /** * Native file input accept attribute value. Also affects client validation settings. */ accept: string; /** * Preferred types for external sources. * See [here](https://uploadcare.com/docs/file-uploader/options/#external-sources-preferred-types) */ externalSourcesPreferredTypes: string; /** * Provide custom CSS to the social sources iframe */ externalSourcesEmbedCss: string; /** * Store uploaded files. */ store: boolean | 'auto'; /** * Mirror the camera view. */ cameraMirror: boolean; /** * Default camera capture mode. */ cameraCapture: 'user' | 'environment' | ''; /** * List of sources for file uploads. */ sourceList: string; /** * Top-level origin for the uploader. * This is used for Google Drive Picker if there is no access to the origin due to the cross-origin policy. */ topLevelOrigin: string; /** * Maximum size of local files in bytes. */ maxLocalFileSizeBytes: number; /** * Thumbnail size. */ thumbSize: number; /** * Show the upload list even if it is empty. */ showEmptyList: boolean; /** * Use local image editor. */ useLocalImageEditor: boolean; /** * Enable cloud image editing. */ useCloudImageEditor: boolean; /** * Tabs to show in the cloud image editor. * * @default 'crop, tuning, filters' */ cloudImageEditorTabs: string; /** * Remove copyright information. */ removeCopyright: boolean; /** * Defines the crop behavior. When uploading images, your users can select a crop area with a defined aspect ratio. */ cropPreset: string; /** * Image shrink options. */ imageShrink: string; /** * Lock scroll when modal is open. */ modalScrollLock: boolean; /** * Show strokes on modal backdrop. */ modalBackdropStrokes: boolean; /** * Wrap the source list. */ sourceListWrap: boolean; /** * Key to revoke Custom OAuth access. See [OAuth docs](https://uploadcare.com/docs/upload-sources/#oauth) for details. */ remoteTabSessionKey: string; /** * Set custom CNAME. */ cdnCname: string; /** * Set CNAME base domain for prefixed CDN URLs. */ cdnCnamePrefixed: string; /** * Set a custom upload URL. */ baseUrl: string; /** * Set a custom social sources URL. */ socialBaseUrl: string; /** * Secure signature for uploads. */ secureSignature: string; /** * Expiry time for secure uploads. */ secureExpire: string; /** * Proxy URL for secure delivery. */ secureDeliveryProxy: string; /** * Maximum number of retry attempts for throttled requests. */ retryThrottledRequestMaxTimes: number; /** * Maximum number of retry attempts for network errors. */ retryNetworkErrorMaxTimes: number; /** * Minimum file size for multipart uploads. */ multipartMinFileSize: number; /** * Chunk size for multipart uploads. */ multipartChunkSize: number; /** * Maximum number of concurrent requests. */ maxConcurrentRequests: number; /** * Maximum number of concurrent multipart requests. */ multipartMaxConcurrentRequests: number; /** * Maximum number of attempts for multipart uploads. */ multipartMaxAttempts: number; /** * Check for URL duplicates. */ checkForUrlDuplicates: boolean; /** * Save URL for recurrent uploads. */ saveUrlForRecurrentUploads: boolean; /** * Group output files. */ groupOutput: boolean; /** * User agent integration string. */ userAgentIntegration: string; /** * Enable debug mode. */ debug: boolean; /** * Locale name for the uploader. */ localeName: string; /** * Expiry threshold for secure uploads. */ secureUploadsExpireThreshold: number; /** * Metadata for the file. */ metadata: Metadata | MetadataCallback | null; /** * Override locale definitions. */ localeDefinitionOverride: LocaleDefinitionOverride | null; /** * Resolver for secure uploads signature. */ secureUploadsSignatureResolver: SecureUploadsSignatureResolver | null; /** * Resolver for secure delivery proxy URL. */ secureDeliveryProxyUrlResolver: SecureDeliveryProxyUrlResolver | null; /** * Resolver for icon href. */ iconHrefResolver: IconHrefResolver | null; /** * Validators for individual files. */ fileValidators: FileValidators; /** * Validators for file collections. */ collectionValidators: CollectionValidators; /** * Timeout for async validation functions, in milliseconds. */ validationTimeout: number; /** * The number of files to validate concurrently. */ validationConcurrency: number; /** * The camera modes to enable in the camera modal, * it is possible to select photo or video capture. * The first mode is the default mode. * @default 'photo,video' */ cameraModes: string; /** * The default tab to open in the camera modal, * it is possible to select video or photo capture * @default 'null' * @deprecated - use `cameraModes` instead */ defaultCameraMode: CameraMode | null; /** * Enable audio recording. * @default true */ enableAudioRecording: boolean; /** * Enable video recording. * @deprecated - use `cameraModes` instead * @default null */ enableVideoRecording: boolean | null; /** * The maximum duration of the video recording in seconds * @default null */ maxVideoRecordingDuration: number | null; /** * A dictionary object that can contain * the following properties from MediaRecorderOptions */ mediaRecorderOptions: MediaRecorderOptions | null; filesViewMode: FilesViewMode; gridShowFileNames: boolean; cloudImageEditorAutoOpen: boolean; qualityInsights: boolean; cloudImageEditorMaskHref: string | null; /** * Adds data-testid attributes to the each block. Needed for testing purposes. * @default false */ testMode: boolean; }; type ConfigComplexType = Pick<ConfigType, (typeof complexConfigKeys)[number]>; type ConfigPlainType = Omit<ConfigType, keyof ConfigComplexType>; type ConfigAttributesType = KebabCaseKeys<ConfigPlainType> & LowerCaseKeys<ConfigPlainType>; type KebabCase$1<S extends string> = S extends `${infer C}${infer T}` ? T extends Uncapitalize<T> ? `${Uncapitalize<C>}${KebabCase$1<T>}` : `${Uncapitalize<C>}-${KebabCase$1<T>}` : S; type KebabCaseKeys<T extends Record<string, unknown>> = { [Key in keyof T as KebabCase$1<Key & string>]: T[Key]; }; type LowerCase<S extends string> = Lowercase<S>; type LowerCaseKeys<T extends Record<string, unknown>> = { [Key in keyof T as Lowercase<Key & string>]: T[Key]; }; type OutputFileStatus = 'idle' | 'uploading' | 'success' | 'failed' | 'removed'; type OutputCustomErrorType = 'CUSTOM_ERROR'; type OutputFileErrorType = OutputCustomErrorType | 'NOT_AN_IMAGE' | 'FORBIDDEN_FILE_TYPE' | 'FILE_SIZE_EXCEEDED' | 'UPLOAD_ERROR' | 'NETWORK_ERROR' | 'UNKNOWN_ERROR'; type OutputCollectionErrorType = OutputCustomErrorType | 'SOME_FILES_HAS_ERRORS' | 'TOO_MANY_FILES' | 'TOO_FEW_FILES'; type OutputFileErrorPayload = { entry: OutputFileEntry; }; type OutputErrorTypePayload = { NOT_AN_IMAGE: OutputFileErrorPayload; FORBIDDEN_FILE_TYPE: OutputFileErrorPayload; FILE_SIZE_EXCEEDED: OutputFileErrorPayload; SOME_FILES_HAS_ERRORS: {}; TOO_MANY_FILES: { min: number; max: number; total: number; }; TOO_FEW_FILES: { min: number; max: number; total: number; }; UPLOAD_ERROR: OutputFileErrorPayload & { error: UploadError; }; NETWORK_ERROR: OutputFileErrorPayload & { error: NetworkError; }; UNKNOWN_ERROR: OutputFileErrorPayload & { error?: Error; }; CUSTOM_ERROR: Record<string, unknown>; }; type OutputError<T extends OutputFileErrorType | OutputCollectionErrorType> = T extends OutputCustomErrorType ? { type?: T; message: string; payload?: OutputErrorTypePayload[T]; } : T extends keyof OutputErrorTypePayload ? { type: T; message: string; payload?: OutputErrorTypePayload[T]; } : never; type OutputErrorFile = OutputError<OutputFileErrorType>; type OutputErrorCollection = OutputError<OutputCollectionErrorType>; type OutputFileEntry<TStatus extends OutputFileStatus = OutputFileStatus> = { status: TStatus; internalId: string; name: string; size: number; isImage: boolean; mimeType: string; metadata: Metadata | null; file: File | Blob | null; externalUrl: string | null; uploadProgress: number; fullPath: string | null; source: SourceTypes | null; isValidationPending: boolean; } & ({ status: 'success'; fileInfo: UploadcareFile; uuid: string; cdnUrl: string; cdnUrlModifiers: string; isUploading: false; isSuccess: true; isFailed: false; isRemoved: false; errors: []; } | { status: 'failed'; fileInfo: UploadcareFile | null; uuid: string | null; cdnUrl: string | null; cdnUrlModifiers: string | null; isUploading: false; isSuccess: false; isFailed: true; isRemoved: false; errors: OutputError<OutputFileErrorType>[]; } | { status: 'uploading'; fileInfo: null; uuid: null; cdnUrl: null; cdnUrlModifiers: null; isUploading: true; isSuccess: false; isFailed: false; isRemoved: false; errors: []; } | { status: 'removed'; fileInfo: UploadcareFile | null; uuid: string | null; cdnUrl: string | null; cdnUrlModifiers: string | null; isUploading: false; isSuccess: false; isFailed: false; isRemoved: true; errors: OutputError<OutputFileErrorType>[]; } | { status: 'idle'; fileInfo: null; uuid: null; cdnUrl: null; cdnUrlModifiers: null; isUploading: false; isSuccess: false; isFailed: false; isRemoved: false; errors: []; }); type OutputCollectionStatus = 'idle' | 'uploading' | 'success' | 'failed'; type GroupFlag = 'has-group' | 'maybe-has-group'; type OutputCollectionState<TStatus extends OutputCollectionStatus = OutputCollectionStatus, TGroupFlag extends GroupFlag = 'maybe-has-group'> = { status: TStatus; totalCount: number; successCount: number; failedCount: number; uploadingCount: number; progress: number; successEntries: OutputFileEntry<'success'>[]; failedEntries: OutputFileEntry<'failed'>[]; uploadingEntries: OutputFileEntry<'uploading'>[]; idleEntries: OutputFileEntry<'idle'>[]; } & (TGroupFlag extends 'has-group' ? { group: UploadcareGroup; } : TGroupFlag extends 'maybe-has-group' ? { group: UploadcareGroup | null; } : never) & ({ status: 'idle'; isFailed: false; isUploading: false; isSuccess: false; errors: []; allEntries: OutputFileEntry<'idle' | 'success'>[]; } | { status: 'uploading'; isFailed: false; isUploading: true; isSuccess: false; errors: []; allEntries: OutputFileEntry[]; } | { status: 'success'; isFailed: false; isUploading: false; isSuccess: true; errors: []; allEntries: OutputFileEntry<'success'>[]; } | { status: 'failed'; isFailed: true; isUploading: false; isSuccess: false; errors: OutputError<OutputCollectionErrorType>[]; allEntries: OutputFileEntry[]; }); declare class SecureUploadsManager { private readonly _block; private _secureToken; constructor(block: UploaderBlock); private _debugPrint; getSecureToken(): Promise<SecureUploadsSignatureAndExpire | null>; } type ChangeMap<T extends TypedSchema> = Record<keyof T, Set<string>>; type TypedCollectionPropertyObserver<T extends TypedSchema> = (changeMap: ChangeMap<T>) => void; type TypedCollectionObserverHandler<T extends TypedSchema> = (list: string[], added: Set<TypedData<T>>, removed: Set<TypedData<T>>) => void; type TypedCollectionOptions<T extends TypedSchema> = { typedSchema: T; watchList?: ExtractKeysFromSchema<T>[]; handler?: TypedCollectionObserverHandler<T>; ctxName?: string; }; declare class TypedCollection<T extends TypedSchema> { private __typedSchema; private __ctxId; private __data; private __watchList; private __subsMap; private __propertyObservers; private __collectionObservers; private __items; private __removed; private __added; private __observeTimeout?; private __notifyTimeout?; private __notifyObservers; constructor(options: TypedCollectionOptions<T>); notify(): void; observeCollection(handler: TypedCollectionObserverHandler<T>): () => void; unobserveCollection(handler: TypedCollectionObserverHandler<T>): void; add(init: Partial<ExtractDataFromSchema<T>>): string; read(id: string): TypedData<T> | null; readProp<K extends ExtractKeysFromSchema<T>>(id: string, propName: K): ExtractDataFromSchema<T>[K] | null; publishProp<K extends ExtractKeysFromSchema<T>>(id: string, propName: K, value: ExtractDataFromSchema<T>[K]): void; remove(id: string): void; clearAll(): void; observeProperties(handler: TypedCollectionPropertyObserver<T>): () => void; unobserveProperties(handler: TypedCollectionPropertyObserver<T>): void; findItems(checkFn: (item: TypedData<T>) => boolean): string[]; items(): string[]; get size(): number; destroy(): void; } declare class UploaderBlock extends ActivityBlock { static extSrcList: Readonly<typeof ExternalUploadSource>; static sourceTypes: Readonly<typeof UploadSource>; protected couldBeCtxOwner: boolean; private isCtxOwner; private _unobserveCollection?; private _unobserveCollectionProperties?; init$: { '*commonProgress': number; '*uploadList': never[]; '*uploadQueue': _uploadcare_upload_client.Queue; '*collectionErrors': OutputErrorCollection[]; '*collectionState': OutputCollectionState | null; '*groupInfo': _uploadcare_upload_client.UploadcareGroup | null; '*uploadTrigger': Set<string>; '*secureUploadsManager': SecureUploadsManager | null; '*currentActivity': null; '*currentActivityParams': {}; '*history': never[]; '*historyBack': null; '*closeModal': () => void; }; private get hasCtxOwner(); initCallback(): void; protected get validationManager(): ValidationManager; get api(): UploaderPublicApi; getAPI(): UploaderPublicApi; get uploadCollection(): TypedCollection<typeof uploadEntrySchema>; destroyCtxCallback(): void; disconnectedCallback(): void; connectedCallback(): void; destroyCallback(): void; private _initCtxOwner; private _observeUploadCollection; private _unobserveUploadCollection; private _createGroup; private _flushOutputItems; private _handleCollectionUpdate; private _handleCollectionPropertiesUpdate; private _flushCommonUploadProgress; openCloudImageEditor(): void; private setInitialCrop; protected getMetadataFor(entryId: string): Promise<_uploadcare_upload_client.Metadata | undefined>; protected getUploadClientOptions(): Promise<FileFromOptions>; getOutputData(): OutputFileEntry[]; } /** * Image size */ interface ImageSize { width: number; height: number; } interface Transformations { enhance?: number; brightness?: number; exposure?: number; gamma?: number; contrast?: number; saturation?: number; vibrance?: number; warmth?: number; rotate?: number; mirror?: boolean; flip?: boolean; filter?: { name: string; amount: number; }; crop?: { dimensions: [number, number]; coords: [number, number]; }; } interface ApplyResult { originalUrl: string; cdnUrlModifiers: string; cdnUrl: string; transformations: Transformations; } interface CropAspectRatio { type: 'aspect-ratio'; width: number; height: number; id: string; hasFreeform?: boolean; } type ActivityParams$1 = { internalId: string; }; declare class CloudImageEditorActivity extends UploaderBlock { couldBeCtxOwner: boolean; activityType: "cloud-image-edit"; private _entry?; private _instance?; get activityParams(): ActivityParams$1; initCallback(): void; handleApply(e: CustomEvent<ApplyResult>): void; handleCancel(): void; mountEditor(): void; unmountEditor(): void; } type ActivityParams = { externalSourceType: string; }; declare class ExternalSource extends UploaderBlock { couldBeCtxOwner: boolean; activityType: "external"; private _messageBridge?; constructor(); get activityParams(): ActivityParams; initCallback(): void; private extractUrlFromSelectedFile; private handleToolbarStateChange; private handleSelectedFilesChange; private handleIframeLoad; private applyTheme; private applyEmbedCss; private setupL10n; private remoteUrl; private mountIframe; private unmountIframe; private resetSelectionStatus; } declare const ACTIVE_PROP = "___ACTIVITY_IS_ACTIVE___"; type ActivityParamsMap = { 'cloud-image-edit': ActivityParams$1; external: ActivityParams; }; declare class ActivityBlock extends Block { protected historyTracked: boolean; private [ACTIVE_PROP]?; init$: { '*currentActivity': null; '*currentActivityParams': {}; '*history': never[]; '*historyBack': null; '*closeModal': () => void; }; _debouncedHistoryFlush: (() => void) & { cancel: () => void; }; private _deactivate; private _activate; initCallback(): void; private _historyFlush; private _isActivityRegistered; private static _activityCallbacks; static activities: Readonly<{ START_FROM: 'start-from'; CAMERA: 'camera'; DRAW: 'draw'; UPLOAD_LIST: 'upload-list'; URL: 'url'; CLOUD_IMG_EDIT: 'cloud-image-edit'; EXTERNAL: 'external'; }>; get isActivityActive(): boolean; get couldOpenActivity(): boolean; /** TODO: remove name argument */ registerActivity(_name: string, options?: { onActivate?: () => void; onDeactivate?: () => void; }): void; unregisterActivity(): void; destroyCallback(): void; get activityKey(): string; get activityParams(): ActivityParamsMap[keyof ActivityParamsMap]; get initActivity(): string; get doneActivity(): string; historyBack(): void; } type RegisteredActivityType = (typeof ActivityBlock)['activities'][keyof (typeof ActivityBlock)['activities']]; type ActivityType = RegisteredActivityType | (string & {}) | null; declare function defineComponents(blockExports: Record<string, any>): void; declare const UC_WINDOW_KEY = "UC"; type IndexModule = Record<string, any>; declare global { interface Window { [UC_WINDOW_KEY]?: IndexModule; } } /** * @param url File Uploader pack url * @param [register] Register connected package, if it not registered yet */ declare function loadFileUploaderFrom(url: string, register?: boolean): Promise<IndexModule | null>; declare class SolutionBlock extends Block { static styleAttrs: string[]; protected requireCtxName: boolean; init$: { '*solution': string | null; '*commonProgress': number; '*uploadList': never[]; '*uploadQueue': _uploadcare_upload_client.Queue; '*collectionErrors': OutputErrorCollection[]; '*collectionState': OutputCollectionState | null; '*groupInfo': _uploadcare_upload_client.UploadcareGroup | null; '*uploadTrigger': Set<string>; '*secureUploadsManager': SecureUploadsManager | null; '*currentActivity': null; '*currentActivityParams': {}; '*history': never[]; '*historyBack': null; '*closeModal': () => void; }; private static _template; initCallback(): void; static set template(value: string); static get template(): string; } declare class ActivityHeader extends ActivityBlock { } declare class CloudImageEditorBlock extends Block { ctxOwner: boolean; static styleAttrs: string[]; private _debouncedShowLoader; constructor(); private _showLoader; /** * To proper work, we need non-zero size the element. So, we'll wait for it. */ private _waitForSize; initCallback(): void; updateImage(): Promise<void>; initEditor(): Promise<void>; } declare class CropFrame extends Block { private readonly _handlePointerUp; private readonly _handlePointerMove; private readonly _handleSvgPointerMove; private _backdropMask?; private _backdropMaskInner?; private _frameThumbs?; private _frameGuides?; private _draggingThumb?; private _hoverThumb?; private _dragStartPoint?; private _dragStartCrop?; private _frameImage?; private _guidesHidden; constructor(); private _shouldThumbBeDisabled; private _createBackdrop; /** * @private Super Tricky workaround for the chromium bug See * https://bugs.chromium.org/p/chromium/issues/detail?id=330815 */ private _resizeBackdrop; private _updateBackdrop; private _updateFrame; private _createThumb; private _createThumbs; private _createGuides; private _createFrame; private _handlePointerDown; private _handlePointerUp_; private _handlePointerMove_; private _calcCropBox; private _handleSvgPointerMove_; private _updateCursor; private _createMask; private _updateMask; private _render; toggleThumbs(visible: boolean): void; initCallback(): void; destroyCallback(): void; } declare class EditorButtonControl extends Block { private _titleEl?; constructor(); initCallback(): void; } declare class EditorFreeformButtonControl extends EditorButtonControl { initCallback(): void; handleClick(): void; } interface EditorAspectRatioButtonControl { get aspectRatio(): CropAspectRatio | undefined; set aspectRatio(value: CropAspectRatio | undefined); } declare class EditorAspectRatioButtonControl extends EditorButtonControl { constructor(); initCallback(): void; handleClick(): void; private _renderRectBasedOnAspectRatio; private _aspectRatio?; } declare const ALL_COLOR_OPERATIONS: readonly ["brightness", "exposure", "gamma", "contrast", "saturation", "vibrance", "warmth", "enhance"]; type ColorOperation = (typeof ALL_COLOR_OPERATIONS)[number]; declare const ALL_FILTERS: readonly ["adaris", "briaril", "calarel", "carris", "cynarel", "cyren", "elmet", "elonni", "enzana", "erydark", "fenralan", "ferand", "galen", "gavin", "gethriel", "iorill", "iothari", "iselva", "jadis", "lavra", "misiara", "namala", "nerion", "nethari", "pamaya", "sarnar", "sedis", "sewen", "sorahel", "sorlen", "tarian", "thellassan", "varriel", "varven", "vevera", "virkas", "yedis", "yllara", "zatvel", "zevcen"]; type FilterId = (typeof ALL_FILTERS)[number]; declare const ALL_CROP_OPERATIONS: readonly ["rotate", "mirror", "flip"]; type CropOperation = (typeof ALL_CROP_OPERATIONS)[number]; /** KeypointsNumber is the number of keypoints loaded from each side of zero, not total number */ declare const COLOR_OPERATIONS_CONFIG: Readonly<{ brightness: { zero: number; range: readonly [-100, 100]; keypointsNumber: number; }; exposure: { zero: number; range: readonly [-500, 500]; keypointsNumber: number; }; gamma: { zero: number; range: readonly [0, 1000]; keypointsNumber: number; }; contrast: { zero: number; range: readonly [-100, 500]; keypointsNumber: number; }; saturation: { zero: number; range: readonly [-100, 500]; keypointsNumber: number; }; vibrance: { zero: number; range: readonly [-100, 500]; keypointsNumber: number; }; warmth: { zero: number; range: readonly [-100, 100]; keypointsNumber: number; }; enhance: { zero: number; range: readonly [0, 100]; keypointsNumber: number; }; filter: { zero: number; range: readonly [0, 100]; keypointsNumber: number; }; }>; interface EditorCropButtonControl { get operation(): CropOperation | undefined; set operation(value: CropOperation | undefined); } declare class EditorCropButtonControl extends EditorButtonControl { private _operation; initCallback(): void; } declare class EditorFilterControl extends EditorButtonControl { private _operation; private _filter; private _originalUrl; private _observer?; private _cancelPreload?; constructor(); private _previewSrc; private _observerCallback; initCallback(): void; destroyCallback(): void; } type Operations = { flip: boolean; mirror: boolean; rotate: number; }; declare class EditorImageCropper extends Block { ctxOwner: boolean; private _commitDebounced; private _handleResizeThrottled; private _imageSize; private _canvas?; private _ctx; private _isActive; private _observer?; private _cancelPreload?; constructor(); private _handleResize; private _syncTransformations; private _initCanvas; private _alignImage; private _alignCrop; private _drawImage; private _draw; private _animateIn; private _getCropDimensions; private _getCropTransformation; private _commit; setValue<K extends keyof Operations>(operation: K, value: Operations[K]): void; getValue<K extends keyof Operations>(operation: K): Operations[K]; activate(imageSize: ImageSize, { fromViewer }?: { fromViewer?: boolean; }): Promise<void>; deactivate({ reset }?: { reset?: boolean; }): void; private _transitionToCrop; private _transitionToImage; private _reset; private _waitForImage; private _handleImageLoading; initCallback(): void; destroyCallback(): void; } type OperationKey = keyof typeof COLOR_OPERATIONS_CONFIG; declare cl