@webiny/api-headless-cms 6.5.2-beta.1 → 6.5.2-beta.3
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/context.js +29 -20
- package/context.js.map +1 -1
- package/crud/AccessControl/AccessControl.d.ts +16 -1
- package/crud/AccessControl/AccessControl.js +22 -1
- package/crud/AccessControl/AccessControl.js.map +1 -1
- package/crud/contentModel/validation.js +4 -4
- package/crud/contentModel/validation.js.map +1 -1
- package/domain/contentEntry/errors.d.ts +4 -0
- package/domain/contentEntry/errors.js +8 -1
- package/domain/contentEntry/errors.js.map +1 -1
- package/domain/contentModel/schemas.js +3 -3
- package/domain/contentModel/schemas.js.map +1 -1
- package/domain/contentModelGroup/validation.js +2 -2
- package/domain/contentModelGroup/validation.js.map +1 -1
- package/export/crud/importing.js +12 -0
- package/export/crud/importing.js.map +1 -1
- package/export/graphql/index.js +1 -0
- package/export/graphql/index.js.map +1 -1
- package/export/types.js.map +1 -1
- package/features/contentEntry/CreateEntry/CreateEntryUseCase.d.ts +12 -2
- package/features/contentEntry/CreateEntry/CreateEntryUseCase.js +18 -4
- package/features/contentEntry/CreateEntry/CreateEntryUseCase.js.map +1 -1
- package/features/contentEntry/CreateEntry/abstractions.d.ts +2 -1
- package/features/contentEntry/CreateEntry/abstractions.js.map +1 -1
- package/features/contentEntry/CreateEntryRevisionFrom/CreateEntryRevisionFromUseCase.js +6 -0
- package/features/contentEntry/CreateEntryRevisionFrom/CreateEntryRevisionFromUseCase.js.map +1 -1
- package/features/contentEntry/DeleteEntry/MoveEntryToBinUseCase.js +4 -1
- package/features/contentEntry/DeleteEntry/MoveEntryToBinUseCase.js.map +1 -1
- package/features/contentEntry/DeleteEntry/decorators/ForceDeleteDecorator.d.ts +9 -2
- package/features/contentEntry/DeleteEntry/decorators/ForceDeleteDecorator.js +26 -4
- package/features/contentEntry/DeleteEntry/decorators/ForceDeleteDecorator.js.map +1 -1
- package/features/contentEntry/DeleteMultipleEntries/DeleteMultipleEntriesUseCase.js +2 -1
- package/features/contentEntry/DeleteMultipleEntries/DeleteMultipleEntriesUseCase.js.map +1 -1
- package/features/contentEntry/DuplicateEntry/abstractions.d.ts +2 -1
- package/features/contentEntry/DuplicateEntry/abstractions.js.map +1 -1
- package/features/contentEntry/GetSingletonEntry/abstractions.d.ts +2 -1
- package/features/contentEntry/GetSingletonEntry/abstractions.js.map +1 -1
- package/features/contentEntry/UpdateEntry/UpdateEntryUseCase.js +8 -0
- package/features/contentEntry/UpdateEntry/UpdateEntryUseCase.js.map +1 -1
- package/features/contentEntry/UpdateSingletonEntry/abstractions.d.ts +2 -1
- package/features/contentEntry/UpdateSingletonEntry/abstractions.js.map +1 -1
- package/features/contentEntry/entryDataFactories/CreateEntryRevisionFromDataFactory/CreateEntryRevisionFromDataFactory.js +34 -28
- package/features/contentEntry/entryDataFactories/CreateEntryRevisionFromDataFactory/CreateEntryRevisionFromDataFactory.js.map +1 -1
- package/features/contentEntry/entryDataFactories/UpdateEntryDataFactory/UpdateEntryDataFactory.d.ts +3 -2
- package/features/contentEntry/entryDataFactories/UpdateEntryDataFactory/UpdateEntryDataFactory.js +39 -31
- package/features/contentEntry/entryDataFactories/UpdateEntryDataFactory/UpdateEntryDataFactory.js.map +1 -1
- package/features/contentEntry/entryDataFactories/canOverrideMetaFields.d.ts +16 -0
- package/features/contentEntry/entryDataFactories/canOverrideMetaFields.js +11 -0
- package/features/contentEntry/entryDataFactories/canOverrideMetaFields.js.map +1 -0
- package/features/contentModel/ModelAccessGuard/abstractions.d.ts +30 -0
- package/features/contentModel/ModelAccessGuard/abstractions.js +5 -0
- package/features/contentModel/ModelAccessGuard/abstractions.js.map +1 -0
- package/features/contentModel/ModelAccessGuard/index.d.ts +2 -0
- package/features/contentModel/ModelAccessGuard/index.js +1 -0
- package/features/contentModel/RefModelsGenerator/RefModelsGenerator.d.ts +3 -3
- package/features/contentModel/RefModelsGenerator/RefModelsGenerator.js +6 -5
- package/features/contentModel/RefModelsGenerator/RefModelsGenerator.js.map +1 -1
- package/features/contentModel/UpdateModel/UpdateModelUseCase.d.ts +3 -1
- package/features/contentModel/UpdateModel/UpdateModelUseCase.js +20 -3
- package/features/contentModel/UpdateModel/UpdateModelUseCase.js.map +1 -1
- package/features/contentModelGroup/DeleteGroup/DeleteGroupUseCase.js +2 -1
- package/features/contentModelGroup/DeleteGroup/DeleteGroupUseCase.js.map +1 -1
- package/features/contentModelGroup/UpdateGroup/UpdateGroupUseCase.js +2 -1
- package/features/contentModelGroup/UpdateGroup/UpdateGroupUseCase.js.map +1 -1
- package/features/modelBuilder/fields/TextFieldType.js.map +1 -1
- package/graphql/generateSchema.js +4 -0
- package/graphql/generateSchema.js.map +1 -1
- package/graphql/schema/cms/getModelResolver.js +14 -0
- package/graphql/schema/cms/getModelResolver.js.map +1 -1
- package/graphql/schema/contentModelGroups.js +11 -12
- package/graphql/schema/contentModelGroups.js.map +1 -1
- package/package.json +25 -25
- package/types/types.d.ts +5 -0
- package/types/types.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/contentEntry/entryDataFactories/UpdateEntryDataFactory/UpdateEntryDataFactory.js","sources":["../../../../../src/features/contentEntry/entryDataFactories/UpdateEntryDataFactory/UpdateEntryDataFactory.ts"],"sourcesContent":["import { createImplementation, Result } from \"@webiny/feature/api\";\nimport {\n type IUpdateEntryDataFactory,\n UpdateEntryDataFactory as FactoryAbstraction\n} from \"./abstractions.js\";\nimport { CmsContext } from \"~/features/shared/abstractions.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport type {\n CmsEntry,\n CmsEntryStatus,\n CmsEntryValues,\n CmsModel,\n UpdateCmsEntryInput,\n UpdateCmsEntryOptionsInput\n} from \"~/types/index.js\";\nimport { getDate } from \"~/utils/date.js\";\nimport { getIdentity } from \"~/utils/identity.js\";\nimport { validateModelEntryData } from \"~/crud/contentEntry/entryDataValidation.js\";\nimport { EntryValidationError } from \"~/domain/contentEntry/errors.js\";\nimport { referenceFieldsMapping } from \"~/crud/contentEntry/referenceFieldsMapping.js\";\nimport { mapAndCleanUpdatedInputData } from \"../mapAndCleanUpdatedInputData.js\";\nimport { getSystem } from \"../system.js\";\nimport { getExpiresAt } from \"../expiresAt.js\";\nimport { ModelToAstConverter } from \"~/features/contentModel/ModelToAstConverter/abstractions.js\";\nimport { ensureItemIds } from \"../../ensureItemIds.js\";\nimport { hasEntryContentChanged } from \"../hasEntryContentChanged.js\";\nimport { GetLatestRevisionByEntryIdUseCase } from \"~/features/contentEntry/GetLatestRevisionByEntryId/index.js\";\n\nconst allowedEntryStatus: string[] = [\"draft\", \"published\", \"unpublished\"];\n\nconst transformEntryStatus = (status: CmsEntryStatus | string): CmsEntryStatus => {\n return allowedEntryStatus.includes(status) ? (status as CmsEntryStatus) : \"draft\";\n};\n\nclass UpdateEntryDataFactoryImpl implements IUpdateEntryDataFactory {\n public constructor(\n private readonly cmsContext: CmsContext.Interface,\n private readonly identityContext: IdentityContext.Interface,\n private readonly modelToAstConverter: ModelToAstConverter.Interface,\n private readonly getLatestRevision: GetLatestRevisionByEntryIdUseCase.Interface\n ) {}\n\n public async create<TValues extends CmsEntryValues = CmsEntryValues>(\n model: CmsModel,\n rawInput: UpdateCmsEntryInput<TValues>,\n originalEntry: CmsEntry<TValues>,\n options?: UpdateCmsEntryOptionsInput\n ): Promise<FactoryAbstraction.Return<TValues>> {\n const latestResult = await this.getLatestRevision.execute<TValues>(model, {\n id: originalEntry.entryId\n });\n if (latestResult.isFail()) {\n return Result.fail(latestResult.error);\n }\n const latestEntry = latestResult.value;\n\n const cleanedValues = mapAndCleanUpdatedInputData<TValues>(\n model,\n rawInput?.values || ({} as TValues)\n );\n\n const invalidFields = await validateModelEntryData({\n context: this.cmsContext,\n model,\n values: cleanedValues,\n entry: originalEntry,\n skipValidation: options?.skipValidation\n });\n if (invalidFields.length > 0) {\n return Result.fail(new EntryValidationError(\"Validation failed.\", invalidFields));\n }\n\n const mergedValues: TValues = {\n ...originalEntry.values,\n ...cleanedValues\n };\n\n const modelAst = this.modelToAstConverter.toAst(model);\n await ensureItemIds(modelAst, mergedValues);\n\n const values = await referenceFieldsMapping<TValues>({\n context: this.cmsContext,\n model,\n values: mergedValues,\n validateEntries: false\n });\n\n const currentIdentity = this.identityContext.getIdentity();\n const currentDateTime = new Date();\n\n /**\n * Saving without changing the content (e.g. clicking \"Save\" without editing anything) is\n * not a modification, so the saved/modified meta fields are kept. Entry-level values are\n * then taken from the latest revision, because storage copies them onto the latest\n * revision when a non-latest revision is updated. Revision-level values are this\n * revision's own. Explicitly provided meta field values always take precedence.\n */\n const contentChanged = hasEntryContentChanged({\n values,\n baselineValues: originalEntry.values\n });\n\n const entryLevelSaved = contentChanged\n ? {\n savedOn: currentDateTime,\n modifiedOn: currentDateTime,\n savedBy: currentIdentity,\n modifiedBy: currentIdentity\n }\n : {\n savedOn: latestEntry.savedOn,\n modifiedOn: latestEntry.modifiedOn,\n savedBy: latestEntry.savedBy,\n modifiedBy: latestEntry.modifiedBy\n };\n\n const revisionLevelSaved = contentChanged\n ? {\n revisionSavedOn: currentDateTime,\n revisionModifiedOn: currentDateTime,\n revisionSavedBy: currentIdentity,\n revisionModifiedBy: currentIdentity\n }\n : {\n revisionSavedOn: originalEntry.revisionSavedOn,\n revisionModifiedOn: originalEntry.revisionModifiedOn,\n revisionSavedBy: originalEntry.revisionSavedBy,\n revisionModifiedBy: originalEntry.revisionModifiedBy\n };\n\n const entry: CmsEntry<TValues> = {\n ...originalEntry,\n revisionCreatedOn: getDate(rawInput.revisionCreatedOn, originalEntry.revisionCreatedOn),\n revisionModifiedOn: getDate(\n rawInput.revisionModifiedOn,\n revisionLevelSaved.revisionModifiedOn\n ),\n revisionSavedOn: getDate(rawInput.revisionSavedOn, revisionLevelSaved.revisionSavedOn),\n revisionDeletedOn: getDate(rawInput.revisionDeletedOn, originalEntry.revisionDeletedOn),\n revisionRestoredOn: getDate(\n rawInput.revisionRestoredOn,\n originalEntry.revisionRestoredOn\n ),\n revisionFirstPublishedOn: getDate(\n rawInput.revisionFirstPublishedOn,\n originalEntry.revisionFirstPublishedOn\n ),\n revisionLastPublishedOn: getDate(\n rawInput.revisionLastPublishedOn,\n originalEntry.revisionLastPublishedOn\n ),\n revisionCreatedBy: getIdentity(\n rawInput.revisionCreatedBy,\n originalEntry.revisionCreatedBy\n )!,\n revisionModifiedBy: getIdentity(\n rawInput.revisionModifiedBy,\n revisionLevelSaved.revisionModifiedBy\n ),\n revisionSavedBy: getIdentity(\n rawInput.revisionSavedBy,\n revisionLevelSaved.revisionSavedBy\n )!,\n revisionDeletedBy: getIdentity(\n rawInput.revisionDeletedBy,\n originalEntry.revisionDeletedBy\n ),\n revisionRestoredBy: getIdentity(\n rawInput.revisionRestoredBy,\n originalEntry.revisionRestoredBy\n ),\n revisionFirstPublishedBy: getIdentity(\n rawInput.revisionFirstPublishedBy,\n originalEntry.revisionFirstPublishedBy\n ),\n revisionLastPublishedBy: getIdentity(\n rawInput.revisionLastPublishedBy,\n originalEntry.revisionLastPublishedBy\n ),\n createdOn: getDate(rawInput.createdOn, latestEntry.createdOn),\n savedOn: getDate(rawInput.savedOn, entryLevelSaved.savedOn),\n modifiedOn: getDate(rawInput.modifiedOn, entryLevelSaved.modifiedOn),\n deletedOn: getDate(rawInput.deletedOn, latestEntry.deletedOn),\n restoredOn: getDate(rawInput.restoredOn, latestEntry.restoredOn),\n firstPublishedOn: getDate(rawInput.firstPublishedOn, latestEntry.firstPublishedOn),\n lastPublishedOn: getDate(rawInput.lastPublishedOn, latestEntry.lastPublishedOn),\n createdBy: getIdentity(rawInput.createdBy, latestEntry.createdBy)!,\n savedBy: getIdentity(rawInput.savedBy, entryLevelSaved.savedBy)!,\n modifiedBy: getIdentity(rawInput.modifiedBy, entryLevelSaved.modifiedBy),\n deletedBy: getIdentity(rawInput.deletedBy, latestEntry.deletedBy),\n restoredBy: getIdentity(rawInput.restoredBy, latestEntry.restoredBy),\n firstPublishedBy: getIdentity(rawInput.firstPublishedBy, latestEntry.firstPublishedBy),\n lastPublishedBy: getIdentity(rawInput.lastPublishedBy, latestEntry.lastPublishedBy),\n values,\n status: transformEntryStatus(originalEntry.status),\n system: getSystem({\n input: rawInput,\n original: originalEntry\n }),\n live: originalEntry.live,\n expiresAt: getExpiresAt({ expiresAt: rawInput.expiresAt }, originalEntry)\n };\n\n const folderId = rawInput.wbyAco_location?.folderId;\n if (folderId) {\n entry.location = {\n folderId\n };\n }\n\n return Result.ok({\n entry,\n input: {\n ...rawInput,\n values: structuredClone(values)\n }\n });\n }\n}\n\nexport const UpdateEntryDataFactory = createImplementation({\n abstraction: FactoryAbstraction,\n implementation: UpdateEntryDataFactoryImpl,\n dependencies: [\n CmsContext,\n IdentityContext,\n ModelToAstConverter,\n GetLatestRevisionByEntryIdUseCase\n ]\n});\n"],"names":["allowedEntryStatus","transformEntryStatus","status","UpdateEntryDataFactoryImpl","cmsContext","identityContext","modelToAstConverter","getLatestRevision","model","rawInput","originalEntry","options","latestResult","Result","latestEntry","cleanedValues","mapAndCleanUpdatedInputData","invalidFields","validateModelEntryData","EntryValidationError","mergedValues","modelAst","ensureItemIds","values","referenceFieldsMapping","currentIdentity","currentDateTime","Date","contentChanged","hasEntryContentChanged","entryLevelSaved","revisionLevelSaved","entry","getDate","getIdentity","getSystem","getExpiresAt","folderId","structuredClone","UpdateEntryDataFactory","createImplementation","FactoryAbstraction","CmsContext","IdentityContext","ModelToAstConverter","GetLatestRevisionByEntryIdUseCase"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAMA,qBAA+B;IAAC;IAAS;IAAa;CAAc;AAE1E,MAAMC,uBAAuB,CAACC,SACnBF,mBAAmB,QAAQ,CAACE,UAAWA,SAA4B;AAG9E,MAAMC;IACF,YACqBC,UAAgC,EAChCC,eAA0C,EAC1CC,mBAAkD,EAClDC,iBAA8D,CACjF;aAJmBH,UAAU,GAAVA;aACAC,eAAe,GAAfA;aACAC,mBAAmB,GAA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pdateEntryDataFactory/UpdateEntryDataFactory.js","sources":["../../../../../src/features/contentEntry/entryDataFactories/UpdateEntryDataFactory/UpdateEntryDataFactory.ts"],"sourcesContent":["import { createImplementation, Result } from \"@webiny/feature/api\";\nimport {\n type IUpdateEntryDataFactory,\n UpdateEntryDataFactory as FactoryAbstraction\n} from \"./abstractions.js\";\nimport { AccessControl, CmsContext } from \"~/features/shared/abstractions.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport type {\n CmsEntry,\n CmsEntryStatus,\n CmsEntryValues,\n CmsModel,\n UpdateCmsEntryInput,\n UpdateCmsEntryOptionsInput\n} from \"~/types/index.js\";\nimport { getDate } from \"~/utils/date.js\";\nimport { getIdentity } from \"~/utils/identity.js\";\nimport { validateModelEntryData } from \"~/crud/contentEntry/entryDataValidation.js\";\nimport { EntryValidationError } from \"~/domain/contentEntry/errors.js\";\nimport { referenceFieldsMapping } from \"~/crud/contentEntry/referenceFieldsMapping.js\";\nimport { mapAndCleanUpdatedInputData } from \"../mapAndCleanUpdatedInputData.js\";\nimport { getSystem } from \"../system.js\";\nimport { canOverrideMetaFields } from \"../canOverrideMetaFields.js\";\nimport { getExpiresAt } from \"../expiresAt.js\";\nimport { ModelToAstConverter } from \"~/features/contentModel/ModelToAstConverter/abstractions.js\";\nimport { ensureItemIds } from \"../../ensureItemIds.js\";\nimport { hasEntryContentChanged } from \"../hasEntryContentChanged.js\";\nimport { GetLatestRevisionByEntryIdUseCase } from \"~/features/contentEntry/GetLatestRevisionByEntryId/index.js\";\n\nconst allowedEntryStatus: string[] = [\"draft\", \"published\", \"unpublished\"];\n\nconst transformEntryStatus = (status: CmsEntryStatus | string): CmsEntryStatus => {\n return allowedEntryStatus.includes(status) ? (status as CmsEntryStatus) : \"draft\";\n};\n\nclass UpdateEntryDataFactoryImpl implements IUpdateEntryDataFactory {\n public constructor(\n private readonly cmsContext: CmsContext.Interface,\n private readonly identityContext: IdentityContext.Interface,\n private readonly modelToAstConverter: ModelToAstConverter.Interface,\n private readonly getLatestRevision: GetLatestRevisionByEntryIdUseCase.Interface,\n private readonly accessControl: AccessControl.Interface\n ) {}\n\n public async create<TValues extends CmsEntryValues = CmsEntryValues>(\n model: CmsModel,\n rawInput: UpdateCmsEntryInput<TValues>,\n originalEntry: CmsEntry<TValues>,\n options?: UpdateCmsEntryOptionsInput\n ): Promise<FactoryAbstraction.Return<TValues>> {\n const latestResult = await this.getLatestRevision.execute<TValues>(model, {\n id: originalEntry.entryId\n });\n if (latestResult.isFail()) {\n return Result.fail(latestResult.error);\n }\n const latestEntry = latestResult.value;\n\n const cleanedValues = mapAndCleanUpdatedInputData<TValues>(\n model,\n rawInput?.values || ({} as TValues)\n );\n\n const invalidFields = await validateModelEntryData({\n context: this.cmsContext,\n model,\n values: cleanedValues,\n entry: originalEntry,\n skipValidation: options?.skipValidation\n });\n if (invalidFields.length > 0) {\n return Result.fail(new EntryValidationError(\"Validation failed.\", invalidFields));\n }\n\n const mergedValues: TValues = {\n ...originalEntry.values,\n ...cleanedValues\n };\n\n const modelAst = this.modelToAstConverter.toAst(model);\n await ensureItemIds(modelAst, mergedValues);\n\n const values = await referenceFieldsMapping<TValues>({\n context: this.cmsContext,\n model,\n values: mergedValues,\n validateEntries: false\n });\n\n // Security: meta field overrides (createdBy, ...) are ignored for identities limited to\n // their own entries, otherwise they could take over (or hand over) an entry.\n const metaInput: Partial<UpdateCmsEntryInput<TValues>> = (await canOverrideMetaFields({\n identityContext: this.identityContext,\n accessControl: this.accessControl,\n model\n }))\n ? rawInput\n : {};\n\n const currentIdentity = this.identityContext.getIdentity();\n const currentDateTime = new Date();\n\n /**\n * Saving without changing the content (e.g. clicking \"Save\" without editing anything) is\n * not a modification, so the saved/modified meta fields are kept. Entry-level values are\n * then taken from the latest revision, because storage copies them onto the latest\n * revision when a non-latest revision is updated. Revision-level values are this\n * revision's own. Explicitly provided meta field values always take precedence.\n */\n const contentChanged = hasEntryContentChanged({\n values,\n baselineValues: originalEntry.values\n });\n\n const entryLevelSaved = contentChanged\n ? {\n savedOn: currentDateTime,\n modifiedOn: currentDateTime,\n savedBy: currentIdentity,\n modifiedBy: currentIdentity\n }\n : {\n savedOn: latestEntry.savedOn,\n modifiedOn: latestEntry.modifiedOn,\n savedBy: latestEntry.savedBy,\n modifiedBy: latestEntry.modifiedBy\n };\n\n const revisionLevelSaved = contentChanged\n ? {\n revisionSavedOn: currentDateTime,\n revisionModifiedOn: currentDateTime,\n revisionSavedBy: currentIdentity,\n revisionModifiedBy: currentIdentity\n }\n : {\n revisionSavedOn: originalEntry.revisionSavedOn,\n revisionModifiedOn: originalEntry.revisionModifiedOn,\n revisionSavedBy: originalEntry.revisionSavedBy,\n revisionModifiedBy: originalEntry.revisionModifiedBy\n };\n\n const entry: CmsEntry<TValues> = {\n ...originalEntry,\n revisionCreatedOn: getDate(\n metaInput.revisionCreatedOn,\n originalEntry.revisionCreatedOn\n ),\n revisionModifiedOn: getDate(\n metaInput.revisionModifiedOn,\n revisionLevelSaved.revisionModifiedOn\n ),\n revisionSavedOn: getDate(metaInput.revisionSavedOn, revisionLevelSaved.revisionSavedOn),\n revisionDeletedOn: getDate(\n metaInput.revisionDeletedOn,\n originalEntry.revisionDeletedOn\n ),\n revisionRestoredOn: getDate(\n metaInput.revisionRestoredOn,\n originalEntry.revisionRestoredOn\n ),\n revisionFirstPublishedOn: getDate(\n metaInput.revisionFirstPublishedOn,\n originalEntry.revisionFirstPublishedOn\n ),\n revisionLastPublishedOn: getDate(\n metaInput.revisionLastPublishedOn,\n originalEntry.revisionLastPublishedOn\n ),\n revisionCreatedBy: getIdentity(\n metaInput.revisionCreatedBy,\n originalEntry.revisionCreatedBy\n )!,\n revisionModifiedBy: getIdentity(\n metaInput.revisionModifiedBy,\n revisionLevelSaved.revisionModifiedBy\n ),\n revisionSavedBy: getIdentity(\n metaInput.revisionSavedBy,\n revisionLevelSaved.revisionSavedBy\n )!,\n revisionDeletedBy: getIdentity(\n metaInput.revisionDeletedBy,\n originalEntry.revisionDeletedBy\n ),\n revisionRestoredBy: getIdentity(\n metaInput.revisionRestoredBy,\n originalEntry.revisionRestoredBy\n ),\n revisionFirstPublishedBy: getIdentity(\n metaInput.revisionFirstPublishedBy,\n originalEntry.revisionFirstPublishedBy\n ),\n revisionLastPublishedBy: getIdentity(\n metaInput.revisionLastPublishedBy,\n originalEntry.revisionLastPublishedBy\n ),\n createdOn: getDate(metaInput.createdOn, latestEntry.createdOn),\n savedOn: getDate(metaInput.savedOn, entryLevelSaved.savedOn),\n modifiedOn: getDate(metaInput.modifiedOn, entryLevelSaved.modifiedOn),\n deletedOn: getDate(metaInput.deletedOn, latestEntry.deletedOn),\n restoredOn: getDate(metaInput.restoredOn, latestEntry.restoredOn),\n firstPublishedOn: getDate(metaInput.firstPublishedOn, latestEntry.firstPublishedOn),\n lastPublishedOn: getDate(metaInput.lastPublishedOn, latestEntry.lastPublishedOn),\n createdBy: getIdentity(metaInput.createdBy, latestEntry.createdBy)!,\n savedBy: getIdentity(metaInput.savedBy, entryLevelSaved.savedBy)!,\n modifiedBy: getIdentity(metaInput.modifiedBy, entryLevelSaved.modifiedBy),\n deletedBy: getIdentity(metaInput.deletedBy, latestEntry.deletedBy),\n restoredBy: getIdentity(metaInput.restoredBy, latestEntry.restoredBy),\n firstPublishedBy: getIdentity(metaInput.firstPublishedBy, latestEntry.firstPublishedBy),\n lastPublishedBy: getIdentity(metaInput.lastPublishedBy, latestEntry.lastPublishedBy),\n values,\n status: transformEntryStatus(originalEntry.status),\n system: getSystem({\n input: rawInput,\n original: originalEntry\n }),\n live: originalEntry.live,\n expiresAt: getExpiresAt({ expiresAt: rawInput.expiresAt }, originalEntry)\n };\n\n const folderId = rawInput.wbyAco_location?.folderId;\n if (folderId) {\n entry.location = {\n folderId\n };\n }\n\n return Result.ok({\n entry,\n input: {\n ...rawInput,\n values: structuredClone(values)\n }\n });\n }\n}\n\nexport const UpdateEntryDataFactory = createImplementation({\n abstraction: FactoryAbstraction,\n implementation: UpdateEntryDataFactoryImpl,\n dependencies: [\n CmsContext,\n IdentityContext,\n ModelToAstConverter,\n GetLatestRevisionByEntryIdUseCase,\n AccessControl\n ]\n});\n"],"names":["allowedEntryStatus","transformEntryStatus","status","UpdateEntryDataFactoryImpl","cmsContext","identityContext","modelToAstConverter","getLatestRevision","accessControl","model","rawInput","originalEntry","options","latestResult","Result","latestEntry","cleanedValues","mapAndCleanUpdatedInputData","invalidFields","validateModelEntryData","EntryValidationError","mergedValues","modelAst","ensureItemIds","values","referenceFieldsMapping","metaInput","canOverrideMetaFields","currentIdentity","currentDateTime","Date","contentChanged","hasEntryContentChanged","entryLevelSaved","revisionLevelSaved","entry","getDate","getIdentity","getSystem","getExpiresAt","folderId","structuredClone","UpdateEntryDataFactory","createImplementation","FactoryAbstraction","CmsContext","IdentityContext","ModelToAstConverter","GetLatestRevisionByEntryIdUseCase","AccessControl"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,MAAMA,qBAA+B;IAAC;IAAS;IAAa;CAAc;AAE1E,MAAMC,uBAAuB,CAACC,SACnBF,mBAAmB,QAAQ,CAACE,UAAWA,SAA4B;AAG9E,MAAMC;IACF,YACqBC,UAAgC,EAChCC,eAA0C,EAC1CC,mBAAkD,EAClDC,iBAA8D,EAC9DC,aAAsC,CACzD;aALmBJ,UAAU,GAAVA;aACAC,eAAe,GAAfA;aACAC,mBAAmB,GAAnBA;aACAC,iBAAiB,GAAjBA;aACAC,aAAa,GAAbA;IAClB;IAEH,MAAa,OACTC,KAAe,EACfC,QAAsC,EACtCC,aAAgC,EAChCC,OAAoC,EACO;QAC3C,MAAMC,eAAe,MAAM,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAUJ,OAAO;YACtE,IAAIE,cAAc,OAAO;QAC7B;QACA,IAAIE,aAAa,MAAM,IACnB,OAAOC,OAAO,IAAI,CAACD,aAAa,KAAK;QAEzC,MAAME,cAAcF,aAAa,KAAK;QAEtC,MAAMG,gBAAgBC,4BAClBR,OACAC,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QV,UAAU,eAAe,EAAEX,YAAY,eAAe;YAC/E,WAAWsB,YAAYX,UAAU,SAAS,EAAEX,YAAY,SAAS;YACjE,SAASsB,YAAYX,UAAU,OAAO,EAAEO,gBAAgB,OAAO;YAC/D,YAAYI,YAAYX,UAAU,UAAU,EAAEO,gBAAgB,UAAU;YACxE,WAAWI,YAAYX,UAAU,SAAS,EAAEX,YAAY,SAAS;YACjE,YAAYsB,YAAYX,UAAU,UAAU,EAAEX,YAAY,UAAU;YACpE,kBAAkBsB,YAAYX,UAAU,gBAAgB,EAAEX,YAAY,gBAAgB;YACtF,iBAAiBsB,YAAYX,UAAU,eAAe,EAAEX,YAAY,eAAe;YACnFS;YACA,QAAQvB,qBAAqBU,cAAc,MAAM;YACjD,QAAQ2B,UAAU;gBACd,OAAO5B;gBACP,UAAUC;YACd;YACA,MAAMA,cAAc,IAAI;YACxB,WAAW4B,aAAa;gBAAE,WAAW7B,SAAS,SAAS;YAAC,GAAGC;QAC/D;QAEA,MAAM6B,WAAW9B,SAAS,eAAe,EAAE;QAC3C,IAAI8B,UACAL,MAAM,QAAQ,GAAG;YACbK;QACJ;QAGJ,OAAO1B,OAAO,EAAE,CAAC;YACbqB;YACA,OAAO;gBACH,GAAGzB,QAAQ;gBACX,QAAQ+B,gBAAgBjB;YAC5B;QACJ;IACJ;AACJ;AAEO,MAAMkB,gDAAyBC,qBAAqB;IACvD,aAAaC;IACb,gBAAgBzC;IAChB,cAAc;QACV0C;QACAC;QACAC;QACAC;QACAC;KACH;AACL"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
|
|
2
|
+
import type { AccessControl } from "../../../features/shared/abstractions.js";
|
|
3
|
+
import type { CmsModel } from "../../../types/index.js";
|
|
4
|
+
interface ICanOverrideMetaFieldsParams {
|
|
5
|
+
identityContext: IdentityContext.Interface;
|
|
6
|
+
accessControl: AccessControl.Interface;
|
|
7
|
+
model: CmsModel;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Security: meta fields (createdBy, savedBy, modifiedOn, ...) decide entry ownership, so an
|
|
11
|
+
* identity limited to its own entries must not be able to set them (e.g. take over an entry by
|
|
12
|
+
* changing createdBy). Only code running without authorization (imports, migrations), full access
|
|
13
|
+
* identities and identities which can already write all entries of the model may override them.
|
|
14
|
+
*/
|
|
15
|
+
export declare const canOverrideMetaFields: (params: ICanOverrideMetaFieldsParams) => Promise<boolean>;
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const canOverrideMetaFields = async (params)=>{
|
|
2
|
+
const { identityContext, accessControl, model } = params;
|
|
3
|
+
if (!identityContext.isAuthorizationEnabled()) return true;
|
|
4
|
+
if (await identityContext.hasFullAccess()) return true;
|
|
5
|
+
return accessControl.canWriteNonOwnedEntries({
|
|
6
|
+
model
|
|
7
|
+
});
|
|
8
|
+
};
|
|
9
|
+
export { canOverrideMetaFields };
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=canOverrideMetaFields.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/contentEntry/entryDataFactories/canOverrideMetaFields.js","sources":["../../../../src/features/contentEntry/entryDataFactories/canOverrideMetaFields.ts"],"sourcesContent":["import type { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport type { AccessControl } from \"~/features/shared/abstractions.js\";\nimport type { CmsModel } from \"~/types/index.js\";\n\ninterface ICanOverrideMetaFieldsParams {\n identityContext: IdentityContext.Interface;\n accessControl: AccessControl.Interface;\n model: CmsModel;\n}\n\n/**\n * Security: meta fields (createdBy, savedBy, modifiedOn, ...) decide entry ownership, so an\n * identity limited to its own entries must not be able to set them (e.g. take over an entry by\n * changing createdBy). Only code running without authorization (imports, migrations), full access\n * identities and identities which can already write all entries of the model may override them.\n */\nexport const canOverrideMetaFields = async (\n params: ICanOverrideMetaFieldsParams\n): Promise<boolean> => {\n const { identityContext, accessControl, model } = params;\n if (!identityContext.isAuthorizationEnabled()) {\n return true;\n }\n if (await identityContext.hasFullAccess()) {\n return true;\n }\n return accessControl.canWriteNonOwnedEntries({ model });\n};\n"],"names":["canOverrideMetaFields","params","identityContext","accessControl","model"],"mappings":"AAgBO,MAAMA,wBAAwB,OACjCC;IAEA,MAAM,EAAEC,eAAe,EAAEC,aAAa,EAAEC,KAAK,EAAE,GAAGH;IAClD,IAAI,CAACC,gBAAgB,sBAAsB,IACvC,OAAO;IAEX,IAAI,MAAMA,gBAAgB,aAAa,IACnC,OAAO;IAEX,OAAOC,cAAc,uBAAuB,CAAC;QAAEC;IAAM;AACzD"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { CmsModel } from "../../../types/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* An additional access rule for a content model, on top of the Headless CMS permissions.
|
|
4
|
+
* When a guard handles a model and denies access, the model and its entries are not accessible,
|
|
5
|
+
* whatever the Headless CMS permissions allow.
|
|
6
|
+
*
|
|
7
|
+
* Use it for a model that belongs to another application with its own permission.
|
|
8
|
+
*/
|
|
9
|
+
export interface IModelAccessGuardParams {
|
|
10
|
+
/**
|
|
11
|
+
* The access being checked: "r" (read), "w" (write) or "d" (delete).
|
|
12
|
+
* Not set means read.
|
|
13
|
+
*/
|
|
14
|
+
rwd?: string;
|
|
15
|
+
/**
|
|
16
|
+
* The publishing action being checked, for example "p" (publish) or "u" (unpublish).
|
|
17
|
+
*/
|
|
18
|
+
pw?: string;
|
|
19
|
+
}
|
|
20
|
+
export interface IModelAccessGuard {
|
|
21
|
+
/** Does this guard apply to the given model? */
|
|
22
|
+
canHandle(model: Pick<CmsModel, "modelId">): boolean;
|
|
23
|
+
/** May the current identity access the model and its entries in the given way? */
|
|
24
|
+
canAccess(params: IModelAccessGuardParams): Promise<boolean>;
|
|
25
|
+
}
|
|
26
|
+
export declare const ModelAccessGuard: import("@webiny/di").Abstraction<IModelAccessGuard>;
|
|
27
|
+
export declare namespace ModelAccessGuard {
|
|
28
|
+
type Interface = IModelAccessGuard;
|
|
29
|
+
type Params = IModelAccessGuardParams;
|
|
30
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/contentModel/ModelAccessGuard/abstractions.js","sources":["../../../../src/features/contentModel/ModelAccessGuard/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { CmsModel } from \"~/types/index.js\";\n\n/**\n * An additional access rule for a content model, on top of the Headless CMS permissions.\n * When a guard handles a model and denies access, the model and its entries are not accessible,\n * whatever the Headless CMS permissions allow.\n *\n * Use it for a model that belongs to another application with its own permission.\n */\nexport interface IModelAccessGuardParams {\n /**\n * The access being checked: \"r\" (read), \"w\" (write) or \"d\" (delete).\n * Not set means read.\n */\n rwd?: string;\n /**\n * The publishing action being checked, for example \"p\" (publish) or \"u\" (unpublish).\n */\n pw?: string;\n}\n\nexport interface IModelAccessGuard {\n /** Does this guard apply to the given model? */\n canHandle(model: Pick<CmsModel, \"modelId\">): boolean;\n /** May the current identity access the model and its entries in the given way? */\n canAccess(params: IModelAccessGuardParams): Promise<boolean>;\n}\n\nexport const ModelAccessGuard = createAbstraction<IModelAccessGuard>(\"Cms/ModelAccessGuard\");\n\nexport namespace ModelAccessGuard {\n export type Interface = IModelAccessGuard;\n export type Params = IModelAccessGuardParams;\n}\n"],"names":["ModelAccessGuard","createAbstraction"],"mappings":";AA6BO,MAAMA,mBAAmBC,kBAAqC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { ModelAccessGuard } from "./abstractions.js";
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { type IRefModelsGenerator, type RefModelMetadata } from "./abstractions.js";
|
|
2
2
|
import { ModelToAstConverter } from "../ModelToAstConverter/abstractions.js";
|
|
3
3
|
import { ValuesSelectionGenerator } from "../ValuesSelectionGenerator/abstractions.js";
|
|
4
|
-
import {
|
|
4
|
+
import { GetModelUseCase } from "../GetModel/abstractions.js";
|
|
5
5
|
import type { CmsModel } from "../../../types/index.js";
|
|
6
6
|
declare class RefModelsGeneratorImpl implements IRefModelsGenerator {
|
|
7
7
|
private readonly modelToAst;
|
|
8
|
-
private readonly
|
|
8
|
+
private readonly getModelUseCase;
|
|
9
9
|
private readonly valuesSelectionGenerator;
|
|
10
|
-
constructor(modelToAst: ModelToAstConverter.Interface,
|
|
10
|
+
constructor(modelToAst: ModelToAstConverter.Interface, getModelUseCase: GetModelUseCase.Interface, valuesSelectionGenerator: ValuesSelectionGenerator.Interface);
|
|
11
11
|
generate(model: CmsModel): Promise<Record<string, RefModelMetadata>>;
|
|
12
12
|
private collectRefModelIds;
|
|
13
13
|
private collectFromFieldNode;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { RefModelsGenerator } from "./abstractions.js";
|
|
2
2
|
import { ModelToAstConverter } from "../ModelToAstConverter/abstractions.js";
|
|
3
3
|
import { ValuesSelectionGenerator } from "../ValuesSelectionGenerator/abstractions.js";
|
|
4
|
-
import {
|
|
4
|
+
import { GetModelUseCase } from "../GetModel/abstractions.js";
|
|
5
5
|
class RefModelsGeneratorImpl {
|
|
6
|
-
constructor(modelToAst,
|
|
6
|
+
constructor(modelToAst, getModelUseCase, valuesSelectionGenerator){
|
|
7
7
|
this.modelToAst = modelToAst;
|
|
8
|
-
this.
|
|
8
|
+
this.getModelUseCase = getModelUseCase;
|
|
9
9
|
this.valuesSelectionGenerator = valuesSelectionGenerator;
|
|
10
10
|
}
|
|
11
11
|
async generate(model) {
|
|
@@ -14,9 +14,10 @@ class RefModelsGeneratorImpl {
|
|
|
14
14
|
for (const node of ast.children)this.collectRefModelIds(node, refModelIds);
|
|
15
15
|
const result = {};
|
|
16
16
|
for (const modelId of refModelIds){
|
|
17
|
-
const fetchResult = await this.
|
|
17
|
+
const fetchResult = await this.getModelUseCase.execute(modelId);
|
|
18
18
|
if (fetchResult.isFail()) continue;
|
|
19
19
|
const refModel = fetchResult.value;
|
|
20
|
+
if (refModel.isPrivate) continue;
|
|
20
21
|
const valuesSelection = this.valuesSelectionGenerator.generate(refModel);
|
|
21
22
|
result[modelId] = {
|
|
22
23
|
valuesSelection
|
|
@@ -47,7 +48,7 @@ const RefModelsGenerator_RefModelsGenerator = RefModelsGenerator.createImplement
|
|
|
47
48
|
implementation: RefModelsGeneratorImpl,
|
|
48
49
|
dependencies: [
|
|
49
50
|
ModelToAstConverter,
|
|
50
|
-
|
|
51
|
+
GetModelUseCase,
|
|
51
52
|
ValuesSelectionGenerator
|
|
52
53
|
]
|
|
53
54
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/contentModel/RefModelsGenerator/RefModelsGenerator.js","sources":["../../../../src/features/contentModel/RefModelsGenerator/RefModelsGenerator.ts"],"sourcesContent":["import {\n RefModelsGenerator as Abstraction,\n type IRefModelsGenerator,\n type RefModelMetadata\n} from \"./abstractions.js\";\nimport { ModelToAstConverter } from \"../ModelToAstConverter/abstractions.js\";\nimport { ValuesSelectionGenerator } from \"../ValuesSelectionGenerator/abstractions.js\";\nimport {
|
|
1
|
+
{"version":3,"file":"features/contentModel/RefModelsGenerator/RefModelsGenerator.js","sources":["../../../../src/features/contentModel/RefModelsGenerator/RefModelsGenerator.ts"],"sourcesContent":["import {\n RefModelsGenerator as Abstraction,\n type IRefModelsGenerator,\n type RefModelMetadata\n} from \"./abstractions.js\";\nimport { ModelToAstConverter } from \"../ModelToAstConverter/abstractions.js\";\nimport { ValuesSelectionGenerator } from \"../ValuesSelectionGenerator/abstractions.js\";\nimport { GetModelUseCase } from \"../GetModel/abstractions.js\";\nimport type {\n CmsModel,\n CmsModelFieldAstNode,\n CmsModelFieldAstNodeField,\n CmsModelFieldAstNodeCollection\n} from \"~/types/index.js\";\n\nclass RefModelsGeneratorImpl implements IRefModelsGenerator {\n constructor(\n private readonly modelToAst: ModelToAstConverter.Interface,\n private readonly getModelUseCase: GetModelUseCase.Interface,\n private readonly valuesSelectionGenerator: ValuesSelectionGenerator.Interface\n ) {}\n\n async generate(model: CmsModel): Promise<Record<string, RefModelMetadata>> {\n const ast = this.modelToAst.toAst(model);\n const refModelIds = new Set<string>();\n\n for (const node of ast.children) {\n this.collectRefModelIds(node, refModelIds);\n }\n\n const result: Record<string, RefModelMetadata> = {};\n\n for (const modelId of refModelIds) {\n // Security: only expose models the current identity can read. Private models are\n // internal and never exposed.\n const fetchResult = await this.getModelUseCase.execute(modelId);\n if (fetchResult.isFail()) {\n continue;\n }\n\n const refModel = fetchResult.value;\n if (refModel.isPrivate) {\n continue;\n }\n const valuesSelection = this.valuesSelectionGenerator.generate(refModel);\n\n result[modelId] = { valuesSelection };\n }\n\n return result;\n }\n\n private collectRefModelIds(node: CmsModelFieldAstNode, modelIds: Set<string>): void {\n if (node.type === \"field\") {\n this.collectFromFieldNode(node, modelIds);\n } else if (node.type === \"collection\") {\n this.collectFromCollectionNode(node, modelIds);\n }\n }\n\n private collectFromFieldNode(node: CmsModelFieldAstNodeField, modelIds: Set<string>): void {\n const { field, children } = node;\n\n if (field.type === \"ref\") {\n const models = field.settings?.models;\n if (Array.isArray(models)) {\n for (const refModel of models) {\n if (refModel.modelId) {\n modelIds.add(refModel.modelId);\n }\n }\n }\n return;\n }\n\n for (const child of children) {\n this.collectRefModelIds(child, modelIds);\n }\n }\n\n private collectFromCollectionNode(\n node: CmsModelFieldAstNodeCollection,\n modelIds: Set<string>\n ): void {\n for (const child of node.children) {\n this.collectRefModelIds(child, modelIds);\n }\n }\n}\n\nexport const RefModelsGenerator = Abstraction.createImplementation({\n implementation: RefModelsGeneratorImpl,\n dependencies: [ModelToAstConverter, GetModelUseCase, ValuesSelectionGenerator]\n});\n"],"names":["RefModelsGeneratorImpl","modelToAst","getModelUseCase","valuesSelectionGenerator","model","ast","refModelIds","Set","node","result","modelId","fetchResult","refModel","valuesSelection","modelIds","field","children","models","Array","child","RefModelsGenerator","Abstraction","ModelToAstConverter","GetModelUseCase","ValuesSelectionGenerator"],"mappings":";;;;AAeA,MAAMA;IACF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AASH,SAChB,IAAI,CAAC,kBAAkB,CAACG,OAAOL;IAEvC;IAEQ,0BACJN,IAAoC,EACpCM,QAAqB,EACjB;QACJ,KAAK,MAAMK,SAASX,KAAK,QAAQ,CAC7B,IAAI,CAAC,kBAAkB,CAACW,OAAOL;IAEvC;AACJ;AAEO,MAAMM,wCAAqBC,mBAAAA,oBAAgC,CAAC;IAC/D,gBAAgBrB;IAChB,cAAc;QAACsB;QAAqBC;QAAiBC;KAAyB;AAClF"}
|
|
@@ -7,6 +7,7 @@ import { TenantContext } from "@webiny/api-core/features/tenancy/TenantContext/i
|
|
|
7
7
|
import type { CmsModel } from "../../../types/index.js";
|
|
8
8
|
import type { CmsModelUpdateInput } from "../../../types/index.js";
|
|
9
9
|
import { GetModelUseCase } from "../../../features/contentModel/GetModel/index.js";
|
|
10
|
+
import { GetGroupUseCase } from "../../../features/contentModelGroup/GetGroup/abstractions.js";
|
|
10
11
|
/**
|
|
11
12
|
* UpdateModelUseCase - Core model update orchestration.
|
|
12
13
|
*
|
|
@@ -29,7 +30,8 @@ declare class UpdateModelUseCaseImpl implements UseCaseAbstraction.Interface {
|
|
|
29
30
|
private repository;
|
|
30
31
|
private accessControl;
|
|
31
32
|
private tenantContext;
|
|
32
|
-
|
|
33
|
+
private getGroupUseCase;
|
|
34
|
+
constructor(getModelUseCase: GetModelUseCase.Interface, eventPublisher: EventPublisher.Interface, repository: UpdateModelRepository.Interface, accessControl: AccessControl.Interface, tenantContext: TenantContext.Interface, getGroupUseCase: GetGroupUseCase.Interface);
|
|
33
35
|
execute(modelId: string, input: CmsModelUpdateInput): Promise<Result<CmsModel, UseCaseAbstraction.Error>>;
|
|
34
36
|
}
|
|
35
37
|
export declare const UpdateModelUseCase: typeof UpdateModelUseCaseImpl & {
|
|
@@ -4,18 +4,21 @@ import { EventPublisher } from "@webiny/api-core/features/eventPublisher/index.j
|
|
|
4
4
|
import { ModelAfterUpdateEvent, ModelBeforeUpdateEvent, ModelUpdateErrorEvent } from "./events.js";
|
|
5
5
|
import { AccessControl } from "../../shared/abstractions.js";
|
|
6
6
|
import { TenantContext } from "@webiny/api-core/features/tenancy/TenantContext/index.js";
|
|
7
|
-
import { ModelNotAuthorizedError, ModelValidationError } from "../../../domain/contentModel/errors.js";
|
|
7
|
+
import { ModelNotAuthorizedError, ModelPersistenceError, ModelValidationError } from "../../../domain/contentModel/errors.js";
|
|
8
8
|
import { createZodError, removeUndefinedValues } from "@webiny/utils";
|
|
9
9
|
import { createModelUpdateValidation } from "../../../domain/contentModel/schemas.js";
|
|
10
10
|
import { ensureTypeTag } from "../../../domain/contentModel/ensureTypeTag.js";
|
|
11
11
|
import { GetModelUseCase } from "../GetModel/index.js";
|
|
12
|
+
import { GetGroupUseCase } from "../../contentModelGroup/GetGroup/abstractions.js";
|
|
13
|
+
import { GroupNotAuthorizedError, GroupNotFoundError } from "../../../domain/contentModelGroup/errors.js";
|
|
12
14
|
class UpdateModelUseCaseImpl {
|
|
13
|
-
constructor(getModelUseCase, eventPublisher, repository, accessControl, tenantContext){
|
|
15
|
+
constructor(getModelUseCase, eventPublisher, repository, accessControl, tenantContext, getGroupUseCase){
|
|
14
16
|
this.getModelUseCase = getModelUseCase;
|
|
15
17
|
this.eventPublisher = eventPublisher;
|
|
16
18
|
this.repository = repository;
|
|
17
19
|
this.accessControl = accessControl;
|
|
18
20
|
this.tenantContext = tenantContext;
|
|
21
|
+
this.getGroupUseCase = getGroupUseCase;
|
|
19
22
|
}
|
|
20
23
|
async execute(modelId, input) {
|
|
21
24
|
const canAccess = await this.accessControl.canAccessModel({
|
|
@@ -25,6 +28,11 @@ class UpdateModelUseCaseImpl {
|
|
|
25
28
|
const getResult = await this.getModelUseCase.execute(modelId);
|
|
26
29
|
if (getResult.isFail()) return getResult;
|
|
27
30
|
const original = structuredClone(getResult.value);
|
|
31
|
+
const canWriteOriginal = await this.accessControl.canAccessModel({
|
|
32
|
+
model: original,
|
|
33
|
+
rwd: "w"
|
|
34
|
+
});
|
|
35
|
+
if (!canWriteOriginal) return Result.fail(ModelNotAuthorizedError.fromModel(original));
|
|
28
36
|
const validationResult = await createModelUpdateValidation().safeParseAsync(input);
|
|
29
37
|
if (!validationResult.success) {
|
|
30
38
|
const zodError = createZodError(validationResult.error);
|
|
@@ -35,6 +43,14 @@ class UpdateModelUseCaseImpl {
|
|
|
35
43
|
}
|
|
36
44
|
const data = removeUndefinedValues(validationResult.data);
|
|
37
45
|
if (0 === Object.keys(data).length) return Result.ok(original);
|
|
46
|
+
if (data.group && data.group !== original.group) {
|
|
47
|
+
const groupResult = await this.getGroupUseCase.execute(data.group);
|
|
48
|
+
if (groupResult.isFail()) {
|
|
49
|
+
const error = groupResult.error;
|
|
50
|
+
if (error instanceof GroupNotFoundError || error instanceof GroupNotAuthorizedError) return Result.fail(error);
|
|
51
|
+
return Result.fail(new ModelPersistenceError(error));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
38
54
|
const tenant = this.tenantContext.getTenant();
|
|
39
55
|
const model = {
|
|
40
56
|
...original,
|
|
@@ -82,7 +98,8 @@ const UpdateModelUseCase_UpdateModelUseCase = UpdateModelUseCase.createImplement
|
|
|
82
98
|
EventPublisher,
|
|
83
99
|
UpdateModelRepository,
|
|
84
100
|
AccessControl,
|
|
85
|
-
TenantContext
|
|
101
|
+
TenantContext,
|
|
102
|
+
GetGroupUseCase
|
|
86
103
|
]
|
|
87
104
|
});
|
|
88
105
|
export { UpdateModelUseCase_UpdateModelUseCase as UpdateModelUseCase };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/contentModel/UpdateModel/UpdateModelUseCase.js","sources":["../../../../src/features/contentModel/UpdateModel/UpdateModelUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { UpdateModelUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { UpdateModelRepository } from \"./abstractions.js\";\nimport { EventPublisher } from \"@webiny/api-core/features/eventPublisher/index.js\";\nimport { ModelBeforeUpdateEvent } from \"./events.js\";\nimport { ModelAfterUpdateEvent } from \"./events.js\";\nimport { ModelUpdateErrorEvent } from \"./events.js\";\nimport { AccessControl } from \"~/features/shared/abstractions.js\";\nimport { TenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/index.js\";\nimport { ModelNotAuthorizedError, ModelValidationError } from \"~/domain/contentModel/errors.js\";\nimport { createZodError } from \"@webiny/utils\";\nimport { removeUndefinedValues } from \"@webiny/utils\";\nimport { createModelUpdateValidation } from \"~/domain/contentModel/schemas.js\";\nimport { ensureTypeTag } from \"~/domain/contentModel/ensureTypeTag.js\";\nimport type { CmsModel } from \"~/types/index.js\";\nimport type { CmsModelUpdateInput } from \"~/types/index.js\";\nimport { GetModelUseCase } from \"~/features/contentModel/GetModel/index.js\";\n\n/**\n * UpdateModelUseCase - Core model update orchestration.\n *\n * Responsibilities:\n * - Validate input (Zod)\n * - Fetch original model\n * - Create updated domain model object\n * - Handle group changes\n * - Handle field ID changes (title, description, image)\n * - Access control checks\n * - Publish before event\n * - Delegate to repository for validation and persistence\n * - Publish after event or error event\n *\n * Note: Repository handles domain validations (API name uniqueness, field validation, etc.)\n */\nclass UpdateModelUseCaseImpl implements UseCaseAbstraction.Interface {\n public constructor(\n private getModelUseCase: GetModelUseCase.Interface,\n private eventPublisher: EventPublisher.Interface,\n private repository: UpdateModelRepository.Interface,\n private accessControl: AccessControl.Interface,\n private tenantContext: TenantContext.Interface\n ) {}\n\n async execute(\n modelId: string,\n input: CmsModelUpdateInput\n ): Promise<Result<CmsModel, UseCaseAbstraction.Error>> {\n // Initial access control check\n const canAccess = await this.accessControl.canAccessModel({ rwd: \"w\" });\n if (!canAccess) {\n return Result.fail(new ModelNotAuthorizedError());\n }\n\n // Get the original model (with access control check)\n const getResult = await this.getModelUseCase.execute(modelId);\n if (getResult.isFail()) {\n return getResult;\n }\n\n const original = structuredClone(getResult.value);\n\n // Validate input\n const validationResult = await createModelUpdateValidation().safeParseAsync(input);\n if (!validationResult.success) {\n const zodError = createZodError(validationResult.error);\n return Result.fail(\n new ModelValidationError({\n message: zodError.message,\n data: zodError.data\n })\n );\n }\n\n const data = removeUndefinedValues(validationResult.data);\n\n // If no changes, return original\n if (Object.keys(data).length === 0) {\n return Result.ok(original);\n }\n\n // Create updated model\n const tenant = this.tenantContext.getTenant();\n\n const model: CmsModel = {\n ...original,\n ...data,\n icon: data.icon ?? original.icon,\n // Handle optional field IDs explicitly\n titleFieldId:\n data.titleFieldId === undefined\n ? original.titleFieldId\n : (data.titleFieldId as string),\n descriptionFieldId:\n data.descriptionFieldId === undefined\n ? original.descriptionFieldId\n : data.descriptionFieldId,\n imageFieldId:\n data.imageFieldId === undefined ? original.imageFieldId : data.imageFieldId,\n description: data.description || original.description,\n tenant: original.tenant || tenant.id,\n savedOn: new Date().toISOString()\n };\n\n // Access control check on the updated model\n const canAccessModel = await this.accessControl.canAccessModel({ model, rwd: \"w\" });\n if (!canAccessModel) {\n return Result.fail(ModelNotAuthorizedError.fromModel(model));\n }\n\n // Ensure type tags\n model.tags = ensureTypeTag(model);\n\n // Publish before event\n await this.eventPublisher.publish(\n new ModelBeforeUpdateEvent({ model, original, input: data })\n );\n\n // Persist via repository (repository will validate)\n const result = await this.repository.execute(model, original);\n if (result.isFail()) {\n // Publish error event\n await this.eventPublisher.publish(\n new ModelUpdateErrorEvent({\n input: data,\n model,\n original,\n error: result.error\n })\n );\n return Result.fail(result.error);\n }\n\n // Publish after event\n await this.eventPublisher.publish(\n new ModelAfterUpdateEvent({\n model: result.value,\n original\n })\n );\n\n return Result.ok(result.value);\n }\n}\n\nexport const UpdateModelUseCase = UseCaseAbstraction.createImplementation({\n implementation: UpdateModelUseCaseImpl,\n dependencies: [\n GetModelUseCase,\n EventPublisher,\n UpdateModelRepository,\n AccessControl,\n TenantContext\n ]\n});\n"],"names":["UpdateModelUseCaseImpl","getModelUseCase","eventPublisher","repository","accessControl","tenantContext","modelId","input","canAccess","Result","ModelNotAuthorizedError","getResult","original","structuredClone","validationResult","createModelUpdateValidation","zodError","createZodError","ModelValidationError","data","removeUndefinedValues","Object","tenant","model","undefined","Date","canAccessModel","ensureTypeTag","ModelBeforeUpdateEvent","result","ModelUpdateErrorEvent","ModelAfterUpdateEvent","UpdateModelUseCase","UseCaseAbstraction","GetModelUseCase","EventPublisher","UpdateModelRepository","AccessControl","TenantContext"],"mappings":";;;;;;;;;;;AAkCA,MAAMA;IACF,YACYC,eAA0C,EAC1CC,cAAwC,EACxCC,UAA2C,EAC3CC,aAAsC,EACtCC,aAAsC,CAChD;aALUJ,eAAe,GAAfA;aACAC,cAAc,GAAdA;aACAC,UAAU,GAAVA;aACAC,aAAa,GAAbA;aACAC,aAAa,GAAbA;IACT;IAEH,MAAM,QACFC,OAAe,EACfC,KAA0B,EACyB;QAEnD,MAAMC,YAAY,MAAM,IAAI,CAAC,aAAa,CAAC,cAAc,CAAC;YAAE,KAAK;QAAI;QACrE,IAAI,CAACA,WACD,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAI3B,MAAMC,YAAY,MAAM,IAAI,CAAC,eAAe,CAAC,OAAO,CAACL;QACrD,IAAIK,UAAU,MAAM,IAChB,OAAOA;QAGX,MAAMC,WAAWC,gBAAgBF,UAAU,KAAK;QAGhD,MAAMG,mBAAmB,MAAMC,8BAA8B,cAAc,CAACR;QAC5E,IAAI,CAACO,iBAAiB,OAAO,EAAE;YAC3B,MAAME,WAAWC,eAAeH,iBAAiB,KAAK;YACtD,OAAOL,OAAO,IAAI,CACd,IAAIS,qBAAqB;gBACrB,SAASF,SAAS,OAAO;gBACzB,MAAMA,SAAS,IAAI;YACvB;QAER;QAEA,MAAMG,OAAOC,sBAAsBN,iBAAiB,IAAI;QAGxD,IAAIO,AAA6B,MAA7BA,OAAO,IAAI,CAACF,MAAM,MAAM,EACxB,OAAOV,OAAO,EAAE,CAACG;QAIrB,MAAMU,SAAS,IAAI,CAAC,aAAa,CAAC,SAAS;QAE3C,MAAMC,QAAkB;YACpB,GAAGX,QAAQ;YACX,GAAGO,IAAI;Y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Ac;QACVkC;QACAC;QACAC;QACAC;QACAC;KACH;AACL"}
|
|
1
|
+
{"version":3,"file":"features/contentModel/UpdateModel/UpdateModelUseCase.js","sources":["../../../../src/features/contentModel/UpdateModel/UpdateModelUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { UpdateModelUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { UpdateModelRepository } from \"./abstractions.js\";\nimport { EventPublisher } from \"@webiny/api-core/features/eventPublisher/index.js\";\nimport { ModelBeforeUpdateEvent } from \"./events.js\";\nimport { ModelAfterUpdateEvent } from \"./events.js\";\nimport { ModelUpdateErrorEvent } from \"./events.js\";\nimport { AccessControl } from \"~/features/shared/abstractions.js\";\nimport { TenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/index.js\";\nimport {\n ModelNotAuthorizedError,\n ModelPersistenceError,\n ModelValidationError\n} from \"~/domain/contentModel/errors.js\";\nimport { createZodError } from \"@webiny/utils\";\nimport { removeUndefinedValues } from \"@webiny/utils\";\nimport { createModelUpdateValidation } from \"~/domain/contentModel/schemas.js\";\nimport { ensureTypeTag } from \"~/domain/contentModel/ensureTypeTag.js\";\nimport type { CmsModel } from \"~/types/index.js\";\nimport type { CmsModelUpdateInput } from \"~/types/index.js\";\nimport { GetModelUseCase } from \"~/features/contentModel/GetModel/index.js\";\nimport { GetGroupUseCase } from \"~/features/contentModelGroup/GetGroup/abstractions.js\";\nimport { GroupNotAuthorizedError, GroupNotFoundError } from \"~/domain/contentModelGroup/errors.js\";\n\n/**\n * UpdateModelUseCase - Core model update orchestration.\n *\n * Responsibilities:\n * - Validate input (Zod)\n * - Fetch original model\n * - Create updated domain model object\n * - Handle group changes\n * - Handle field ID changes (title, description, image)\n * - Access control checks\n * - Publish before event\n * - Delegate to repository for validation and persistence\n * - Publish after event or error event\n *\n * Note: Repository handles domain validations (API name uniqueness, field validation, etc.)\n */\nclass UpdateModelUseCaseImpl implements UseCaseAbstraction.Interface {\n public constructor(\n private getModelUseCase: GetModelUseCase.Interface,\n private eventPublisher: EventPublisher.Interface,\n private repository: UpdateModelRepository.Interface,\n private accessControl: AccessControl.Interface,\n private tenantContext: TenantContext.Interface,\n private getGroupUseCase: GetGroupUseCase.Interface\n ) {}\n\n async execute(\n modelId: string,\n input: CmsModelUpdateInput\n ): Promise<Result<CmsModel, UseCaseAbstraction.Error>> {\n // Initial access control check\n const canAccess = await this.accessControl.canAccessModel({ rwd: \"w\" });\n if (!canAccess) {\n return Result.fail(new ModelNotAuthorizedError());\n }\n\n // Get the original model (with access control check)\n const getResult = await this.getModelUseCase.execute(modelId);\n if (getResult.isFail()) {\n return getResult;\n }\n\n const original = structuredClone(getResult.value);\n\n // Security: write access must be checked on the model as it is now. Checking only the\n // updated model would let a user move a model out of a group they can only read.\n const canWriteOriginal = await this.accessControl.canAccessModel({\n model: original,\n rwd: \"w\"\n });\n if (!canWriteOriginal) {\n return Result.fail(ModelNotAuthorizedError.fromModel(original));\n }\n\n // Validate input\n const validationResult = await createModelUpdateValidation().safeParseAsync(input);\n if (!validationResult.success) {\n const zodError = createZodError(validationResult.error);\n return Result.fail(\n new ModelValidationError({\n message: zodError.message,\n data: zodError.data\n })\n );\n }\n\n const data = removeUndefinedValues(validationResult.data);\n\n // If no changes, return original\n if (Object.keys(data).length === 0) {\n return Result.ok(original);\n }\n\n // Security: when moving the model to another group, that group must exist and be\n // accessible to the current identity.\n if (data.group && data.group !== original.group) {\n const groupResult = await this.getGroupUseCase.execute(data.group);\n if (groupResult.isFail()) {\n const error = groupResult.error;\n if (\n error instanceof GroupNotFoundError ||\n error instanceof GroupNotAuthorizedError\n ) {\n return Result.fail(error);\n }\n return Result.fail(new ModelPersistenceError(error));\n }\n }\n\n // Create updated model\n const tenant = this.tenantContext.getTenant();\n\n const model: CmsModel = {\n ...original,\n ...data,\n icon: data.icon ?? original.icon,\n // Handle optional field IDs explicitly\n titleFieldId:\n data.titleFieldId === undefined\n ? original.titleFieldId\n : (data.titleFieldId as string),\n descriptionFieldId:\n data.descriptionFieldId === undefined\n ? original.descriptionFieldId\n : data.descriptionFieldId,\n imageFieldId:\n data.imageFieldId === undefined ? original.imageFieldId : data.imageFieldId,\n description: data.description || original.description,\n tenant: original.tenant || tenant.id,\n savedOn: new Date().toISOString()\n };\n\n // Access control check on the updated model\n const canAccessModel = await this.accessControl.canAccessModel({ model, rwd: \"w\" });\n if (!canAccessModel) {\n return Result.fail(ModelNotAuthorizedError.fromModel(model));\n }\n\n // Ensure type tags\n model.tags = ensureTypeTag(model);\n\n // Publish before event\n await this.eventPublisher.publish(\n new ModelBeforeUpdateEvent({ model, original, input: data })\n );\n\n // Persist via repository (repository will validate)\n const result = await this.repository.execute(model, original);\n if (result.isFail()) {\n // Publish error event\n await this.eventPublisher.publish(\n new ModelUpdateErrorEvent({\n input: data,\n model,\n original,\n error: result.error\n })\n );\n return Result.fail(result.error);\n }\n\n // Publish after event\n await this.eventPublisher.publish(\n new ModelAfterUpdateEvent({\n model: result.value,\n original\n })\n );\n\n return Result.ok(result.value);\n }\n}\n\nexport const UpdateModelUseCase = UseCaseAbstraction.createImplementation({\n implementation: UpdateModelUseCaseImpl,\n dependencies: [\n GetModelUseCase,\n EventPublisher,\n UpdateModelRepository,\n AccessControl,\n TenantContext,\n GetGroupUseCase\n ]\n});\n"],"names":["UpdateModelUseCaseImpl","getModelUseCase","eventPublisher","repository","accessControl","tenantContext","getGroupUseCase","modelId","input","canAccess","Result","ModelNotAuthorizedError","getResult","original","structuredClone","canWriteOriginal","validationResult","createModelUpdateValidation","zodError","createZodError","ModelValidationError","data","removeUndefinedValues","Object","groupResult","error","GroupNotFoundError","GroupNotAuthorizedError","ModelPersistenceError","tenant","model","undefined","Date","canAccessModel","ensureTypeTag","ModelBeforeUpdateEvent","result","ModelUpdateErrorEvent","ModelAfterUpdateEvent","UpdateModelUseCase","UseCaseAbstraction","GetModelUseCase","EventPublisher","UpdateModelRepository","AccessControl","TenantContext","GetGroupUseCase"],"mappings":";;;;;;;;;;;;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,OAAOhB;gBACPS;gBACAjB;gBACA,OAAOuB,OAAO,KAAK;YACvB;YAEJ,OAAO1B,OAAO,IAAI,CAAC0B,OAAO,KAAK;QACnC;QAGA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIE,sBAAsB;YACtB,OAAOF,OAAO,KAAK;YACnBvB;QACJ;QAGJ,OAAOH,OAAO,EAAE,CAAC0B,OAAO,KAAK;IACjC;AACJ;AAEO,MAAMG,wCAAqBC,mBAAAA,oBAAuC,CAAC;IACtE,gBAAgBxC;IAChB,cAAc;QACVyC;QACAC;QACAC;QACAC;QACAC;QACAC;KACH;AACL"}
|
|
@@ -21,7 +21,8 @@ class DeleteGroupUseCaseImpl {
|
|
|
21
21
|
if (getResult.isFail()) return Result.fail(getResult.error);
|
|
22
22
|
const group = getResult.value;
|
|
23
23
|
const canAccessGroup = await this.accessControl.canAccessGroup({
|
|
24
|
-
group
|
|
24
|
+
group,
|
|
25
|
+
rwd: "d"
|
|
25
26
|
});
|
|
26
27
|
if (!canAccessGroup) return Result.fail(new GroupNotAuthorizedError());
|
|
27
28
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/contentModelGroup/DeleteGroup/DeleteGroupUseCase.js","sources":["../../../../src/features/contentModelGroup/DeleteGroup/DeleteGroupUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { createImplementation } from \"@webiny/feature/api\";\nimport { DeleteGroupUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { DeleteGroupRepository } from \"./abstractions.js\";\nimport { GetGroupUseCase } from \"~/features/contentModelGroup/GetGroup/abstractions.js\";\nimport { EventPublisher } from \"@webiny/api-core/features/eventPublisher/index.js\";\nimport { GroupBeforeDeleteEvent } from \"./events.js\";\nimport { GroupAfterDeleteEvent } from \"./events.js\";\nimport { GroupDeleteErrorEvent } from \"./events.js\";\nimport { AccessControl } from \"~/features/shared/abstractions.js\";\nimport { GroupNotAuthorizedError } from \"~/domain/contentModelGroup/errors.js\";\n\n/**\n * DeleteGroupUseCase - Orchestrates group deletion.\n *\n * Responsibilities:\n * - Fetch original group\n * - Access control checks\n * - Publish before event\n * - Delegate to repository\n * - Publish after event or error event\n */\nclass DeleteGroupUseCaseImpl implements UseCaseAbstraction.Interface {\n public constructor(\n private eventPublisher: EventPublisher.Interface,\n private repository: DeleteGroupRepository.Interface,\n private getGroupUseCase: GetGroupUseCase.Interface,\n private accessControl: AccessControl.Interface\n ) {}\n\n async execute(groupId: string): Promise<Result<void, UseCaseAbstraction.Error>> {\n // Initial access control check\n const canAccess = await this.accessControl.canAccessGroup({ rwd: \"d\" });\n if (!canAccess) {\n return Result.fail(new GroupNotAuthorizedError());\n }\n\n // Fetch original group\n const getResult = await this.getGroupUseCase.execute(groupId);\n if (getResult.isFail()) {\n return Result.fail(getResult.error);\n }\n const group = getResult.value;\n\n // Access control check on group\n const canAccessGroup = await this.accessControl.canAccessGroup({ group });\n if (!canAccessGroup) {\n return Result.fail(new GroupNotAuthorizedError());\n }\n\n try {\n // Publish before event\n await this.eventPublisher.publish(\n new GroupBeforeDeleteEvent({\n group\n })\n );\n\n // Persist via repository\n const result = await this.repository.execute(group);\n if (result.isFail()) {\n // Publish error event\n await this.eventPublisher.publish(\n new GroupDeleteErrorEvent({\n group,\n error: result.error\n })\n );\n return Result.fail(result.error);\n }\n\n // Publish after event\n await this.eventPublisher.publish(\n new GroupAfterDeleteEvent({\n group\n })\n );\n\n return Result.ok();\n } catch (error) {\n // Publish error event for unexpected errors\n await this.eventPublisher.publish(\n new GroupDeleteErrorEvent({\n group,\n error: error as Error\n })\n );\n return Result.fail(error as UseCaseAbstraction.Error);\n }\n }\n}\n\nexport const DeleteGroupUseCase = createImplementation({\n abstraction: UseCaseAbstraction,\n implementation: DeleteGroupUseCaseImpl,\n dependencies: [EventPublisher, DeleteGroupRepository, GetGroupUseCase, AccessControl]\n});\n"],"names":["DeleteGroupUseCaseImpl","eventPublisher","repository","getGroupUseCase","accessControl","groupId","canAccess","Result","GroupNotAuthorizedError","getResult","group","canAccessGroup","GroupBeforeDeleteEvent","result","GroupDeleteErrorEvent","GroupAfterDeleteEvent","error","DeleteGroupUseCase","createImplementation","UseCaseAbstraction","EventPublisher","DeleteGroupRepository","GetGroupUseCase","AccessControl"],"mappings":";;;;;;;AAsBA,MAAMA;IACF,YACYC,cAAwC,EACxCC,UAA2C,EAC3CC,eAA0C,EAC1CC,aAAsC,CAChD;aAJUH,cAAc,GAAdA;aACAC,UAAU,GAAVA;aACAC,eAAe,GAAfA;aACAC,aAAa,GAAbA;IACT;IAEH,MAAM,QAAQC,OAAe,EAAmD;QAE5E,MAAMC,YAAY,MAAM,IAAI,CAAC,aAAa,CAAC,cAAc,CAAC;YAAE,KAAK;QAAI;QACrE,IAAI,CAACA,WACD,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAI3B,MAAMC,YAAY,MAAM,IAAI,CAAC,eAAe,CAAC,OAAO,CAACJ;QACrD,IAAII,UAAU,MAAM,IAChB,OAAOF,OAAO,IAAI,CAACE,UAAU,KAAK;QAEtC,MAAMC,QAAQD,UAAU,KAAK;QAG7B,MAAME,iBAAiB,MAAM,IAAI,CAAC,aAAa,CAAC,cAAc,CAAC;YAAED;
|
|
1
|
+
{"version":3,"file":"features/contentModelGroup/DeleteGroup/DeleteGroupUseCase.js","sources":["../../../../src/features/contentModelGroup/DeleteGroup/DeleteGroupUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { createImplementation } from \"@webiny/feature/api\";\nimport { DeleteGroupUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { DeleteGroupRepository } from \"./abstractions.js\";\nimport { GetGroupUseCase } from \"~/features/contentModelGroup/GetGroup/abstractions.js\";\nimport { EventPublisher } from \"@webiny/api-core/features/eventPublisher/index.js\";\nimport { GroupBeforeDeleteEvent } from \"./events.js\";\nimport { GroupAfterDeleteEvent } from \"./events.js\";\nimport { GroupDeleteErrorEvent } from \"./events.js\";\nimport { AccessControl } from \"~/features/shared/abstractions.js\";\nimport { GroupNotAuthorizedError } from \"~/domain/contentModelGroup/errors.js\";\n\n/**\n * DeleteGroupUseCase - Orchestrates group deletion.\n *\n * Responsibilities:\n * - Fetch original group\n * - Access control checks\n * - Publish before event\n * - Delegate to repository\n * - Publish after event or error event\n */\nclass DeleteGroupUseCaseImpl implements UseCaseAbstraction.Interface {\n public constructor(\n private eventPublisher: EventPublisher.Interface,\n private repository: DeleteGroupRepository.Interface,\n private getGroupUseCase: GetGroupUseCase.Interface,\n private accessControl: AccessControl.Interface\n ) {}\n\n async execute(groupId: string): Promise<Result<void, UseCaseAbstraction.Error>> {\n // Initial access control check\n const canAccess = await this.accessControl.canAccessGroup({ rwd: \"d\" });\n if (!canAccess) {\n return Result.fail(new GroupNotAuthorizedError());\n }\n\n // Fetch original group\n const getResult = await this.getGroupUseCase.execute(groupId);\n if (getResult.isFail()) {\n return Result.fail(getResult.error);\n }\n const group = getResult.value;\n\n // Access control check on group\n const canAccessGroup = await this.accessControl.canAccessGroup({ group, rwd: \"d\" });\n if (!canAccessGroup) {\n return Result.fail(new GroupNotAuthorizedError());\n }\n\n try {\n // Publish before event\n await this.eventPublisher.publish(\n new GroupBeforeDeleteEvent({\n group\n })\n );\n\n // Persist via repository\n const result = await this.repository.execute(group);\n if (result.isFail()) {\n // Publish error event\n await this.eventPublisher.publish(\n new GroupDeleteErrorEvent({\n group,\n error: result.error\n })\n );\n return Result.fail(result.error);\n }\n\n // Publish after event\n await this.eventPublisher.publish(\n new GroupAfterDeleteEvent({\n group\n })\n );\n\n return Result.ok();\n } catch (error) {\n // Publish error event for unexpected errors\n await this.eventPublisher.publish(\n new GroupDeleteErrorEvent({\n group,\n error: error as Error\n })\n );\n return Result.fail(error as UseCaseAbstraction.Error);\n }\n }\n}\n\nexport const DeleteGroupUseCase = createImplementation({\n abstraction: UseCaseAbstraction,\n implementation: DeleteGroupUseCaseImpl,\n dependencies: [EventPublisher, DeleteGroupRepository, GetGroupUseCase, AccessControl]\n});\n"],"names":["DeleteGroupUseCaseImpl","eventPublisher","repository","getGroupUseCase","accessControl","groupId","canAccess","Result","GroupNotAuthorizedError","getResult","group","canAccessGroup","GroupBeforeDeleteEvent","result","GroupDeleteErrorEvent","GroupAfterDeleteEvent","error","DeleteGroupUseCase","createImplementation","UseCaseAbstraction","EventPublisher","DeleteGroupRepository","GetGroupUseCase","AccessControl"],"mappings":";;;;;;;AAsBA,MAAMA;IACF,YACYC,cAAwC,EACxCC,UAA2C,EAC3CC,eAA0C,EAC1CC,aAAsC,CAChD;aAJUH,cAAc,GAAdA;aACAC,UAAU,GAAVA;aACAC,eAAe,GAAfA;aACAC,aAAa,GAAbA;IACT;IAEH,MAAM,QAAQC,OAAe,EAAmD;QAE5E,MAAMC,YAAY,MAAM,IAAI,CAAC,aAAa,CAAC,cAAc,CAAC;YAAE,KAAK;QAAI;QACrE,IAAI,CAACA,WACD,OAAOC,OAAO,IAAI,CAAC,IAAIC;QAI3B,MAAMC,YAAY,MAAM,IAAI,CAAC,eAAe,CAAC,OAAO,CAACJ;QACrD,IAAII,UAAU,MAAM,IAChB,OAAOF,OAAO,IAAI,CAACE,UAAU,KAAK;QAEtC,MAAMC,QAAQD,UAAU,KAAK;QAG7B,MAAME,iBAAiB,MAAM,IAAI,CAAC,aAAa,CAAC,cAAc,CAAC;YAAED;YAAO,KAAK;QAAI;QACjF,IAAI,CAACC,gBACD,OAAOJ,OAAO,IAAI,CAAC,IAAIC;QAG3B,IAAI;YAEA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAII,uBAAuB;gBACvBF;YACJ;YAIJ,MAAMG,SAAS,MAAM,IAAI,CAAC,UAAU,CAAC,OAAO,CAACH;YAC7C,IAAIG,OAAO,MAAM,IAAI;gBAEjB,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIC,sBAAsB;oBACtBJ;oBACA,OAAOG,OAAO,KAAK;gBACvB;gBAEJ,OAAON,OAAO,IAAI,CAACM,OAAO,KAAK;YACnC;YAGA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIE,sBAAsB;gBACtBL;YACJ;YAGJ,OAAOH,OAAO,EAAE;QACpB,EAAE,OAAOS,OAAO;YAEZ,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIF,sBAAsB;gBACtBJ;gBACA,OAAOM;YACX;YAEJ,OAAOT,OAAO,IAAI,CAACS;QACvB;IACJ;AACJ;AAEO,MAAMC,wCAAqBC,qBAAqB;IACnD,aAAaC;IACb,gBAAgBnB;IAChB,cAAc;QAACoB;QAAgBC;QAAuBC;QAAiBC;KAAc;AACzF"}
|
|
@@ -25,7 +25,8 @@ class UpdateGroupUseCaseImpl {
|
|
|
25
25
|
if (getResult.isFail()) return Result.fail(getResult.error);
|
|
26
26
|
const original = getResult.value;
|
|
27
27
|
const canAccessGroup = await this.accessControl.canAccessGroup({
|
|
28
|
-
group: original
|
|
28
|
+
group: original,
|
|
29
|
+
rwd: "w"
|
|
29
30
|
});
|
|
30
31
|
if (!canAccessGroup) return Result.fail(new GroupNotAuthorizedError());
|
|
31
32
|
const validationResult = await createGroupUpdateValidation().safeParseAsync(input);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/contentModelGroup/UpdateGroup/UpdateGroupUseCase.js","sources":["../../../../src/features/contentModelGroup/UpdateGroup/UpdateGroupUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { createImplementation } from \"@webiny/feature/api\";\nimport { UpdateGroupUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { UpdateGroupRepository } from \"./abstractions.js\";\nimport { GetGroupUseCase } from \"~/features/contentModelGroup/GetGroup/abstractions.js\";\nimport { EventPublisher } from \"@webiny/api-core/features/eventPublisher/index.js\";\nimport { GroupBeforeUpdateEvent } from \"./events.js\";\nimport { GroupAfterUpdateEvent } from \"./events.js\";\nimport { GroupUpdateErrorEvent } from \"./events.js\";\nimport { AccessControl } from \"~/features/shared/abstractions.js\";\nimport { TenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/index.js\";\nimport {\n GroupNotAuthorizedError,\n GroupValidationError\n} from \"~/domain/contentModelGroup/errors.js\";\nimport { createZodError } from \"@webiny/utils\";\nimport { createGroupUpdateValidation } from \"~/domain/contentModelGroup/validation.js\";\nimport type { CmsGroup } from \"~/types/index.js\";\nimport type { CmsGroupUpdateInput } from \"~/types/index.js\";\n\n/**\n * UpdateGroupUseCase - Orchestrates group updates.\n *\n * Responsibilities:\n * - Fetch original group\n * - Access control checks\n * - Validate input (Zod)\n * - Skip if no changes\n * - Merge changes\n * - Publish before event\n * - Delegate to repository\n * - Publish after event or error event\n */\nclass UpdateGroupUseCaseImpl implements UseCaseAbstraction.Interface {\n public constructor(\n private eventPublisher: EventPublisher.Interface,\n private repository: UpdateGroupRepository.Interface,\n private getGroupUseCase: GetGroupUseCase.Interface,\n private accessControl: AccessControl.Interface,\n private tenantContext: TenantContext.Interface\n ) {}\n\n async execute(\n groupId: string,\n input: CmsGroupUpdateInput\n ): Promise<Result<CmsGroup, UseCaseAbstraction.Error>> {\n // Initial access control check\n const canAccess = await this.accessControl.canAccessGroup({ rwd: \"w\" });\n if (!canAccess) {\n return Result.fail(new GroupNotAuthorizedError());\n }\n\n // Fetch original group\n const getResult = await this.getGroupUseCase.execute(groupId);\n if (getResult.isFail()) {\n return Result.fail(getResult.error);\n }\n const original = getResult.value;\n\n // Access control check on original group\n const canAccessGroup = await this.accessControl.canAccessGroup({
|
|
1
|
+
{"version":3,"file":"features/contentModelGroup/UpdateGroup/UpdateGroupUseCase.js","sources":["../../../../src/features/contentModelGroup/UpdateGroup/UpdateGroupUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport { createImplementation } from \"@webiny/feature/api\";\nimport { UpdateGroupUseCase as UseCaseAbstraction } from \"./abstractions.js\";\nimport { UpdateGroupRepository } from \"./abstractions.js\";\nimport { GetGroupUseCase } from \"~/features/contentModelGroup/GetGroup/abstractions.js\";\nimport { EventPublisher } from \"@webiny/api-core/features/eventPublisher/index.js\";\nimport { GroupBeforeUpdateEvent } from \"./events.js\";\nimport { GroupAfterUpdateEvent } from \"./events.js\";\nimport { GroupUpdateErrorEvent } from \"./events.js\";\nimport { AccessControl } from \"~/features/shared/abstractions.js\";\nimport { TenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/index.js\";\nimport {\n GroupNotAuthorizedError,\n GroupValidationError\n} from \"~/domain/contentModelGroup/errors.js\";\nimport { createZodError } from \"@webiny/utils\";\nimport { createGroupUpdateValidation } from \"~/domain/contentModelGroup/validation.js\";\nimport type { CmsGroup } from \"~/types/index.js\";\nimport type { CmsGroupUpdateInput } from \"~/types/index.js\";\n\n/**\n * UpdateGroupUseCase - Orchestrates group updates.\n *\n * Responsibilities:\n * - Fetch original group\n * - Access control checks\n * - Validate input (Zod)\n * - Skip if no changes\n * - Merge changes\n * - Publish before event\n * - Delegate to repository\n * - Publish after event or error event\n */\nclass UpdateGroupUseCaseImpl implements UseCaseAbstraction.Interface {\n public constructor(\n private eventPublisher: EventPublisher.Interface,\n private repository: UpdateGroupRepository.Interface,\n private getGroupUseCase: GetGroupUseCase.Interface,\n private accessControl: AccessControl.Interface,\n private tenantContext: TenantContext.Interface\n ) {}\n\n async execute(\n groupId: string,\n input: CmsGroupUpdateInput\n ): Promise<Result<CmsGroup, UseCaseAbstraction.Error>> {\n // Initial access control check\n const canAccess = await this.accessControl.canAccessGroup({ rwd: \"w\" });\n if (!canAccess) {\n return Result.fail(new GroupNotAuthorizedError());\n }\n\n // Fetch original group\n const getResult = await this.getGroupUseCase.execute(groupId);\n if (getResult.isFail()) {\n return Result.fail(getResult.error);\n }\n const original = getResult.value;\n\n // Access control check on original group\n const canAccessGroup = await this.accessControl.canAccessGroup({\n group: original,\n rwd: \"w\"\n });\n if (!canAccessGroup) {\n return Result.fail(new GroupNotAuthorizedError());\n }\n\n // Validate input\n const validationResult = await createGroupUpdateValidation().safeParseAsync(input);\n if (!validationResult.success) {\n const zodError = createZodError(validationResult.error);\n return Result.fail(\n new GroupValidationError(zodError.message, zodError.data!.invalidFields)\n );\n }\n const data = validationResult.data;\n\n // Skip if no changes\n if (Object.keys(data).length === 0) {\n return Result.ok(original);\n }\n\n // Merge changes\n const tenant = this.tenantContext.getTenant();\n const group: CmsGroup = {\n ...original,\n ...data,\n tenant: tenant.id,\n savedOn: new Date().toISOString()\n };\n\n try {\n // Publish before event\n await this.eventPublisher.publish(\n new GroupBeforeUpdateEvent({\n original,\n group\n })\n );\n\n // Persist via repository\n const result = await this.repository.execute(group);\n if (result.isFail()) {\n // Publish error event\n await this.eventPublisher.publish(\n new GroupUpdateErrorEvent({\n input,\n original,\n group,\n error: result.error\n })\n );\n return Result.fail(result.error);\n }\n\n // Publish after event\n await this.eventPublisher.publish(\n new GroupAfterUpdateEvent({\n original,\n group: result.value\n })\n );\n\n return Result.ok(result.value);\n } catch (error) {\n // Publish error event for unexpected errors\n await this.eventPublisher.publish(\n new GroupUpdateErrorEvent({\n input,\n original,\n group,\n error: error as Error\n })\n );\n return Result.fail(error as UseCaseAbstraction.Error);\n }\n }\n}\n\nexport const UpdateGroupUseCase = createImplementation({\n abstraction: UseCaseAbstraction,\n implementation: UpdateGroupUseCaseImpl,\n dependencies: [\n EventPublisher,\n UpdateGroupRepository,\n GetGroupUseCase,\n AccessControl,\n TenantContext\n ]\n});\n"],"names":["UpdateGroupUseCaseImpl","eventPublisher","repository","getGroupUseCase","accessControl","tenantContext","groupId","input","canAccess","Result","GroupNotAuthorizedError","getResult","original","canAccessGroup","validationResult","createGroupUpdateValidation","zodError","createZodError","GroupValidationError","data","Object","tenant","group","Date","GroupBeforeUpdateEvent","result","GroupUpdateErrorEvent","GroupAfterUpdateEvent","error","UpdateGroupUseCase","createImplementation","UseCaseAbstraction","EventPublisher","UpdateGroupRepository","GetGroupUseCase","AccessControl","TenantContext"],"mappings":";;;;;;;;;;A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;YAEA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIC,uBAAuB;gBACvBZ;gBACAU;YACJ;YAIJ,MAAMG,SAAS,MAAM,IAAI,CAAC,UAAU,CAAC,OAAO,CAACH;YAC7C,IAAIG,OAAO,MAAM,IAAI;gBAEjB,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIC,sBAAsB;oBACtBnB;oBACAK;oBACAU;oBACA,OAAOG,OAAO,KAAK;gBACvB;gBAEJ,OAAOhB,OAAO,IAAI,CAACgB,OAAO,KAAK;YACnC;YAGA,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIE,sBAAsB;gBACtBf;gBACA,OAAOa,OAAO,KAAK;YACvB;YAGJ,OAAOhB,OAAO,EAAE,CAACgB,OAAO,KAAK;QACjC,EAAE,OAAOG,OAAO;YAEZ,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIF,sBAAsB;gBACtBnB;gBACAK;gBACAU;gBACA,OAAOM;YACX;YAEJ,OAAOnB,OAAO,IAAI,CAACmB;QACvB;IACJ;AACJ;AAEO,MAAMC,wCAAqBC,qBAAqB;IACnD,aAAaC;IACb,gBAAgB/B;IAChB,cAAc;QACVgC;QACAC;QACAC;QACAC;QACAC;KACH;AACL"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/modelBuilder/fields/TextFieldType.js","sources":["../../../../src/features/modelBuilder/fields/TextFieldType.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/feature/api\";\nimport { DataFieldBuilder } from \"./FieldBuilder.js\";\nimport { FieldType, type IFieldTypeFactory } from \"./abstractions.js\";\nimport type { FieldTypeValidator } from \"./fieldTypeValidator.js\";\n\nexport enum TextFieldSubTypes {\n COMPRESSED = \"compressed\",\n ENCRYPTED = \"encrypted\"\n}\n\nexport enum TextFieldTypes {\n TEXT = \"text\",\n COMPRESSED = \"text:compressed\",\n ENCRYPTED = \"text:encrypted\"\n}\n\nexport interface ITextFieldBuilder\n extends\n DataFieldBuilder<\"text\">,\n FieldTypeValidator.Required,\n FieldTypeValidator.MinLength,\n FieldTypeValidator.MaxLength,\n FieldTypeValidator.Pattern,\n FieldTypeValidator.Email,\n FieldTypeValidator.Url,\n FieldTypeValidator.LowerCase,\n FieldTypeValidator.UpperCase,\n FieldTypeValidator.LowerCaseSpace,\n FieldTypeValidator.UpperCaseSpace,\n FieldTypeValidator.Unique {\n compress(): this;\n encrypt(): this;\n}\n\n// Module augmentation for TypeScript autocomplete\ndeclare module \"../abstractions.js\" {\n interface IFieldBuilderRegistry {\n text(): ITextFieldBuilder;\n }\n}\n\nclass TextFieldBuilder extends DataFieldBuilder<\"text\"> implements ITextFieldBuilder {\n public constructor() {\n super(\"text\");\n }\n\n required(message?: string): this {\n return this.validation({\n name: \"required\",\n message: message || \"Value is required.\",\n settings: {}\n });\n }\n\n minLength(value: number, message?: string): this {\n return this.validation({\n name: \"minLength\",\n message: message || \"Value is too short.\",\n settings: { value: String(value) }\n });\n }\n\n maxLength(value: number, message?: string): this {\n return this.validation({\n name: \"maxLength\",\n message: message || \"Value is too long.\",\n settings: { value: String(value) }\n });\n }\n\n pattern(regex: string, flags: string = \"\", message?: string): this {\n return this.validation({\n name: \"pattern\",\n message: message || \"Invalid value.\",\n settings: {\n preset: \"custom\",\n regex,\n flags\n }\n });\n }\n\n email(message?: string): this {\n return this.validation({\n name: \"pattern\",\n message: message || \"Please enter a valid e-mail.\",\n settings: {\n preset: \"email\",\n regex: null,\n flags: null\n }\n });\n }\n\n url(message?: string): this {\n return this.validation({\n name: \"pattern\",\n message: message || \"Please enter a valid URL.\",\n settings: {\n preset: \"url\",\n regex: null,\n flags: null\n }\n });\n }\n\n lowerCase(message?: string): this {\n return this.validation({\n name: \"pattern\",\n message: message || \"Only lower case characters are allowed.\",\n settings: {\n preset: \"lowerCase\",\n regex: null,\n flags: null\n }\n });\n }\n\n upperCase(message?: string): this {\n return this.validation({\n name: \"pattern\",\n message: message || \"Only upper case characters are allowed.\",\n settings: {\n preset: \"upperCase\",\n regex: null,\n flags: null\n }\n });\n }\n\n lowerCaseSpace(message?: string): this {\n return this.validation({\n name: \"pattern\",\n message: message || \"Only lower case characters and space are allowed.\",\n settings: {\n preset: \"lowerCaseSpace\",\n regex: null,\n flags: null\n }\n });\n }\n\n upperCaseSpace(message?: string): this {\n return this.validation({\n name: \"pattern\",\n message: message || \"Only upper case characters and space are allowed.\",\n settings: {\n preset: \"upperCaseSpace\",\n regex: null,\n flags: null\n }\n });\n }\n\n unique(message?: string): this {\n return this.validation({\n name: \"unique\",\n message: message || \"Value must be unique.\",\n settings: {}\n });\n }\n\n public compress(): this {\n this.setSubType(TextFieldSubTypes.COMPRESSED);\n\n this.settings({\n disableFullTextSearch: true\n });\n\n return this;\n }\n public encrypt(): this {\n this.setSubType(TextFieldSubTypes.ENCRYPTED);\n\n this.settings({\n disableFullTextSearch: true\n });\n\n return this;\n }\n}\n\nclass TextFieldTypeFactory implements IFieldTypeFactory {\n readonly type = \"text\";\n\n create(): ITextFieldBuilder {\n return new TextFieldBuilder();\n }\n}\n\nexport const TextFieldType = createImplementation({\n abstraction: FieldType,\n implementation: TextFieldTypeFactory,\n dependencies: []\n});\n"],"names":["TextFieldSubTypes","TextFieldTypes","TextFieldBuilder","DataFieldBuilder","message","value","String","regex","flags","TextFieldTypeFactory","TextFieldType","createImplementation","FieldType"],"mappings":";;;AAKO,IAAKA,kCAAiBA,WAAAA,GAAAA,
|
|
1
|
+
{"version":3,"file":"features/modelBuilder/fields/TextFieldType.js","sources":["../../../../src/features/modelBuilder/fields/TextFieldType.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/feature/api\";\nimport { DataFieldBuilder } from \"./FieldBuilder.js\";\nimport { FieldType, type IFieldTypeFactory } from \"./abstractions.js\";\nimport type { FieldTypeValidator } from \"./fieldTypeValidator.js\";\n\nexport enum TextFieldSubTypes {\n COMPRESSED = \"compressed\",\n ENCRYPTED = \"encrypted\"\n}\n\nexport enum TextFieldTypes {\n TEXT = \"text\",\n COMPRESSED = \"text:compressed\",\n ENCRYPTED = \"text:encrypted\"\n}\n\nexport interface ITextFieldBuilder\n extends\n DataFieldBuilder<\"text\">,\n FieldTypeValidator.Required,\n FieldTypeValidator.MinLength,\n FieldTypeValidator.MaxLength,\n FieldTypeValidator.Pattern,\n FieldTypeValidator.Email,\n FieldTypeValidator.Url,\n FieldTypeValidator.LowerCase,\n FieldTypeValidator.UpperCase,\n FieldTypeValidator.LowerCaseSpace,\n FieldTypeValidator.UpperCaseSpace,\n FieldTypeValidator.Unique {\n compress(): this;\n encrypt(): this;\n}\n\n// Module augmentation for TypeScript autocomplete\ndeclare module \"../abstractions.js\" {\n interface IFieldBuilderRegistry {\n text(): ITextFieldBuilder;\n }\n}\n\nclass TextFieldBuilder extends DataFieldBuilder<\"text\"> implements ITextFieldBuilder {\n public constructor() {\n super(\"text\");\n }\n\n required(message?: string): this {\n return this.validation({\n name: \"required\",\n message: message || \"Value is required.\",\n settings: {}\n });\n }\n\n minLength(value: number, message?: string): this {\n return this.validation({\n name: \"minLength\",\n message: message || \"Value is too short.\",\n settings: { value: String(value) }\n });\n }\n\n maxLength(value: number, message?: string): this {\n return this.validation({\n name: \"maxLength\",\n message: message || \"Value is too long.\",\n settings: { value: String(value) }\n });\n }\n\n pattern(regex: string, flags: string = \"\", message?: string): this {\n return this.validation({\n name: \"pattern\",\n message: message || \"Invalid value.\",\n settings: {\n preset: \"custom\",\n regex,\n flags\n }\n });\n }\n\n email(message?: string): this {\n return this.validation({\n name: \"pattern\",\n message: message || \"Please enter a valid e-mail.\",\n settings: {\n preset: \"email\",\n regex: null,\n flags: null\n }\n });\n }\n\n url(message?: string): this {\n return this.validation({\n name: \"pattern\",\n message: message || \"Please enter a valid URL.\",\n settings: {\n preset: \"url\",\n regex: null,\n flags: null\n }\n });\n }\n\n lowerCase(message?: string): this {\n return this.validation({\n name: \"pattern\",\n message: message || \"Only lower case characters are allowed.\",\n settings: {\n preset: \"lowerCase\",\n regex: null,\n flags: null\n }\n });\n }\n\n upperCase(message?: string): this {\n return this.validation({\n name: \"pattern\",\n message: message || \"Only upper case characters are allowed.\",\n settings: {\n preset: \"upperCase\",\n regex: null,\n flags: null\n }\n });\n }\n\n lowerCaseSpace(message?: string): this {\n return this.validation({\n name: \"pattern\",\n message: message || \"Only lower case characters and space are allowed.\",\n settings: {\n preset: \"lowerCaseSpace\",\n regex: null,\n flags: null\n }\n });\n }\n\n upperCaseSpace(message?: string): this {\n return this.validation({\n name: \"pattern\",\n message: message || \"Only upper case characters and space are allowed.\",\n settings: {\n preset: \"upperCaseSpace\",\n regex: null,\n flags: null\n }\n });\n }\n\n unique(message?: string): this {\n return this.validation({\n name: \"unique\",\n message: message || \"Value must be unique.\",\n settings: {}\n });\n }\n\n public compress(): this {\n this.setSubType(TextFieldSubTypes.COMPRESSED);\n\n this.settings({\n disableFullTextSearch: true\n });\n\n return this;\n }\n public encrypt(): this {\n this.setSubType(TextFieldSubTypes.ENCRYPTED);\n\n this.settings({\n disableFullTextSearch: true\n });\n\n return this;\n }\n}\n\nclass TextFieldTypeFactory implements IFieldTypeFactory {\n readonly type = \"text\";\n\n create(): ITextFieldBuilder {\n return new TextFieldBuilder();\n }\n}\n\nexport const TextFieldType = createImplementation({\n abstraction: FieldType,\n implementation: TextFieldTypeFactory,\n dependencies: []\n});\n"],"names":["TextFieldSubTypes","TextFieldTypes","TextFieldBuilder","DataFieldBuilder","message","value","String","regex","flags","TextFieldTypeFactory","TextFieldType","createImplementation","FieldType"],"mappings":";;;AAKO,IAAKA,kCAAiBA,WAAAA,GAAAA,SAAAA,iBAAAA;;;;;AAKtB,IAAKC,+BAAcA,WAAAA,GAAAA,SAAAA,cAAAA;;;;;;AA+B1B,MAAMC,yBAAyBC;IAC3B,aAAqB;QACjB,KAAK,CAAC;IACV;IAEA,SAASC,OAAgB,EAAQ;QAC7B,OAAO,IAAI,CAAC,UAAU,CAAC;YACnB,MAAM;YACN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AC,UAAU,CAAC;YACnB,MAAM;YACN,SAASA,WAAW;YACpB,UAAU;gBACN,QAAQ;gBACR,OAAO;gBACP,OAAO;YACX;QACJ;IACJ;IAEA,eAAeA,OAAgB,EAAQ;QACnC,OAAO,IAAI,CAAC,UAAU,CAAC;YACnB,MAAM;YACN,SAASA,WAAW;YACpB,UAAU;gBACN,QAAQ;gBACR,OAAO;gBACP,OAAO;YACX;QACJ;IACJ;IAEA,OAAOA,OAAgB,EAAQ;QAC3B,OAAO,IAAI,CAAC,UAAU,CAAC;YACnB,MAAM;YACN,SAASA,WAAW;YACpB,UAAU,CAAC;QACf;IACJ;IAEO,WAAiB;QACpB,IAAI,CAAC,UAAU,CAAC;QAEhB,IAAI,CAAC,QAAQ,CAAC;YACV,uBAAuB;QAC3B;QAEA,OAAO,IAAI;IACf;IACO,UAAgB;QACnB,IAAI,CAAC,UAAU,CAAC;QAEhB,IAAI,CAAC,QAAQ,CAAC;YACV,uBAAuB;QAC3B;QAEA,OAAO,IAAI;IACf;AACJ;AAEA,MAAMK;IAGF,SAA4B;QACxB,OAAO,IAAIP;IACf;;aAJS,IAAI,GAAG;;AAKpB;AAEO,MAAMQ,gBAAgBC,qBAAqB;IAC9C,aAAaC;IACb,gBAAgBH;IAChB,cAAc,EAAE;AACpB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { buildSchemaPlugins } from "./buildSchemaPlugins.js";
|
|
2
2
|
import { createExecutableSchema } from "./createExecutableSchema.js";
|
|
3
3
|
import { CmsGraphQLSchemaPlugin } from "../plugins/index.js";
|
|
4
|
+
const generatedPlugins = new WeakSet();
|
|
4
5
|
const generateSchema = async (params)=>{
|
|
5
6
|
const { context, models } = params;
|
|
6
7
|
let generatedSchemaPlugins = [];
|
|
@@ -13,8 +14,11 @@ const generateSchema = async (params)=>{
|
|
|
13
14
|
console.log("Error while building schema plugins.");
|
|
14
15
|
throw ex;
|
|
15
16
|
}
|
|
17
|
+
for (const plugin of generatedSchemaPlugins)generatedPlugins.add(plugin);
|
|
16
18
|
context.plugins.register(generatedSchemaPlugins);
|
|
19
|
+
const currentlyGenerated = new Set(generatedSchemaPlugins);
|
|
17
20
|
const schemaPlugins = context.plugins.byType(CmsGraphQLSchemaPlugin.type).filter((pl)=>{
|
|
21
|
+
if (generatedPlugins.has(pl) && !currentlyGenerated.has(pl)) return false;
|
|
18
22
|
if ("function" == typeof pl.isApplicable) return pl.isApplicable(context);
|
|
19
23
|
return true;
|
|
20
24
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graphql/generateSchema.js","sources":["../../src/graphql/generateSchema.ts"],"sourcesContent":["import type { CmsContext, CmsModel } from \"~/types/index.js\";\nimport { buildSchemaPlugins } from \"./buildSchemaPlugins.js\";\nimport { createExecutableSchema } from \"./createExecutableSchema.js\";\nimport type { GraphQLSchema } from \"graphql/type/index.js\";\nimport type { ICmsGraphQLSchemaPlugin } from \"~/plugins/index.js\";\nimport { CmsGraphQLSchemaPlugin } from \"~/plugins/index.js\";\n\ninterface GenerateSchemaParams {\n context: CmsContext;\n models: CmsModel[];\n}\nexport const generateSchema = async (params: GenerateSchemaParams): Promise<GraphQLSchema> => {\n const { context, models } = params;\n\n let generatedSchemaPlugins: ICmsGraphQLSchemaPlugin[] = [];\n try {\n generatedSchemaPlugins = await buildSchemaPlugins({ context, models });\n } catch (ex) {\n console.log(`Error while building schema plugins.`);\n throw ex;\n }\n\n context.plugins.register(generatedSchemaPlugins);\n\n const schemaPlugins = context.plugins\n .byType<ICmsGraphQLSchemaPlugin>(CmsGraphQLSchemaPlugin.type)\n .filter(pl => {\n if (typeof pl.isApplicable === \"function\") {\n return pl.isApplicable(context);\n }\n return true;\n });\n\n return createExecutableSchema({\n plugins: schemaPlugins\n });\n};\n"],"names":["generateSchema","params","context","models","generatedSchemaPlugins","buildSchemaPlugins","ex","console","schemaPlugins","CmsGraphQLSchemaPlugin","pl","createExecutableSchema"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"graphql/generateSchema.js","sources":["../../src/graphql/generateSchema.ts"],"sourcesContent":["import type { CmsContext, CmsModel } from \"~/types/index.js\";\nimport { buildSchemaPlugins } from \"./buildSchemaPlugins.js\";\nimport { createExecutableSchema } from \"./createExecutableSchema.js\";\nimport type { GraphQLSchema } from \"graphql/type/index.js\";\nimport type { ICmsGraphQLSchemaPlugin } from \"~/plugins/index.js\";\nimport { CmsGraphQLSchemaPlugin } from \"~/plugins/index.js\";\n\n/**\n * Plugins generated for a specific endpoint (their SDL depends on `context.cms.READ/PREVIEW/MANAGE`\n * at generation time). They are registered into `context.plugins`, so we must remember them to\n * exclude them when a schema for another endpoint is generated within the same request.\n */\nconst generatedPlugins = new WeakSet<ICmsGraphQLSchemaPlugin>();\n\ninterface GenerateSchemaParams {\n context: CmsContext;\n models: CmsModel[];\n}\nexport const generateSchema = async (params: GenerateSchemaParams): Promise<GraphQLSchema> => {\n const { context, models } = params;\n\n let generatedSchemaPlugins: ICmsGraphQLSchemaPlugin[] = [];\n try {\n generatedSchemaPlugins = await buildSchemaPlugins({ context, models });\n } catch (ex) {\n console.log(`Error while building schema plugins.`);\n throw ex;\n }\n\n for (const plugin of generatedSchemaPlugins) {\n generatedPlugins.add(plugin);\n }\n context.plugins.register(generatedSchemaPlugins);\n\n const currentlyGenerated = new Set(generatedSchemaPlugins);\n\n const schemaPlugins = context.plugins\n .byType<ICmsGraphQLSchemaPlugin>(CmsGraphQLSchemaPlugin.type)\n .filter(pl => {\n // Security: skip plugins generated earlier in this request for another endpoint\n // (e.g. manage-only mutations when generating the read schema).\n if (generatedPlugins.has(pl) && !currentlyGenerated.has(pl)) {\n return false;\n }\n if (typeof pl.isApplicable === \"function\") {\n return pl.isApplicable(context);\n }\n return true;\n });\n\n return createExecutableSchema({\n plugins: schemaPlugins\n });\n};\n"],"names":["generatedPlugins","WeakSet","generateSchema","params","context","models","generatedSchemaPlugins","buildSchemaPlugins","ex","console","plugin","currentlyGenerated","Set","schemaPlugins","CmsGraphQLSchemaPlugin","pl","createExecutableSchema"],"mappings":";;;AAYA,MAAMA,mBAAmB,IAAIC;AAMtB,MAAMC,iBAAiB,OAAOC;IACjC,MAAM,EAAEC,OAAO,EAAEC,MAAM,EAAE,GAAGF;IAE5B,IAAIG,yBAAoD,EAAE;IAC1D,IAAI;QACAA,yBAAyB,MAAMC,mBAAmB;YAAEH;YAASC;QAAO;IACxE,EAAE,OAAOG,IAAI;QACTC,QAAQ,GAAG,CAAC;QACZ,MAAMD;IACV;IAEA,KAAK,MAAME,UAAUJ,uBACjBN,iBAAiB,GAAG,CAACU;IAEzBN,QAAQ,OAAO,CAAC,QAAQ,CAACE;IAEzB,MAAMK,qBAAqB,IAAIC,IAAIN;IAEnC,MAAMO,gBAAgBT,QAAQ,OAAO,CAChC,MAAM,CAA0BU,uBAAuB,IAAI,EAC3D,MAAM,CAACC,CAAAA;QAGJ,IAAIf,iBAAiB,GAAG,CAACe,OAAO,CAACJ,mBAAmB,GAAG,CAACI,KACpD,OAAO;QAEX,IAAI,AAA2B,cAA3B,OAAOA,GAAG,YAAY,EACtB,OAAOA,GAAG,YAAY,CAACX;QAE3B,OAAO;IACX;IAEJ,OAAOY,uBAAuB;QAC1B,SAASH;IACb;AACJ"}
|
|
@@ -1,10 +1,24 @@
|
|
|
1
|
+
import { NotAuthorizedError } from "../../../utils/errors.js";
|
|
1
2
|
import { getErrorMessage, getModel } from "./helpers.js";
|
|
2
3
|
import { ComponentMapGenerator } from "../../../features/contentModel/ComponentMapGenerator/abstractions.js";
|
|
3
4
|
import { ValuesSelectionGenerator } from "../../../features/contentModel/ValuesSelectionGenerator/abstractions.js";
|
|
4
5
|
import { RefModelsGenerator } from "../../../features/contentModel/RefModelsGenerator/abstractions.js";
|
|
6
|
+
const ENDPOINTS = [
|
|
7
|
+
"read",
|
|
8
|
+
"preview",
|
|
9
|
+
"manage"
|
|
10
|
+
];
|
|
11
|
+
const ensureCanAccessAnyEndpoint = async (context)=>{
|
|
12
|
+
for (const endpoint of ENDPOINTS){
|
|
13
|
+
const permission = await context.security.getPermission(`cms.endpoint.${endpoint}`);
|
|
14
|
+
if (permission) return;
|
|
15
|
+
}
|
|
16
|
+
throw new NotAuthorizedError("Not allowed to access CMS endpoints.");
|
|
17
|
+
};
|
|
5
18
|
const createGetModelResolver = ()=>async ({ args, context })=>{
|
|
6
19
|
const { modelId } = args;
|
|
7
20
|
try {
|
|
21
|
+
await ensureCanAccessAnyEndpoint(context);
|
|
8
22
|
const model = await getModel(context, modelId);
|
|
9
23
|
const componentMapGenerator = context.container.resolve(ComponentMapGenerator);
|
|
10
24
|
const valuesSelectionGenerator = context.container.resolve(ValuesSelectionGenerator);
|