payload 4.0.0-beta.10 → 4.0.0-beta.12
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.
- package/dist/admin/forms/Form.d.ts +0 -7
- package/dist/admin/forms/Form.d.ts.map +1 -1
- package/dist/admin/forms/Form.js.map +1 -1
- package/dist/collections/operations/count.d.ts.map +1 -1
- package/dist/collections/operations/count.js +3 -1
- package/dist/collections/operations/count.js.map +1 -1
- package/dist/collections/operations/countVersions.d.ts.map +1 -1
- package/dist/collections/operations/countVersions.js +3 -1
- package/dist/collections/operations/countVersions.js.map +1 -1
- package/dist/collections/operations/delete.d.ts.map +1 -1
- package/dist/collections/operations/delete.js +9 -7
- package/dist/collections/operations/delete.js.map +1 -1
- package/dist/collections/operations/find.d.ts.map +1 -1
- package/dist/collections/operations/find.js +9 -15
- package/dist/collections/operations/find.js.map +1 -1
- package/dist/collections/operations/findDistinct.d.ts.map +1 -1
- package/dist/collections/operations/findDistinct.js +3 -1
- package/dist/collections/operations/findDistinct.js.map +1 -1
- package/dist/collections/operations/findVersions.d.ts.map +1 -1
- package/dist/collections/operations/findVersions.js +10 -8
- package/dist/collections/operations/findVersions.js.map +1 -1
- package/dist/collections/operations/renameFile.d.ts.map +1 -1
- package/dist/collections/operations/renameFile.js +16 -9
- package/dist/collections/operations/renameFile.js.map +1 -1
- package/dist/collections/operations/update.d.ts.map +1 -1
- package/dist/collections/operations/update.js +9 -15
- package/dist/collections/operations/update.js.map +1 -1
- package/dist/database/cloneWhere.d.ts +10 -0
- package/dist/database/cloneWhere.d.ts.map +1 -0
- package/dist/database/cloneWhere.js +31 -0
- package/dist/database/cloneWhere.js.map +1 -0
- package/dist/database/nestedRelationshipReadConstraint.d.ts +20 -0
- package/dist/database/nestedRelationshipReadConstraint.d.ts.map +1 -0
- package/dist/database/nestedRelationshipReadConstraint.js +33 -0
- package/dist/database/nestedRelationshipReadConstraint.js.map +1 -0
- package/dist/database/queryValidation/validateSearchParams.d.ts.map +1 -1
- package/dist/database/queryValidation/validateSearchParams.js +36 -1
- package/dist/database/queryValidation/validateSearchParams.js.map +1 -1
- package/dist/database/queryValidation/validateSortQuery.d.ts.map +1 -1
- package/dist/database/queryValidation/validateSortQuery.js +4 -2
- package/dist/database/queryValidation/validateSortQuery.js.map +1 -1
- package/dist/database/sanitizeJoinQuery.d.ts +2 -2
- package/dist/database/sanitizeJoinQuery.d.ts.map +1 -1
- package/dist/database/sanitizeJoinQuery.js +26 -1
- package/dist/database/sanitizeJoinQuery.js.map +1 -1
- package/dist/exports/internal.d.ts +1 -0
- package/dist/exports/internal.d.ts.map +1 -1
- package/dist/exports/internal.js +1 -0
- package/dist/exports/internal.js.map +1 -1
- package/dist/fields/hooks/beforeChange/index.d.ts.map +1 -1
- package/dist/fields/hooks/beforeChange/index.js +6 -0
- package/dist/fields/hooks/beforeChange/index.js.map +1 -1
- package/dist/fields/mergeBaseFields.d.ts.map +1 -1
- package/dist/fields/mergeBaseFields.js +24 -0
- package/dist/fields/mergeBaseFields.js.map +1 -1
- package/dist/globals/operations/countGlobalVersions.d.ts.map +1 -1
- package/dist/globals/operations/countGlobalVersions.js +3 -1
- package/dist/globals/operations/countGlobalVersions.js.map +1 -1
- package/dist/globals/operations/findVersions.d.ts.map +1 -1
- package/dist/globals/operations/findVersions.js +10 -8
- package/dist/globals/operations/findVersions.js.map +1 -1
- package/dist/hierarchy/utils/findUseAsTitle.js +11 -11
- package/dist/hierarchy/utils/findUseAsTitle.js.map +1 -1
- package/dist/index.bundled.d.ts +55 -11
- package/dist/uploads/fileVersioning/archive.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/archive.js +5 -13
- package/dist/uploads/fileVersioning/archive.js.map +1 -1
- package/dist/uploads/fileVersioning/cloudStorage.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/cloudStorage.js +6 -7
- package/dist/uploads/fileVersioning/cloudStorage.js.map +1 -1
- package/dist/uploads/fileVersioning/resolveHistoricalFile.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/resolveHistoricalFile.js +48 -48
- package/dist/uploads/fileVersioning/resolveHistoricalFile.js.map +1 -1
- package/dist/uploads/fileVersioning/restore.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/restore.js +7 -9
- package/dist/uploads/fileVersioning/restore.js.map +1 -1
- package/dist/uploads/fileVersioning/restoreRequestTime.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/restoreRequestTime.js +22 -36
- package/dist/uploads/fileVersioning/restoreRequestTime.js.map +1 -1
- package/dist/uploads/fileVersioning/storedFiles.d.ts +39 -8
- package/dist/uploads/fileVersioning/storedFiles.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/storedFiles.js +150 -93
- package/dist/uploads/fileVersioning/storedFiles.js.map +1 -1
- package/dist/uploads/fileVersioning/types.d.ts +13 -1
- package/dist/uploads/fileVersioning/types.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/types.js.map +1 -1
- package/dist/uploads/generateFileData/plan/planUploadStages.d.ts.map +1 -1
- package/dist/uploads/generateFileData/plan/planUploadStages.js +2 -0
- package/dist/uploads/generateFileData/plan/planUploadStages.js.map +1 -1
- package/dist/uploads/getBaseFields.d.ts.map +1 -1
- package/dist/uploads/getBaseFields.js +4 -1
- package/dist/uploads/getBaseFields.js.map +1 -1
- package/dist/uploads/transformState/planUpload.d.ts +4 -1
- package/dist/uploads/transformState/planUpload.d.ts.map +1 -1
- package/dist/uploads/transformState/planUpload.js +52 -2
- package/dist/uploads/transformState/planUpload.js.map +1 -1
- package/dist/utilities/configToJSONSchema.d.ts.map +1 -1
- package/dist/utilities/configToJSONSchema.js +6 -0
- package/dist/utilities/configToJSONSchema.js.map +1 -1
- package/dist/utilities/deepMerge.d.ts +55 -3
- package/dist/utilities/deepMerge.d.ts.map +1 -1
- package/dist/utilities/deepMerge.js +104 -9
- package/dist/utilities/deepMerge.js.map +1 -1
- package/dist/utilities/sanitizeUpdateData.d.ts +5 -0
- package/dist/utilities/sanitizeUpdateData.d.ts.map +1 -0
- package/dist/utilities/sanitizeUpdateData.js +10 -0
- package/dist/utilities/sanitizeUpdateData.js.map +1 -0
- package/package.json +2 -3
package/dist/index.bundled.d.ts
CHANGED
|
@@ -17,8 +17,6 @@ export { z } from 'zod/mini';
|
|
|
17
17
|
import * as zod_v4_core from 'zod/v4/core';
|
|
18
18
|
import { lookup } from 'dns';
|
|
19
19
|
import { core } from 'zod';
|
|
20
|
-
import deepMerge from 'deepmerge';
|
|
21
|
-
export { default as deepMerge } from 'deepmerge';
|
|
22
20
|
import { PinoPretty } from 'pino-pretty';
|
|
23
21
|
import { DatePickerProps } from 'react-datepicker';
|
|
24
22
|
|
|
@@ -8516,13 +8514,6 @@ type FieldState = {
|
|
|
8516
8514
|
fieldSchema?: Field | TabAsField;
|
|
8517
8515
|
filterOptions?: FilterOptionsResult;
|
|
8518
8516
|
initialValue?: unknown;
|
|
8519
|
-
/**
|
|
8520
|
-
* Every time a field is changed locally, this flag is set to true. Prevents form state from server from overwriting local changes.
|
|
8521
|
-
* After merging server form state, this flag is reset.
|
|
8522
|
-
*
|
|
8523
|
-
* @experimental This property is experimental and may change in the future. Use at your own risk.
|
|
8524
|
-
*/
|
|
8525
|
-
isModified?: boolean;
|
|
8526
8517
|
/**
|
|
8527
8518
|
* The path of the field when its custom components were last rendered.
|
|
8528
8519
|
* This is used to denote if a field has been rendered, and if so,
|
|
@@ -16266,12 +16257,65 @@ declare function deepCopyObjectSimple<T extends JsonValue>(value: T, filterUndef
|
|
|
16266
16257
|
*/
|
|
16267
16258
|
declare function deepCopyObjectComplex<T>(object: T, cache?: WeakMap<any, any>): T;
|
|
16268
16259
|
|
|
16260
|
+
type DeepMergeArrayMergeOptions = {
|
|
16261
|
+
cloneUnlessOtherwiseSpecified(value: object, options?: DeepMergeOptions): any;
|
|
16262
|
+
isMergeableObject(value: object): boolean;
|
|
16263
|
+
};
|
|
16264
|
+
type DeepMergeOptions = {
|
|
16265
|
+
/**
|
|
16266
|
+
* Merges two arrays. Defaults to concatenating `target` and `source`.
|
|
16267
|
+
*/
|
|
16268
|
+
arrayMerge?: (target: any[], source: any[], options: ResolvedDeepMergeOptions) => any[];
|
|
16269
|
+
/**
|
|
16270
|
+
* When `false`, mergeable values are copied by reference instead of being deeply cloned.
|
|
16271
|
+
* @default true
|
|
16272
|
+
*/
|
|
16273
|
+
clone?: boolean;
|
|
16274
|
+
/**
|
|
16275
|
+
* Returns a custom merge function for a given key, or `undefined` to use the default merge.
|
|
16276
|
+
*/
|
|
16277
|
+
customMerge?: (key: string, options?: DeepMergeOptions) => ((x: any, y: any) => any) | undefined;
|
|
16278
|
+
/**
|
|
16279
|
+
* Determines whether a value should be merged recursively or copied as-is.
|
|
16280
|
+
*/
|
|
16281
|
+
isMergeableObject?(value: object): boolean;
|
|
16282
|
+
};
|
|
16283
|
+
type ResolvedDeepMergeOptions = {
|
|
16284
|
+
arrayMerge: NonNullable<DeepMergeOptions['arrayMerge']>;
|
|
16285
|
+
isMergeableObject: (value: unknown) => boolean;
|
|
16286
|
+
} & DeepMergeArrayMergeOptions & DeepMergeOptions;
|
|
16287
|
+
/**
|
|
16288
|
+
* Fully-featured deepMerge. Returns a new object and does not mutate its arguments.
|
|
16289
|
+
*
|
|
16290
|
+
* Array handling: arrays are concatenated unless `arrayMerge` is provided.
|
|
16291
|
+
*
|
|
16292
|
+
* `__proto__` keys are never copied to the result, preventing prototype poisoning of the returned
|
|
16293
|
+
* object when merging untrusted input (e.g. parsed JSON).
|
|
16294
|
+
*/
|
|
16295
|
+
declare function deepMerge<T>(x: Partial<T>, y: Partial<T>, options?: DeepMergeOptions): T;
|
|
16296
|
+
declare function deepMerge<T1, T2>(x: Partial<T1>, y: Partial<T2>, options?: DeepMergeOptions): T1 & T2;
|
|
16297
|
+
declare namespace deepMerge {
|
|
16298
|
+
var all: typeof deepMergeAll;
|
|
16299
|
+
}
|
|
16300
|
+
/**
|
|
16301
|
+
* Keeps the `deepMerge.Options` / `deepMerge.ArrayMergeOptions` type references from the former
|
|
16302
|
+
* `deepmerge` dependency working.
|
|
16303
|
+
*/
|
|
16304
|
+
declare namespace deepMerge {
|
|
16305
|
+
type ArrayMergeOptions = DeepMergeArrayMergeOptions;
|
|
16306
|
+
type Options = DeepMergeOptions;
|
|
16307
|
+
}
|
|
16308
|
+
/**
|
|
16309
|
+
* Deep-merges all objects in the array, from left to right.
|
|
16310
|
+
*/
|
|
16311
|
+
declare function deepMergeAll<T = object>(objects: Partial<T>[], options?: DeepMergeOptions): T;
|
|
16312
|
+
declare function deepMergeAll(objects: object[], options?: DeepMergeOptions): object;
|
|
16269
16313
|
/**
|
|
16270
16314
|
* Fully-featured deepMerge.
|
|
16271
16315
|
*
|
|
16272
16316
|
* Array handling: Arrays in the target object are combined with the source object's arrays.
|
|
16273
16317
|
*/
|
|
16274
|
-
declare function deepMergeWithCombinedArrays<T extends object>(obj1: object, obj2: object, options?:
|
|
16318
|
+
declare function deepMergeWithCombinedArrays<T extends object>(obj1: object, obj2: object, options?: DeepMergeOptions): T;
|
|
16275
16319
|
/**
|
|
16276
16320
|
* Fully-featured deepMerge.
|
|
16277
16321
|
*
|
|
@@ -17543,5 +17587,5 @@ interface GlobalAdminCustom extends Record<string, any> {
|
|
|
17543
17587
|
interface GlobalAdminCustom extends Record<string, any> {
|
|
17544
17588
|
}
|
|
17545
17589
|
|
|
17546
|
-
export { APIError, APIErrorName, Action, AuthenticationError, BasePayload, DEFAULT_ALLOW_HAS_MANY, DEFAULT_HIERARCHY_TREE_LIMIT, DatabaseKVAdapter, DuplicateCollection, DuplicateFieldName, DuplicateGlobal, EntityType, ErrorDeletingFile, FileRetrievalError, FileUploadError, Forbidden, HIERARCHY_DEFAULT_LOCALE, HIERARCHY_SLUG_PATH_FIELD, HIERARCHY_TITLE_PATH_FIELD, InMemoryKVAdapter, InvalidConfiguration, InvalidFieldName, InvalidFieldRelationship, JWTAuthentication, JWT_AUTH_VERSION, JobCancelledError, Locked, LockedAuth, MissingCollectionLabel, MissingEditorProp, MissingFieldInputOptions, MissingFieldType, MissingFile, NotFound, QueryError, TransformerContractError, UnauthorizedError, UnverifiedEmail, ValidationError, ValidationErrorName, _internal_jobSystemGlobals, _internal_resetJobSystemGlobals, _internal_safeFetchGlobal, accessOperation, addDataAndFileToRequest, addDefaultsToConfig, addLocalesToRequestFromData, traverseFields$4 as afterChangeTraverseFields, promise as afterReadPromise, traverseFields$3 as afterReadTraverseFields, appendVersionToQueryKey, accountLockFields as baseAccountLockFields, baseAuthFields, baseBlockFields, emailFieldConfig as baseEmailField, baseIDField, sessionsFieldConfig as baseSessionsField, usernameFieldConfig as baseUsernameField, verificationFields as baseVerificationFields, batchProcessing, traverseFields$2 as beforeChangeTraverseFields, traverseFields$1 as beforeValidateTraverseFields, buildConfig, buildVersionCollectionFields, buildVersionCompoundIndexes, buildVersionGlobalFields, canAccessAdmin, checkDependencies, checkLoginPermission, combineQueries, commitTransaction, configToJSONSchema, countDocumentsInputSchema, countDocumentsLocalInputSchema, countGlobalVersionsInputSchema, countGlobalVersionsLocalInputSchema, countOperation, countRunnableOrActiveJobsForQueue, countVersionsInputSchema, countVersionsLocalInputSchema, createAPIKeyFields, createArrayFromCommaDelineated, createAuthToken, createClientBlocks, createClientCollectionConfig, createClientCollectionConfigs, createClientConfig, createClientField, createClientFields, createClientGlobalConfig, createClientGlobalConfigs, createCreatedByField, createDatabaseAdapter, createDataloaderCacheKey, createDocumentsInputSchema, createDocumentsLocalInputSchema, createFolderField, createMigration, createOperation, createPayloadRequest, createPayloadRequestFromWebRequest, createTagField, createUnauthenticatedClientConfig, createUpdatedByField, databaseKVAdapter, deepCopyObject, deepCopyObjectComplex, deepCopyObjectSimple, deepMergeSimple, deepMergeWithCombinedArrays, deepMergeWithReactComponents, deepMergeWithSourceArrays, initialized as default, defaultBeginTransaction, defaultLoggerOptions, defaultUserCollection, definePlugin, deleteByIDOperation, deleteCollectionVersions, deleteDocumentsInputSchema, deleteDocumentsLocalInputSchema, deleteOperation, docAccessOperation$1 as docAccessOperation, docAccessOperation as docAccessOperationGlobal, docHasTimestamps, duplicateDocumentInputSchema, duplicateDocumentLocalInputSchema, duplicateOperation, dynamicImport, enforceMaxVersions, entityToJSONSchema, entityToStandaloneJSONSchema, escapeRegExp, executeAccess, executeAuthStrategies, extractAccessFromPermission, extractJWT, fieldsToJSONSchema, findByIDOperation, findDistinctInputSchema, findDistinctLocalInputSchema, findDocumentsInputSchema, findDocumentsLocalInputSchema, findGlobalInputSchema, findGlobalLocalInputSchema, findGlobalVersionByIDInputSchema, findGlobalVersionByIDLocalInputSchema, findGlobalVersionsInputSchema, findGlobalVersionsLocalInputSchema, findMigrationDir, findOneOperation, findOperation, findUp, findUpSync, findVersionByIDInputSchema, findVersionByIDLocalInputSchema, findVersionByIDOperation$1 as findVersionByIDOperation, findVersionByIDOperation as findVersionByIDOperationGlobal, findVersionsInputSchema, findVersionsLocalInputSchema, findVersionsOperation$1 as findVersionsOperation, findVersionsOperation as findVersionsOperationGlobal, flattenAllFields, flattenTopLevelFields, flattenWhereToOperators, forgotPasswordOperation, formatErrors, formatLabels, formatNames, genImportMapIterateFields, generateCookie, generateExpiredPayloadCookie, generateImportMap, generatePayloadCookie, generatePayloadFileURL, getAccessResults, getAncestors, getBlockSelect, getCollectionIDFieldTypes, getCollectionInputSchema, getCollectionSchemaInputSchema, getCollectionVirtualFieldNames, getConfigInfoInputSchema, getCookieExpiration, getCurrentDate, getDataLoader, getDefaultValue, getDependencies, getFieldByPath, getFieldsToSign, getFileByPath, getGlobalInputSchema, getGlobalSchemaInputSchema, getGlobalVirtualFieldNames, getHierarchyFieldName, getInitialTreeData, getLocalI18n, getLocalizedPaths, getLoginOptions, getMigrations, getObjectDotNotation, getPayload, getPredefinedMigration, getQueryDraftsSort, getRegisteredDevReloadStrategy, getRequestLanguage, getSlugFallbackValue, getUniqueFieldValue, handleEndpoints, hasDraftValidationEnabled, hasDraftsEnabled, hasWhereAccessResult, headersWithCors, importHandlerPath, inMemoryKVAdapter, incrementLoginAttempts, initOperation, initTransaction, injectHierarchyButton, isEntityHidden, isPlainObject, isUserMenuSettingsGroup, isValidID, isolateObjectProperty, jobAfterRead, jwtSign, killTransaction, logError, loginOperation, logoutOperation, mapAsync, meOperation, mergeHeaders, migrate, migrateDown, migrateRefresh, migrateReset, migrateStatus, migrationTemplate, migrationsCollection, parseCookies, parseDocumentID, parseErrorResponse, parseParams, pathExistsAndIsAccessible, pathExistsAndIsAccessibleSync, readMigrationFiles, redeemRefreshToken, refreshOperation, registerBlockInterface, registerCLIExitCodeHandler, registerDevReloadStrategy, registerFirstUserOperation, registerUploadVariants, reload, renameFileOperation, resetLoginAttempts, resetPasswordOperation, resolveHierarchyCollections, restoreGlobalVersionInputSchema, restoreGlobalVersionLocalInputSchema, restoreVersionInputSchema, restoreVersionLocalInputSchema, restoreVersionOperation$1 as restoreVersionOperation, restoreVersionOperation as restoreVersionOperationGlobal, rotateSecret, sanitizeConfig, sanitizeFallbackLocale, sanitizeField, sanitizeFields, sanitizeJoinParams, sanitizeLocales, sanitizePopulateParam, sanitizeSelectParam, sanitizeSortParams, saveVersion, serverOnlyAdminConfigProperties, serverOnlyConfigProperties, serverProps, sortableFieldTypes, strictObject, stripUnselectedFields, stripVirtualFields, toWords, transformPointDataToPayload, traverseFields, unlockOperation, updateByIDOperation, updateDocumentInputSchema, updateDocumentLocalInputSchema, updateGlobalInputSchema, updateGlobalLocalInputSchema, updateOperation$1 as updateOperation, updateOperation as updateOperationGlobal, validateBlocksFilterOptions, validateCollectionData, validateGlobalData, validateQueryPaths, validateSearchParam, validations, verifyEmailOperation, versionDefaults, withNullableJSONSchemaType, writeMigrationIndex };
|
|
17590
|
+
export { APIError, APIErrorName, Action, AuthenticationError, BasePayload, DEFAULT_ALLOW_HAS_MANY, DEFAULT_HIERARCHY_TREE_LIMIT, DatabaseKVAdapter, DuplicateCollection, DuplicateFieldName, DuplicateGlobal, EntityType, ErrorDeletingFile, FileRetrievalError, FileUploadError, Forbidden, HIERARCHY_DEFAULT_LOCALE, HIERARCHY_SLUG_PATH_FIELD, HIERARCHY_TITLE_PATH_FIELD, InMemoryKVAdapter, InvalidConfiguration, InvalidFieldName, InvalidFieldRelationship, JWTAuthentication, JWT_AUTH_VERSION, JobCancelledError, Locked, LockedAuth, MissingCollectionLabel, MissingEditorProp, MissingFieldInputOptions, MissingFieldType, MissingFile, NotFound, QueryError, TransformerContractError, UnauthorizedError, UnverifiedEmail, ValidationError, ValidationErrorName, _internal_jobSystemGlobals, _internal_resetJobSystemGlobals, _internal_safeFetchGlobal, accessOperation, addDataAndFileToRequest, addDefaultsToConfig, addLocalesToRequestFromData, traverseFields$4 as afterChangeTraverseFields, promise as afterReadPromise, traverseFields$3 as afterReadTraverseFields, appendVersionToQueryKey, accountLockFields as baseAccountLockFields, baseAuthFields, baseBlockFields, emailFieldConfig as baseEmailField, baseIDField, sessionsFieldConfig as baseSessionsField, usernameFieldConfig as baseUsernameField, verificationFields as baseVerificationFields, batchProcessing, traverseFields$2 as beforeChangeTraverseFields, traverseFields$1 as beforeValidateTraverseFields, buildConfig, buildVersionCollectionFields, buildVersionCompoundIndexes, buildVersionGlobalFields, canAccessAdmin, checkDependencies, checkLoginPermission, combineQueries, commitTransaction, configToJSONSchema, countDocumentsInputSchema, countDocumentsLocalInputSchema, countGlobalVersionsInputSchema, countGlobalVersionsLocalInputSchema, countOperation, countRunnableOrActiveJobsForQueue, countVersionsInputSchema, countVersionsLocalInputSchema, createAPIKeyFields, createArrayFromCommaDelineated, createAuthToken, createClientBlocks, createClientCollectionConfig, createClientCollectionConfigs, createClientConfig, createClientField, createClientFields, createClientGlobalConfig, createClientGlobalConfigs, createCreatedByField, createDatabaseAdapter, createDataloaderCacheKey, createDocumentsInputSchema, createDocumentsLocalInputSchema, createFolderField, createMigration, createOperation, createPayloadRequest, createPayloadRequestFromWebRequest, createTagField, createUnauthenticatedClientConfig, createUpdatedByField, databaseKVAdapter, deepCopyObject, deepCopyObjectComplex, deepCopyObjectSimple, deepMerge, deepMergeSimple, deepMergeWithCombinedArrays, deepMergeWithReactComponents, deepMergeWithSourceArrays, initialized as default, defaultBeginTransaction, defaultLoggerOptions, defaultUserCollection, definePlugin, deleteByIDOperation, deleteCollectionVersions, deleteDocumentsInputSchema, deleteDocumentsLocalInputSchema, deleteOperation, docAccessOperation$1 as docAccessOperation, docAccessOperation as docAccessOperationGlobal, docHasTimestamps, duplicateDocumentInputSchema, duplicateDocumentLocalInputSchema, duplicateOperation, dynamicImport, enforceMaxVersions, entityToJSONSchema, entityToStandaloneJSONSchema, escapeRegExp, executeAccess, executeAuthStrategies, extractAccessFromPermission, extractJWT, fieldsToJSONSchema, findByIDOperation, findDistinctInputSchema, findDistinctLocalInputSchema, findDocumentsInputSchema, findDocumentsLocalInputSchema, findGlobalInputSchema, findGlobalLocalInputSchema, findGlobalVersionByIDInputSchema, findGlobalVersionByIDLocalInputSchema, findGlobalVersionsInputSchema, findGlobalVersionsLocalInputSchema, findMigrationDir, findOneOperation, findOperation, findUp, findUpSync, findVersionByIDInputSchema, findVersionByIDLocalInputSchema, findVersionByIDOperation$1 as findVersionByIDOperation, findVersionByIDOperation as findVersionByIDOperationGlobal, findVersionsInputSchema, findVersionsLocalInputSchema, findVersionsOperation$1 as findVersionsOperation, findVersionsOperation as findVersionsOperationGlobal, flattenAllFields, flattenTopLevelFields, flattenWhereToOperators, forgotPasswordOperation, formatErrors, formatLabels, formatNames, genImportMapIterateFields, generateCookie, generateExpiredPayloadCookie, generateImportMap, generatePayloadCookie, generatePayloadFileURL, getAccessResults, getAncestors, getBlockSelect, getCollectionIDFieldTypes, getCollectionInputSchema, getCollectionSchemaInputSchema, getCollectionVirtualFieldNames, getConfigInfoInputSchema, getCookieExpiration, getCurrentDate, getDataLoader, getDefaultValue, getDependencies, getFieldByPath, getFieldsToSign, getFileByPath, getGlobalInputSchema, getGlobalSchemaInputSchema, getGlobalVirtualFieldNames, getHierarchyFieldName, getInitialTreeData, getLocalI18n, getLocalizedPaths, getLoginOptions, getMigrations, getObjectDotNotation, getPayload, getPredefinedMigration, getQueryDraftsSort, getRegisteredDevReloadStrategy, getRequestLanguage, getSlugFallbackValue, getUniqueFieldValue, handleEndpoints, hasDraftValidationEnabled, hasDraftsEnabled, hasWhereAccessResult, headersWithCors, importHandlerPath, inMemoryKVAdapter, incrementLoginAttempts, initOperation, initTransaction, injectHierarchyButton, isEntityHidden, isPlainObject, isUserMenuSettingsGroup, isValidID, isolateObjectProperty, jobAfterRead, jwtSign, killTransaction, logError, loginOperation, logoutOperation, mapAsync, meOperation, mergeHeaders, migrate, migrateDown, migrateRefresh, migrateReset, migrateStatus, migrationTemplate, migrationsCollection, parseCookies, parseDocumentID, parseErrorResponse, parseParams, pathExistsAndIsAccessible, pathExistsAndIsAccessibleSync, readMigrationFiles, redeemRefreshToken, refreshOperation, registerBlockInterface, registerCLIExitCodeHandler, registerDevReloadStrategy, registerFirstUserOperation, registerUploadVariants, reload, renameFileOperation, resetLoginAttempts, resetPasswordOperation, resolveHierarchyCollections, restoreGlobalVersionInputSchema, restoreGlobalVersionLocalInputSchema, restoreVersionInputSchema, restoreVersionLocalInputSchema, restoreVersionOperation$1 as restoreVersionOperation, restoreVersionOperation as restoreVersionOperationGlobal, rotateSecret, sanitizeConfig, sanitizeFallbackLocale, sanitizeField, sanitizeFields, sanitizeJoinParams, sanitizeLocales, sanitizePopulateParam, sanitizeSelectParam, sanitizeSortParams, saveVersion, serverOnlyAdminConfigProperties, serverOnlyConfigProperties, serverProps, sortableFieldTypes, strictObject, stripUnselectedFields, stripVirtualFields, toWords, transformPointDataToPayload, traverseFields, unlockOperation, updateByIDOperation, updateDocumentInputSchema, updateDocumentLocalInputSchema, updateGlobalInputSchema, updateGlobalLocalInputSchema, updateOperation$1 as updateOperation, updateOperation as updateOperationGlobal, validateBlocksFilterOptions, validateCollectionData, validateGlobalData, validateQueryPaths, validateSearchParam, validations, verifyEmailOperation, versionDefaults, withNullableJSONSchemaType, writeMigrationIndex };
|
|
17547
17591
|
export type { Access, AccessArgs, AccessResult, AdminClient, AdminComponent, AdminContext, AdminDependencies, AdminFunction, AdminView, AdminViewAdapter, AdminViewClientProps, AdminViewComponent, AdminViewConfig, AdminViewKey, AdminViewServerProps as AdminViewProps, AdminViewServerProps, AdminViewServerPropsOnly, AfterErrorHook$1 as AfterErrorHook, AfterErrorHookArgs, AfterErrorResult, AfterListClientProps, AfterListServerProps, AfterListServerPropsOnly, AfterListTableClientProps, AfterListTableServerProps, AfterListTableServerPropsOnly, AllOperations, AllowList, Ancestor, ApplyDisableErrors, ArrayField, ArrayFieldClient, ArrayFieldClientProps, ArrayFieldDescriptionClientProps, ArrayFieldDescriptionServerProps, ArrayFieldDiffClientProps, ArrayFieldDiffServerProps, ArrayFieldErrorClientProps, ArrayFieldErrorServerProps, ArrayFieldLabelClientProps, ArrayFieldLabelServerProps, ArrayFieldServerProps, ArrayFieldValidation, Auth, AuthCollection, AuthCollectionSlug, AuthOperations, AuthOperationsFromCollectionSlug, AuthRuntimeFields, AuthStrategy, AuthStrategyFunction, AuthStrategyFunctionArgs, AuthStrategyResult, AuthenticatedUser, Authorship, BaseAccess, BaseDatabaseAdapter, BaseFilter, BaseListFilter, BaseLocalizationConfig, BaseValidateOptions, BaseVersionField, BatchProcessing, BatchProcessingArgs, BatchProcessingOperation, BatchProcessingOptions, BatchProcessingResult, BatchProcessorResult, BeforeDocumentControlsClientProps, BeforeDocumentControlsServerProps, BeforeDocumentControlsServerPropsOnly, BeforeListClientProps, BeforeListServerProps, BeforeListServerPropsOnly, BeforeListTableClientProps, BeforeListTableServerProps, BeforeListTableServerPropsOnly, BeforeValidateOperation, BeginTransaction, Block, BlockJSX, BlockPermissions, BlockRowLabelClientProps, BlockRowLabelServerProps, BlockSlug, BlocksField, BlocksFieldClient, BlocksFieldClientProps, BlocksFieldDescriptionClientProps, BlocksFieldDescriptionServerProps, BlocksFieldDiffClientProps, BlocksFieldDiffServerProps, BlocksFieldErrorClientProps, BlocksFieldErrorServerProps, BlocksFieldLabelClientProps, BlocksFieldLabelServerProps, BlocksFieldServerProps, BlocksFieldValidation, BlocksPermissions, BrowserAutoComplete, BuildFormStateArgs, BuildTableStateArgs, BulkOperationResult, CLICommand, CLICommandDescription, CLICommandEntry, CLICommandResult, CLICommands, CLIExitCodeHandler, CLIFieldOverride, CLIGlobalOptionDescription, CLIHelp, CLIInputSchema, CLIRuntime, CORSConfig, CanTransformArgs, CanTransformResult, CheckboxField, CheckboxFieldClient, CheckboxFieldClientProps, CheckboxFieldDescriptionClientProps, CheckboxFieldDescriptionServerProps, CheckboxFieldDiffClientProps, CheckboxFieldDiffServerProps, CheckboxFieldErrorClientProps, CheckboxFieldErrorServerProps, CheckboxFieldLabelClientProps, CheckboxFieldLabelServerProps, CheckboxFieldServerProps, CheckboxFieldValidation, ClientBlock, ClientCollectionConfig, ClientComponentProps, ClientConfig, ClientField, ClientFieldBase, ClientFieldProps, ClientFieldSchemaMap, ClientFieldWithOptionalType, ClientGlobalConfig, DocumentViewClientProps as ClientSideEditViewProps, ClientTab, ClientUploadSession, ClientWidget, CodeField, CodeFieldClient, CodeFieldClientProps, CodeFieldDescriptionClientProps, CodeFieldDescriptionServerProps, CodeFieldDiffClientProps, CodeFieldDiffServerProps, CodeFieldErrorClientProps, CodeFieldErrorServerProps, CodeFieldLabelClientProps, CodeFieldLabelServerProps, CodeFieldServerProps, CodeFieldValidation, CollapsedPreferences, CollapsibleField, CollapsibleFieldClient, CollapsibleFieldClientProps, CollapsibleFieldDescriptionClientProps, CollapsibleFieldDescriptionServerProps, CollapsibleFieldDiffClientProps, CollapsibleFieldDiffServerProps, CollapsibleFieldErrorClientProps, CollapsibleFieldErrorServerProps, CollapsibleFieldLabelClientProps, CollapsibleFieldLabelServerProps, CollapsibleFieldServerProps, Collection, CollectionAccess, CollectionAdminCustom, CollectionAdminOptions, AfterChangeHook as CollectionAfterChangeHook, AfterDeleteHook as CollectionAfterDeleteHook, AfterErrorHook as CollectionAfterErrorHook, AfterForgotPasswordHook as CollectionAfterForgotPasswordHook, AfterLoginHook as CollectionAfterLoginHook, AfterLogoutHook as CollectionAfterLogoutHook, AfterMeHook as CollectionAfterMeHook, AfterOperationHook as CollectionAfterOperationHook, AfterReadHook as CollectionAfterReadHook, AfterRefreshHook as CollectionAfterRefreshHook, BeforeChangeHook as CollectionBeforeChangeHook, BeforeDeleteHook as CollectionBeforeDeleteHook, BeforeLoginHook as CollectionBeforeLoginHook, BeforeOperationHook as CollectionBeforeOperationHook, BeforeReadHook as CollectionBeforeReadHook, BeforeValidateHook as CollectionBeforeValidateHook, CollectionConfig, CollectionCustom, MeHook as CollectionMeHook, CollectionPermission, CollectionPreferences, RefreshHook as CollectionRefreshHook, CollectionSlug, Column, ColumnPreference, CommitTransaction, ComponentRenderer, CompoundIndex, ConcurrencyConfig, Condition, ConditionalDateProps, Config, ConfirmPasswordFieldValidation, Connect, CookieOptions$1 as CookieOptions, CookieStore, Copy, CopyArgs, Count, CountArgs, CountGlobalVersionArgs, CountGlobalVersions, CountVersions, Create, CreateArgs, CreateClientConfigArgs, CreateFolderFieldOptions, CreateGlobal, CreateGlobalArgs, CreateGlobalVersion, CreateGlobalVersionArgs, CreateMigration, CreateMigrationResult, CreatePayloadRequestArgs, CreateTagFieldOptions, CreateVersion, CreateVersionArgs, Crop, CurrentHierarchyItem, CustomComponent, CustomDocumentViewConfig, CustomPayloadRequestProperties, CustomComponent as CustomPreviewButton, CustomComponent as CustomPublishButton, CustomComponent as CustomSaveButton, CustomComponent as CustomSaveDraftButton, CustomStatus, CustomUpload, CustomVersionParser, DBIdentifierName, DashboardConfig, Data, DataFromCollectionSlug, DataFromGlobalSlug, DataFromWidgetSlug, DatabaseAdapter, DatabaseAdapterResult as DatabaseAdapterObj, DatabaseKVAdapterOptions, DateField, DateFieldClient, DateFieldClientProps, DateFieldDescriptionClientProps, DateFieldDescriptionServerProps, DateFieldDiffClientProps, DateFieldDiffServerProps, DateFieldErrorClientProps, DateFieldErrorServerProps, DateFieldLabelClientProps, DateFieldLabelServerProps, DateFieldServerProps, DateFieldValidation, DayPickerProps, DefaultCellComponentProps, DefaultDocumentIDType, DefaultDocumentViewConfig, DefaultServerCellComponentProps, DefaultServerFunctionArgs, DefaultValue, DeleteMany, DeleteManyArgs, DeleteOne, DeleteOneArgs, DeleteVersions, DeleteVersionsArgs, Description, DescriptionFunction, Destroy, DevReloadCleanup, DevReloadStrategy, Document, DocumentEvent, DocumentPermissions, DocumentPreferences, DocumentSlots, DocumentSubViewTypes, DocumentTabClientProps, DocumentTabComponent, DocumentTabCondition, DocumentTabConfig, DocumentTabServerProps as DocumentTabProps, DocumentTabServerProps, DocumentTabServerPropsOnly, DocumentViewClientProps, DocumentViewComponent, DocumentViewConfig, DocumentViewServerProps, DocumentViewServerPropsOnly, DraftTransformCollectionWithSelect, DynamicMigrationTemplate, EditConfig, EditConfigWithRoot, EditConfigWithoutRoot, EditMenuItemsClientProps, EditMenuItemsServerProps, EditMenuItemsServerPropsOnly, EditViewComponent, EditViewConfig, EditViewProps, EmailAdapter, EmailField, EmailFieldClient, EmailFieldClientProps, EmailFieldDescriptionClientProps, EmailFieldDescriptionServerProps, EmailFieldDiffClientProps, EmailFieldDiffServerProps, EmailFieldErrorClientProps, EmailFieldErrorServerProps, EmailFieldLabelClientProps, EmailFieldLabelServerProps, EmailFieldServerProps, EmailFieldValidation, Endpoint, EntityDescription, EntityDescriptionComponent, EntityDescriptionFunction, EntityInputSchema, EntityPolicies, ErrorResult, ExternalFileHeaderFilterContext, FetchAPIFileUploadOptions, Field, FieldAccess, FieldAccessArgs, FieldAffectingData, FieldAffectingDataClient, FieldBase, FieldBaseClient, FieldClientProps, FieldCustom, FieldDescriptionClientProps, FieldDescriptionServerProps, FieldDiffClientProps, FieldDiffServerProps, FieldErrorClientProps, FieldErrorServerProps, FieldHook, FieldHookArgs, FieldLabelClientProps, FieldLabelServerProps, FieldOperation, FieldPaths, FieldPermissions, FieldPosition, FieldPresentationalOnly, FieldPresentationalOnlyClient, FieldRow, FieldSchemaMap, FieldServerProps, FieldState, FieldTypes, FieldWithMany, FieldWithManyClient, FieldWithMaxDepth, FieldWithMaxDepthClient, FieldWithPath, FieldWithPathClient, FieldWithSubFields, FieldWithSubFieldsClient, FieldsPermissions, FieldsPreferences, FieldsToJSONSchemaArgs, File$1 as File, FileAllowList, FileData, FileHandlerOperation, FileSize, FileSizes, FileSource, FileToSave, FilterOptions, FilterOptionsProps, FilterOptionsResult, Find, FindArgs, FindDistinct, FindGlobal, FindGlobalArgs, FindGlobalVersions, FindGlobalVersionsArgs, FindOne, FindOneArgs, FindOptions, FindVersions, FindVersionsArgs, FlattenedArrayField, FlattenedBlock, FlattenedBlocksField, FlattenedField$1 as FlattenedField, FlattenedGroupField, FlattenedJoinField, FlattenedTabAsField, FocalPoint, FoldersConfig, FieldState as FormField, FieldStateWithoutComponents as FormFieldWithoutComponents, FormState, FormStateWithoutComponents, GenerateImageName, GeneratePreviewURL, GenerateSchema, GenerateUploadInstructions, GenerateViewMetadata, GeneratedTypes, GenericDescriptionProps, GenericErrorProps, GenericLabelProps, GetAdminThumbnail, GetInitialTreeDataArgs, GlobalAccess, GlobalAdminCustom, GlobalAdminOptions, AfterChangeHook$1 as GlobalAfterChangeHook, AfterReadHook$1 as GlobalAfterReadHook, BeforeChangeHook$1 as GlobalBeforeChangeHook, BeforeOperationHook$1 as GlobalBeforeOperationHook, BeforeReadHook$1 as GlobalBeforeReadHook, BeforeValidateHook$1 as GlobalBeforeValidateHook, GlobalConfig, GlobalCustom, GlobalPermission, GlobalSlug, GlobalUploadConfig, GraphQLExtension, GraphQLInfo, GroupField, GroupFieldClient, GroupFieldClientProps, GroupFieldDescriptionClientProps, GroupFieldDescriptionServerProps, GroupFieldDiffClientProps, GroupFieldDiffServerProps, GroupFieldErrorClientProps, GroupFieldErrorServerProps, GroupFieldLabelClientProps, GroupFieldLabelServerProps, GroupFieldServerProps, HandleTransformRequestArgs, HandleTransformRequestResult, HasManyRelationshipOperator, HiddenFieldProps, HierarchyConfig, HierarchyViewData, HookName, HookOperationType, IDTypeForCollectionSlug, IfAny, ImageSize, ImportMap, ImportMapGenerators, IncomingAuthType, Init, InitOptions, InitPageResult, InitialTreeData, InsideFieldsPreferences, IsAny, JSONField, JSONFieldClient, JSONFieldClientProps, JSONFieldDescriptionClientProps, JSONFieldDescriptionServerProps, JSONFieldDiffClientProps, JSONFieldDiffServerProps, JSONFieldErrorClientProps, JSONFieldErrorServerProps, JSONFieldLabelClientProps, JSONFieldLabelServerProps, JSONFieldServerProps, JSONFieldValidation, JWTAuthVersion, Job, JobLog, JobTaskStatus, JobsConfig, JoinField, JoinFieldClient, JoinFieldClientProps, JoinFieldDescriptionClientProps, JoinFieldDescriptionServerProps, JoinFieldDiffClientProps, JoinFieldDiffServerProps, JoinFieldErrorClientProps, JoinFieldErrorServerProps, JoinFieldLabelClientProps, JoinFieldLabelServerProps, JoinFieldServerProps, JoinParams, JoinQuery, JsonArray, JsonObject, JsonValue, KVAdapter, KVAdapterResult, KVStoreValue, LabelFunction, Labels, LabelsClient, LanguageOptions, LinkAdapterProps, CollectionPreferences as ListPreferences, ListQuery, ListViewClientProps, ListViewGroup, ListViewServerProps, ListViewServerPropsOnly, ListViewSlotSharedClientProps, ListViewSlots, LivePreviewConfig, LivePreviewURLType, Locale, LocalizationConfig, LocalizationConfigWithLabels, LocalizationConfigWithNoLabels, LoginResult, LoginWithUsernameOptions, MappedClientComponent, MappedEmptyComponent, MappedServerComponent, MarkdownRichTextAdapter, MarkdownRichTextAdapterProvider, MaybePromise, MeOperationResult, MetaConfig, Migration, MigrationData, MigrationResult, MigrationStatus, MigrationTemplateArgs, NamedGroupField, NamedGroupFieldClient, NamedTab, NavGroupPreferences, NavPreferences, NoResultsClientProps, NoResultsServerProps, NoResultsServerPropsOnly, NonPresentationalField, NonPresentationalFieldClient, NumberField, NumberFieldClient, NumberFieldClientProps, NumberFieldDescriptionClientProps, NumberFieldDescriptionServerProps, NumberFieldDiffClientProps, NumberFieldDiffServerProps, NumberFieldErrorClientProps, NumberFieldErrorServerProps, NumberFieldLabelClientProps, NumberFieldLabelServerProps, NumberFieldManyValidation, NumberFieldServerProps, NumberFieldSingleValidation, NumberFieldValidation, OGImageConfig, Operation, Operator, Option, OptionLabel, OptionObject, OrderableEndpointBody, OriginalFileData, PaginatedDistinctDocs, PaginatedDocs, Params, ParsedErrorResponse, ParsedNonFieldError, ParsedParams, PasswordFieldValidation, PathToQuery, Payload, PayloadClientComponentProps, PayloadClientReactComponent, PayloadComponent, PayloadComponentProps, EmailAdapter as PayloadEmailAdapter, PayloadHandler, PayloadLogger, PayloadReactComponent, PayloadRequest, PayloadRequestAPI, PayloadServerAction, PayloadServerComponentProps, PayloadServerReactComponent, PayloadTypes, PayloadTypesShape, Permission, Permissions, PickPreserveOptional, PinnedDocument, PinnedDocumentsPreferences, Plugin, PluginsMap, PointField, PointFieldClient, PointFieldClientProps, PointFieldDescriptionClientProps, PointFieldDescriptionServerProps, PointFieldDiffClientProps, PointFieldDiffServerProps, PointFieldErrorClientProps, PointFieldErrorServerProps, PointFieldLabelClientProps, PointFieldLabelServerProps, PointFieldServerProps, PointFieldValidation, PolymorphicRelationshipField, PolymorphicRelationshipFieldClient, PopulateType, PreferenceRequest, PreferenceUpdateRequest, PreviewButtonClientProps, PreviewButtonServerProps, PreviewButtonServerPropsOnly, ProbedImageSize, ProviderState, PublishButtonClientProps, PublishButtonServerProps, PublishButtonServerPropsOnly, QueryDrafts, QueryDraftsArgs, QueryPreset, RadioField, RadioFieldClient, RadioFieldClientProps, RadioFieldDescriptionClientProps, RadioFieldDescriptionServerProps, RadioFieldDiffClientProps, RadioFieldDiffServerProps, RadioFieldErrorClientProps, RadioFieldErrorServerProps, RadioFieldLabelClientProps, RadioFieldLabelServerProps, RadioFieldServerProps, RadioFieldValidation, RawParams, RawPayloadComponent, RecentlyViewedItem, RecentlyViewedPreferences, ReconciledSegments, RegisteredImageSizeOptions, RegisteredPlugins, RelatedDocumentsGrouped, RelationshipField, RelationshipFieldClient, RelationshipFieldClientProps, RelationshipFieldDescriptionClientProps, RelationshipFieldDescriptionServerProps, RelationshipFieldDiffClientProps, RelationshipFieldDiffServerProps, RelationshipFieldErrorClientProps, RelationshipFieldErrorServerProps, RelationshipFieldLabelClientProps, RelationshipFieldLabelServerProps, RelationshipFieldManyValidation, RelationshipFieldServerProps, RelationshipFieldSingleValidation, RelationshipFieldValidation, RelationshipValue, RenderConfigArgs, RenderDocumentVersionsProperties, RenderEntityConfigArgs, RenderFieldConfigArgs, RenderRootConfigArgs, RenderedField, ReplaceAny, RequestContext, RequiredDataFromCollection, RequiredDataFromCollectionSlug, ReservedObject, ResolvedComponent, ResolvedFilterOptions, RichTextAdapter, RichTextAdapterProvider, RichTextField, RichTextFieldClient, RichTextFieldClientProps, RichTextFieldDescriptionClientProps, RichTextFieldDescriptionServerProps, RichTextFieldDiffClientProps, RichTextFieldDiffServerProps, RichTextFieldErrorClientProps, RichTextFieldErrorServerProps, RichTextFieldLabelClientProps, RichTextFieldLabelServerProps, RichTextFieldServerProps, RichTextFieldValidation, RichTextHooks, RollbackTransaction, RootLivePreviewConfig, RotateSecretArgs, RotateSecretResult, RouterAdapterComponent, RouterAdapterRouter, Row, RowField, RowFieldClient, RowFieldClientProps, RowFieldDescriptionClientProps, RowFieldDescriptionServerProps, RowFieldDiffClientProps, RowFieldDiffServerProps, RowFieldErrorClientProps, RowFieldErrorServerProps, RowFieldLabelClientProps, RowFieldLabelServerProps, RowFieldServerProps, RowLabel, RowLabelComponent, RunInlineTaskFunction, RunJobAccess, RunJobAccessArgs, RunTaskFunction, RunTaskFunctions, SanitizeFieldArgs, SanitizedAuthorship, SanitizedBlockPermissions, SanitizedBlocksPermissions, SanitizedCollectionConfig, SanitizedCollectionPermission, SanitizedCompoundIndex, SanitizedConfig, SanitizedDashboardConfig, SanitizedDocumentPermissions, SanitizedFieldPermissions, SanitizedFieldsPermissions, SanitizedGlobalConfig, SanitizedGlobalPermission, SanitizedHierarchyConfig, SanitizedHierarchyRelatedCollection, SanitizedJoins, SanitizedLabelProps, SanitizedLocalizationConfig, SanitizedPermissions, SanitizedUploadConfig, SaveButtonClientProps, SaveButtonServerProps, SaveButtonServerPropsOnly, SaveDraftButtonClientProps, SaveDraftButtonServerProps, SaveDraftButtonServerPropsOnly, SchedulePublish, SchedulePublishTaskInput, SchemaVariant, SegmentedUploadCapability, SegmentedUploadLimits, SelectExcludeType, SelectField, SelectFieldClient, SelectFieldClientProps, SelectFieldDescriptionClientProps, SelectFieldDescriptionServerProps, SelectFieldDiffClientProps, SelectFieldDiffServerProps, SelectFieldErrorClientProps, SelectFieldErrorServerProps, SelectFieldLabelClientProps, SelectFieldLabelServerProps, SelectFieldManyValidation, SelectFieldServerProps, SelectFieldSingleValidation, SelectFieldValidation, SelectFn, SelectFnArgs, SelectFnOperation, SelectIncludeType, SelectMode, SelectType, SendEmailOptions, ServerAdapter, ServerComponentProps, ServerFieldBase, ServerFunction, ServerFunctionArgs, ServerFunctionClient, ServerFunctionClientArgs, ServerFunctionConfig, ServerFunctionHandler, ServerOnlyCollectionAdminProperties, ServerOnlyCollectionProperties, ServerOnlyFieldAdminProperties, ServerOnlyFieldProperties, ServerOnlyGlobalAdminProperties, ServerOnlyGlobalProperties, ServerOnlyLivePreviewProperties, ServerOnlyUploadProperties, ServerProps, ServerPropsFromView, DocumentViewServerProps as ServerSideEditViewProps, SharedAdminComponents, SharedEditViewComponents, SharedEntityViews, SharedLocalAPIOptions, SharedProps, SidebarTab, SidebarTabClientProps, SidebarTabServerProps, SidebarTabServerPropsOnly, SingleRelationshipField, SingleRelationshipFieldClient, SingleTaskStatus, SlugField, SlugFieldClient, SlugFieldClientProps, SlugifyServerFunctionArgs, Sort, StaticDescription, StaticLabel, StorageAdapter, StringKeyOf, Tab, TabAsField, TabAsFieldClient, TabsField, TabsFieldClient, TabsFieldClientProps, TabsFieldDescriptionClientProps, TabsFieldDescriptionServerProps, TabsFieldDiffClientProps, TabsFieldDiffServerProps, TabsFieldErrorClientProps, TabsFieldErrorServerProps, TabsFieldLabelClientProps, TabsFieldLabelServerProps, TabsFieldServerProps, TabsPreferences, TagsConfig, TaskConfig, TaskHandler, TaskHandlerArgs, TaskHandlerResult, TaskHandlerResults, TaskInput, TaskOutput, TaskSlug, TextField, TextFieldClient, TextFieldClientProps, TextFieldDescriptionClientProps, TextFieldDescriptionServerProps, TextFieldDiffClientProps, TextFieldDiffServerProps, TextFieldErrorClientProps, TextFieldErrorServerProps, TextFieldLabelClientProps, TextFieldLabelServerProps, TextFieldManyValidation, TextFieldServerProps, TextFieldSingleValidation, TextFieldValidation, TextareaField, TextareaFieldClient, TextareaFieldClientProps, TextareaFieldDescriptionClientProps, TextareaFieldDescriptionServerProps, TextareaFieldDiffClientProps, TextareaFieldDiffServerProps, TextareaFieldErrorClientProps, TextareaFieldErrorServerProps, TextareaFieldLabelClientProps, TextareaFieldLabelServerProps, TextareaFieldServerProps, TextareaFieldValidation, TimePickerProps, Timezone, TimezonesConfig, Transaction, TransformCollectionWithSelect, TransformDataWithSelect, TransformDefinition, TransformFileArgs, TransformFileResult, TransformGlobalWithSelect, TransformValidate, TransformValueSchema, TraverseFieldsCallback, TypeWithID, TypeWithTimestamps, TypeWithVersion, TypedAuthOperations, TypedBlock, TypedCollection, TypedCollectionJoins, TypedCollectionSelect, TypedFallbackLocale, TypedGlobal, TypedGlobalSelect, TypedJobs, TypedLocale, TypedUploadCollection, TypedWidget, UIField, UIFieldClient, UIFieldClientProps, UIFieldDiffClientProps, UIFieldDiffServerProps, UIFieldServerProps, UnauthenticatedClientConfig, UnnamedGroupField, UnnamedGroupFieldClient, UnnamedTab, UnpublishButtonClientProps, UnpublishButtonServerProps, UnpublishButtonServerPropsOnly, UntypedPayloadTypes, UpdateGlobal, UpdateGlobalArgs, UpdateGlobalVersion, UpdateGlobalVersionArgs, UpdateJobs, UpdateJobsArgs, UpdateMany, UpdateManyArgs, UpdateOne, UpdateOneArgs, UpdateVersion, UpdateVersionArgs, UploadCollectionSlug, UploadConfig, UploadEdits, UploadField, UploadFieldClient, UploadFieldClientProps, UploadFieldDescriptionClientProps, UploadFieldDescriptionServerProps, UploadFieldDiffClientProps, UploadFieldDiffServerProps, UploadFieldErrorClientProps, UploadFieldErrorServerProps, UploadFieldLabelClientProps, UploadFieldLabelServerProps, UploadFieldManyValidation, UploadFieldServerProps, UploadFieldSingleValidation, UploadFieldValidation, UploadFilePreviewClientProps, UploadInstructions, UploadInstructionsAccess, UploadInstructionsCapability, UploadInstructionsRequest, UploadSegment, UploadSegmentRequest, UploadSessionCancelReason, UploadSessionDoc, UploadSessionError, UploadSessionIntent, UploadSessionOperation, UploadSessionSaveOptions, UploadSessionStatus, UploadSessionTransferConfig, UploadSessionsConfig, UploadTransformer, Upsert, UpsertArgs, User, UserMenuSettingsGroup, UserMenuSettingsItem, UserSession, UsernameFieldValidation, Validate, ValidateCollectionOptions, ValidateGlobalOptions, ValidateOptions, ValidationFieldError, ValidationResult, ValueWithRelation, VerifyConfig, VersionField, VersionOperations, VersionTab, ViewDescriptionClientProps, ViewDescriptionServerProps, ViewDescriptionServerPropsOnly, ViewTypes, VisibleEntities, Where, WhereField, Widget, WidgetInstance, WidgetServerProps, WidgetSlug, WidgetWidth, WithSelectFn, WithServerSidePropsComponent, WithServerSidePropsComponentProps, WorkflowConfig, WorkflowHandler, WorkflowSlug, checkFileRestrictionsParams };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"archive.d.ts","sourceRoot":"","sources":["../../../src/uploads/fileVersioning/archive.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAA;AAElF,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AACtE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAA;AAC7D,OAAO,KAAK,EAAE,cAAc,EA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ACpB,KAAG,UAAU,GAAG,SAoChB,CAAA"}
|
|
@@ -5,7 +5,7 @@ import { removeUnreferencedStagedObjects, scheduleUnreferencedFileCleanup } from
|
|
|
5
5
|
import { runFileOperationPlan, stageLocalUploadFiles } from './fileOperationManager.js';
|
|
6
6
|
import { copyLocalFile } from './localStorage.js';
|
|
7
7
|
import { getArchivedFilename } from './naming.js';
|
|
8
|
-
import { collectStoredFiles, getStoredFileIdentity, withLegacyUploadFileData } from './storedFiles.js';
|
|
8
|
+
import { collectStoredFiles, getStoredFileIdentity, getUploadFileObject, withLegacyUploadFileData } from './storedFiles.js';
|
|
9
9
|
export const runLocalFileUpdate = async ({ id, collection, current, files, next, req, write })=>{
|
|
10
10
|
const storedCurrent = withLegacyUploadFileData({
|
|
11
11
|
collection,
|
|
@@ -237,18 +237,10 @@ export const replaceStoredFileReferences = ({ files, replacements, version })=>{
|
|
|
237
237
|
}
|
|
238
238
|
const archivedFilename = path.posix.basename(archivedKey);
|
|
239
239
|
for (const role of file.roles){
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
break;
|
|
245
|
-
case 'original':
|
|
246
|
-
stored = archived.original;
|
|
247
|
-
break;
|
|
248
|
-
case 'size':
|
|
249
|
-
stored = archived.variants?.[role.sizeKey];
|
|
250
|
-
break;
|
|
251
|
-
}
|
|
240
|
+
const stored = getUploadFileObject({
|
|
241
|
+
doc: archived,
|
|
242
|
+
role
|
|
243
|
+
});
|
|
252
244
|
if (typeof stored?.filename === 'string') {
|
|
253
245
|
const previousFilename = stored.filename;
|
|
254
246
|
const directory = path.posix.dirname(previousFilename);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/uploads/fileVersioning/archive.ts"],"sourcesContent":["import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport type { SanitizedCollectionConfig } from '../../collections/config/types.js'\nimport type { Config } from '../../config/types.js'\nimport type { JsonObject, PayloadRequest } from '../../types/index.js'\nimport type { FileToSave } from '../types.js'\nimport type { StagedObject } from './fileOperationManager.js'\nimport type { StoredFileList } from './types.js'\n\nimport { saveVersion } from '../../versions/saveVersion.js'\nimport { removeUnreferencedStagedObjects, scheduleUnreferencedFileCleanup } from './cleanup.js'\nimport { runFileOperationPlan, stageLocalUploadFiles } from './fileOperationManager.js'\nimport { copyLocalFile } from './localStorage.js'\nimport { getArchivedFilename } from './naming.js'\nimport {\n collectStoredFiles,\n getStoredFileIdentity,\n withLegacyUploadFileData,\n} from './storedFiles.js'\n\ntype VersionRow = {\n createdAt: string\n id: number | string\n latest?: boolean\n parent: number | string\n publishedLocale?: string\n updatedAt: string\n version: JsonObject\n}\n\nexport const runLocalFileUpdate = async <T>({\n id,\n collection,\n current,\n files,\n next,\n req,\n write,\n}: {\n collection: SanitizedCollectionConfig\n current: JsonObject\n files: FileToSave[]\n id: number | string\n next: JsonObject\n req: PayloadRequest\n write: () => Promise<T>\n}): Promise<T> => {\n const storedCurrent = withLegacyUploadFileData({\n collection,\n config: req.payload.config,\n doc: current,\n })\n const nextDoc = { ...storedCurrent, ...next }\n\n if (\n !hasLocalFileChange({\n collection,\n config: req.payload.config,\n current,\n hasNewFiles: files.length > 0,\n next: nextDoc,\n req,\n })\n ) {\n return write()\n }\n\n return runFileOperationPlan({\n cleanupStagedAfterWriteFailure: (objects) =>\n removeUnreferencedStagedObjects({ collection, objects, req }),\n req,\n stage: ({ trackStagedObject }) =>\n stageLocalUploadFiles({\n files,\n staticDir: collection.upload.staticDir!,\n trackStagedObject,\n }),\n write: async ({ trackStagedObject }) => {\n await archiveOutgoingLocalFiles({\n id,\n collection,\n current,\n next: nextDoc,\n req,\n trackStagedObject,\n })\n\n const result = await write()\n\n await scheduleUnreferencedFileCleanup({\n candidates: getOutgoingLocalFiles({\n collection,\n config: req.payload.config,\n current,\n next: nextDoc,\n req,\n }),\n collection,\n req,\n })\n\n return result\n },\n })\n}\n\n/** Also detects removals, which have no new upload to stage. */\nconst hasLocalFileChange = ({\n collection,\n config,\n current,\n hasNewFiles,\n next,\n req,\n}: {\n collection: SanitizedCollectionConfig\n config: Pick<Config, 'routes' | 'serverURL'>\n current: JsonObject\n hasNewFiles: boolean\n next: JsonObject\n req: PayloadRequest\n}): boolean =>\n !collection.upload.disableLocalStorage &&\n (hasNewFiles ||\n getOutgoingLocalFiles({\n collection,\n config,\n current,\n next,\n req,\n }).length > 0)\n\n/** Preserves outgoing local objects and repairs every retained version that referenced them. */\nexport const archiveOutgoingLocalFiles = async ({\n id,\n collection,\n current,\n next,\n req,\n trackStagedObject,\n}: {\n collection: SanitizedCollectionConfig\n current: JsonObject\n id: number | string\n next: JsonObject\n req: PayloadRequest\n trackStagedObject: (object: StagedObject) => void\n}): Promise<void> => {\n const outgoing = getOutgoingLocalFiles({\n collection,\n config: req.payload.config,\n current,\n next,\n req,\n })\n\n if (!outgoing.length || !collection.versions) {\n return\n }\n\n const currentWithState = withLegacyUploadFileData({\n collection,\n config: req.payload.config,\n doc: current,\n })\n let versions = await getVersions({ id, collection, req })\n\n if (!versions.length) {\n await saveVersion({\n id,\n collection,\n docWithLocales: currentWithState,\n draft: false,\n operation: 'update',\n payload: req.payload,\n req,\n })\n versions = await getVersions({ id, collection, req })\n }\n\n const replacements = new Map<string, string>()\n for (const file of outgoing) {\n const identity = getStoredFileIdentity(file)\n const newestVersion = versions.find(({ version }) => {\n const stored = withLegacyUploadFileData({\n collection,\n config: req.payload.config,\n doc: version,\n })\n\n return collectStoredFiles({ collection, doc: stored, req }).some(\n (candidate) => getStoredFileIdentity(candidate) === identity,\n )\n })\n\n if (!newestVersion) {\n continue\n }\n\n const directory = path.posix.dirname(file.key)\n let archivedKey: string\n let suffix = 0\n\n while (true) {\n const archivedFilename = getArchivedFilename({\n filename: path.posix.basename(file.key),\n versionID: suffix ? `${newestVersion.id}-${suffix}` : newestVersion.id,\n })\n archivedKey = directory === '.' ? archivedFilename : `${directory}/${archivedFilename}`\n\n try {\n await copyLocalFile({\n from: file.key,\n staticDir: collection.upload.staticDir!,\n to: archivedKey,\n })\n break\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw err\n }\n suffix += 1\n }\n }\n trackStagedObject({\n key: archivedKey,\n remove: () => fs.rm(path.join(collection.upload.staticDir!, archivedKey), { force: true }),\n })\n replacements.set(identity, archivedKey)\n }\n\n for (const row of versions) {\n const stored = withLegacyUploadFileData({\n collection,\n config: req.payload.config,\n doc: row.version,\n })\n const version = replaceStoredFileReferences({\n files: collectStoredFiles({ collection, doc: stored, req }),\n replacements,\n version: stored,\n })\n\n if (!version) {\n continue\n }\n\n await req.payload.db.updateVersion({\n id: row.id,\n collection: collection.slug,\n req,\n versionData: {\n createdAt: row.createdAt,\n latest: row.latest,\n parent: row.parent,\n publishedLocale: row.publishedLocale,\n updatedAt: row.updatedAt,\n version,\n },\n })\n }\n}\n\nconst getOutgoingLocalFiles = ({\n collection,\n config,\n current,\n next,\n req,\n}: {\n collection: SanitizedCollectionConfig\n config: Pick<Config, 'routes' | 'serverURL'>\n current: JsonObject\n next: JsonObject\n req: PayloadRequest\n}): StoredFileList => {\n const currentWithState = withLegacyUploadFileData({ collection, config, doc: current })\n const currentFiles = collectStoredFiles({ collection, doc: currentWithState, req })\n const nextFiles = collectStoredFiles({ collection, doc: next, req, trustGenerated: true })\n const nextIdentities = new Set(nextFiles.map(getStoredFileIdentity))\n return currentFiles.filter((file) => !nextIdentities.has(getStoredFileIdentity(file)))\n}\n\nconst getVersions = async ({\n id,\n collection,\n req,\n}: {\n collection: SanitizedCollectionConfig\n id: number | string\n req: PayloadRequest\n}): Promise<VersionRow[]> => {\n const { docs } = await req.payload.db.findVersions<JsonObject>({\n collection: collection.slug,\n limit: 0,\n pagination: false,\n req,\n sort: '-updatedAt',\n where: { parent: { equals: id } },\n })\n\n return docs\n}\n\nexport const replaceStoredFileReferences = ({\n files,\n replacements,\n version,\n}: {\n files: StoredFileList\n replacements: Map<string, string>\n version: JsonObject\n}): JsonObject | undefined => {\n if (!files.length) {\n return\n }\n\n const archived = structuredClone(version)\n let hasChanged = false\n\n for (const file of files) {\n const archivedKey = replacements.get(getStoredFileIdentity(file))\n\n if (!archivedKey) {\n continue\n }\n\n const archivedFilename = path.posix.basename(archivedKey)\n\n for (const role of file.roles) {\n let stored: JsonObject | undefined\n switch (role.type) {\n case 'default':\n stored = archived\n break\n case 'original':\n stored = archived.original as JsonObject | undefined\n break\n case 'size':\n stored = (archived.variants as Record<string, JsonObject> | undefined)?.[role.sizeKey]\n break\n }\n\n if (typeof stored?.filename === 'string') {\n const previousFilename = stored.filename\n const directory = path.posix.dirname(previousFilename)\n const filename = directory === '.' ? archivedFilename : `${directory}/${archivedFilename}`\n stored.filename = filename\n stored.url = replaceURLFilename({\n filename,\n previousFilename,\n url: stored.url,\n })\n hasChanged = true\n }\n }\n }\n\n return hasChanged ? archived : undefined\n}\n\nconst replaceURLFilename = ({\n filename,\n previousFilename,\n url,\n}: {\n filename: string\n previousFilename: string\n url: unknown\n}): unknown => {\n if (typeof url !== 'string') {\n return url\n }\n\n const previous = encodeURIComponent(previousFilename)\n const index = url.lastIndexOf(`/${previous}`)\n\n return index < 0\n ? url\n : `${url.slice(0, index + 1)}${encodeURIComponent(filename)}${url.slice(index + 1 + previous.length)}`\n}\n"],"names":["fs","path","saveVersion","removeUnreferencedStagedObjects","scheduleUnreferencedFileCleanup","runFileOperationPlan","stageLocalUploadFiles","copyLocalFile","getArchivedFilename","collectStoredFiles","getStoredFileIdentity","withLegacyUploadFileData","runLocalFileUpdate","id","collection","current","files","next","req","write","storedCurrent","config","payload","doc","nextDoc","hasLocalFileChange","hasNewFiles","length","cleanupStagedAfterWriteFailure","objects","stage","trackStagedObject","staticDir","upload","archiveOutgoingLocalFiles","result","candidates","getOutgoingLocalFiles","disableLocalStorage","outgoing","versions","currentWithState","getVersions","docWithLocales","draft","operation","replacements","Map","file","identity","newestVersion","find","version","stored","some","candidate","directory","posix","dirname","key","archivedKey","suffix","archivedFilename","filename","basename","versionID","from","to","err","code","remove","rm","join","force","set","row","replaceStoredFileReferences","db","updateVersion","slug","versionData","createdAt","latest","parent","publishedLocale","updatedAt","currentFiles","nextFiles","trustGenerated","nextIdentities","Set","map","filter","has","docs","findVersions","limit","pagination","sort","where","equals","archived","structuredClone","hasChanged","get","role","roles","type","original","variants","sizeKey","previousFilename","url","replaceURLFilename","undefined","previous","encodeURIComponent","index","lastIndexOf","slice"],"mappings":"AAAA,OAAOA,QAAQ,mBAAkB;AACjC,OAAOC,UAAU,YAAW;AAS5B,SAASC,WAAW,QAAQ,gCAA+B;AAC3D,SAASC,+BAA+B,EAAEC,+BAA+B,QAAQ,eAAc;AAC/F,SAASC,oBAAoB,EAAEC,qBAAqB,QAAQ,4BAA2B;AACvF,SAASC,aAAa,QAAQ,oBAAmB;AACjD,SAASC,mBAAmB,QAAQ,cAAa;AACjD,SACEC,kBAAkB,EAClBC,qBAAqB,EACrBC,wBAAwB,QACnB,mBAAkB;AAYzB,OAAO,MAAMC,qBAAqB,OAAU,EAC1CC,EAAE,EACFC,UAAU,EACVC,OAAO,EACPC,KAAK,EACLC,IAAI,EACJC,GAAG,EACHC,KAAK,EASN;IACC,MAAMC,gBAAgBT,yBAAyB;QAC7CG;QACAO,QAAQH,IAAII,OAAO,CAACD,MAAM;QAC1BE,KAAKR;IACP;IACA,MAAMS,UAAU;QAAE,GAAGJ,aAAa;QAAE,GAAGH,IAAI;IAAC;IAE5C,IACE,CAACQ,mBAAmB;QAClBX;QACAO,QAAQH,IAAII,OAAO,CAACD,MAAM;QAC1BN;QACAW,aAAaV,MAAMW,MAAM,GAAG;QAC5BV,MAAMO;QACNN;IACF,IACA;QACA,OAAOC;IACT;IAEA,OAAOd,qBAAqB;QAC1BuB,gCAAgC,CAACC,UAC/B1B,gCAAgC;gBAAEW;gBAAYe;gBAASX;YAAI;QAC7DA;QACAY,OAAO,CAAC,EAAEC,iBAAiB,EAAE,GAC3BzB,sBAAsB;gBACpBU;gBACAgB,WAAWlB,WAA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AC9BlD;oBACAgD;oBACAC,KAAK3D,OAAO2D,GAAG;gBACjB;gBACAT,aAAa;YACf;QACF;IACF;IAEA,OAAOA,aAAaF,WAAWa;AACjC,EAAC;AAED,MAAMD,qBAAqB,CAAC,EAC1BlD,QAAQ,EACRgD,gBAAgB,EAChBC,GAAG,EAKJ;IACC,IAAI,OAAOA,QAAQ,UAAU;QAC3B,OAAOA;IACT;IAEA,MAAMG,WAAWC,mBAAmBL;IACpC,MAAMM,QAAQL,IAAIM,WAAW,CAAC,CAAC,CAAC,EAAEH,UAAU;IAE5C,OAAOE,QAAQ,IACXL,MACA,GAAGA,IAAIO,KAAK,CAAC,GAAGF,QAAQ,KAAKD,mBAAmBrD,YAAYiD,IAAIO,KAAK,CAACF,QAAQ,IAAIF,SAASxF,MAAM,GAAG;AAC1G"}
|
|
1
|
+
{"version":3,"sources":["../../../src/uploads/fileVersioning/archive.ts"],"sourcesContent":["import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport type { SanitizedCollectionConfig } from '../../collections/config/types.js'\nimport type { Config } from '../../config/types.js'\nimport type { JsonObject, PayloadRequest } from '../../types/index.js'\nimport type { FileToSave } from '../types.js'\nimport type { StagedObject } from './fileOperationManager.js'\nimport type { StoredFileList } from './types.js'\n\nimport { saveVersion } from '../../versions/saveVersion.js'\nimport { removeUnreferencedStagedObjects, scheduleUnreferencedFileCleanup } from './cleanup.js'\nimport { runFileOperationPlan, stageLocalUploadFiles } from './fileOperationManager.js'\nimport { copyLocalFile } from './localStorage.js'\nimport { getArchivedFilename } from './naming.js'\nimport {\n collectStoredFiles,\n getStoredFileIdentity,\n getUploadFileObject,\n withLegacyUploadFileData,\n} from './storedFiles.js'\n\ntype VersionRow = {\n createdAt: string\n id: number | string\n latest?: boolean\n parent: number | string\n publishedLocale?: string\n updatedAt: string\n version: JsonObject\n}\n\nexport const runLocalFileUpdate = async <T>({\n id,\n collection,\n current,\n files,\n next,\n req,\n write,\n}: {\n collection: SanitizedCollectionConfig\n current: JsonObject\n files: FileToSave[]\n id: number | string\n next: JsonObject\n req: PayloadRequest\n write: () => Promise<T>\n}): Promise<T> => {\n const storedCurrent = withLegacyUploadFileData({\n collection,\n config: req.payload.config,\n doc: current,\n })\n const nextDoc = { ...storedCurrent, ...next }\n\n if (\n !hasLocalFileChange({\n collection,\n config: req.payload.config,\n current,\n hasNewFiles: files.length > 0,\n next: nextDoc,\n req,\n })\n ) {\n return write()\n }\n\n return runFileOperationPlan({\n cleanupStagedAfterWriteFailure: (objects) =>\n removeUnreferencedStagedObjects({ collection, objects, req }),\n req,\n stage: ({ trackStagedObject }) =>\n stageLocalUploadFiles({\n files,\n staticDir: collection.upload.staticDir!,\n trackStagedObject,\n }),\n write: async ({ trackStagedObject }) => {\n await archiveOutgoingLocalFiles({\n id,\n collection,\n current,\n next: nextDoc,\n req,\n trackStagedObject,\n })\n\n const result = await write()\n\n await scheduleUnreferencedFileCleanup({\n candidates: getOutgoingLocalFiles({\n collection,\n config: req.payload.config,\n current,\n next: nextDoc,\n req,\n }),\n collection,\n req,\n })\n\n return result\n },\n })\n}\n\n/** Also detects removals, which have no new upload to stage. */\nconst hasLocalFileChange = ({\n collection,\n config,\n current,\n hasNewFiles,\n next,\n req,\n}: {\n collection: SanitizedCollectionConfig\n config: Pick<Config, 'routes' | 'serverURL'>\n current: JsonObject\n hasNewFiles: boolean\n next: JsonObject\n req: PayloadRequest\n}): boolean =>\n !collection.upload.disableLocalStorage &&\n (hasNewFiles ||\n getOutgoingLocalFiles({\n collection,\n config,\n current,\n next,\n req,\n }).length > 0)\n\n/** Preserves outgoing local objects and repairs every retained version that referenced them. */\nexport const archiveOutgoingLocalFiles = async ({\n id,\n collection,\n current,\n next,\n req,\n trackStagedObject,\n}: {\n collection: SanitizedCollectionConfig\n current: JsonObject\n id: number | string\n next: JsonObject\n req: PayloadRequest\n trackStagedObject: (object: StagedObject) => void\n}): Promise<void> => {\n const outgoing = getOutgoingLocalFiles({\n collection,\n config: req.payload.config,\n current,\n next,\n req,\n })\n\n if (!outgoing.length || !collection.versions) {\n return\n }\n\n const currentWithState = withLegacyUploadFileData({\n collection,\n config: req.payload.config,\n doc: current,\n })\n let versions = await getVersions({ id, collection, req })\n\n if (!versions.length) {\n await saveVersion({\n id,\n collection,\n docWithLocales: currentWithState,\n draft: false,\n operation: 'update',\n payload: req.payload,\n req,\n })\n versions = await getVersions({ id, collection, req })\n }\n\n const replacements = new Map<string, string>()\n for (const file of outgoing) {\n const identity = getStoredFileIdentity(file)\n const newestVersion = versions.find(({ version }) => {\n const stored = withLegacyUploadFileData({\n collection,\n config: req.payload.config,\n doc: version,\n })\n\n return collectStoredFiles({ collection, doc: stored, req }).some(\n (candidate) => getStoredFileIdentity(candidate) === identity,\n )\n })\n\n if (!newestVersion) {\n continue\n }\n\n const directory = path.posix.dirname(file.key)\n let archivedKey: string\n let suffix = 0\n\n while (true) {\n const archivedFilename = getArchivedFilename({\n filename: path.posix.basename(file.key),\n versionID: suffix ? `${newestVersion.id}-${suffix}` : newestVersion.id,\n })\n archivedKey = directory === '.' ? archivedFilename : `${directory}/${archivedFilename}`\n\n try {\n await copyLocalFile({\n from: file.key,\n staticDir: collection.upload.staticDir!,\n to: archivedKey,\n })\n break\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw err\n }\n suffix += 1\n }\n }\n trackStagedObject({\n key: archivedKey,\n remove: () => fs.rm(path.join(collection.upload.staticDir!, archivedKey), { force: true }),\n })\n replacements.set(identity, archivedKey)\n }\n\n for (const row of versions) {\n const stored = withLegacyUploadFileData({\n collection,\n config: req.payload.config,\n doc: row.version,\n })\n const version = replaceStoredFileReferences({\n files: collectStoredFiles({ collection, doc: stored, req }),\n replacements,\n version: stored,\n })\n\n if (!version) {\n continue\n }\n\n await req.payload.db.updateVersion({\n id: row.id,\n collection: collection.slug,\n req,\n versionData: {\n createdAt: row.createdAt,\n latest: row.latest,\n parent: row.parent,\n publishedLocale: row.publishedLocale,\n updatedAt: row.updatedAt,\n version,\n },\n })\n }\n}\n\nconst getOutgoingLocalFiles = ({\n collection,\n config,\n current,\n next,\n req,\n}: {\n collection: SanitizedCollectionConfig\n config: Pick<Config, 'routes' | 'serverURL'>\n current: JsonObject\n next: JsonObject\n req: PayloadRequest\n}): StoredFileList => {\n const currentWithState = withLegacyUploadFileData({ collection, config, doc: current })\n const currentFiles = collectStoredFiles({ collection, doc: currentWithState, req })\n const nextFiles = collectStoredFiles({ collection, doc: next, req, trustGenerated: true })\n const nextIdentities = new Set(nextFiles.map(getStoredFileIdentity))\n return currentFiles.filter((file) => !nextIdentities.has(getStoredFileIdentity(file)))\n}\n\nconst getVersions = async ({\n id,\n collection,\n req,\n}: {\n collection: SanitizedCollectionConfig\n id: number | string\n req: PayloadRequest\n}): Promise<VersionRow[]> => {\n const { docs } = await req.payload.db.findVersions<JsonObject>({\n collection: collection.slug,\n limit: 0,\n pagination: false,\n req,\n sort: '-updatedAt',\n where: { parent: { equals: id } },\n })\n\n return docs\n}\n\nexport const replaceStoredFileReferences = ({\n files,\n replacements,\n version,\n}: {\n files: StoredFileList\n replacements: Map<string, string>\n version: JsonObject\n}): JsonObject | undefined => {\n if (!files.length) {\n return\n }\n\n const archived = structuredClone(version)\n let hasChanged = false\n\n for (const file of files) {\n const archivedKey = replacements.get(getStoredFileIdentity(file))\n\n if (!archivedKey) {\n continue\n }\n\n const archivedFilename = path.posix.basename(archivedKey)\n\n for (const role of file.roles) {\n const stored = getUploadFileObject({ doc: archived, role })\n\n if (typeof stored?.filename === 'string') {\n const previousFilename = stored.filename\n const directory = path.posix.dirname(previousFilename)\n const filename = directory === '.' ? archivedFilename : `${directory}/${archivedFilename}`\n stored.filename = filename\n stored.url = replaceURLFilename({\n filename,\n previousFilename,\n url: stored.url,\n })\n hasChanged = true\n }\n }\n }\n\n return hasChanged ? archived : undefined\n}\n\nconst replaceURLFilename = ({\n filename,\n previousFilename,\n url,\n}: {\n filename: string\n previousFilename: string\n url: unknown\n}): unknown => {\n if (typeof url !== 'string') {\n return url\n }\n\n const previous = encodeURIComponent(previousFilename)\n const index = url.lastIndexOf(`/${previous}`)\n\n return index < 0\n ? url\n : `${url.slice(0, index + 1)}${encodeURIComponent(filename)}${url.slice(index + 1 + previous.length)}`\n}\n"],"names":["fs","path","saveVersion","removeUnreferencedStagedObjects","scheduleUnreferencedFileCleanup","runFileOperationPlan","stageLocalUploadFiles","copyLocalFile","getArchivedFilename","collectStoredFiles","getStoredFileIdentity","getUploadFileObject","withLegacyUploadFileData","runLocalFileUpdate","id","collection","current","files","next","req","write","storedCurrent","config","payload","doc","nextDoc","hasLocalFileChange","hasNewFiles","length","cleanupStagedAfterWriteFailure","objects","stage","trackStagedObject","staticDir","upload","archiveOutgoingLocalFiles","result","candidates","getOutgoingLocalFiles","disableLocalStorage","outgoing","versions","currentWithState","getVersions","docWithLocales","draft","operation","replacements","Map","file","identity","newestVersion","find","version","stored","some","candidate","directory","posix","dirname","key","archivedKey","suffix","archivedFilename","filename","basename","versionID","from","to","err","code","remove","rm","join","force","set","row","replaceStoredFileReferences","db","updateVersion","slug","versionData","createdAt","latest","parent","publishedLocale","updatedAt","currentFiles","nextFiles","trustGenerated","nextIdentities","Set","map","filter","has","docs","findVersions","limit","pagination","sort","where","equals","archived","structuredClone","hasChanged","get","role","roles","previousFilename","url","replaceURLFilename","undefined","previous","encodeURIComponent","index","lastIndexOf","slice"],"mappings":"AAAA,OAAOA,QAAQ,mBAAkB;AACjC,OAAOC,UAAU,YAAW;AAS5B,SAASC,WAAW,QAAQ,gCAA+B;AAC3D,SAASC,+BAA+B,EAAEC,+BAA+B,QAAQ,eAAc;AAC/F,SAASC,oBAAoB,EAAEC,qBAAqB,QAAQ,4BAA2B;AACvF,SAASC,aAAa,QAAQ,oBAAmB;AACjD,SAASC,mBAAmB,QAAQ,cAAa;AACjD,SACEC,kBAAkB,EAClBC,qBAAqB,EACrBC,mBAAmB,EACnBC,wBAAwB,QACnB,mBAAkB;AAYzB,OAAO,MAAMC,qBAA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} from '../../versions/saveVersion.js';
|
|
2
2
|
import { collectStoredFiles as collectSavedFiles, removeUnreferencedStagedObjects, scheduleUnreferencedFileCleanup } from './cleanup.js';
|
|
3
3
|
import { runFileCreationPlan, runFileOperationPlan } from './fileOperationManager.js';
|
|
4
|
-
import { collectStoredFiles, getStoredFileIdentity, withLegacyCloudUploadFileData } from './storedFiles.js';
|
|
4
|
+
import { collectStoredFiles, getStoredFileIdentity, isManagedUpload, withLegacyCloudUploadFileData } from './storedFiles.js';
|
|
5
5
|
/** Request context keys that carry one upload's cloud storage state. */ const cloudStorageStateKeys = [
|
|
6
6
|
'_payloadCloudStorage',
|
|
7
7
|
'_payloadManagedCloudMetadata',
|
|
@@ -122,9 +122,9 @@ export const runCloudFileUpdate = async ({ id, collection, current, data, files,
|
|
|
122
122
|
Object.assign(data, metadata);
|
|
123
123
|
},
|
|
124
124
|
write: async ()=>{
|
|
125
|
-
if (collection.versions && !
|
|
125
|
+
if (collection.versions && !isManagedUpload({
|
|
126
126
|
doc: current
|
|
127
|
-
}) &&
|
|
127
|
+
}) && isManagedUpload({
|
|
128
128
|
doc: storedCurrent
|
|
129
129
|
})) {
|
|
130
130
|
await persistLegacyCloudVersions({
|
|
@@ -201,7 +201,7 @@ const persistLegacyCloudVersions = async ({ id, collection, current, req })=>{
|
|
|
201
201
|
});
|
|
202
202
|
for (const row of versions.docs){
|
|
203
203
|
hasVersions = true;
|
|
204
|
-
if (
|
|
204
|
+
if (isManagedUpload({
|
|
205
205
|
doc: row.version
|
|
206
206
|
})) {
|
|
207
207
|
continue;
|
|
@@ -211,7 +211,7 @@ const persistLegacyCloudVersions = async ({ id, collection, current, req })=>{
|
|
|
211
211
|
doc: row.version,
|
|
212
212
|
req
|
|
213
213
|
});
|
|
214
|
-
if (!
|
|
214
|
+
if (!isManagedUpload({
|
|
215
215
|
doc: version
|
|
216
216
|
})) {
|
|
217
217
|
continue;
|
|
@@ -235,7 +235,7 @@ const persistLegacyCloudVersions = async ({ id, collection, current, req })=>{
|
|
|
235
235
|
}
|
|
236
236
|
page += 1;
|
|
237
237
|
}
|
|
238
|
-
if (!hasVersions &&
|
|
238
|
+
if (!hasVersions && isManagedUpload({
|
|
239
239
|
doc: current
|
|
240
240
|
})) {
|
|
241
241
|
await saveVersion({
|
|
@@ -249,7 +249,6 @@ const persistLegacyCloudVersions = async ({ id, collection, current, req })=>{
|
|
|
249
249
|
});
|
|
250
250
|
}
|
|
251
251
|
};
|
|
252
|
-
const hasStoredOriginal = ({ doc })=>Boolean(doc.original && typeof doc.original === 'object' && typeof doc.original.filename === 'string');
|
|
253
252
|
const withCloudHookGuard = async ({ metadata, req, write })=>{
|
|
254
253
|
const restoreCloudHookState = captureCloudHookState({
|
|
255
254
|
req
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/uploads/fileVersioning/cloudStorage.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../../collections/config/types.js'\nimport type { JsonObject, PayloadRequest } from '../../types/index.js'\nimport type { FileToSave } from '../types.js'\nimport type { StagedObject } from './fileOperationManager.js'\n\nimport { saveVersion } from '../../versions/saveVersion.js'\nimport {\n collectStoredFiles as collectSavedFiles,\n removeUnreferencedStagedObjects,\n scheduleUnreferencedFileCleanup,\n} from './cleanup.js'\nimport { runFileCreationPlan, runFileOperationPlan } from './fileOperationManager.js'\nimport {\n collectStoredFiles,\n getStoredFileIdentity,\n withLegacyCloudUploadFileData,\n} from './storedFiles.js'\n\n/** Request context keys that carry one upload's cloud storage state. */\nconst cloudStorageStateKeys = [\n '_payloadCloudStorage',\n '_payloadManagedCloudMetadata',\n '_payloadManagedCloudStorage',\n '_payloadVerifiedProviderOriginal',\n 'skipCloudStorage',\n]\n\n/**\n * Removes the caller's cloud storage state from `req.context`, for a nested file operation that\n * shares the caller's context. Returns a function that puts the caller's values back.\n */\nexport const hideCloudStorageState = ({ req }: { req: PayloadRequest }): (() => void) => {\n const restoreCloudStorageState = captureContextKeys({ keys: cloudStorageStateKeys, req })\n\n for (const key of cloudStorageStateKeys) {\n delete req.context?.[key]\n }\n\n return restoreCloudStorageState\n}\n\n/** Preserve the caller's cloud flags; nested Local API calls can replace req.context. */\nexport const captureCloudHookState = ({ req }: { req: PayloadRequest }): (() => void) =>\n captureContextKeys({\n keys: ['_payloadManagedCloudStorage', '_payloadManagedCloudMetadata'],\n req,\n })\n\nexport const runCloudFileCreation = async <T>({\n collection,\n data,\n files,\n req,\n write,\n}: {\n collection: SanitizedCollectionConfig\n data: JsonObject\n files: FileToSave[]\n req: PayloadRequest\n write: () => Promise<T>\n}): Promise<T> => {\n const operations = collection.upload.fileOperations\n\n if (\n !operations ||\n req.context?.skipCloudStorage ||\n (files.length === 0 && !req.context?._payloadVerifiedProviderOriginal)\n ) {\n return write()\n }\n\n let metadata: Record<string, unknown> = {}\n\n return runFileCreationPlan({\n cleanupStagedAfterWriteFailure: (objects) =>\n removeUnreferencedStagedObjects({ collection, objects, req }),\n req,\n stage: async ({ trackStagedObject }) => {\n trackClientUploadOriginal({ collection, data, req, trackStagedObject })\n const staged = await operations.stage({\n data,\n files,\n req,\n trackStagedObject,\n })\n metadata = staged.metadata\n Object.assign(data, metadata)\n },\n // Create's version and afterChange hooks run after the database insert. The\n // outer create operation restores the previous guard after those hooks finish.\n write: () => {\n req.context ??= {}\n req.context._payloadManagedCloudStorage = true\n req.context._payloadManagedCloudMetadata = metadata\n return write()\n },\n })\n}\n\nexport const runCloudFileUpdate = async <T>({\n id,\n collection,\n current,\n data,\n files,\n req,\n write,\n}: {\n collection: SanitizedCollectionConfig\n current: JsonObject\n data: JsonObject\n files: FileToSave[]\n id: number | string\n req: PayloadRequest\n write: () => Promise<T>\n}): Promise<T> => {\n const operations = collection.upload.fileOperations\n const storedCurrent = operations\n ? await withLegacyCloudUploadFileData({ collection, doc: current, req })\n : current\n const nextFiles = collectStoredFiles({\n collection,\n doc: { ...storedCurrent, ...data },\n req,\n trustGenerated: true,\n })\n const currentFiles = collectStoredFiles({ collection, doc: storedCurrent, req })\n const nextIdentities = new Set(nextFiles.map(getStoredFileIdentity))\n const hasStoredFileChange =\n nextIdentities.size !== currentFiles.length ||\n currentFiles.some((file) => !nextIdentities.has(getStoredFileIdentity(file)))\n\n if (\n !operations ||\n req.context?.skipCloudStorage ||\n (files.length === 0 && !req.context?._payloadVerifiedProviderOriginal && !hasStoredFileChange)\n ) {\n return write()\n }\n\n let metadata: Record<string, unknown> = {}\n\n return runFileOperationPlan({\n cleanupStagedAfterWriteFailure: (objects) =>\n removeUnreferencedStagedObjects({ collection, objects, req }),\n req,\n stage: async ({ trackStagedObject }) => {\n if (files.length === 0 && !req.context?._payloadVerifiedProviderOriginal) {\n return\n }\n trackClientUploadOriginal({ collection, data, req, trackStagedObject })\n const staged = await operations.stage({\n data,\n files,\n req,\n trackStagedObject,\n })\n metadata = staged.metadata\n Object.assign(data, metadata)\n },\n write: async () => {\n if (\n collection.versions &&\n !hasStoredOriginal({ doc: current }) &&\n hasStoredOriginal({ doc: storedCurrent })\n ) {\n await persistLegacyCloudVersions({ id, collection, current: storedCurrent, req })\n }\n\n const result = await withCloudHookGuard({\n metadata,\n req,\n write,\n })\n\n await scheduleUnreferencedFileCleanup({\n candidates: await collectSavedFiles({ collection, doc: storedCurrent, req }),\n collection,\n req,\n })\n\n return result\n },\n })\n}\n\n/** Track a verified client-uploaded source, retaining it if another document still references it. */\nconst trackClientUploadOriginal = ({\n collection,\n data,\n req,\n trackStagedObject,\n}: {\n collection: SanitizedCollectionConfig\n data: JsonObject\n req: PayloadRequest\n trackStagedObject: (object: StagedObject) => void\n}): void => {\n const verifiedOriginal = req.context?._payloadVerifiedProviderOriginal as\n | { key: string }\n | undefined\n\n if (!verifiedOriginal) {\n return\n }\n\n const original = collectStoredFiles({ collection, doc: data, req, trustGenerated: true }).find(\n ({ key, roles }) =>\n key === verifiedOriginal.key && roles.some((role) => role.type === 'original'),\n )\n\n if (!original) {\n return\n }\n\n const object: StagedObject = {\n key: original.key,\n remove: () => collection.upload.fileOperations!.delete({ key: original.key, req }),\n }\n\n trackStagedObject({\n key: object.key,\n remove: () => removeUnreferencedStagedObjects({ collection, objects: [object], req }),\n })\n}\n\nconst persistLegacyCloudVersions = async ({\n id,\n collection,\n current,\n req,\n}: {\n collection: SanitizedCollectionConfig\n current: JsonObject\n id: number | string\n req: PayloadRequest\n}): Promise<void> => {\n let page = 1\n let hasVersions = false\n\n while (true) {\n const versions = await req.payload.db.findVersions<JsonObject>({\n collection: collection.slug,\n limit: 100,\n page,\n req,\n where: { parent: { equals: id } },\n })\n\n for (const row of versions.docs) {\n hasVersions = true\n if (hasStoredOriginal({ doc: row.version })) {\n continue\n }\n\n const version = await withLegacyCloudUploadFileData({\n collection,\n doc: row.version,\n req,\n })\n if (!hasStoredOriginal({ doc: version })) {\n continue\n }\n\n await req.payload.db.updateVersion({\n id: row.id,\n collection: collection.slug,\n req,\n versionData: {\n createdAt: row.createdAt,\n latest: row.latest,\n parent: row.parent,\n publishedLocale: row.publishedLocale,\n updatedAt: row.updatedAt,\n version,\n },\n })\n }\n\n if (versions.docs.length < 100) {\n break\n }\n page += 1\n }\n\n if (!hasVersions && hasStoredOriginal({ doc: current })) {\n await saveVersion({\n id,\n collection,\n docWithLocales: current,\n draft: false,\n operation: 'update',\n payload: req.payload,\n req,\n })\n }\n}\n\nconst hasStoredOriginal = ({ doc }: { doc: JsonObject }): boolean =>\n Boolean(\n doc.original &&\n typeof doc.original === 'object' &&\n typeof (doc.original as Record<string, unknown>).filename === 'string',\n )\n\nconst withCloudHookGuard = async <T>({\n metadata,\n req,\n write,\n}: {\n metadata: Record<string, unknown>\n req: PayloadRequest\n write: () => Promise<T>\n}): Promise<T> => {\n const restoreCloudHookState = captureCloudHookState({ req })\n req.context ??= {}\n req.context._payloadManagedCloudStorage = true\n req.context._payloadManagedCloudMetadata = metadata\n\n try {\n return await write()\n } finally {\n restoreCloudHookState()\n }\n}\n\n/** Returns a function that puts back the current values of `keys` in `req.context`. */\nconst captureContextKeys = ({\n keys,\n req,\n}: {\n keys: string[]\n req: PayloadRequest\n}): (() => void) => {\n const previousState = keys.map((key) => ({\n hasProperty: Object.hasOwn(req.context ?? {}, key),\n key,\n value: req.context?.[key],\n }))\n\n return () => {\n req.context ??= {}\n for (const { hasProperty, key, value } of previousState) {\n if (hasProperty) {\n req.context[key] = value\n } else {\n delete req.context[key]\n }\n }\n }\n}\n"],"names":["saveVersion","collectStoredFiles","collectSavedFiles","removeUnreferencedStagedObjects","scheduleUnreferencedFileCleanup","runFileCreationPlan","runFileOperationPlan","getStoredFileIdentity","withLegacyCloudUploadFileData","cloudStorageStateKeys","hideCloudStorageState","req","restoreCloudStorageState","captureContextKeys","keys","key","context","captureCloudHookState","runCloudFileCreation","collection","data","files","write","operations","upload","fileOperations","skipCloudStorage","length","_payloadVerifiedProviderOriginal","metadata","cleanupStagedAfterWriteFailure","objects","stage","trackStagedObject","trackClientUploadOriginal","staged","Object","assign","_payloadManagedCloudStorage","_payloadManagedCloudMetadata","runCloudFileUpdate","id","current","storedCurrent","doc","nextFiles","trustGenerated","currentFiles","nextIdentities","Set","map","hasStoredFileChange","size","some","file","has","versions","hasStoredOriginal","persistLegacyCloudVersions","result","withCloudHookGuard","candidates","verifiedOriginal","original","find","roles","role","type","object","remove","delete","page","hasVersions","payload","db","findVersions","slug","limit","where","parent","equals","row","docs","version","updateVersion","versionData","createdAt","latest","publishedLocale","updatedAt","docWithLocales","draft","operation","Boolean","filename","restoreCloudHookState","previousState","hasProperty","hasOwn","value"],"mappings":"AAKA,SAASA,WAAW,QAAQ,gCAA+B;AAC3D,SACEC,sBAAsBC,iBAAiB,EACvCC,+BAA+B,EAC/BC,+BAA+B,QAC1B,eAAc;AACrB,SAASC,mBAAmB,EAAEC,oBAAoB,QAAQ,4BAA2B;AACrF,SACEL,kBAAkB,EAClBM,qBAAqB,EACrBC,6BAA6B,QACxB,mBAAkB;AAEzB,sEAAsE,GACtE,MAAMC,wBAAwB;IAC5B;IACA;IACA;IACA;IACA;CAC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B9D;QACF;IACF;AACF;AAEA,MAAM8C,oBAAoB,CAAC,EAAEb,GAAG,EAAuB,GACrDiD,QACEjD,IAAImB,QAAQ,IACZ,OAAOnB,IAAImB,QAAQ,KAAK,YACxB,OAAO,AAACnB,IAAImB,QAAQ,CAA6B+B,QAAQ,KAAK;AAGlE,MAAMlC,qBAAqB,OAAU,EACnC/B,QAAQ,EACRlB,GAAG,EACHW,KAAK,EAKN;IACC,MAAMyE,wBAAwB9E,sBAAsB;QAAEN;IAAI;IAC1DA,IAAIK,OAAO,KAAK,CAAC;IACjBL,IAAIK,OAAO,CAACsB,2BAA2B,GAAG;IAC1C3B,IAAIK,OAAO,CAACuB,4BAA4B,GAAGV;IAE3C,IAAI;QACF,OAAO,MAAMP;IACf,SAAU;QACRyE;IACF;AACF;AAEA,qFAAqF,GACrF,MAAMlF,qBAAqB,CAAC,EAC1BC,IAAI,EACJH,GAAG,EAIJ;IACC,MAAMqF,gBAAgBlF,KAAKoC,GAAG,CAAC,CAACnC,MAAS,CAAA;YACvCkF,aAAa7D,OAAO8D,MAAM,CAACvF,IAAIK,OAAO,IAAI,CAAC,GAAGD;YAC9CA;YACAoF,OAAOxF,IAAIK,OAAO,EAAE,CAACD,IAAI;QAC3B,CAAA;IAEA,OAAO;QACLJ,IAAIK,OAAO,KAAK,CAAC;QACjB,KAAK,MAAM,EAAEiF,WAAW,EAAElF,GAAG,EAAEoF,KAAK,EAAE,IAAIH,cAAe;YACvD,IAAIC,aAAa;gBACftF,IAAIK,OAAO,CAACD,IAAI,GAAGoF;YACrB,OAAO;gBACL,OAAOxF,IAAIK,OAAO,CAACD,IAAI;YACzB;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/uploads/fileVersioning/cloudStorage.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../../collections/config/types.js'\nimport type { JsonObject, PayloadRequest } from '../../types/index.js'\nimport type { FileToSave } from '../types.js'\nimport type { StagedObject } from './fileOperationManager.js'\n\nimport { saveVersion } from '../../versions/saveVersion.js'\nimport {\n collectStoredFiles as collectSavedFiles,\n removeUnreferencedStagedObjects,\n scheduleUnreferencedFileCleanup,\n} from './cleanup.js'\nimport { runFileCreationPlan, runFileOperationPlan } from './fileOperationManager.js'\nimport {\n collectStoredFiles,\n getStoredFileIdentity,\n isManagedUpload,\n withLegacyCloudUploadFileData,\n} from './storedFiles.js'\n\n/** Request context keys that carry one upload's cloud storage state. */\nconst cloudStorageStateKeys = [\n '_payloadCloudStorage',\n '_payloadManagedCloudMetadata',\n '_payloadManagedCloudStorage',\n '_payloadVerifiedProviderOriginal',\n 'skipCloudStorage',\n]\n\n/**\n * Removes the caller's cloud storage state from `req.context`, for a nested file operation that\n * shares the caller's context. Returns a function that puts the caller's values back.\n */\nexport const hideCloudStorageState = ({ req }: { req: PayloadRequest }): (() => void) => {\n const restoreCloudStorageState = captureContextKeys({ keys: cloudStorageStateKeys, req })\n\n for (const key of cloudStorageStateKeys) {\n delete req.context?.[key]\n }\n\n return restoreCloudStorageState\n}\n\n/** Preserve the caller's cloud flags; nested Local API calls can replace req.context. */\nexport const captureCloudHookState = ({ req }: { req: PayloadRequest }): (() => void) =>\n captureContextKeys({\n keys: ['_payloadManagedCloudStorage', '_payloadManagedCloudMetadata'],\n req,\n })\n\nexport const runCloudFileCreation = async <T>({\n collection,\n data,\n files,\n req,\n write,\n}: {\n collection: SanitizedCollectionConfig\n data: JsonObject\n files: FileToSave[]\n req: PayloadRequest\n write: () => Promise<T>\n}): Promise<T> => {\n const operations = collection.upload.fileOperations\n\n if (\n !operations ||\n req.context?.skipCloudStorage ||\n (files.length === 0 && !req.context?._payloadVerifiedProviderOriginal)\n ) {\n return write()\n }\n\n let metadata: Record<string, unknown> = {}\n\n return runFileCreationPlan({\n cleanupStagedAfterWriteFailure: (objects) =>\n removeUnreferencedStagedObjects({ collection, objects, req }),\n req,\n stage: async ({ trackStagedObject }) => {\n trackClientUploadOriginal({ collection, data, req, trackStagedObject })\n const staged = await operations.stage({\n data,\n files,\n req,\n trackStagedObject,\n })\n metadata = staged.metadata\n Object.assign(data, metadata)\n },\n // Create's version and afterChange hooks run after the database insert. The\n // outer create operation restores the previous guard after those hooks finish.\n write: () => {\n req.context ??= {}\n req.context._payloadManagedCloudStorage = true\n req.context._payloadManagedCloudMetadata = metadata\n return write()\n },\n })\n}\n\nexport const runCloudFileUpdate = async <T>({\n id,\n collection,\n current,\n data,\n files,\n req,\n write,\n}: {\n collection: SanitizedCollectionConfig\n current: JsonObject\n data: JsonObject\n files: FileToSave[]\n id: number | string\n req: PayloadRequest\n write: () => Promise<T>\n}): Promise<T> => {\n const operations = collection.upload.fileOperations\n const storedCurrent = operations\n ? await withLegacyCloudUploadFileData({ collection, doc: current, req })\n : current\n const nextFiles = collectStoredFiles({\n collection,\n doc: { ...storedCurrent, ...data },\n req,\n trustGenerated: true,\n })\n const currentFiles = collectStoredFiles({ collection, doc: storedCurrent, req })\n const nextIdentities = new Set(nextFiles.map(getStoredFileIdentity))\n const hasStoredFileChange =\n nextIdentities.size !== currentFiles.length ||\n currentFiles.some((file) => !nextIdentities.has(getStoredFileIdentity(file)))\n\n if (\n !operations ||\n req.context?.skipCloudStorage ||\n (files.length === 0 && !req.context?._payloadVerifiedProviderOriginal && !hasStoredFileChange)\n ) {\n return write()\n }\n\n let metadata: Record<string, unknown> = {}\n\n return runFileOperationPlan({\n cleanupStagedAfterWriteFailure: (objects) =>\n removeUnreferencedStagedObjects({ collection, objects, req }),\n req,\n stage: async ({ trackStagedObject }) => {\n if (files.length === 0 && !req.context?._payloadVerifiedProviderOriginal) {\n return\n }\n trackClientUploadOriginal({ collection, data, req, trackStagedObject })\n const staged = await operations.stage({\n data,\n files,\n req,\n trackStagedObject,\n })\n metadata = staged.metadata\n Object.assign(data, metadata)\n },\n write: async () => {\n if (\n collection.versions &&\n !isManagedUpload({ doc: current }) &&\n isManagedUpload({ doc: storedCurrent })\n ) {\n await persistLegacyCloudVersions({ id, collection, current: storedCurrent, req })\n }\n\n const result = await withCloudHookGuard({\n metadata,\n req,\n write,\n })\n\n await scheduleUnreferencedFileCleanup({\n candidates: await collectSavedFiles({ collection, doc: storedCurrent, req }),\n collection,\n req,\n })\n\n return result\n },\n })\n}\n\n/** Track a verified client-uploaded source, retaining it if another document still references it. */\nconst trackClientUploadOriginal = ({\n collection,\n data,\n req,\n trackStagedObject,\n}: {\n collection: SanitizedCollectionConfig\n data: JsonObject\n req: PayloadRequest\n trackStagedObject: (object: StagedObject) => void\n}): void => {\n const verifiedOriginal = req.context?._payloadVerifiedProviderOriginal as\n | { key: string }\n | undefined\n\n if (!verifiedOriginal) {\n return\n }\n\n const original = collectStoredFiles({ collection, doc: data, req, trustGenerated: true }).find(\n ({ key, roles }) =>\n key === verifiedOriginal.key && roles.some((role) => role.type === 'original'),\n )\n\n if (!original) {\n return\n }\n\n const object: StagedObject = {\n key: original.key,\n remove: () => collection.upload.fileOperations!.delete({ key: original.key, req }),\n }\n\n trackStagedObject({\n key: object.key,\n remove: () => removeUnreferencedStagedObjects({ collection, objects: [object], req }),\n })\n}\n\nconst persistLegacyCloudVersions = async ({\n id,\n collection,\n current,\n req,\n}: {\n collection: SanitizedCollectionConfig\n current: JsonObject\n id: number | string\n req: PayloadRequest\n}): Promise<void> => {\n let page = 1\n let hasVersions = false\n\n while (true) {\n const versions = await req.payload.db.findVersions<JsonObject>({\n collection: collection.slug,\n limit: 100,\n page,\n req,\n where: { parent: { equals: id } },\n })\n\n for (const row of versions.docs) {\n hasVersions = true\n if (isManagedUpload({ doc: row.version })) {\n continue\n }\n\n const version = await withLegacyCloudUploadFileData({\n collection,\n doc: row.version,\n req,\n })\n if (!isManagedUpload({ doc: version })) {\n continue\n }\n\n await req.payload.db.updateVersion({\n id: row.id,\n collection: collection.slug,\n req,\n versionData: {\n createdAt: row.createdAt,\n latest: row.latest,\n parent: row.parent,\n publishedLocale: row.publishedLocale,\n updatedAt: row.updatedAt,\n version,\n },\n })\n }\n\n if (versions.docs.length < 100) {\n break\n }\n page += 1\n }\n\n if (!hasVersions && isManagedUpload({ doc: current })) {\n await saveVersion({\n id,\n collection,\n docWithLocales: current,\n draft: false,\n operation: 'update',\n payload: req.payload,\n req,\n })\n }\n}\n\nconst withCloudHookGuard = async <T>({\n metadata,\n req,\n write,\n}: {\n metadata: Record<string, unknown>\n req: PayloadRequest\n write: () => Promise<T>\n}): Promise<T> => {\n const restoreCloudHookState = captureCloudHookState({ req })\n req.context ??= {}\n req.context._payloadManagedCloudStorage = true\n req.context._payloadManagedCloudMetadata = metadata\n\n try {\n return await write()\n } finally {\n restoreCloudHookState()\n }\n}\n\n/** Returns a function that puts back the current values of `keys` in `req.context`. */\nconst captureContextKeys = ({\n keys,\n req,\n}: {\n keys: string[]\n req: PayloadRequest\n}): (() => void) => {\n const previousState = keys.map((key) => ({\n hasProperty: Object.hasOwn(req.context ?? {}, key),\n key,\n value: req.context?.[key],\n }))\n\n return () => {\n req.context ??= {}\n for (const { hasProperty, key, value } of previousState) {\n if (hasProperty) {\n req.context[key] = value\n } else {\n delete req.context[key]\n }\n }\n }\n}\n"],"names":["saveVersion","collectStoredFiles","collectSavedFiles","removeUnreferencedStagedObjects","scheduleUnreferencedFileCleanup","runFileCreationPlan","runFileOperationPlan","getStoredFileIdentity","isManagedUpload","withLegacyCloudUploadFileData","cloudStorageStateKeys","hideCloudStorageState","req","restoreCloudStorageState","captureContextKeys","keys","key","context","captureCloudHookState","runCloudFileCreation","collection","data","files","write","operations","upload","fileOperations","skipCloudStorage","length","_payloadVerifiedProviderOriginal","metadata","cleanupStagedAfterWriteFailure","objects","stage","trackStagedObject","trackClientUploadOriginal","staged","Object","assign","_payloadManagedCloudStorage","_payloadManagedCloudMetadata","runCloudFileUpdate","id","current","storedCurrent","doc","nextFiles","trustGenerated","currentFiles","nextIdentities","Set","map","hasStoredFileChange","size","some","file","has","versions","persistLegacyCloudVersions","result","withCloudHookGuard","candidates","verifiedOriginal","original","find","roles","role","type","object","remove","delete","page","hasVersions","payload","db","findVersions","slug","limit","where","parent","equals","row","docs","version","updateVersion","versionData","createdAt","latest","publishedLocale","updatedAt","docWithLocales","draft","operation","restoreCloudHookState","previousState","hasProperty","hasOwn","value"],"mappings":"AAKA,SAASA,WAAW,QAAQ,gCAA+B;AAC3D,SACEC,sBAAsBC,iBAAiB,EACvCC,+BAA+B,EAC/BC,+BAA+B,QAC1B,eAAc;AACrB,SAASC,mBAAmB,EAAEC,oBAAoB,QAAQ,4BAA2B;AACrF,SACEL,kBAAkB,EAClBM,qBAAqB,EACrBC,eAAe,EACfC,6BAA6B,QACxB,mBAAkB;AAEzB,sEAAsE,GACtE,MAAMC,wBAAwB;IAC5B;IACA;IACA;IACA;IACA;CACD;AAED;;;CAGC,GACD,OAAO,MAAMC,wBAAwB,CAAC,EAAEC,GAAG,EAA2B;IACpE,MAAMC,2BAA2BC,mBAAmB;QAAEC,MAAML;QAAuBE;IAAI;IAEvF,KAAK,MAAMI,OAAON,sBAAuB;QACvC,OAAOE,IAAIK,OAAO,EAAE,CAACD,IAAI;IAC3B;IAEA,OAAOH;AACT,EAAC;AAED,uFAAuF,GACvF,OAAO,MAAMK,wBAAwB,CAAC,EAAEN,GAAG,EAA2B,GACpEE,mBAAmB;QACjBC,MAAM;YAAC;YAA+B;SAA+B;QACrEH;IACF,GAAE;AAEJ,OAAO,MAAMO,uBAAuB,OAAU,EAC5CC,UAAU,EACVC,IAAI,EACJC,KAAK,EACLV,GAAG,EACHW,KAAK,EAON;IACC,MAAMC,aAAaJ,WAAWK,MAAM,CAACC,cAAc;IAEnD,IACE,CAACF,cACDZ,IAAIK,OAAO,EAAEU,oBACZL,MAAMM,MAAM,KAAK,KAAK,CAAChB,IAAIK,OAAO,EAAEY,kCACrC;QACA,OAAON;IACT;IAEA,IAAIO,WAAoC,CAAC;IAEzC,OAAOzB,oBAAoB;QACzB0B,gCAAgC,CAACC,UAC/B7B,gCAAgC;gBAAEiB;gBAAYY;gBAASpB;YAAI;QAC7DA;QACAqB,OAAO,OAAO,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OAAO;gBACL,OAAOrF,IAAIK,OAAO,CAACD,IAAI;YACzB;QACF;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveHistoricalFile.d.ts","sourceRoot":"","sources":["../../../src/uploads/fileVersioning/resolveHistoricalFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAA;AACnE,OAAO,KAAK,EAAc,cAAc,EAAE,MAAM,sBAAsB,CAAA;AACtE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,0CAA0C,CAAA;AAkBtF,MAAM,MAAM,cAAc,GAAG;IAC3B,QAAQ,EAAE,sBAAsB,CAAA;IAChC;;;OAGG;IACH,gBAAgB,EAAE,OAAO,CAAA;CAC1B,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,kEAO/B;IACD,UAAU,EAAE,UAAU,CAAA;IACtB,QAAQ,EAAE,MAAM,CAAA;IAChB,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,GAAG,EAAE,cAAc,CAAA;IACnB,SAAS,EAAE,MAAM,CAAA;CAClB,KAAG,OAAO,CAAC,cAAc,
|
|
1
|
+
{"version":3,"file":"resolveHistoricalFile.d.ts","sourceRoot":"","sources":["../../../src/uploads/fileVersioning/resolveHistoricalFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAA;AACnE,OAAO,KAAK,EAAc,cAAc,EAAE,MAAM,sBAAsB,CAAA;AACtE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,0CAA0C,CAAA;AAkBtF,MAAM,MAAM,cAAc,GAAG;IAC3B,QAAQ,EAAE,sBAAsB,CAAA;IAChC;;;OAGG;IACH,gBAAgB,EAAE,OAAO,CAAA;CAC1B,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,kEAO/B;IACD,UAAU,EAAE,UAAU,CAAA;IACtB,QAAQ,EAAE,MAAM,CAAA;IAChB,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,GAAG,EAAE,cAAc,CAAA;IACnB,SAAS,EAAE,MAAM,CAAA;CAClB,KAAG,OAAO,CAAC,cAAc,CAyCzB,CAAA"}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { NotFound } from '../../errors/NotFound.js';
|
|
2
2
|
import { checkFileAccess } from '../checkFileAccess.js';
|
|
3
3
|
import { isOriginalFileRequest } from '../isOriginalFileRequest.js';
|
|
4
|
-
import {
|
|
5
|
-
import { collectStoredFiles, hasStoredOriginal, withLegacyCloudUploadFileData } from './storedFiles.js';
|
|
4
|
+
import { getUploadFileEntries, getUploadFileObjects, hasStoredOriginal, withLegacyCloudUploadFileData } from './storedFiles.js';
|
|
6
5
|
/**
|
|
7
6
|
* Resolves a version's exact file entry after checking version read access. A stored entry also
|
|
8
7
|
* gets an ordinary read check of the parent here. An entry built at request time gets its file
|
|
@@ -19,15 +18,23 @@ import { collectStoredFiles, hasStoredOriginal, withLegacyCloudUploadFileData }
|
|
|
19
18
|
}
|
|
20
19
|
});
|
|
21
20
|
const matched = docs[0];
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
21
|
+
let historical;
|
|
22
|
+
let resolveFailure;
|
|
23
|
+
try {
|
|
24
|
+
historical = matched ? await resolveVersionFile({
|
|
25
|
+
collection,
|
|
26
|
+
filename,
|
|
27
|
+
isOriginal,
|
|
28
|
+
prefix,
|
|
29
|
+
req,
|
|
30
|
+
row: matched
|
|
31
|
+
}) : undefined;
|
|
32
|
+
} catch (err) {
|
|
33
|
+
resolveFailure = {
|
|
34
|
+
err
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
// Check both policies before exposing a missing version, a filename mismatch or a damaged entry.
|
|
31
38
|
if (!historical?.isBuiltAtRequest) {
|
|
32
39
|
await checkFileAccess({
|
|
33
40
|
collection,
|
|
@@ -44,6 +51,9 @@ import { collectStoredFiles, hasStoredOriginal, withLegacyCloudUploadFileData }
|
|
|
44
51
|
req,
|
|
45
52
|
showHiddenFields: true
|
|
46
53
|
});
|
|
54
|
+
if (resolveFailure) {
|
|
55
|
+
throw resolveFailure.err;
|
|
56
|
+
}
|
|
47
57
|
if (!historical) {
|
|
48
58
|
throw new NotFound(req.t);
|
|
49
59
|
}
|
|
@@ -55,25 +65,42 @@ const resolveVersionFile = async ({ collection, filename, isOriginal, prefix, re
|
|
|
55
65
|
doc: row.version,
|
|
56
66
|
req
|
|
57
67
|
});
|
|
58
|
-
|
|
68
|
+
// A shared filename means the main file unless the request asks for the original.
|
|
69
|
+
const values = getUploadFileObjects({
|
|
70
|
+
doc: saved
|
|
71
|
+
});
|
|
72
|
+
const match = isOriginalFileRequest({
|
|
59
73
|
doc: saved,
|
|
60
74
|
filename,
|
|
61
75
|
isOriginal
|
|
62
|
-
});
|
|
63
|
-
|
|
76
|
+
}) ? values.find(({ role })=>role.type === 'original') : values.find(({ role, value })=>role.type !== 'original' && value.filename === filename);
|
|
77
|
+
// Find the requested file, then read only the entries it needs. Reading an entry throws for an
|
|
78
|
+
// unsafe storage key, so a damaged entry elsewhere in the version must not fail this request.
|
|
79
|
+
if (!match || prefix !== undefined && (match.value.prefix ?? '') !== prefix) {
|
|
64
80
|
return;
|
|
65
81
|
}
|
|
66
|
-
const
|
|
82
|
+
const [entry] = getUploadFileEntries({
|
|
67
83
|
collection: collection.config,
|
|
68
84
|
doc: saved,
|
|
69
|
-
req
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
85
|
+
req,
|
|
86
|
+
roles: [
|
|
87
|
+
match.role
|
|
88
|
+
]
|
|
73
89
|
});
|
|
90
|
+
const isBuiltAtRequest = entry?.status === 'requestTime';
|
|
91
|
+
// A file built on request is built from the original, so only then is the original read too.
|
|
74
92
|
const hasFile = isBuiltAtRequest ? hasStoredOriginal({
|
|
75
|
-
|
|
76
|
-
|
|
93
|
+
entries: getUploadFileEntries({
|
|
94
|
+
collection: collection.config,
|
|
95
|
+
doc: saved,
|
|
96
|
+
req,
|
|
97
|
+
roles: [
|
|
98
|
+
{
|
|
99
|
+
type: 'original'
|
|
100
|
+
}
|
|
101
|
+
]
|
|
102
|
+
})
|
|
103
|
+
}) : entry?.status === 'stored';
|
|
77
104
|
if (!hasFile) {
|
|
78
105
|
return;
|
|
79
106
|
}
|
|
@@ -85,32 +112,5 @@ const resolveVersionFile = async ({ collection, filename, isOriginal, prefix, re
|
|
|
85
112
|
isBuiltAtRequest
|
|
86
113
|
};
|
|
87
114
|
};
|
|
88
|
-
function getHistoricalEntry({ doc, filename, isOriginal }) {
|
|
89
|
-
if (isOriginalFileRequest({
|
|
90
|
-
doc,
|
|
91
|
-
filename,
|
|
92
|
-
isOriginal
|
|
93
|
-
})) {
|
|
94
|
-
return {
|
|
95
|
-
type: 'original',
|
|
96
|
-
value: doc.original
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
if (doc.filename === filename) {
|
|
100
|
-
return {
|
|
101
|
-
type: 'default',
|
|
102
|
-
value: doc
|
|
103
|
-
};
|
|
104
|
-
}
|
|
105
|
-
for (const [sizeKey, value] of Object.entries(doc.variants ?? {})){
|
|
106
|
-
if (value?.filename === filename) {
|
|
107
|
-
return {
|
|
108
|
-
type: 'size',
|
|
109
|
-
sizeKey,
|
|
110
|
-
value
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
115
|
|
|
116
116
|
//# sourceMappingURL=resolveHistoricalFile.js.map
|