@phtngyn/cms 0.2.0-beta.2 → 0.2.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +2 -0
  2. package/package.json +6 -6
  3. package/src/Content.js +41 -18
  4. package/src/Content.js.map +1 -1
  5. package/src/{S3MediaObjects-D5Ns4FM6.js → S3MediaObjects-CR3p1WTg.js} +8 -2
  6. package/src/S3MediaObjects-CR3p1WTg.js.map +1 -0
  7. package/src/cli.js +2 -2
  8. package/src/connection-D5S9Iph-.js.map +1 -1
  9. package/src/{dev-lifecycle-CZ7iCzG9.js → dev-lifecycle-D3f9-upa.js} +2 -2
  10. package/src/dev-lifecycle-D3f9-upa.js.map +1 -0
  11. package/src/{installation-BNuoRDOz.js → installation-fZtNxtoW.js} +27 -12
  12. package/src/installation-fZtNxtoW.js.map +1 -0
  13. package/src/internal/configuration.js +1 -1
  14. package/src/internal/dev-lifecycle.js +1 -1
  15. package/src/internal/studio-app.js +8 -6
  16. package/src/internal/studio-app.js.map +1 -1
  17. package/src/runtime/delivery/document-page.js +1 -5
  18. package/src/runtime/delivery/document-page.js.map +1 -1
  19. package/src/runtime/delivery/plugin.js +34 -5
  20. package/src/runtime/delivery/plugin.js.map +1 -1
  21. package/src/runtime/delivery/useCmsDocumentSeo.d.ts +1 -0
  22. package/src/runtime/delivery/useCmsDocumentSeo.js +5 -4
  23. package/src/runtime/delivery/useCmsDocumentSeo.js.map +1 -1
  24. package/src/runtime/forms/useCmsForm.js +53 -30
  25. package/src/runtime/forms/useCmsForm.js.map +1 -1
  26. package/src/runtime/i18n/useCmsI18n.js.map +1 -1
  27. package/src/runtime/installation.js +1 -1
  28. package/src/runtime/plugin.js +1 -1
  29. package/src/runtime/preview/plugin.client.js +1 -1
  30. package/src/runtime/preview/plugin.client.js.map +1 -1
  31. package/src/runtime/preview/store.js +1 -1
  32. package/src/{store-B49J21NA.js → store-CCsjHaZm.js} +6 -6
  33. package/src/store-CCsjHaZm.js.map +1 -0
  34. package/studio/host.js +2562 -2556
  35. package/src/S3MediaObjects-D5Ns4FM6.js.map +0 -1
  36. package/src/dev-lifecycle-CZ7iCzG9.js.map +0 -1
  37. package/src/installation-BNuoRDOz.js.map +0 -1
  38. package/src/store-B49J21NA.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"S3MediaObjects-CR3p1WTg.js","names":["InternalError","Forbidden","invalid","CmsMarkdownDocumentSchema","SourcePathSchema","nestedValue","DocumentValidationResultSchema","DocumentSummarySchema","DeletedDocumentSchema","renderDocumentMarkdown","DocumentMutationResultSchema","MediaReferenceSchema","ContentPlanSchema","DocumentStateModule.makeDocumentState","DocumentMutationResultSchema","DocumentHistoryCursorSchema","DocumentHistoryInvalidCursorError","EffectRuntime","DocumentRevisionPageSchema","DocumentRevisionComparisonSchema","DocumentHistoryComparisonTooLargeError","EffectRuntime","PublishedDocumentNotFoundError","DocumentSurroundSchema","PublishedDocumentPageSchema","DocumentNavigationItemSchema","DocumentMediaUnavailableError","DocumentIdSchema","DocumentNotFoundError","ContentSnapshotSchema","ContentApplyResultSchema","requestActivity","ActivityContextSchema","SeoCapabilitiesSchema","GlobalSeoSettingsSchema","SeoMutationResultSchema","SeoConfirmationRequiredError","SeoSnapshotSchema","CompiledDocumentSchema","SitemapEntrySchema","SeoStateSchema"],"sources":["../../../../protocol/src/internal/documents/errors.ts","../../../../protocol/src/Activity.ts","../../../../protocol/src/internal/documents/history.ts","../../../../protocol/src/Collaboration.ts","../../../../protocol/src/Users.ts","../../../../protocol/src/Initialization.ts","../../../../protocol/src/internal/http/failures.ts","../../../../protocol/src/internal/http/delivery.ts","../../../../protocol/src/StudioHttp.ts","../../../../document/src/Seo.ts","../../../../server/src/internal/access-control.ts","../../../../document/src/internal/editor/render.ts","../../../../document/src/internal/document-engine/relocate-links.ts","../../../../document/src/DocumentPlanning.ts","../../../../server/src/internal/documents/document-state.ts","../../../../server/src/internal/documents/document-tree-mutation.ts","../../../../server/src/internal/documents/document-lifecycle.ts","../../../../server/src/internal/documents/document-media-references.ts","../../../../server/src/internal/documents/content-transfer.ts","../../../../server/src/internal/documents/document-mutation.ts","../../../../server/src/internal/documents/document-store.ts","../../../../server/src/internal/documents/document-failures.ts","../../../../server/src/internal/cursor.ts","../../../../server/src/internal/documents/document-history.ts","../../../../server/src/internal/documents/document-delivery.ts","../../../../server/src/internal/documents/documents.ts","../../../../server/src/internal/seo/seo-store.ts","../../../../server/src/internal/seo/seo.ts","../../../../server/src/internal/media/media-object-store.ts","../../../../server/src/internal/media/media-failures.ts","../../../../s3/src/internal/client.ts","../../../../s3/src/internal/media-object-store.ts","../../../../s3/src/S3MediaObjects.ts"],"sourcesContent":["import { Schema } from 'effect'\nimport { DocumentIssue, PublishedDocumentLookup } from './models'\nimport { DocumentId, DocumentVersion, RevisionId, SourcePath } from './scalars'\nimport { MediaObjectKey } from '../../Media'\n\nexport class DocumentNotFound extends Schema.TaggedError<DocumentNotFound>()('Document.NotFound', {\n documentId: DocumentId,\n revisionId: Schema.optionalKey(RevisionId),\n}) {}\n\nexport class DocumentPathConflict extends Schema.TaggedError<DocumentPathConflict>()('Document.PathConflict', {\n sourcePath: SourcePath,\n}) {}\n\nexport class DocumentVersionConflict extends Schema.TaggedError<DocumentVersionConflict>()('Document.VersionConflict', {\n documentId: DocumentId,\n expectedVersion: DocumentVersion,\n actualVersion: DocumentVersion,\n}) {}\n\nexport class DocumentMediaUnavailable extends Schema.TaggedError<DocumentMediaUnavailable>()(\n 'Document.MediaUnavailable',\n {\n documentId: DocumentId,\n mediaKeys: Schema.Array(MediaObjectKey).check(Schema.isMinLength(1)),\n },\n) {}\n\nexport class DocumentValidationFailed extends Schema.TaggedError<DocumentValidationFailed>()(\n 'Document.ValidationFailed',\n {\n issues: Schema.Array(DocumentIssue),\n },\n) {}\n\nexport class PublishedDocumentNotFound extends Schema.TaggedError<PublishedDocumentNotFound>()(\n 'PublishedDocument.NotFound',\n { lookup: PublishedDocumentLookup },\n) {}\n","/**\n * Immutable completed Activity facts. Pages are ordered newest-first; cursors are opaque,\n * stable continuation tokens and an invalid cursor is a caller-visible failure.\n */\nimport { Schema } from 'effect'\nimport { StudioActor } from './AccessControl'\nimport { DocumentId } from './internal/documents/scalars'\nimport { nonNegativeInt } from './internal/scalars'\nimport { RequestId } from './Identity'\nimport { MediaId } from './Media'\n\nexport const ActivityId = Schema.String.check(Schema.isUUID()).pipe(Schema.brand('ActivityId'))\n\nexport type ActivityId = typeof ActivityId.Type\n\nexport const ActivityCursor = Schema.NonEmptyString.pipe(Schema.brand('ActivityCursor'))\n\nexport type ActivityCursor = typeof ActivityCursor.Type\n\nexport const ACTIVITY_ACTIONS = [\n 'document.created',\n 'document.updated',\n 'document.moved',\n 'document.trashed',\n 'document.revision.restored',\n 'document.untrashed',\n 'document.published',\n 'document.unpublished',\n 'media.uploaded',\n 'media.replaced',\n 'media.removed',\n 'media.cleaned',\n 'seo.saved',\n 'seo.published',\n 'user.created',\n 'user.removed',\n 'user.role.changed',\n 'user.sessions.revoked',\n 'authentication.signed-in',\n 'authentication.signed-out',\n 'authentication.password.changed',\n 'authentication.password.reset',\n] as const\n\nexport const ActivityAction = Schema.Literals(ACTIVITY_ACTIONS)\n\nexport type ActivityAction = typeof ActivityAction.Type\n\nconst DocumentActivityTarget = Schema.Struct({\n kind: Schema.tag('document'),\n documentId: DocumentId,\n})\n\nconst MediaActivityTarget = Schema.Struct({\n kind: Schema.tag('media'),\n mediaId: MediaId,\n})\n\nconst MediaLibraryActivityTarget = Schema.Struct({ kind: Schema.tag('media-library') })\n\nexport const ActivityTarget = Schema.Union([\n DocumentActivityTarget,\n MediaActivityTarget,\n MediaLibraryActivityTarget,\n Schema.Struct({ kind: Schema.tag('seo') }),\n Schema.Struct({ kind: Schema.tag('user'), userId: Schema.NonEmptyString }),\n]).pipe(Schema.toTaggedUnion('kind'))\n\nexport type ActivityTarget = typeof ActivityTarget.Type\n\nexport const ActivityTargetKind = Schema.Literals(['document', 'media', 'media-library', 'seo', 'user'])\n\nexport type ActivityTargetKind = typeof ActivityTargetKind.Type\n\nexport const ActivityContext = Schema.Struct({\n actor: StudioActor,\n requestId: RequestId,\n reason: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(1_000))),\n}).annotate({ identifier: 'ActivityContext' })\n\nexport interface ActivityContext extends Schema.Schema.Type<typeof ActivityContext> {}\n\nexport const ActivityEntry = Schema.Struct({\n id: ActivityId,\n action: ActivityAction,\n actor: StudioActor,\n requestId: RequestId,\n reason: ActivityContext.fields.reason,\n target: ActivityTarget,\n details: Schema.JsonObject,\n occurredAt: Schema.DateTimeUtcFromString,\n}).annotate({ identifier: 'ActivityEntry' })\n\nexport interface ActivityEntry extends Schema.Schema.Type<typeof ActivityEntry> {}\n\nexport const ActivityEntryDraft = Schema.Struct({\n action: ActivityAction,\n context: ActivityContext,\n target: ActivityTarget,\n details: Schema.JsonObject,\n}).annotate({ identifier: 'ActivityEntryDraft' })\n\nexport interface ActivityEntryDraft extends Schema.Schema.Type<typeof ActivityEntryDraft> {}\n\nexport const ActivityQuery = Schema.Struct({\n action: Schema.optionalKey(ActivityAction),\n actorId: Schema.optionalKey(StudioActor.fields.id),\n cursor: Schema.optionalKey(ActivityCursor),\n limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))),\n requestId: Schema.optionalKey(RequestId),\n targetId: Schema.optionalKey(Schema.NonEmptyString),\n targetKind: Schema.optionalKey(ActivityTargetKind),\n}).annotate({ identifier: 'ActivityQuery' })\n\nexport interface ActivityQuery extends Schema.Schema.Type<typeof ActivityQuery> {}\n\nexport const ActivityPage = Schema.Struct({\n entries: Schema.Array(ActivityEntry),\n nextCursor: Schema.optionalKey(ActivityCursor),\n total: nonNegativeInt,\n}).annotate({ identifier: 'ActivityPage' })\n\nexport interface ActivityPage extends Schema.Schema.Type<typeof ActivityPage> {}\n\nexport class ActivityCursorInvalid extends Schema.TaggedError<ActivityCursorInvalid>()('Activity.CursorInvalid', {}) {}\n","import { Schema } from 'effect'\nimport { ActivityEntry } from '../../Activity'\nimport { nonNegativeInt } from '../scalars'\nimport { DocumentRevisionAction } from './models'\nimport { DocumentHistoryCursor, DocumentVersion, DocumentId, RevisionId, SourcePath } from './scalars'\n\nexport const DocumentRevisionSummary = Schema.Struct({\n action: DocumentRevisionAction,\n activity: ActivityEntry,\n createdAt: Schema.DateTimeUtcFromString,\n documentId: DocumentId,\n revisionId: RevisionId,\n sourcePath: SourcePath,\n version: DocumentVersion,\n}).annotate({\n identifier: 'DocumentRevisionSummary',\n})\n\nexport interface DocumentRevisionSummary extends Schema.Schema.Type<typeof DocumentRevisionSummary> {}\n\nexport const DocumentRevision = Schema.Struct({\n ...DocumentRevisionSummary.fields,\n markdown: Schema.String,\n}).annotate({ identifier: 'DocumentRevision' })\n\nexport interface DocumentRevision extends Schema.Schema.Type<typeof DocumentRevision> {}\n\nexport const DocumentHistoryQuery = Schema.Struct({\n documentId: DocumentId,\n cursor: Schema.optionalKey(DocumentHistoryCursor),\n limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))),\n}).annotate({ identifier: 'DocumentHistoryQuery' })\n\nexport interface DocumentHistoryQuery extends Schema.Schema.Type<typeof DocumentHistoryQuery> {}\n\nexport const DocumentRevisionPage = Schema.Struct({\n revisions: Schema.Array(DocumentRevisionSummary),\n nextCursor: Schema.optionalKey(DocumentHistoryCursor),\n total: nonNegativeInt,\n}).annotate({ identifier: 'DocumentRevisionPage' })\n\nexport interface DocumentRevisionPage extends Schema.Schema.Type<typeof DocumentRevisionPage> {}\n\nconst LineNumber = Schema.Int.check(Schema.isGreaterThan(0))\n\nexport const DocumentRevisionChange = Schema.Union([\n Schema.Struct({ kind: Schema.tag('equal'), beforeLine: LineNumber, afterLine: LineNumber, line: Schema.String }),\n Schema.Struct({ kind: Schema.tag('added'), afterLine: LineNumber, line: Schema.String }),\n Schema.Struct({ kind: Schema.tag('removed'), beforeLine: LineNumber, line: Schema.String }),\n]).pipe(Schema.toTaggedUnion('kind'))\n\nexport type DocumentRevisionChange = typeof DocumentRevisionChange.Type\n\nexport const CompareDocumentRevisionsInput = Schema.Struct({\n documentId: DocumentId,\n fromRevisionId: RevisionId,\n toRevisionId: RevisionId,\n}).annotate({ identifier: 'CompareDocumentRevisionsInput' })\n\nexport interface CompareDocumentRevisionsInput extends Schema.Schema.Type<typeof CompareDocumentRevisionsInput> {}\n\nexport const DocumentRevisionComparison = Schema.Struct({\n from: DocumentRevision,\n to: DocumentRevision,\n changes: Schema.Array(DocumentRevisionChange),\n}).annotate({ identifier: 'DocumentRevisionComparison' })\n\nexport interface DocumentRevisionComparison extends Schema.Schema.Type<typeof DocumentRevisionComparison> {}\n\nexport class DocumentHistoryInvalidCursor extends Schema.TaggedError<DocumentHistoryInvalidCursor>()(\n 'DocumentHistory.InvalidCursor',\n {},\n) {}\n\nexport class DocumentHistoryComparisonTooLarge extends Schema.TaggedError<DocumentHistoryComparisonTooLarge>()(\n 'DocumentHistory.ComparisonTooLarge',\n {\n maximumEditLength: Schema.Int.check(Schema.isGreaterThan(0)),\n maximumLines: Schema.Int.check(Schema.isGreaterThan(0)),\n },\n) {}\n","/**\n * Collaboration handshake and WebSocket envelopes. Command results correlate by RequestId;\n * checkpoints carry the durable state vector needed for retry and recovery.\n */\nimport { DocumentMutationResult, DocumentSource, DocumentValidationResult, CmsMarkdownDocument } from './Documents'\nimport { RequestId } from './Identity'\nimport { Schema } from 'effect'\n\nexport const StateVector = Schema.String.check(Schema.isBase64()).pipe(Schema.brand('StateVector'))\n\nexport type StateVector = typeof StateVector.Type\n\nconst HttpErrorStatus = Schema.Int.check(Schema.isBetween({ minimum: 400, maximum: 599 }))\n\nexport const CollaborationUser = Schema.Struct({\n color: Schema.NonEmptyString,\n id: Schema.NonEmptyString,\n name: Schema.NonEmptyString,\n})\n\nexport interface CollaborationUser extends Schema.Schema.Type<typeof CollaborationUser> {}\n\nexport const CollaborationTicket = Schema.Struct({\n authoringRevision: Schema.NonEmptyString,\n authoredStateVector: StateVector,\n documentName: Schema.NonEmptyString,\n source: DocumentSource,\n token: Schema.NonEmptyString,\n url: Schema.NonEmptyString,\n user: CollaborationUser,\n workingStateVector: StateVector,\n}).annotate({ identifier: 'CollaborationTicket' })\n\nexport interface CollaborationTicket extends Schema.Schema.Type<typeof CollaborationTicket> {}\n\nexport const CollaborationPreview = DocumentValidationResult.pipe(\n Schema.fieldsAssign({\n markdown: Schema.String,\n preview: Schema.Struct({\n body: CmsMarkdownDocument,\n fallbacks: Schema.Record(Schema.String, Schema.String),\n }),\n }),\n).annotate({ identifier: 'CollaborationPreview' })\n\nexport interface CollaborationPreview extends Schema.Schema.Type<typeof CollaborationPreview> {}\n\nconst CheckpointMessage = Schema.Struct({\n type: Schema.tag('checkpoint'),\n})\n\nconst PreviewMessage = Schema.Struct({\n type: Schema.tag('preview'),\n requestId: RequestId,\n})\n\nconst PublishMessage = Schema.Struct({\n type: Schema.tag('publish'),\n requestId: RequestId,\n})\n\nexport const CollaborationClientMessage = Schema.Union([CheckpointMessage, PreviewMessage, PublishMessage]).pipe(\n Schema.toTaggedUnion('type'),\n)\n\nexport type CollaborationClientMessage = typeof CollaborationClientMessage.Type\n\nconst requestFailure = {\n error: Schema.NonEmptyString,\n statusCode: HttpErrorStatus,\n}\n\nconst RequestFailure = Schema.Struct({\n status: Schema.tag('failure'),\n ...requestFailure,\n})\n\nconst PreviewOutcome = Schema.Union([\n Schema.Struct({\n status: Schema.tag('success'),\n result: CollaborationPreview,\n }),\n RequestFailure,\n]).pipe(Schema.toTaggedUnion('status'))\n\nconst PublishCheckpoint = Schema.Struct({\n authoredStateVector: StateVector,\n result: Schema.optionalKey(DocumentMutationResult),\n})\n\nconst PublishOutcome = Schema.Union([\n Schema.Struct({\n status: Schema.tag('success'),\n authoredStateVector: StateVector,\n result: DocumentMutationResult,\n }),\n Schema.Struct({\n status: Schema.tag('failure'),\n ...requestFailure,\n checkpoint: Schema.optionalKey(PublishCheckpoint),\n }),\n]).pipe(Schema.toTaggedUnion('status'))\n\nconst WorkingSavedMessage = Schema.Struct({\n type: Schema.tag('working-saved'),\n workingStateVector: StateVector,\n})\n\nconst WorkingSaveErrorMessage = Schema.Struct({\n type: Schema.tag('working-save-error'),\n error: Schema.NonEmptyString,\n})\n\nconst PreviewResultMessage = Schema.Struct({\n type: Schema.tag('preview-result'),\n requestId: RequestId,\n outcome: PreviewOutcome,\n})\n\nconst PublishResultMessage = Schema.Struct({\n type: Schema.tag('publish-result'),\n requestId: RequestId,\n outcome: PublishOutcome,\n})\n\nexport const CollaborationServerMessage = Schema.Union([\n WorkingSavedMessage,\n WorkingSaveErrorMessage,\n PreviewResultMessage,\n PublishResultMessage,\n]).pipe(Schema.toTaggedUnion('type'))\n\nexport type CollaborationServerMessage = typeof CollaborationServerMessage.Type\n","/**\n * User administration inputs, offset-paginated directory results, and caller-visible command\n * failures. Commands carry no idempotency key; clients resolve ambiguous outcomes by listing again.\n */\nimport { Schema } from 'effect'\nimport { Role } from './AccessControl'\nimport { nonNegativeInt } from './internal/scalars'\n\nexport const UserEmail = Schema.NonEmptyString.check(\n Schema.isMaxLength(320),\n Schema.isPattern(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/u),\n).annotate({ identifier: 'UserEmail' })\n\nexport type UserEmail = typeof UserEmail.Type\n\nexport const UserName = Schema.NonEmptyString.check(Schema.isMaxLength(200)).annotate({\n identifier: 'UserName',\n})\n\nexport type UserName = typeof UserName.Type\n\nexport const UserPassword = Schema.NonEmptyString.check(Schema.isMinLength(8), Schema.isMaxLength(200)).annotate({\n identifier: 'UserPassword',\n})\n\nexport type UserPassword = typeof UserPassword.Type\n\nexport const User = Schema.Struct({\n id: Schema.NonEmptyString,\n email: UserEmail,\n name: UserName,\n role: Role,\n emailVerified: Schema.Boolean,\n banned: Schema.Boolean,\n createdAt: Schema.DateTimeUtcFromString,\n updatedAt: Schema.DateTimeUtcFromString,\n}).annotate({ identifier: 'User' })\n\nexport interface User extends Schema.Schema.Type<typeof User> {}\n\nexport const UserPage = Schema.Struct({\n users: Schema.Array(User),\n total: nonNegativeInt,\n}).annotate({ identifier: 'UserPage' })\n\nexport interface UserPage extends Schema.Schema.Type<typeof UserPage> {}\n\nexport const UserQuery = Schema.Struct({\n limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))),\n offset: Schema.optionalKey(nonNegativeInt),\n search: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(200))),\n}).annotate({ identifier: 'UserQuery' })\n\nexport interface UserQuery extends Schema.Schema.Type<typeof UserQuery> {}\n\nexport const CreateUserInput = Schema.Struct({\n email: UserEmail,\n name: UserName,\n password: UserPassword,\n role: Role,\n}).annotate({ identifier: 'CreateUserInput' })\n\nexport interface CreateUserInput extends Schema.Schema.Type<typeof CreateUserInput> {}\n\nexport class UserAlreadyExists extends Schema.TaggedError<UserAlreadyExists>()('User.AlreadyExists', {\n email: UserEmail,\n}) {}\n\nexport class UserNotFound extends Schema.TaggedError<UserNotFound>()('User.NotFound', {\n userId: User.fields.id,\n}) {}\n\nexport class UserSelfRemovalDenied extends Schema.TaggedError<UserSelfRemovalDenied>()('User.SelfRemovalDenied', {\n userId: User.fields.id,\n}) {}\n\nexport class UserSelfRoleChangeDenied extends Schema.TaggedError<UserSelfRoleChangeDenied>()(\n 'User.SelfRoleChangeDenied',\n { userId: User.fields.id },\n) {}\n\nexport class UserAdministrationDenied extends Schema.TaggedError<UserAdministrationDenied>()(\n 'UserAdministration.Denied',\n {},\n) {}\n","import { Schema } from 'effect'\nimport { UserEmail, UserName, UserPassword } from './Users'\n\nexport const InitializationInput = Schema.Struct({\n email: UserEmail,\n initializationToken: Schema.NonEmptyString.check(Schema.isMaxLength(512)),\n name: UserName,\n password: UserPassword,\n}).annotate({ identifier: 'InitializationInput' })\n\nexport interface InitializationInput extends Schema.Schema.Type<typeof InitializationInput> {}\n\nexport const InitializationState = Schema.Struct({\n needsAdministrator: Schema.Boolean,\n}).annotate({ identifier: 'InitializationState' })\n\nexport interface InitializationState extends Schema.Schema.Type<typeof InitializationState> {}\n\nexport class InitializationAlreadyCompleted extends Schema.TaggedError<InitializationAlreadyCompleted>()(\n 'Initialization.AlreadyCompleted',\n {},\n) {}\n\nexport class InitializationProofInvalid extends Schema.TaggedError<InitializationProofInvalid>()(\n 'Initialization.ProofInvalid',\n {},\n) {}\n","import { Schema } from 'effect'\n\nexport class StudioInternalError extends Schema.TaggedError<StudioInternalError>()('Studio.InternalError', {\n message: Schema.Literal('The request could not be completed.'),\n}) {}\n\nexport function studioInternalError(): StudioInternalError {\n return new StudioInternalError({ message: 'The request could not be completed.' })\n}\n","import {\n CompiledDocument,\n DocumentNavigationItem,\n DocumentNavigationQuery,\n DocumentSurround,\n PublishedDocumentLookup,\n PublishedDocumentNotFound,\n PublishedDocumentPage,\n PublishedDocumentQuery,\n PublishedDocumentSurroundQuery,\n} from '../../Documents'\nimport { AccessDenied } from '../../AccessControl'\nimport { Schema } from 'effect'\nimport { HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from 'effect/unstable/httpapi'\nimport { StudioInternalError } from './failures'\nimport { SeoSnapshot, SitemapEntry } from '../../Seo'\n\nconst DeliverySurroundPayload = Schema.Struct({\n lookup: PublishedDocumentLookup,\n query: PublishedDocumentSurroundQuery,\n}).annotate({ identifier: 'DeliverySurroundPayload' })\n\nconst InternalError = StudioInternalError.pipe(HttpApiSchema.status(500))\n\nconst PublishedNotFound = PublishedDocumentNotFound.pipe(HttpApiSchema.status(404))\n\nconst Forbidden = AccessDenied.pipe(HttpApiSchema.status(403))\n\nexport const PublishedDeliveryApi = HttpApiGroup.make('delivery')\n .add(\n HttpApiEndpoint.post('read', '/read', {\n payload: PublishedDocumentLookup,\n success: CompiledDocument,\n error: [PublishedNotFound, InternalError],\n }),\n HttpApiEndpoint.post('query', '/query', {\n payload: PublishedDocumentQuery,\n success: PublishedDocumentPage,\n error: InternalError,\n }),\n HttpApiEndpoint.post('navigation', '/navigation', {\n payload: DocumentNavigationQuery,\n success: Schema.Array(DocumentNavigationItem),\n error: InternalError,\n }),\n HttpApiEndpoint.post('surround', '/surround', {\n payload: DeliverySurroundPayload,\n success: DocumentSurround,\n error: [PublishedNotFound, InternalError],\n }),\n HttpApiEndpoint.get('seo', '/seo', {\n success: SeoSnapshot,\n error: InternalError,\n }),\n HttpApiEndpoint.get('sitemap', '/sitemap', {\n success: Schema.Array(SitemapEntry),\n error: InternalError,\n }),\n )\n .prefix('/delivery')\n\nexport const PreviewDeliveryApi = HttpApiGroup.make('previewDelivery')\n .add(\n HttpApiEndpoint.post('read', '/read', {\n payload: PublishedDocumentLookup,\n success: CompiledDocument,\n error: [PublishedNotFound, InternalError, Forbidden],\n }),\n HttpApiEndpoint.post('query', '/query', {\n payload: PublishedDocumentQuery,\n success: PublishedDocumentPage,\n error: [InternalError, Forbidden],\n }),\n HttpApiEndpoint.post('navigation', '/navigation', {\n payload: DocumentNavigationQuery,\n success: Schema.Array(DocumentNavigationItem),\n error: [InternalError, Forbidden],\n }),\n HttpApiEndpoint.post('surround', '/surround', {\n payload: DeliverySurroundPayload,\n success: DocumentSurround,\n error: [PublishedNotFound, InternalError, Forbidden],\n }),\n HttpApiEndpoint.get('seo', '/seo', {\n success: SeoSnapshot,\n error: [InternalError, Forbidden],\n }),\n )\n .prefix('/preview')\n","import { FormSubmission, FormResult } from './Forms'\nimport {\n ContentApplyInput,\n ContentApplyResult,\n ContentPlan,\n ContentSnapshot,\n ContentTransferConflict,\n ContentTransferInput,\n} from './ContentTransfer'\n/**\n * Studio HTTP paths, middleware contracts, payloads, and the composed CMS API. Every expected\n * caller failure is a tagged schema with an explicit status; unclassified failures become the\n * deliberately opaque `StudioInternalError`.\n */\nimport {\n AccessDenied,\n AuthenticationRequired,\n Role,\n StudioActor,\n StudioEntryDenied,\n StudioRequestContext,\n} from './AccessControl'\nimport { ActivityCursorInvalid, ActivityPage, ActivityQuery } from './Activity'\nimport { CollaborationTicket } from './Collaboration'\nimport { DocumentConfiguration, MediaConfiguration } from './Configuration'\nimport {\n CompareDocumentRevisionsInput,\n CreateDocumentInput,\n DeletedDocument,\n DocumentBrowseQuery,\n DocumentHistoryComparisonTooLarge,\n DocumentHistoryInvalidCursor,\n DocumentHistoryQuery,\n DocumentId,\n DocumentIssue,\n DocumentMediaUnavailable,\n DocumentMutationResult,\n DocumentNotFound,\n DocumentPathConflict,\n DocumentRevision,\n DocumentRevisionComparison,\n DocumentRevisionPage,\n DocumentSource,\n DocumentSummary,\n DocumentValidationFailed,\n DocumentValidationResult,\n DocumentVersionConflict,\n MoveDocumentInput,\n DuplicateDocumentInput,\n PublishDocumentInput,\n RemoveDocumentInput,\n RestoreDocumentInput,\n PublicPath,\n UndeleteDocumentInput,\n UpdateDocumentInput,\n} from './Documents'\nimport {\n InitializationAlreadyCompleted,\n InitializationInput,\n InitializationProofInvalid,\n InitializationState,\n} from './Initialization'\nimport {\n MediaAsset,\n MediaCleanupReport,\n MediaConflict,\n MediaFolder,\n MediaId,\n MediaIntegrityReport,\n MediaInvalid,\n MediaNotFound,\n MediaPage,\n MediaQuery,\n MediaReferenced,\n MediaTooLarge,\n MediaUpload,\n} from './Media'\nimport {\n CreateUserInput,\n User,\n UserAdministrationDenied,\n UserAlreadyExists,\n UserNotFound,\n UserPage,\n UserQuery,\n UserSelfRemovalDenied,\n UserSelfRoleChangeDenied,\n} from './Users'\nimport { Context, Schema } from 'effect'\nimport { Multipart } from 'effect/unstable/http'\nimport { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema } from 'effect/unstable/httpapi'\nimport { PreviewDeliveryApi, PublishedDeliveryApi } from './internal/http/delivery'\nimport { StudioInternalError } from './internal/http/failures'\nimport { STUDIO_API_PATH } from './HttpPaths'\nimport {\n PublishSeoInput,\n SaveSeoInput,\n SeoConfiguration,\n SeoConfirmationRequired,\n SeoMediaUnavailable,\n SeoMutationResult,\n SeoState,\n SeoVersionConflict,\n} from './Seo'\n\nexport { StudioInternalError, studioInternalError } from './internal/http/failures'\n\nexport {\n CMS_AUTHENTICATION_PATH,\n CMS_DELIVERY_SEO_PATH,\n CMS_DELIVERY_SITEMAP_PATH,\n CMS_LIVENESS_PATH,\n CMS_PREVIEW_SEO_PATH,\n CMS_READINESS_PATH,\n STUDIO_API_PATH,\n STUDIO_APP_PATH,\n STUDIO_BASE_PATH,\n STUDIO_COLLABORATION_PATH,\n} from './HttpPaths'\n\nconst ApiVersion = Schema.NonEmptyString.pipe(Schema.brand('ApiVersion'))\n\nexport const StudioBootstrap = Schema.Struct({\n basePath: PublicPath,\n documents: DocumentConfiguration,\n media: MediaConfiguration,\n seo: Schema.optionalKey(SeoConfiguration),\n version: ApiVersion,\n}).annotate({ identifier: 'StudioBootstrap' })\n\nexport interface StudioBootstrap extends Schema.Schema.Type<typeof StudioBootstrap> {}\n\nexport class StudioBadRequest extends Schema.TaggedError<StudioBadRequest>()('Studio.BadRequest', {\n kind: Schema.Literals(['Headers', 'Params', 'Payload', 'Query']),\n}) {}\n\nexport class StudioRequestConflict extends Schema.TaggedError<StudioRequestConflict>()('Studio.RequestConflict', {\n retryable: Schema.Literal(true),\n}) {}\n\nexport class StudioSchemaError extends HttpApiMiddleware.Service<StudioSchemaError>()(\n '@internal/protocol/StudioSchemaError',\n {\n error: [StudioBadRequest.pipe(HttpApiSchema.status(400)), StudioInternalError.pipe(HttpApiSchema.status(500))],\n },\n) {}\n\nexport class CurrentStudioRequest extends Context.Service<CurrentStudioRequest, StudioRequestContext>()(\n '@internal/protocol/CurrentStudioRequest',\n) {}\n\nexport class StudioAuthentication extends HttpApiMiddleware.Service<\n StudioAuthentication,\n { provides: CurrentStudioRequest }\n>()('@internal/protocol/StudioAuthentication', {\n error: [\n AuthenticationRequired.pipe(HttpApiSchema.status(401)),\n StudioEntryDenied.pipe(HttpApiSchema.status(403)),\n StudioInternalError.pipe(HttpApiSchema.status(500)),\n ],\n}) {}\n\nconst ValidateDocumentPayload = Schema.Struct({\n expectedVersion: UpdateDocumentInput.fields.expectedVersion,\n markdown: UpdateDocumentInput.fields.markdown,\n})\n\nconst UpdateDocumentPayload = ValidateDocumentPayload.pipe(\n Schema.fieldsAssign({ reason: UpdateDocumentInput.fields.reason }),\n)\n\nconst MoveDocumentPayload = Schema.Struct({\n expectedVersion: MoveDocumentInput.fields.expectedVersion,\n location: MoveDocumentInput.fields.location,\n reason: MoveDocumentInput.fields.reason,\n})\n\nconst PublishDocumentPayload = Schema.Struct({\n expectedVersion: PublishDocumentInput.fields.expectedVersion,\n reason: PublishDocumentInput.fields.reason,\n})\n\nconst RemoveDocumentPayload = Schema.Struct({\n expectedVersion: RemoveDocumentInput.fields.expectedVersion,\n reason: RemoveDocumentInput.fields.reason,\n})\n\nconst RestoreDocumentPayload = Schema.Struct({\n expectedVersion: RestoreDocumentInput.fields.expectedVersion,\n revisionId: RestoreDocumentInput.fields.revisionId,\n reason: RestoreDocumentInput.fields.reason,\n})\n\nconst UndeleteDocumentPayload = Schema.Struct({\n expectedVersion: UndeleteDocumentInput.fields.expectedVersion,\n reason: UndeleteDocumentInput.fields.reason,\n})\n\nconst ChangeRolePayload = Schema.Struct({ role: Role }).annotate({\n identifier: 'ChangeRolePayload',\n})\n\nexport const MediaUploadQuery = Schema.Struct({\n declaredByteSize: MediaUpload.fields.declaredByteSize,\n folder: Schema.optionalKey(MediaFolder),\n}).annotate({ identifier: 'MediaUploadQuery' })\n\nexport interface MediaUploadQuery extends Schema.Schema.Type<typeof MediaUploadQuery> {}\n\nconst MediaUploadPayload = Schema.Struct({\n file: Multipart.SingleFileSchema,\n}).pipe(HttpApiSchema.asMultipartStream({ maxParts: 1 }))\n\nconst NotFound = DocumentNotFound.pipe(HttpApiSchema.status(404))\n\nconst VersionConflict = DocumentVersionConflict.pipe(HttpApiSchema.status(409))\n\nconst Conflict = Schema.Union([DocumentMediaUnavailable, DocumentPathConflict, DocumentVersionConflict]).pipe(\n HttpApiSchema.status(409),\n)\n\nconst ValidationFailed = DocumentValidationFailed.pipe(HttpApiSchema.status(422))\n\nconst RequestConflict = StudioRequestConflict.pipe(HttpApiSchema.status(409))\n\nconst InternalError = StudioInternalError.pipe(HttpApiSchema.status(500))\n\nconst Forbidden = AccessDenied.pipe(HttpApiSchema.status(403))\n\nconst MutationErrors = [NotFound, Conflict, ValidationFailed, RequestConflict, Forbidden, InternalError] as const\n\nconst MediaNotFoundResponse = MediaNotFound.pipe(HttpApiSchema.status(404))\n\nconst MediaInvalidQuery = MediaInvalid.pipe(HttpApiSchema.status(400))\n\nconst MediaInvalidUpload = MediaInvalid.pipe(HttpApiSchema.status(422))\n\nconst MediaTooLargeResponse = MediaTooLarge.pipe(HttpApiSchema.status(413))\n\nconst MediaReferencedResponse = MediaReferenced.pipe(HttpApiSchema.status(409))\n\nconst MediaConflictResponse = MediaConflict.pipe(HttpApiSchema.status(409))\n\nconst InvalidActivityCursor = ActivityCursorInvalid.pipe(HttpApiSchema.status(400))\n\nconst InvalidHistoryCursor = DocumentHistoryInvalidCursor.pipe(HttpApiSchema.status(400))\n\nconst HistoryComparisonTooLarge = DocumentHistoryComparisonTooLarge.pipe(HttpApiSchema.status(422))\n\nconst ContentConflict = ContentTransferConflict.pipe(HttpApiSchema.status(409))\n\nconst AlreadyInitialized = InitializationAlreadyCompleted.pipe(HttpApiSchema.status(409))\n\nconst InitializationProofRejected = InitializationProofInvalid.pipe(HttpApiSchema.status(403))\n\nconst UserAdministrationForbidden = UserAdministrationDenied.pipe(HttpApiSchema.status(403))\n\nconst UserDuplicate = UserAlreadyExists.pipe(HttpApiSchema.status(409))\n\nconst MissingUser = UserNotFound.pipe(HttpApiSchema.status(404))\n\nconst UserSelfRemoval = UserSelfRemovalDenied.pipe(HttpApiSchema.status(409))\n\nconst UserSelfRoleChange = UserSelfRoleChangeDenied.pipe(HttpApiSchema.status(409))\n\nconst SeoConflict = SeoVersionConflict.pipe(HttpApiSchema.status(409))\n\nconst SeoConfirmation = SeoConfirmationRequired.pipe(HttpApiSchema.status(409))\n\nconst SeoMediaInvalid = SeoMediaUnavailable.pipe(HttpApiSchema.status(422))\n\nconst StudioDocumentsApi = HttpApiGroup.make('documents')\n .add(\n HttpApiEndpoint.get('browse', '/', {\n query: DocumentBrowseQuery,\n success: Schema.Array(DocumentSummary),\n error: [Forbidden, InternalError],\n }),\n HttpApiEndpoint.get('trash', '/trash', {\n success: Schema.Array(DeletedDocument),\n error: [Forbidden, InternalError],\n }),\n HttpApiEndpoint.get('read', '/:documentId', {\n params: { documentId: DocumentId },\n success: DocumentSource,\n error: [NotFound, Forbidden, InternalError],\n }),\n HttpApiEndpoint.post('create', '/', {\n payload: CreateDocumentInput,\n success: DocumentMutationResult.pipe(HttpApiSchema.status(201)),\n error: MutationErrors,\n }),\n HttpApiEndpoint.put('update', '/:documentId', {\n params: { documentId: DocumentId },\n payload: UpdateDocumentPayload,\n success: DocumentMutationResult,\n error: MutationErrors,\n }),\n HttpApiEndpoint.post('validate', '/:documentId/validate', {\n params: { documentId: DocumentId },\n payload: ValidateDocumentPayload,\n success: DocumentValidationResult,\n error: [NotFound, VersionConflict, Forbidden, InternalError],\n }),\n HttpApiEndpoint.post('move', '/:documentId/move', {\n params: { documentId: DocumentId },\n payload: MoveDocumentPayload,\n success: DocumentMutationResult,\n error: MutationErrors,\n }),\n HttpApiEndpoint.post('duplicate', '/:documentId/duplicate', {\n params: { documentId: DocumentId },\n payload: Schema.Struct({\n ...MoveDocumentPayload.fields,\n includeChildren: DuplicateDocumentInput.fields.includeChildren,\n locale: DuplicateDocumentInput.fields.locale,\n }),\n success: DocumentMutationResult,\n error: MutationErrors,\n }),\n HttpApiEndpoint.post('unpublish', '/:documentId/unpublish', {\n params: { documentId: DocumentId },\n payload: PublishDocumentPayload,\n success: DocumentMutationResult,\n error: MutationErrors,\n }),\n HttpApiEndpoint.post('publish', '/:documentId/publish', {\n params: { documentId: DocumentId },\n payload: PublishDocumentPayload,\n success: DocumentMutationResult,\n error: MutationErrors,\n }),\n HttpApiEndpoint.post('remove', '/:documentId/remove', {\n params: { documentId: DocumentId },\n payload: RemoveDocumentPayload,\n success: DocumentMutationResult,\n error: MutationErrors,\n }),\n HttpApiEndpoint.post('restore', '/:documentId/restore', {\n params: { documentId: DocumentId },\n payload: RestoreDocumentPayload,\n success: DocumentMutationResult,\n error: MutationErrors,\n }),\n HttpApiEndpoint.post('undelete', '/:documentId/undelete', {\n params: { documentId: DocumentId },\n payload: UndeleteDocumentPayload,\n success: DocumentMutationResult,\n error: MutationErrors,\n }),\n )\n .middleware(StudioAuthentication)\n .prefix('/documents')\n\nconst StudioContentApi = HttpApiGroup.make('content')\n .add(\n HttpApiEndpoint.get('snapshot', '/snapshot', {\n success: ContentSnapshot,\n error: [Forbidden, InternalError],\n }),\n HttpApiEndpoint.post('plan', '/plan', {\n payload: ContentTransferInput,\n success: ContentPlan,\n error: [ContentConflict, Forbidden, InternalError],\n }),\n HttpApiEndpoint.post('apply', '/apply', {\n payload: ContentApplyInput,\n success: ContentApplyResult,\n error: [ContentConflict, ValidationFailed, Forbidden, InternalError],\n }),\n )\n .middleware(StudioAuthentication)\n .prefix('/content')\n\nconst StudioMediaApi = HttpApiGroup.make('media')\n .add(\n HttpApiEndpoint.get('search', '/', {\n query: MediaQuery,\n success: MediaPage,\n error: [MediaInvalidQuery, Forbidden, InternalError],\n }),\n HttpApiEndpoint.post('upload', '/', {\n query: MediaUploadQuery,\n payload: MediaUploadPayload,\n success: MediaAsset.pipe(HttpApiSchema.status(201)),\n error: [MediaInvalidUpload, MediaTooLargeResponse, Forbidden, InternalError],\n }),\n HttpApiEndpoint.put('replace', '/:mediaId', {\n params: { mediaId: MediaId },\n query: MediaUploadQuery,\n payload: MediaUploadPayload,\n success: MediaAsset,\n error: [\n MediaNotFoundResponse,\n MediaConflictResponse,\n MediaInvalidUpload,\n MediaTooLargeResponse,\n Forbidden,\n InternalError,\n ],\n }),\n HttpApiEndpoint.post('cleanup', '/cleanup', {\n success: MediaCleanupReport,\n error: [Forbidden, InternalError],\n }),\n HttpApiEndpoint.get('integrity', '/integrity', {\n success: MediaIntegrityReport,\n error: [Forbidden, InternalError],\n }),\n HttpApiEndpoint.get('get', '/:mediaId', {\n params: { mediaId: MediaId },\n success: MediaAsset,\n error: [MediaNotFoundResponse, Forbidden, InternalError],\n }),\n HttpApiEndpoint.delete('remove', '/:mediaId', {\n params: { mediaId: MediaId },\n success: HttpApiSchema.NoContent,\n error: [MediaNotFoundResponse, MediaConflictResponse, MediaReferencedResponse, Forbidden, InternalError],\n }),\n )\n .middleware(StudioAuthentication)\n .prefix('/media')\n\nconst StudioConfigurationApi = HttpApiGroup.make('configuration')\n .add(\n HttpApiEndpoint.get('bootstrap', '/bootstrap', {\n success: StudioBootstrap,\n }),\n )\n .middleware(StudioAuthentication)\n\nconst StudioSessionApi = HttpApiGroup.make('session')\n .add(HttpApiEndpoint.get('current', '/session', { success: StudioActor }))\n .middleware(StudioAuthentication)\n\nconst InitializationApi = HttpApiGroup.make('initialization').add(\n HttpApiEndpoint.get('status', '/initialization', {\n success: InitializationState,\n error: InternalError,\n }),\n HttpApiEndpoint.post('claim', '/initialization', {\n payload: InitializationInput,\n success: User.pipe(HttpApiSchema.status(201)),\n error: [AlreadyInitialized, InitializationProofRejected, InternalError],\n }),\n)\n\nconst StudioDiagnosticsApi = HttpApiGroup.make('diagnostics')\n .add(\n HttpApiEndpoint.get('documents', '/diagnostics/documents', {\n success: Schema.Array(DocumentIssue),\n error: [Forbidden, InternalError],\n }),\n )\n .middleware(StudioAuthentication)\n\nconst StudioHistoryApi = HttpApiGroup.make('history')\n .add(\n HttpApiEndpoint.get('list', '/', {\n query: DocumentHistoryQuery,\n success: DocumentRevisionPage,\n error: [InvalidHistoryCursor, Forbidden, InternalError],\n }),\n HttpApiEndpoint.get('read', '/:documentId/:revisionId', {\n params: { documentId: DocumentId, revisionId: DocumentRevision.fields.revisionId },\n success: DocumentRevision,\n error: [NotFound, Forbidden, InternalError],\n }),\n HttpApiEndpoint.post('compare', '/compare', {\n payload: CompareDocumentRevisionsInput,\n success: DocumentRevisionComparison,\n error: [NotFound, HistoryComparisonTooLarge, Forbidden, InternalError],\n }),\n )\n .middleware(StudioAuthentication)\n .prefix('/history')\n\nconst StudioActivityApi = HttpApiGroup.make('activity')\n .add(\n HttpApiEndpoint.get('list', '/', {\n query: ActivityQuery,\n success: ActivityPage,\n error: [InvalidActivityCursor, Forbidden, InternalError],\n }),\n )\n .middleware(StudioAuthentication)\n .prefix('/activity')\n\nconst StudioSeoApi = HttpApiGroup.make('seo')\n .add(\n HttpApiEndpoint.get('read', '/', {\n success: SeoState,\n error: [Forbidden, InternalError],\n }),\n HttpApiEndpoint.put('save', '/', {\n payload: SaveSeoInput,\n success: SeoMutationResult,\n error: [SeoConflict, SeoConfirmation, SeoMediaInvalid, Forbidden, InternalError],\n }),\n HttpApiEndpoint.post('publish', '/publish', {\n payload: PublishSeoInput,\n success: SeoMutationResult,\n error: [SeoConflict, SeoConfirmation, SeoMediaInvalid, Forbidden, InternalError],\n }),\n )\n .middleware(StudioAuthentication)\n .prefix('/seo')\n\nconst StudioUserAdministrationApi = HttpApiGroup.make('users')\n .add(\n HttpApiEndpoint.get('list', '/', {\n query: UserQuery,\n success: UserPage,\n error: [UserAdministrationForbidden, InternalError],\n }),\n HttpApiEndpoint.post('create', '/', {\n payload: CreateUserInput,\n success: User.pipe(HttpApiSchema.status(201)),\n error: [UserDuplicate, UserAdministrationForbidden, InternalError],\n }),\n HttpApiEndpoint.post('changeRole', '/:userId/role', {\n params: { userId: User.fields.id },\n payload: ChangeRolePayload,\n success: User,\n error: [MissingUser, UserSelfRoleChange, UserAdministrationForbidden, InternalError],\n }),\n HttpApiEndpoint.post('revokeSessions', '/:userId/sessions/revoke', {\n params: { userId: User.fields.id },\n success: User,\n error: [MissingUser, UserAdministrationForbidden, InternalError],\n }),\n HttpApiEndpoint.delete('remove', '/:userId', {\n params: { userId: User.fields.id },\n success: User,\n error: [MissingUser, UserSelfRemoval, UserAdministrationForbidden, InternalError],\n }),\n )\n .middleware(StudioAuthentication)\n .prefix('/users')\n\nconst StudioCollaborationApi = HttpApiGroup.make('collaboration')\n .add(\n HttpApiEndpoint.post('ticket', '/:documentId/ticket', {\n params: { documentId: DocumentId },\n success: CollaborationTicket,\n error: [NotFound, Forbidden, InternalError],\n }),\n )\n .middleware(StudioAuthentication)\n .prefix('/collaboration')\n\nconst FormsApi = HttpApiGroup.make('forms')\n .add(HttpApiEndpoint.post('submit', '/submit', { payload: FormSubmission, success: FormResult }))\n .prefix('/forms')\n\nexport class StudioApi extends HttpApi.make('StudioApi')\n .add(\n FormsApi,\n InitializationApi,\n PublishedDeliveryApi,\n StudioConfigurationApi,\n StudioSessionApi,\n StudioDiagnosticsApi,\n PreviewDeliveryApi.middleware(StudioAuthentication),\n StudioDocumentsApi,\n StudioContentApi,\n StudioHistoryApi,\n StudioActivityApi,\n StudioSeoApi,\n StudioUserAdministrationApi,\n StudioMediaApi,\n StudioCollaborationApi,\n )\n .middleware(StudioSchemaError)\n .prefix(STUDIO_API_PATH) {}\n","import type { CompiledDocument } from '@internal/protocol/Documents'\nimport type {\n DocumentStructuredData,\n GlobalSeoSettings,\n ResolvedSeo,\n SeoCapabilities,\n SiteIdentity,\n} from '@internal/protocol/Seo'\nimport { SeoUrl } from '@internal/protocol/Seo'\n\nexport interface ResolveDocumentSeoInput {\n readonly document: CompiledDocument\n readonly global: GlobalSeoSettings\n readonly capabilities: SeoCapabilities\n}\n\nexport function resolveDocumentSeo({ document, global, capabilities }: ResolveDocumentSeoInput): ResolvedSeo {\n const authored = document.seo\n const baseTitle = authored?.title ?? document.title\n const title = global.titleTemplate?.replaceAll('%s', baseTitle) ?? baseTitle\n const description = authored?.description ?? document.description ?? global.defaultDescription\n const socialTitle = authored?.socialTitle ?? global.socialTitle ?? title\n const socialDescription = authored?.socialDescription ?? global.socialDescription ?? description\n const socialImage = authored?.socialImage ?? global.socialImage\n const canonicalUrl = authored?.canonicalUrl ?? SeoUrl.make(new URL(document.path, `${global.canonicalOrigin}/`).href)\n const structuredData = resolveStructuredData(authored?.structuredData, capabilities)\n const identity = resolveIdentity(global.identity, capabilities)\n\n return {\n title,\n ...(description === undefined ? undefined : { description }),\n socialTitle,\n ...(socialDescription === undefined ? undefined : { socialDescription }),\n ...(socialImage === undefined ? undefined : { socialImage }),\n canonicalUrl,\n index: global.index && (authored?.index ?? true),\n follow: global.follow && (authored?.follow ?? true),\n ...(structuredData === undefined ? undefined : { structuredData }),\n ...(identity === undefined ? undefined : { identity }),\n }\n}\n\nfunction resolveStructuredData(\n authored: DocumentStructuredData | undefined,\n capabilities: SeoCapabilities,\n): DocumentStructuredData | undefined {\n if (authored && capabilities.structuredDataTypes.includes(authored.type)) return authored\n\n return capabilities.structuredDataTypes.includes('WebPage') ? { type: 'WebPage' } : undefined\n}\n\nfunction resolveIdentity(identity: SiteIdentity | undefined, capabilities: SeoCapabilities): SiteIdentity | undefined {\n return identity && capabilities.identityTypes.includes(identity.type) ? identity : undefined\n}\n","import type { StudioAction, StudioAccessDecision, StudioRequestContext } from '@internal/protocol/AccessControl'\nimport { DOCUMENT_ACTIONS, MEDIA_ACTIONS } from '@internal/protocol/AccessControl'\nimport { AccessDenied } from '@internal/protocol/AccessControl'\nimport { Context, Effect, Layer } from 'effect'\n\nconst VIEWER_ACTIONS = new Set<StudioAction>([\n 'document.browse',\n 'document.read',\n 'document.trash',\n 'document.history',\n 'media.read',\n 'media.search',\n 'media.integrity',\n])\n\nconst EDITOR_ACTIONS = new Set<StudioAction>([\n ...DOCUMENT_ACTIONS.filter((action) => action !== 'document.transfer'),\n ...MEDIA_ACTIONS.filter((action) => action !== 'media.cleanup'),\n])\n\nexport interface AccessControlApi {\n readonly require: (context: StudioRequestContext, decision: StudioAccessDecision) => Effect.Effect<void, AccessDenied>\n}\n\nexport class AccessControl extends Context.Service<AccessControl, AccessControlApi>()(\n '@internal/server/AccessControl',\n) {}\n\nexport const defaultAccessControlLayer = Layer.succeed(\n AccessControl,\n AccessControl.of({\n require: Effect.fn('AccessControl.require')(function* (\n context: StudioRequestContext,\n decision: StudioAccessDecision,\n ) {\n if (isAllowed(context, decision.action)) return\n\n return yield* new AccessDenied({\n action: decision.action,\n actorId: context.actor.id,\n resource: decision.resource,\n })\n }),\n }),\n)\n\nfunction isAllowed(context: StudioRequestContext, action: StudioAction): boolean {\n return context.actor.roles.some((role) => {\n if (role === 'administrator') return true\n\n return (role === 'editor' && EDITOR_ACTIONS.has(action)) || (role === 'viewer' && VIEWER_ACTIONS.has(action))\n })\n}\n","import type { CmsMarkdownDocument } from '@internal/protocol/Documents'\nimport { renderMarkdown } from 'comark/render'\nimport { Effect } from 'effect'\nimport { toComarkDocument } from '../comark/document-adapter'\nimport { EditorRenderFailed } from './errors'\nimport { withoutEditorMetadata } from './metadata'\n\nexport const renderEditorMarkdown = Effect.fn('EditorDocument.renderMarkdown')((document: CmsMarkdownDocument) => {\n return Effect.tryPromise({\n try: () => renderMarkdown(toComarkDocument(withoutEditorMetadata(document))),\n catch: (cause) => new EditorRenderFailed({ cause }),\n })\n})\n","import type { BlockProp } from '@internal/protocol/Authoring'\nimport type { ComponentDefinition } from '@internal/protocol/Configuration'\nimport type { CmsMarkdownDocument, CompiledDocument, MarkdownNode } from '@internal/protocol/Documents'\nimport type { NodeRenderData } from 'comark'\nimport { Predicate, Schema } from 'effect'\nimport { createCmsComarkRenderData, mutableJsonObject } from '../comark/document-adapter'\nimport { encodeCmsEditorComponentAttributes, projectCmsEditorComponentAttributes } from '../comark/bindings'\nimport { referenceTarget } from './reference-target'\n\n/** Rewrites only semantic page links, preserving bindings and unrelated content. */\nexport function rewriteDocumentRoutes(\n document: CompiledDocument,\n destinations: ReadonlyMap<string, string>,\n components: ReadonlyArray<ComponentDefinition> = [],\n): CmsMarkdownDocument | undefined {\n let changed = false\n\n function link(value: Schema.Json | undefined): Schema.Json | undefined {\n const target = referenceTarget('a', new Map([['href', value]]), document.path, undefined)\n\n if (target?.kind !== 'document' || !Predicate.isString(value)) return value\n const destination = destinations.get(target.path)\n const sourceMoved = destinations.has(document.path)\n\n if (!destination && (!sourceMoved || value.startsWith('/'))) return value\n const suffix = value.match(/[?#].*$/u)?.[0] ?? ''\n const next = `${destination ?? target.path}${suffix}`\n\n if (next !== value) changed = true\n\n return next\n }\n\n function properties(fields: ReadonlyArray<BlockProp>, values: Schema.JsonObject): Schema.JsonObject {\n const result = mutableJsonObject(values)\n\n for (const field of fields) {\n const value = values[field.name] === undefined ? field.defaultValue : values[field.name]\n\n if (field.input === 'link') {\n const next = link(value)\n\n if (next !== undefined && next !== value) result[field.name] = next\n } else if (field.fields) {\n const next = Array.isArray(value)\n ? value.map((item) => (Schema.is(Schema.JsonObject)(item) ? properties(field.fields ?? [], item) : item))\n : Schema.is(Schema.JsonObject)(value)\n ? properties(field.fields, value)\n : value\n\n if (next !== undefined && JSON.stringify(next) !== JSON.stringify(value)) result[field.name] = next\n }\n }\n\n return result\n }\n\n function visit(node: MarkdownNode, renderData: NodeRenderData): MarkdownNode {\n if (Predicate.isString(node) || node[0] === null) return node\n const [tag, attributes, ...children] = node\n const projection = projectCmsEditorComponentAttributes(attributes, renderData)\n\n const fields =\n components.find((component) => component.name.toLowerCase() === tag.toLowerCase())?.authoring.props ?? []\n\n let props = properties(fields, projection.props)\n\n if (tag === 'a') {\n const href = link(projection.props.href)\n\n if (href !== undefined) props = Object.assign({}, props, { href })\n }\n\n const nextAttributes =\n JSON.stringify(props) === JSON.stringify(projection.props)\n ? attributes\n : encodeCmsEditorComponentAttributes(props, projection.bindings)\n\n return [tag, nextAttributes, ...children.map((child) => visit(child, projection.renderData))]\n }\n\n const nodes = document.body.nodes.map((node) => visit(node, createCmsComarkRenderData(document.body)))\n\n return changed ? Object.assign({}, document.body, { nodes }) : undefined\n}\n","import type { DocumentConfiguration, CollectionDefinition } from '@internal/protocol/Configuration'\nimport type {\n CmsMarkdownDocument,\n CompiledDocument,\n DocumentLocation,\n CreateDocumentInput,\n DocumentSummary,\n} from '@internal/protocol/Documents'\nimport type { Locale } from '@internal/protocol/Configuration'\nimport type { PublicPath, SourcePath } from '@internal/protocol/Documents'\nimport {\n CmsMarkdownDocument as CmsMarkdownDocumentSchema,\n DocumentValidationFailed,\n} from '@internal/protocol/Documents'\nimport { SourcePath as SourcePathSchema } from '@internal/protocol/Documents'\nimport { Effect, Result, Schema } from 'effect'\nimport {\n localizeDocumentPath,\n normalizeDocumentRelativePath,\n normalizePublicPath,\n parseDocumentAddress,\n resolveDocumentAddress,\n type DocumentAddressError,\n} from './internal/document-address'\nimport { renderEditorMarkdown } from './internal/editor/render'\nimport type { EditorRenderFailed } from './internal/editor/errors'\n\nexport interface DocumentCreationPlan {\n readonly collection: CollectionDefinition\n readonly data: Readonly<Record<string, string>>\n readonly key: PublicPath\n readonly locale?: Locale\n readonly path: PublicPath\n readonly sourcePath: SourcePath\n readonly title: string\n}\n\nexport interface InitialDocumentSource {\n readonly body: CmsMarkdownDocument\n readonly markdown: string\n}\n\nexport function planDocumentCreation(\n configuration: DocumentConfiguration,\n input: CreateDocumentInput,\n): Result.Result<DocumentCreationPlan, DocumentValidationFailed> {\n return Result.gen(function* () {\n const collection = configuration.types.find((candidate) => candidate.collection === input.collection)\n\n if (!collection) return yield* invalid(`Document collection \"${input.collection}\" does not exist.`, 'collection')\n\n const title = input.title.trim()\n\n if (!title) return yield* invalid('A document title is required.', 'title')\n\n const locale = yield* resolveLocale(configuration, input.locale)\n const address = yield* parseDocumentAddress(collection.addressPattern).pipe(Result.mapError(addressInvalid))\n const relativePath = yield* resolveRelativePath(collection, input.location)\n\n const data = Object.fromEntries(\n address.tokens.flatMap((token) => {\n if (token.name === 'slug' && relativePath) return [[token.name, relativePath.split('/').at(-1) ?? relativePath]]\n\n return []\n }),\n )\n\n const relativeKey = yield* normalizePublicPath(relativePath).pipe(Result.mapError(addressInvalid))\n const key = yield* resolveDocumentAddress(address, relativeKey, data).pipe(Result.mapError(addressInvalid))\n const sourcePath = documentSourcePath(collection, relativePath, locale)\n const path = localizeDocumentPath(key, locale, configuration.locales)\n\n return Object.assign(\n {\n collection,\n data,\n key,\n path,\n sourcePath,\n title,\n },\n locale === undefined ? undefined : { locale },\n ) satisfies DocumentCreationPlan\n })\n}\n\nexport const createInitialDocumentSource: (\n plan: DocumentCreationPlan,\n) => Effect.Effect<InitialDocumentSource, EditorRenderFailed> = Effect.fn('DocumentPlanning.createInitialSource')(\n function* (plan: DocumentCreationPlan) {\n const body = CmsMarkdownDocumentSchema.make({\n frontmatter: initialFrontmatter(plan),\n meta: {},\n nodes: [['h1', {}, plan.title]],\n })\n\n return {\n body,\n markdown: yield* renderEditorMarkdown(body),\n } satisfies InitialDocumentSource\n },\n)\n\nexport function planDocumentMove(\n configuration: DocumentConfiguration,\n document: CompiledDocument,\n location: DocumentLocation,\n): Result.Result<SourcePath, DocumentValidationFailed> {\n return Result.gen(function* () {\n const collection = configuration.types.find((candidate) => candidate.collection === document.collection)\n\n if (!collection) {\n return yield* invalid(`Document collection \"${document.collection}\" does not exist.`, 'documentId')\n }\n\n const relativePath = yield* resolveRelativePath(collection, location)\n\n return documentSourcePath(collection, relativePath, document.locale)\n })\n}\n\nexport function documentRelativePath(\n collection: CollectionDefinition,\n entry: Pick<DocumentSummary, 'document' | 'sourcePath'>,\n): string | undefined {\n let sourcePath: string = entry.sourcePath\n\n if (entry.document.locale && sourcePath.startsWith(`${entry.document.locale}/`)) {\n sourcePath = sourcePath.slice(entry.document.locale.length + 1)\n }\n\n if (collection.directory !== '.' && sourcePath.startsWith(`${collection.directory}/`)) {\n sourcePath = sourcePath.slice(collection.directory.length + 1)\n }\n\n sourcePath = sourcePath.replace(/\\.(?:md|mdc)$/iu, '')\n\n return sourcePath.toLocaleLowerCase() === 'index' ? undefined : sourcePath.replace(/\\/index$/iu, '')\n}\n\nfunction documentSourcePath(\n collection: CollectionDefinition,\n relativePath: string,\n locale: Locale | undefined,\n): SourcePath {\n const sourceName = relativePath ? `${relativePath}.md` : 'index.md'\n\n return SourcePathSchema.make(\n [locale, collection.directory === '.' ? undefined : collection.directory, sourceName]\n .filter((value) => value !== undefined)\n .join('/'),\n )\n}\n\nfunction initialFrontmatter(plan: DocumentCreationPlan): Schema.JsonObject {\n let frontmatter: Schema.JsonObject = { ...plan.data, title: plan.title }\n\n for (const field of plan.collection.authoringFields) {\n if (field.defaultValue !== undefined && nestedValue(frontmatter, field.path) === undefined) {\n frontmatter = setNestedValue(frontmatter, field.path.split('.'), field.defaultValue)\n }\n }\n\n return frontmatter\n}\n\nfunction nestedValue(value: Schema.JsonObject, path: string): Schema.Json | undefined {\n return path\n .split('.')\n .reduce<Schema.Json | undefined>(\n (current, segment) => (isJsonObject(current) ? current[segment] : undefined),\n value,\n )\n}\n\nfunction setNestedValue(target: Schema.JsonObject, path: ReadonlyArray<string>, value: Schema.Json): Schema.JsonObject {\n const [segment, ...rest] = path\n\n if (!segment) return target\n\n if (rest.length === 0) return Object.assign({}, target, { [segment]: value })\n const current = target[segment]\n\n return Object.assign({}, target, {\n [segment]: setNestedValue(isJsonObject(current) ? current : {}, rest, value),\n })\n}\n\nconst isJsonObject = Schema.is(Schema.JsonObject)\n\nfunction resolveLocale(\n configuration: DocumentConfiguration,\n requested: Locale | undefined,\n): Result.Result<Locale | undefined, DocumentValidationFailed> {\n const locales = configuration.locales\n\n if (!locales) {\n return requested === undefined\n ? Result.succeed(undefined)\n : invalid(`Document locale \"${requested}\" is not configured.`, 'locale')\n }\n\n const locale = requested ?? locales.defaultLocale\n\n return locales.locales.includes(locale)\n ? Result.succeed(locale)\n : invalid(`Document locale \"${locale}\" does not exist.`, 'locale')\n}\n\nfunction resolveRelativePath(\n collection: CollectionDefinition,\n location: DocumentLocation,\n): Result.Result<string, DocumentValidationFailed> {\n if (location.kind === 'home') {\n return collection.addressPattern === '/:path*'\n ? Result.succeed('')\n : invalid('Only a root catch-all collection can use the home location.', 'location')\n }\n\n if (location.parent !== undefined && !collection.hierarchy)\n return invalid(`Document collection \"${collection.collection}\" does not allow hierarchy.`, 'location.parent')\n\n return normalizeDocumentRelativePath(\n [location.parent, location.slug].filter((value) => value !== undefined).join('/'),\n ).pipe(Result.mapError((error) => addressInvalid({ ...error, field: 'location' })))\n}\n\nfunction addressInvalid(error: DocumentAddressError): DocumentValidationFailed {\n return new DocumentValidationFailed({\n issues: [validationIssue(error.message, error.field)],\n })\n}\n\nfunction invalid(message: string, field?: string): Result.Result<never, DocumentValidationFailed> {\n return Result.fail(\n new DocumentValidationFailed({\n issues: [validationIssue(message, field)],\n }),\n )\n}\n\nfunction validationIssue(message: string, field: string | undefined) {\n return field === undefined\n ? { code: 'document.invalid' as const, message, severity: 'error' as const }\n : { code: 'document.invalid' as const, field, message, severity: 'error' as const }\n}\n\n/** Updates route-owned frontmatter when relocating a page in a slug-addressed collection. */\nexport const relocateDocumentMarkdown = Effect.fn('DocumentPlanning.relocateMarkdown')(function* (\n configuration: DocumentConfiguration,\n document: CompiledDocument,\n location: DocumentLocation,\n markdown: string,\n) {\n const collection = configuration.types.find((type) => type.collection === document.collection)\n\n if (!collection || !collection.addressPattern.includes(':slug') || location.kind === 'home') return markdown\n\n return yield* renderEditorMarkdown({\n ...document.body,\n frontmatter: { ...document.body.frontmatter, slug: location.slug },\n })\n})\n\nexport { rewriteDocumentRoutes } from './internal/document-engine/relocate-links'\n\nexport { renderEditorMarkdown as renderDocumentMarkdown } from './internal/editor/render'\n","import type {\n DocumentCatalog,\n DocumentCompilationSource,\n DocumentEngine,\n DocumentParseFailed,\n} from '@internal/document/DocumentEngine'\nimport type {\n DocumentSummary,\n DocumentBrowseQuery,\n DeletedDocument,\n CompiledDocument,\n DocumentIssue,\n} from '@internal/protocol/Documents'\nimport type { DocumentId, SourcePath } from '@internal/protocol/Documents'\nimport type { DocumentStoreSnapshot } from './document-store'\nimport { DocumentCompilationFailed } from '@internal/document/DocumentEngine'\nimport {\n DocumentSummary as DocumentSummarySchema,\n DeletedDocument as DeletedDocumentSchema,\n DocumentValidationFailed,\n DocumentValidationResult as DocumentValidationResultSchema,\n} from '@internal/protocol/Documents'\nimport { Effect, Result, Schema } from 'effect'\n\nconst isDocumentCompilationFailed = Schema.is(DocumentCompilationFailed)\n\nexport interface DocumentState {\n readonly activeById: ReadonlyMap<DocumentId, DocumentStoreSnapshot['active'][number]>\n readonly authored: DocumentCatalog\n readonly authoredById: ReadonlyMap<DocumentId, CompiledDocument>\n readonly published: DocumentCatalog\n readonly publishedById: ReadonlyMap<DocumentId, CompiledDocument>\n readonly snapshot: DocumentStoreSnapshot\n}\n\nexport function makeDocumentState(\n authored: DocumentCatalog,\n published: DocumentCatalog,\n snapshot: DocumentStoreSnapshot,\n): DocumentState {\n const activeById = new Map<DocumentId, DocumentStoreSnapshot['active'][number]>()\n\n for (const source of snapshot.active) {\n if (activeById.has(source.documentId)) {\n throw new Error(`Document \"${source.documentId}\" appears more than once in the repository snapshot.`)\n }\n\n activeById.set(source.documentId, source)\n }\n\n const authoredById = new Map<DocumentId, CompiledDocument>()\n\n for (const document of authored.documents) {\n if (authoredById.has(document.id)) {\n throw new Error(`Compiled document \"${document.id}\" appears more than once in the authored catalog.`)\n }\n\n if (!activeById.has(document.id)) {\n throw new Error(`Compiled document \"${document.id}\" is missing from the repository snapshot.`)\n }\n\n authoredById.set(document.id, document)\n }\n\n for (const documentId of activeById.keys()) {\n if (!authoredById.has(documentId)) {\n throw new Error(`Compiled document \"${documentId}\" is missing from the repository snapshot.`)\n }\n }\n\n const publishedById = new Map<DocumentId, CompiledDocument>()\n\n for (const document of published.documents) {\n if (publishedById.has(document.id)) {\n throw new Error(`Compiled document \"${document.id}\" appears more than once in the published catalog.`)\n }\n\n publishedById.set(document.id, document)\n }\n\n return { activeById, authored, authoredById, published, publishedById, snapshot }\n}\n\nexport const compileDocumentState = Effect.fn('DocumentState.compile')(function* (\n engine: DocumentEngine,\n snapshot: DocumentStoreSnapshot,\n previous?: DocumentState,\n) {\n const authored = yield* engine.compileAll({ previous: previous?.authored, sources: authoredSources(snapshot) })\n const published = yield* engine.compileAll({ previous: previous?.published, sources: publishedSources(snapshot) })\n\n return makeDocumentState(authored, published, snapshot)\n})\n\nexport function authoredSources(snapshot: DocumentStoreSnapshot): ReadonlyArray<DocumentCompilationSource> {\n return snapshot.active.map((source) => ({\n documentId: source.documentId,\n draft: source.publishedVersion !== source.version,\n markdown: source.markdown,\n sourcePath: source.sourcePath,\n }))\n}\n\nexport function publishedSources(snapshot: DocumentStoreSnapshot): ReadonlyArray<DocumentCompilationSource> {\n return snapshot.published.map((source) => ({\n documentId: source.documentId,\n draft: false,\n markdown: source.markdown,\n publishedAt: source.editedAt,\n sourcePath: source.sourcePath,\n }))\n}\n\nexport const compileValidCatalog = Effect.fn('DocumentState.compileValid')(function* (\n engine: DocumentEngine,\n sources: ReadonlyArray<DocumentCompilationSource>,\n previous: DocumentCatalog,\n) {\n const result = yield* Effect.result(engine.compileAll({ previous, sources }))\n\n if (Result.isFailure(result)) {\n return yield* new DocumentValidationFailed({\n issues: compilationIssues(result.failure),\n })\n }\n\n const errors = result.success.issues.filter((issue) => issue.severity === 'error')\n\n if (errors.length > 0) return yield* new DocumentValidationFailed({ issues: errors })\n\n return result.success\n})\n\nexport const validateDocumentSources = Effect.fn('DocumentState.validate')(function* (\n engine: DocumentEngine,\n sources: ReadonlyArray<DocumentCompilationSource>,\n sourcePath: SourcePath,\n previous: DocumentCatalog,\n) {\n const result = yield* Effect.result(engine.compileAll({ previous, sources }))\n\n if (Result.isFailure(result)) {\n return DocumentValidationResultSchema.make({\n issues: compilationIssues(result.failure),\n valid: false,\n })\n }\n\n const catalog = result.success\n const document = catalog.documents.find((candidate) => candidate.source.path === sourcePath)\n const issues = catalog.issues\n\n const validation = {\n issues,\n valid: document !== undefined && !issues.some((issue) => issue.severity === 'error'),\n }\n\n return DocumentValidationResultSchema.make(\n Object.assign(validation, document === undefined ? undefined : { document }),\n )\n})\n\nexport function authoringEntries(state: DocumentState, query: DocumentBrowseQuery): ReadonlyArray<DocumentSummary> {\n return state.snapshot.active.flatMap((source) => {\n const document = state.authoredById.get(source.documentId)\n\n if (!document) throw new Error(`Compiled document \"${source.documentId}\" is missing from the repository snapshot.`)\n\n if (query.collection !== undefined && document.collection !== query.collection) return []\n\n if (query.locale !== undefined && document.locale !== query.locale) return []\n\n return [\n DocumentSummarySchema.make({\n ...browseMetadata(state, source),\n document,\n sourcePath: source.sourcePath,\n version: source.version,\n }),\n ]\n })\n}\n\nexport function deletedEntries(state: DocumentState): ReadonlyArray<DeletedDocument> {\n return state.snapshot.deleted.map((source) =>\n DeletedDocumentSchema.make({\n ...(source.title ? { title: source.title } : undefined),\n ...(source.path ? { path: source.path } : undefined),\n ...(source.trashBatchId ? { trashBatchId: source.trashBatchId } : undefined),\n documentId: source.documentId,\n deletedAt: source.deletedAt,\n sourcePath: source.sourcePath,\n version: source.version,\n }),\n )\n}\n\nexport function entryById(state: DocumentState, documentId: DocumentId): DocumentSummary | undefined {\n const source = state.activeById.get(documentId)\n const document = state.authoredById.get(documentId)\n\n return source && document\n ? DocumentSummarySchema.make({\n ...browseMetadata(state, source),\n document,\n sourcePath: source.sourcePath,\n version: source.version,\n })\n : undefined\n}\n\nfunction compilationIssues(error: DocumentCompilationFailed | DocumentParseFailed): ReadonlyArray<DocumentIssue> {\n if (isDocumentCompilationFailed(error)) return error.issues\n\n return [\n {\n code: 'markdown.parse',\n message: errorMessage(error.cause),\n severity: 'error',\n sourcePath: error.sourcePath,\n },\n ]\n}\n\nfunction errorMessage(cause: unknown): string {\n return cause instanceof Error && cause.message ? cause.message : 'Markdown could not be parsed.'\n}\n\nfunction browseMetadata(state: DocumentState, source: DocumentStoreSnapshot['active'][number]) {\n const live = state.publishedById.get(source.documentId)\n\n const metadata: {\n -readonly [\n Key in 'createdBy' | 'editedBy' | 'editedAt' | 'publishedVersion' | 'publishedPath'\n ]?: DocumentSummary[Key]\n } = {}\n\n if (source.createdBy) metadata.createdBy = source.createdBy\n\n if (source.editedBy) metadata.editedBy = source.editedBy\n\n if (source.editedAt) metadata.editedAt = source.editedAt\n\n if (source.publishedVersion) metadata.publishedVersion = source.publishedVersion\n\n if (live) metadata.publishedPath = live.path\n\n return metadata\n}\n","import type { DocumentCompilationSource } from '@internal/document/DocumentEngine'\nimport {\n documentRelativePath,\n planDocumentMove,\n relocateDocumentMarkdown,\n rewriteDocumentRoutes,\n renderDocumentMarkdown,\n} from '@internal/document/DocumentPlanning'\nimport type {\n DocumentId,\n DocumentLocation,\n DocumentSource,\n DuplicateDocumentInput,\n MoveDocumentInput,\n RemoveDocumentInput,\n UndeleteDocumentInput,\n} from '@internal/protocol/Documents'\nimport {\n DocumentNotFound,\n DocumentPathConflict,\n DocumentValidationFailed,\n DocumentVersionConflict,\n} from '@internal/protocol/Documents'\nimport { Effect, Schema } from 'effect'\nimport { RelativeDocumentPath, Slug } from '@internal/protocol/Documents'\nimport type { DocumentLifecycleDependencies } from './document-lifecycle'\nimport type { DocumentState } from './document-state'\nimport type { DocumentCommitPlan } from './document-store'\nimport { authoredSources, compileValidCatalog, publishedSources } from './document-state'\n\nexport type TreeCommand =\n | { readonly action: 'document.move'; readonly input: MoveDocumentInput }\n | {\n readonly action: 'document.duplicate'\n readonly input: DuplicateDocumentInput\n readonly nextDocumentId: Effect.Effect<DocumentId>\n }\n | { readonly action: 'document.remove'; readonly input: RemoveDocumentInput }\n | { readonly action: 'document.undelete'; readonly input: UndeleteDocumentInput }\n\n/** Selects by route boundaries, never by title or a raw prefix such as /about matching /about-us. */\nexport function subtreeIds(state: DocumentState, documentId: DocumentId): ReadonlyArray<DocumentId> {\n const parent = state.authoredById.get(documentId)\n\n if (!parent) return [documentId]\n\n return state.authored.documents\n .filter(\n (page) =>\n page.id === parent.id ||\n (parent.key !== '/' &&\n page.collection === parent.collection &&\n page.locale === parent.locale &&\n page.key.startsWith(`${parent.key}/`)),\n )\n .map((page) => page.id)\n}\n\nexport const prepareTreeMutation = Effect.fn('Documents.prepareTreeMutation')(function* (\n dependencies: DocumentLifecycleDependencies,\n state: DocumentState,\n command: TreeCommand,\n) {\n const { configuration, engine } = dependencies\n const input = command.input\n\n const root =\n command.action === 'document.undelete'\n ? state.snapshot.deleted.find((source) => source.documentId === input.documentId)\n : state.activeById.get(input.documentId)\n\n if (!root) return yield* new DocumentNotFound({ documentId: input.documentId })\n\n if (root.version !== input.expectedVersion)\n return yield* new DocumentVersionConflict({\n documentId: root.documentId,\n actualVersion: root.version,\n expectedVersion: input.expectedVersion,\n })\n let sources: ReadonlyArray<DocumentSource>\n\n if (command.action === 'document.undelete') {\n const deleted = state.snapshot.deleted.find((source) => source.documentId === root.documentId)\n sources = state.snapshot.deleted.filter(\n (source) =>\n source.documentId === root.documentId ||\n (deleted &&\n deleted.trashBatchId &&\n source.trashBatchId === deleted.trashBatchId &&\n deleted.path !== undefined &&\n source.path?.startsWith(`${deleted.path}/`)),\n )\n } else {\n const ids = new Set(\n command.action === 'document.duplicate' && !command.input.includeChildren\n ? [root.documentId]\n : subtreeIds(state, root.documentId),\n )\n\n sources = state.snapshot.active.filter((source) => ids.has(source.documentId))\n }\n\n sources = [root, ...sources.filter((source) => source.documentId !== root.documentId)]\n const plans: DocumentCommitPlan[] = []\n const parent = state.authoredById.get(root.documentId)\n\n for (const source of sources) {\n if (command.action === 'document.remove' || command.action === 'document.undelete') {\n const page = state.authoredById.get(source.documentId)\n plans.push({\n ...(command.action === 'document.remove'\n ? { trashBatchId: root.version, title: page?.title, path: page?.path }\n : undefined),\n action: command.action,\n documentId: source.documentId,\n expectedVersion: source.version,\n markdown: source.markdown,\n sourcePath: source.sourcePath,\n })\n continue\n }\n\n const page = state.authoredById.get(source.documentId)\n const collection = configuration.types.find((type) => type.collection === page?.collection)\n\n if (!page || !parent || !collection) return yield* new DocumentNotFound({ documentId: source.documentId })\n\n if (command.action === 'document.duplicate' && !collection.canCreate)\n return yield* invalid('This collection does not allow new pages.')\n const destination = command.input.location\n\n if (parent.key === '/' && command.action === 'document.move')\n return yield* invalid('The home page cannot be moved.')\n const rootRelative = documentRelativePath(collection, { document: parent, sourcePath: root.sourcePath }) ?? ''\n\n const nextRelative =\n destination.kind === 'home' ? '' : [destination.parent, destination.slug].filter(Boolean).join('/')\n\n const copiesToAnotherLocale =\n command.action === 'document.duplicate' &&\n command.input.locale !== undefined &&\n command.input.locale !== parent.locale\n\n if (\n !copiesToAnotherLocale &&\n rootRelative &&\n (nextRelative === rootRelative || nextRelative.startsWith(`${rootRelative}/`))\n )\n return yield* invalid('Choose a destination outside this page and its subpages.')\n const relative = documentRelativePath(collection, { document: page, sourcePath: source.sourcePath }) ?? ''\n const suffix = source.documentId === root.documentId ? '' : relative.slice(rootRelative.length)\n const target = `${nextRelative}${suffix}`\n const segments = target.split('/').filter(Boolean)\n const slug = segments.pop()\n\n const location: DocumentLocation = slug\n ? Object.assign(\n { kind: 'entry' as const, slug: yield* decodeSlug(slug) },\n segments.length ? { parent: yield* decodeParent(segments.join('/')) } : undefined,\n )\n : { kind: 'home' }\n\n const destinationPage =\n command.action === 'document.duplicate' && command.input.locale\n ? Object.assign({}, page, { locale: command.input.locale })\n : page\n\n const sourcePath = yield* Effect.fromResult(planDocumentMove(configuration, destinationPage, location))\n\n const markdown = yield* relocateDocumentMarkdown(configuration, destinationPage, location, source.markdown).pipe(\n Effect.mapError(() => invalid('The page could not be copied to its new URL.')),\n )\n\n if (command.action === 'document.duplicate') {\n const documentId = yield* command.nextDocumentId\n plans.push({ action: 'document.create', documentId, markdown, sourcePath })\n } else {\n plans.push({\n action: 'document.move',\n documentId: source.documentId,\n expectedVersion: source.version,\n markdown,\n sourcePath,\n publishedVersion: source.publishedVersion,\n })\n }\n }\n\n const changed = new Set(plans.map((plan) => plan.documentId))\n\n const nextSources: DocumentCompilationSource[] = authoredSources(state.snapshot).filter(\n (source) => !changed.has(source.documentId),\n )\n\n if (command.action !== 'document.remove')\n for (const plan of plans) {\n if (nextSources.some((source) => source.sourcePath === plan.sourcePath))\n return yield* new DocumentPathConflict({ sourcePath: plan.sourcePath })\n nextSources.push({\n documentId: plan.documentId,\n draft: true,\n markdown: plan.markdown,\n sourcePath: plan.sourcePath,\n })\n }\n\n if (command.action === 'document.move' || command.action === 'document.duplicate') {\n const preliminary = yield* engine.compileAll({ sources: nextSources, previous: state.authored })\n const destinations = new Map<string, string>()\n\n for (let index = 0; index < sources.length; index++) {\n const original = sources[index]\n const plan = plans[index]\n const oldPage = original && state.authoredById.get(original.documentId)\n const newPage = plan && preliminary.documents.find((document) => document.id === plan.documentId)\n\n if (oldPage && newPage) destinations.set(oldPage.path, newPage.path)\n }\n\n const originals = command.action === 'document.move' ? state.snapshot.active : sources\n\n for (const source of originals) {\n const page = state.authoredById.get(source.documentId)\n\n if (!page) continue\n const body = rewriteDocumentRoutes(page, destinations, dependencies.components)\n\n if (!body) continue\n\n const index =\n command.action === 'document.duplicate'\n ? sources.findIndex((item) => item.documentId === source.documentId)\n : plans.findIndex((plan) => plan.documentId === source.documentId)\n\n const existing = index >= 0 ? plans[index] : undefined\n const projected = existing && preliminary.documents.find((document) => document.id === existing.documentId)\n\n const markdown = yield* renderDocumentMarkdown(\n Object.assign({}, body, { frontmatter: projected?.body.frontmatter ?? body.frontmatter }),\n ).pipe(Effect.mapError(() => invalid('Page links could not be updated.')))\n\n if (existing) plans[index] = { ...existing, markdown }\n else\n plans.push({\n action: 'document.update',\n documentId: source.documentId,\n expectedVersion: source.version,\n sourcePath: source.sourcePath,\n markdown,\n publishedVersion: source.publishedVersion,\n })\n }\n\n for (const plan of plans) {\n const index = nextSources.findIndex((source) => source.documentId === plan.documentId)\n const updated = { documentId: plan.documentId, sourcePath: plan.sourcePath, markdown: plan.markdown, draft: true }\n\n if (index >= 0) nextSources[index] = updated\n else nextSources.push(updated)\n }\n }\n\n const first = plans[0]\n\n if (!first) return yield* Effect.die(new Error('Empty subtree mutation.'))\n\n return {\n authored: yield* compileValidCatalog(engine, nextSources, state.authored),\n published:\n command.action === 'document.remove'\n ? yield* compileValidCatalog(\n engine,\n publishedSources(state.snapshot).filter((source) => !changed.has(source.documentId)),\n state.published,\n )\n : state.published,\n commitPlan: first,\n additionalPlans: plans.slice(1),\n }\n})\n\nconst decodeSlug = (value: string) =>\n Schema.decodeEffect(Slug)(value).pipe(Effect.mapError(() => invalid('Invalid URL ending.')))\n\nconst decodeParent = (value: string) =>\n Schema.decodeEffect(RelativeDocumentPath)(value).pipe(Effect.mapError(() => invalid('Invalid parent URL.')))\n\nfunction invalid(message: string) {\n return new DocumentValidationFailed({ issues: [{ code: 'document.invalid', severity: 'error', message }] })\n}\n","import type { DocumentCatalog, DocumentCompilationSource, DocumentEngine } from '@internal/document/DocumentEngine'\nimport { prepareTreeMutation, type TreeCommand } from './document-tree-mutation'\nimport type { DocumentConfiguration } from '@internal/protocol/Configuration'\nimport type {\n DocumentMutationResult,\n UnpublishDocumentInput,\n MoveDocumentInput,\n PublishDocumentInput,\n RemoveDocumentInput,\n RestoreDocumentInput,\n UndeleteDocumentInput,\n UpdateDocumentInput,\n} from '@internal/protocol/Documents'\nimport type { DocumentId, SourcePath } from '@internal/protocol/Documents'\nimport type { DocumentCommitPlan, DocumentStoreApi } from './document-store'\nimport type { DocumentState } from './document-state'\nimport {\n DocumentMutationResult as DocumentMutationResultSchema,\n DocumentNotFound,\n DocumentPathConflict,\n DocumentVersionConflict,\n} from '@internal/protocol/Documents'\nimport { Data, Effect } from 'effect'\nimport {\n authoredSources,\n compileValidCatalog,\n entryById,\n publishedSources,\n validateDocumentSources,\n} from './document-state'\n\nexport type DocumentLifecycleCommand =\n | {\n readonly action: 'document.create'\n readonly documentId: DocumentId\n readonly markdown: string\n readonly sourcePath: SourcePath\n }\n | { readonly action: 'document.update'; readonly input: UpdateDocumentInput }\n | { readonly action: 'document.move'; readonly input: MoveDocumentInput }\n | { readonly action: 'document.remove'; readonly input: RemoveDocumentInput }\n | { readonly action: 'document.restore'; readonly input: RestoreDocumentInput }\n | { readonly action: 'document.undelete'; readonly input: UndeleteDocumentInput }\n | { readonly action: 'document.publish'; readonly input: PublishDocumentInput }\n | { readonly action: 'document.unpublish'; readonly input: UnpublishDocumentInput }\n | Extract<TreeCommand, { readonly action: 'document.duplicate' }>\n\nexport interface DocumentLifecycleDependencies {\n readonly engine: DocumentEngine\n readonly configuration: DocumentConfiguration\n readonly repository: DocumentStoreApi\n readonly components?: ReadonlyArray<import('@internal/protocol/Configuration').ComponentDefinition>\n}\n\ntype PreparedDocumentMutation = Data.TaggedEnum<{\n Commit: {\n readonly authored: DocumentCatalog\n readonly published: DocumentCatalog\n readonly additionalPlans?: ReadonlyArray<DocumentCommitPlan>\n readonly commitPlan: DocumentCommitPlan\n }\n Unchanged: {\n readonly result: DocumentMutationResult\n }\n}>\n\nconst PreparedDocumentMutation = Data.taggedEnum<PreparedDocumentMutation>()\n\nexport const prepareDocumentMutation = Effect.fn('DocumentLifecycle.prepare')(function* (\n dependencies: DocumentLifecycleDependencies,\n state: DocumentState,\n command: DocumentLifecycleCommand,\n) {\n const { engine, repository } = dependencies\n\n if (\n command.action === 'document.move' ||\n command.action === 'document.remove' ||\n command.action === 'document.undelete' ||\n command.action === 'document.duplicate'\n )\n return PreparedDocumentMutation.Commit(yield* prepareTreeMutation(dependencies, state, command))\n const authored = authoredSources(state.snapshot)\n const published = publishedSources(state.snapshot)\n\n switch (command.action) {\n case 'document.create': {\n yield* ensurePathAvailable(state, command.sourcePath)\n\n const nextAuthored = [\n ...authored,\n {\n documentId: command.documentId,\n draft: true,\n markdown: command.markdown,\n sourcePath: command.sourcePath,\n },\n ]\n\n return PreparedDocumentMutation.Commit({\n authored: yield* compileValidCatalog(engine, nextAuthored, state.authored),\n published: state.published,\n commitPlan: {\n action: command.action,\n documentId: command.documentId,\n markdown: command.markdown,\n sourcePath: command.sourcePath,\n },\n })\n }\n\n case 'document.update': {\n const current = yield* requireActive(state, command.input.documentId)\n yield* requireVersion(current, command.input.expectedVersion)\n\n const nextAuthored = replaceSource(authored, {\n documentId: current.documentId,\n draft: true,\n markdown: command.input.markdown,\n sourcePath: current.sourcePath,\n })\n\n return PreparedDocumentMutation.Commit({\n authored: yield* compileValidCatalog(engine, nextAuthored, state.authored),\n published: state.published,\n commitPlan: {\n action: command.action,\n documentId: current.documentId,\n expectedVersion: command.input.expectedVersion,\n markdown: command.input.markdown,\n publishedVersion: current.publishedVersion,\n sourcePath: current.sourcePath,\n },\n })\n }\n\n case 'document.restore': {\n const current = yield* requireActive(state, command.input.documentId)\n yield* requireVersion(current, command.input.expectedVersion)\n const historical = yield* repository.revision(current.documentId, command.input.revisionId)\n\n const nextAuthored = replaceSource(authored, {\n documentId: current.documentId,\n draft: true,\n markdown: historical.markdown,\n sourcePath: current.sourcePath,\n })\n\n return PreparedDocumentMutation.Commit({\n authored: yield* compileValidCatalog(engine, nextAuthored, state.authored),\n published: state.published,\n commitPlan: {\n action: command.action,\n documentId: current.documentId,\n expectedVersion: command.input.expectedVersion,\n markdown: historical.markdown,\n publishedVersion: current.publishedVersion,\n revisionId: command.input.revisionId,\n sourcePath: current.sourcePath,\n },\n })\n }\n\n case 'document.unpublish': {\n const current = yield* requireActive(state, command.input.documentId)\n yield* requireVersion(current, command.input.expectedVersion)\n\n return PreparedDocumentMutation.Commit({\n authored: yield* compileValidCatalog(\n engine,\n replaceSource(authored, {\n documentId: current.documentId,\n draft: true,\n markdown: current.markdown,\n sourcePath: current.sourcePath,\n }),\n state.authored,\n ),\n published: yield* compileValidCatalog(engine, withoutDocument(published, current.documentId), state.published),\n commitPlan: {\n action: command.action,\n documentId: current.documentId,\n expectedVersion: current.version,\n markdown: current.markdown,\n sourcePath: current.sourcePath,\n revisionId: current.revisionId,\n },\n })\n }\n\n case 'document.publish': {\n const current = yield* requireActive(state, command.input.documentId)\n yield* requireVersion(current, command.input.expectedVersion)\n\n if (current.publishedVersion === current.version) {\n const entry = entryById(state, current.documentId)\n\n const result = {\n action: 'document.publish' as const,\n affectedDocumentIds: [current.documentId],\n documentId: current.documentId,\n generation: state.snapshot.generation,\n revisionId: current.revisionId,\n sourcePath: current.sourcePath,\n version: current.version,\n }\n\n return PreparedDocumentMutation.Unchanged({\n result: DocumentMutationResultSchema.make(Object.assign(result, entry === undefined ? undefined : { entry })),\n })\n }\n\n const source = {\n documentId: current.documentId,\n draft: false,\n markdown: current.markdown,\n sourcePath: current.sourcePath,\n } satisfies DocumentCompilationSource\n\n return PreparedDocumentMutation.Commit({\n authored: yield* compileValidCatalog(engine, replaceSource(authored, source), state.authored),\n published: yield* compileValidCatalog(engine, replaceSource(published, source), state.published),\n commitPlan: {\n action: command.action,\n documentId: current.documentId,\n expectedVersion: command.input.expectedVersion,\n markdown: current.markdown,\n revisionId: current.revisionId,\n sourcePath: current.sourcePath,\n },\n })\n }\n }\n})\n\nexport const validateDocumentUpdate = Effect.fn('DocumentLifecycle.validateUpdate')(function* (\n engine: DocumentEngine,\n state: DocumentState,\n input: UpdateDocumentInput,\n) {\n const current = yield* requireActive(state, input.documentId)\n yield* requireVersion(current, input.expectedVersion)\n\n const source = {\n documentId: current.documentId,\n draft: true,\n markdown: input.markdown,\n sourcePath: current.sourcePath,\n } satisfies DocumentCompilationSource\n\n return yield* validateDocumentSources(\n engine,\n replaceSource(authoredSources(state.snapshot), source),\n current.sourcePath,\n state.authored,\n )\n})\n\nfunction requireActive(state: DocumentState, documentId: DocumentId) {\n const source = state.activeById.get(documentId)\n\n return source ? Effect.succeed(source) : Effect.fail(new DocumentNotFound({ documentId }))\n}\n\nfunction requireVersion(\n source: DocumentState['snapshot']['active'][number],\n expectedVersion: DocumentState['snapshot']['active'][number]['version'],\n): Effect.Effect<void, DocumentVersionConflict> {\n return source.version === expectedVersion\n ? Effect.void\n : Effect.fail(\n new DocumentVersionConflict({\n actualVersion: source.version,\n documentId: source.documentId,\n expectedVersion,\n }),\n )\n}\n\nfunction ensurePathAvailable(\n state: DocumentState,\n sourcePath: SourcePath,\n exceptDocumentId?: DocumentId,\n): Effect.Effect<void, DocumentPathConflict> {\n return state.snapshot.active.some(\n (source) => source.sourcePath === sourcePath && source.documentId !== exceptDocumentId,\n )\n ? Effect.fail(new DocumentPathConflict({ sourcePath }))\n : Effect.void\n}\n\nfunction replaceSource(\n sources: ReadonlyArray<DocumentCompilationSource>,\n source: DocumentCompilationSource,\n): ReadonlyArray<DocumentCompilationSource> {\n return [...sources.filter((candidate) => candidate.documentId !== source.documentId), source]\n}\n\nfunction withoutDocument(\n sources: ReadonlyArray<DocumentCompilationSource>,\n documentId: DocumentId,\n): ReadonlyArray<DocumentCompilationSource> {\n return sources.filter((source) => source.documentId !== documentId)\n}\n","import type { DocumentCatalog, DocumentReference } from '@internal/document/DocumentEngine'\nimport type { DocumentId } from '@internal/protocol/Documents'\nimport type { MediaReference } from '@internal/protocol/Media'\nimport { MediaObjectKey, MediaReference as MediaReferenceSchema } from '@internal/protocol/Media'\n\nexport function projectMediaReferences(\n authored: DocumentCatalog,\n published: DocumentCatalog,\n documentId?: DocumentId,\n): ReadonlyArray<MediaReference> {\n const references = [...referencesFromCatalog(authored, documentId), ...referencesFromCatalog(published, documentId)]\n\n return [...new Map(references.map((reference) => [referenceIdentity(reference), reference])).values()]\n}\n\nfunction referencesFromCatalog(catalog: DocumentCatalog, documentId?: DocumentId): ReadonlyArray<MediaReference> {\n return catalog.references.all\n .filter(\n (reference) =>\n reference.target.kind === 'media' && (documentId === undefined || reference.source.documentId === documentId),\n )\n .map(toMediaReference)\n}\n\nfunction toMediaReference(reference: DocumentReference): MediaReference {\n if (reference.target.kind !== 'media') throw new Error('Expected a media reference.')\n\n return MediaReferenceSchema.make({\n documentId: reference.source.documentId,\n ...(reference.target.mediaId ? { mediaId: reference.target.mediaId } : undefined),\n nodePath: reference.nodePath,\n objectKey: MediaObjectKey.make(reference.target.key),\n path: reference.source.path,\n sourcePath: reference.source.sourcePath,\n })\n}\n\nfunction referenceIdentity(reference: MediaReference): string {\n return `${reference.documentId}:${reference.sourcePath}:${reference.nodePath.join('.')}:${reference.objectKey}`\n}\n","import type { DocumentCompilationSource, DocumentEngine } from '@internal/document/DocumentEngine'\nimport type {\n ContentApplyResult,\n ContentPlan,\n ContentPlanEntry,\n ContentTransferInput,\n} from '@internal/protocol/ContentTransfer'\nimport type { DocumentSource } from '@internal/protocol/Documents'\nimport type { DocumentCommitPlan } from './document-store'\nimport type { DocumentState } from './document-state'\nimport { ContentPlan as ContentPlanSchema, ContentTransferConflict } from '@internal/protocol/ContentTransfer'\nimport { DocumentId, DocumentValidationResult } from '@internal/protocol/Documents'\nimport { Crypto, DateTime, Effect } from 'effect'\nimport { authoredSources, publishedSources, validateDocumentSources } from './document-state'\n\nexport interface PlannedContentTransfer {\n readonly plan: ContentPlan\n readonly authoredSources: ReadonlyArray<DocumentCompilationSource>\n readonly publishedSources: ReadonlyArray<DocumentCompilationSource>\n readonly commitPlans: ReadonlyArray<DocumentCommitPlan>\n readonly counts: Pick<ContentApplyResult, 'created' | 'updated' | 'published' | 'unchanged'>\n}\n\n/** Plan all incoming sources against one document generation, including cross-document references. */\nexport const planContentTransfer = Effect.fn('ContentTransfer.plan')(function* (\n engine: DocumentEngine,\n state: DocumentState,\n input: ContentTransferInput,\n crypto: Crypto.Crypto,\n) {\n const currentByPath = new Map(state.snapshot.active.map((source) => [source.sourcePath, source]))\n const seen = new Set<string>()\n const commitPlans: DocumentCommitPlan[] = []\n const entries: ContentPlanEntry[] = []\n const authored = new Map(authoredSources(state.snapshot).map((source) => [source.sourcePath, source]))\n const published = new Map(publishedSources(state.snapshot).map((source) => [source.sourcePath, source]))\n const now = yield* DateTime.now\n let created = 0\n let updated = 0\n let publishedCount = 0\n let unchanged = 0\n\n for (const source of input.sources) {\n if (seen.has(source.sourcePath))\n return yield* new ContentTransferConflict({ message: `Duplicate source path: ${source.sourcePath}` })\n seen.add(source.sourcePath)\n const current: DocumentSource | undefined = currentByPath.get(source.sourcePath)\n const shouldPublish = input.publish && source.published\n\n const action = !current\n ? 'create'\n : current.markdown !== source.markdown\n ? input.overwrite\n ? 'update'\n : 'conflict'\n : shouldPublish && current.publishedVersion !== current.version\n ? 'publish'\n : 'unchanged'\n\n entries.push({ sourcePath: source.sourcePath, action, currentRevisionId: current?.revisionId ?? null })\n\n if (action === 'create' || action === 'update') {\n const documentId = current?.documentId ?? DocumentId.make(yield* crypto.randomUUIDv4.pipe(Effect.orDie))\n\n if (current) {\n commitPlans.push({\n action: 'document.update',\n documentId,\n expectedVersion: current.version,\n markdown: source.markdown,\n publish: shouldPublish,\n publishedVersion: current.publishedVersion,\n sourcePath: source.sourcePath,\n })\n updated++\n } else {\n commitPlans.push({\n action: 'document.create',\n documentId,\n markdown: source.markdown,\n publish: shouldPublish,\n sourcePath: source.sourcePath,\n })\n created++\n }\n\n if (shouldPublish) publishedCount++\n\n authored.set(source.sourcePath, {\n documentId,\n draft: !shouldPublish,\n markdown: source.markdown,\n sourcePath: source.sourcePath,\n })\n\n if (shouldPublish)\n published.set(source.sourcePath, {\n documentId,\n draft: false,\n markdown: source.markdown,\n publishedAt: now,\n sourcePath: source.sourcePath,\n })\n } else if (action === 'publish' && current) {\n commitPlans.push({\n action: 'document.publish',\n documentId: current.documentId,\n expectedVersion: current.version,\n markdown: current.markdown,\n revisionId: current.revisionId,\n sourcePath: current.sourcePath,\n })\n publishedCount++\n\n authored.set(source.sourcePath, {\n documentId: current.documentId,\n draft: false,\n markdown: current.markdown,\n sourcePath: current.sourcePath,\n })\n published.set(source.sourcePath, {\n documentId: current.documentId,\n draft: false,\n markdown: current.markdown,\n publishedAt: now,\n sourcePath: current.sourcePath,\n })\n } else if (action === 'unchanged') {\n unchanged++\n }\n }\n\n const firstPath = input.sources[0]?.sourcePath\n\n const authoredValidation = firstPath\n ? yield* validateDocumentSources(engine, [...authored.values()], firstPath, state.authored)\n : DocumentValidationResult.make({ issues: [], valid: true })\n\n const publishedValidation =\n input.publish && firstPath\n ? yield* validateDocumentSources(engine, [...published.values()], firstPath, state.published)\n : DocumentValidationResult.make({ issues: [], valid: true })\n\n const issues = [...authoredValidation.issues, ...publishedValidation.issues]\n\n const plan = ContentPlanSchema.make({\n generation: state.snapshot.generation,\n entries,\n issues,\n valid:\n authoredValidation.valid &&\n !entries.some((entry) => entry.action === 'conflict') &&\n !issues.some((issue) => issue.severity === 'error'),\n })\n\n return {\n plan,\n authoredSources: [...authored.values()],\n publishedSources: [...published.values()],\n commitPlans,\n counts: { created, updated, published: publishedCount, unchanged },\n } satisfies PlannedContentTransfer\n})\n","import type { AccessControlApi } from '../access-control'\nimport type { ActivityContext } from '@internal/protocol/Activity'\nimport type { DocumentCatalog } from '@internal/document/DocumentEngine'\nimport type { DocumentLifecycleCommand, DocumentLifecycleDependencies } from './document-lifecycle'\nimport type { DocumentCommitPlan, DocumentStoreApi } from './document-store'\nimport type { DocumentState } from './document-state'\nimport { DocumentMutationResult as DocumentMutationResultSchema } from '@internal/protocol/Documents'\nimport { Effect, Predicate } from 'effect'\nimport { prepareDocumentMutation } from './document-lifecycle'\nimport { projectMediaReferences } from './document-media-references'\nimport { entryById } from './document-state'\nimport * as DocumentStateModule from './document-state'\nimport { subtreeIds } from './document-tree-mutation'\n\ninterface ApprovedDocumentPlans {\n readonly repository: DocumentStoreApi\n readonly current: DocumentState\n readonly plans: readonly [DocumentCommitPlan, ...DocumentCommitPlan[]]\n readonly authored: DocumentCatalog\n readonly published: DocumentCatalog\n readonly activity: ActivityContext\n}\n\n/** Commit validated sources and their media references through one generation fence. */\nexport const commitApprovedDocumentPlans = Effect.fn('Documents.commitApprovedPlans')(function* (\n input: ApprovedDocumentPlans,\n) {\n const [plan, ...additionalPlans] = input.plans\n\n return yield* input.repository.commit({\n activity: input.activity,\n plan,\n additionalPlans,\n expectedGeneration: input.current.snapshot.generation,\n mediaReferences: input.plans.flatMap((candidate) =>\n projectMediaReferences(input.authored, input.published, candidate.documentId),\n ),\n })\n})\n\n/** Authorize every affected document before the adapter commits the approved plan atomically. */\nexport const commitDocumentMutation = Effect.fn('Documents.commitMutation')(function* (\n accessControl: AccessControlApi,\n dependencies: DocumentLifecycleDependencies,\n current: DocumentState,\n command: DocumentLifecycleCommand,\n activity: ActivityContext,\n) {\n if (\n command.action === 'document.move' ||\n command.action === 'document.remove' ||\n command.action === 'document.duplicate'\n ) {\n const ids =\n command.action === 'document.duplicate' && !command.input.includeChildren\n ? [command.input.documentId]\n : subtreeIds(current, command.input.documentId)\n\n for (const documentId of ids) {\n yield* accessControl.require(\n { actor: activity.actor, requestId: activity.requestId },\n { action: command.action, resource: { kind: 'document', documentId } },\n )\n }\n\n if (command.action === 'document.duplicate') {\n const source = current.authoredById.get(command.input.documentId)\n\n if (source)\n yield* accessControl.require(\n { actor: activity.actor, requestId: activity.requestId },\n {\n action: 'document.create',\n resource: {\n kind: 'collection',\n collection: source.collection,\n locale: command.input.locale ?? source.locale,\n },\n },\n )\n }\n }\n\n const prepared = yield* prepareDocumentMutation(dependencies, current, command)\n\n if (command.action === 'document.move' && Predicate.isTagged('Commit')(prepared)) {\n for (const plan of prepared.additionalPlans ?? [])\n if (plan.action === 'document.update')\n yield* accessControl.require(\n { actor: activity.actor, requestId: activity.requestId },\n { action: 'document.update', resource: { kind: 'document', documentId: plan.documentId } },\n )\n }\n\n if (command.action === 'document.undelete' && Predicate.isTagged('Commit')(prepared)) {\n for (const plan of [prepared.commitPlan, ...(prepared.additionalPlans ?? [])])\n yield* accessControl.require(\n { actor: activity.actor, requestId: activity.requestId },\n { action: 'document.undelete', resource: { kind: 'document', documentId: plan.documentId } },\n )\n }\n\n if (Predicate.isTagged('Unchanged')(prepared)) return { kind: 'unchanged' as const, result: prepared.result }\n\n const committed = yield* commitApprovedDocumentPlans({\n repository: dependencies.repository,\n current,\n plans: [prepared.commitPlan, ...(prepared.additionalPlans ?? [])],\n authored: prepared.authored,\n published: prepared.published,\n activity,\n })\n\n const next = DocumentStateModule.makeDocumentState(prepared.authored, prepared.published, committed.snapshot)\n const entry = entryById(next, committed.mutation.documentId)\n\n const result = DocumentMutationResultSchema.make(\n Object.assign({}, committed.mutation, entry === undefined ? undefined : { entry }),\n )\n\n return { kind: 'committed' as const, next, result }\n})\n","import type { ActivityContext } from '@internal/protocol/Activity'\nimport type {\n DocumentMutationResult,\n DocumentMediaUnavailable,\n DocumentNotFound,\n DocumentPathConflict,\n DocumentRevision,\n DocumentSource,\n DocumentVersionConflict,\n} from '@internal/protocol/Documents'\nimport type { DocumentId, RevisionId, SourcePath } from '@internal/protocol/Documents'\nimport type { MediaReference } from '@internal/protocol/Media'\nimport type { Effect } from 'effect'\nimport { DocumentGeneration } from '@internal/protocol/Documents'\nimport { Context, DateTime } from 'effect'\nimport { DocumentGenerationConflict, DocumentPersistenceError } from './document-failures'\n\nexport interface DocumentStoreSnapshot {\n readonly active: ReadonlyArray<DocumentSource>\n readonly deleted: ReadonlyArray<DeletedDocumentSource>\n readonly generation: DocumentGeneration\n readonly published: ReadonlyArray<DocumentSource>\n}\n\nexport interface DeletedDocumentSource extends DocumentSource {\n readonly trashBatchId?: DocumentSource['version']\n readonly title?: string\n readonly path?: import('@internal/protocol/Documents').PublicPath\n readonly deletedAt: DateTime.Utc\n}\n\nexport interface DocumentStoreHistoryCursor {\n readonly createdAt: DateTime.Utc\n readonly revisionId: RevisionId\n}\n\nexport interface DocumentStoreHistoryQuery {\n readonly documentId: DocumentId\n readonly cursor?: DocumentStoreHistoryCursor\n readonly limit: number\n}\n\nexport interface DocumentStoreHistoryPage {\n readonly revisions: ReadonlyArray<DocumentRevision>\n readonly next?: DocumentStoreHistoryCursor\n readonly total: number\n}\n\n/**\n * A product-approved persistence plan. The adapter applies these exact source\n * values after the generation fence succeeds; it does not repeat lifecycle\n * validation or reconstruct document content from its own snapshot.\n */\nexport type DocumentCommitPlan =\n | {\n readonly action: 'document.create'\n readonly documentId: DocumentId\n readonly markdown: string\n readonly publish?: boolean\n readonly sourcePath: SourcePath\n }\n | {\n readonly action: 'document.update'\n readonly documentId: DocumentId\n readonly expectedVersion: DocumentSource['version']\n readonly markdown: string\n readonly publish?: boolean\n readonly publishedVersion?: DocumentSource['publishedVersion']\n readonly sourcePath: SourcePath\n }\n | {\n readonly action: 'document.move'\n readonly documentId: DocumentId\n readonly expectedVersion: DocumentSource['version']\n readonly markdown: string\n readonly publishedVersion?: DocumentSource['publishedVersion']\n readonly sourcePath: SourcePath\n }\n | {\n readonly action: 'document.remove'\n readonly trashBatchId?: DocumentSource['version']\n readonly title?: string\n readonly path?: import('@internal/protocol/Documents').PublicPath\n readonly documentId: DocumentId\n readonly expectedVersion: DocumentSource['version']\n readonly markdown: string\n readonly sourcePath: SourcePath\n }\n | {\n readonly action: 'document.restore'\n readonly documentId: DocumentId\n readonly expectedVersion: DocumentSource['version']\n readonly markdown: string\n readonly publishedVersion?: DocumentSource['publishedVersion']\n readonly revisionId: RevisionId\n readonly sourcePath: SourcePath\n }\n | {\n readonly action: 'document.undelete'\n readonly documentId: DocumentId\n readonly expectedVersion: DocumentSource['version']\n readonly markdown: string\n readonly sourcePath: SourcePath\n }\n | {\n readonly action: 'document.publish' | 'document.unpublish'\n readonly documentId: DocumentId\n readonly expectedVersion: DocumentSource['version']\n readonly markdown: string\n readonly revisionId: RevisionId\n readonly sourcePath: SourcePath\n }\n\nexport interface DocumentStoreCommitInput {\n readonly activity?: ActivityContext\n readonly additionalPlans?: ReadonlyArray<DocumentCommitPlan>\n readonly plan: DocumentCommitPlan\n readonly expectedGeneration: DocumentGeneration\n /** Complete next authored/published media-reference union for every affected document. */\n readonly mediaReferences: ReadonlyArray<MediaReference>\n}\n\nexport interface DocumentStoreSynchronizeMediaReferencesInput {\n readonly expectedGeneration: DocumentGeneration\n /** Complete media-reference projection for the current document generation. */\n readonly references: ReadonlyArray<MediaReference>\n}\n\n/**\n * The snapshot must describe exactly the semantic state produced by `mutation`.\n * Core reuses the candidate catalogs it validated before commit, so adapters\n * must not rewrite source paths or Markdown while applying a command.\n */\nexport interface DocumentStoreCommitResult {\n readonly mutation: DocumentMutationResult\n readonly snapshot: DocumentStoreSnapshot\n}\n\nexport type DocumentStoreError =\n | DocumentGenerationConflict\n | DocumentMediaUnavailable\n | DocumentNotFound\n | DocumentPathConflict\n | DocumentPersistenceError\n | DocumentVersionConflict\n\n/**\n * Durable document state. A commit atomically advances the catalog generation,\n * revision/head state, and publication state, then returns that exact snapshot.\n * Calling `load` without a generation must always return a snapshot; passing a\n * generation may return `undefined` only when durable state has not advanced.\n */\nexport interface DocumentStoreApi {\n readonly commit: (input: DocumentStoreCommitInput) => Effect.Effect<DocumentStoreCommitResult, DocumentStoreError>\n readonly load: (\n after?: DocumentGeneration,\n ) => Effect.Effect<DocumentStoreSnapshot | undefined, DocumentPersistenceError>\n readonly revisions: (\n query: DocumentStoreHistoryQuery,\n ) => Effect.Effect<DocumentStoreHistoryPage, DocumentPersistenceError>\n readonly revision: (\n documentId: DocumentId,\n revisionId: RevisionId,\n ) => Effect.Effect<DocumentRevision, DocumentNotFound | DocumentPersistenceError>\n readonly synchronizeMediaReferences: (\n input: DocumentStoreSynchronizeMediaReferencesInput,\n ) => Effect.Effect<void, DocumentGenerationConflict | DocumentMediaUnavailable | DocumentPersistenceError>\n}\n\nexport class DocumentStore extends Context.Service<DocumentStore, DocumentStoreApi>()(\n '@internal/server/DocumentStore',\n) {}\n","import { DocumentGeneration } from '@internal/protocol/Documents'\nimport { Schema } from 'effect'\n\nexport class DocumentPersistenceError extends Schema.TaggedError<DocumentPersistenceError>()(\n 'Documents.PersistenceError',\n {\n operation: Schema.NonEmptyString,\n cause: Schema.Defect(),\n },\n) {}\n\nexport class DocumentGenerationConflict extends Schema.TaggedError<DocumentGenerationConflict>()(\n 'Documents.GenerationConflict',\n {\n expectedGeneration: DocumentGeneration,\n actualGeneration: DocumentGeneration,\n },\n) {}\n","import { flow, Encoding, Result, Schema } from 'effect'\n\ninterface CursorCodec<Payload, Cursor, Error> {\n readonly decode: (cursor: Cursor) => Result.Result<Payload, Error>\n readonly encode: (payload: Payload) => Cursor\n}\n\nexport function cursorCodec<Payload, Cursor extends string, Error>(\n schema: Schema.Codec<Payload, string>,\n makeCursor: (value: string) => Cursor,\n invalid: () => Error,\n): CursorCodec<Payload, Cursor, Error> {\n const decodeJson = Schema.decodeUnknownResult(schema)\n const encodeJson = flow(Schema.encodeResult(schema), Result.getOrThrow)\n\n return {\n decode: (cursor) => {\n const decoded = Encoding.decodeBase64UrlString(cursor)\n\n if (Result.isFailure(decoded)) return Result.fail(invalid())\n\n return decodeJson(decoded.success).pipe(Result.mapError(invalid))\n },\n encode: (payload) => makeCursor(Encoding.encodeBase64Url(encodeJson(payload))),\n }\n}\n","import type { AccessDenied, StudioRequestContext } from '@internal/protocol/AccessControl'\nimport type {\n CompareDocumentRevisionsInput,\n DocumentHistoryComparisonTooLarge,\n DocumentHistoryInvalidCursor,\n DocumentHistoryQuery,\n DocumentNotFound,\n DocumentRevision,\n DocumentRevisionChange,\n DocumentRevisionComparison,\n DocumentRevisionPage,\n} from '@internal/protocol/Documents'\nimport type { DocumentId } from '@internal/protocol/Documents'\nimport type { Effect } from 'effect'\nimport type { DocumentPersistenceError } from './document-failures'\nimport {\n DocumentHistoryComparisonTooLarge as DocumentHistoryComparisonTooLargeError,\n DocumentHistoryInvalidCursor as DocumentHistoryInvalidCursorError,\n DocumentRevisionComparison as DocumentRevisionComparisonSchema,\n DocumentRevisionPage as DocumentRevisionPageSchema,\n} from '@internal/protocol/Documents'\nimport { DocumentHistoryCursor as DocumentHistoryCursorSchema, RevisionId } from '@internal/protocol/Documents'\nimport { Effect as EffectRuntime, Schema } from 'effect'\nimport { diffArrays } from 'diff'\nimport type { AccessControlApi } from '../../AccessControl'\nimport type { DocumentStoreApi } from './document-store'\nimport { cursorCodec } from '../cursor'\n\nexport interface DocumentHistoryApi {\n readonly compare: (\n context: StudioRequestContext,\n input: CompareDocumentRevisionsInput,\n ) => Effect.Effect<\n DocumentRevisionComparison,\n AccessDenied | DocumentHistoryComparisonTooLarge | DocumentNotFound | DocumentPersistenceError\n >\n readonly list: (\n context: StudioRequestContext,\n query: DocumentHistoryQuery,\n ) => Effect.Effect<DocumentRevisionPage, AccessDenied | DocumentHistoryInvalidCursor | DocumentPersistenceError>\n readonly read: (\n context: StudioRequestContext,\n documentId: DocumentId,\n revisionId: DocumentRevision['revisionId'],\n ) => Effect.Effect<DocumentRevision, AccessDenied | DocumentNotFound | DocumentPersistenceError>\n}\n\nconst CursorPayload = Schema.Struct({\n createdAt: Schema.DateTimeUtcFromString,\n revisionId: RevisionId,\n})\n\nconst CursorJson = Schema.fromJsonString(CursorPayload)\n\nconst cursors = cursorCodec(\n CursorJson,\n (value) => DocumentHistoryCursorSchema.make(value),\n () => new DocumentHistoryInvalidCursorError(),\n)\n\nexport function documentHistoryCapability(\n accessControl: AccessControlApi,\n repository: DocumentStoreApi,\n): DocumentHistoryApi {\n const requireHistory = (context: StudioRequestContext, documentId: DocumentId) =>\n accessControl.require(context, {\n action: 'document.history',\n resource: { documentId, kind: 'document' },\n })\n\n const read = EffectRuntime.fn('Documents.history.read')(function* (\n context: StudioRequestContext,\n documentId: DocumentId,\n revisionId: DocumentRevision['revisionId'],\n ) {\n yield* requireHistory(context, documentId)\n\n return yield* repository.revision(documentId, revisionId)\n })\n\n const list = EffectRuntime.fn('Documents.history.list')(function* (\n context: StudioRequestContext,\n query: DocumentHistoryQuery,\n ) {\n yield* requireHistory(context, query.documentId)\n const cursor = query.cursor ? yield* EffectRuntime.fromResult(cursors.decode(query.cursor)) : undefined\n\n const page = yield* repository.revisions({\n cursor,\n documentId: query.documentId,\n limit: query.limit ?? 25,\n })\n\n const output = {\n revisions: page.revisions.map(({ markdown: _markdown, ...revision }) => revision),\n total: page.total,\n }\n\n return page.next\n ? DocumentRevisionPageSchema.make({ ...output, nextCursor: cursors.encode(page.next) })\n : DocumentRevisionPageSchema.make(output)\n })\n\n const compare = EffectRuntime.fn('Documents.history.compare')(function* (\n context: StudioRequestContext,\n input: CompareDocumentRevisionsInput,\n ) {\n yield* requireHistory(context, input.documentId)\n const from = yield* repository.revision(input.documentId, input.fromRevisionId)\n const to = yield* repository.revision(input.documentId, input.toRevisionId)\n const changes = yield* compareLines(from.markdown, to.markdown)\n\n return DocumentRevisionComparisonSchema.make({ changes, from, to })\n })\n\n return { compare, list, read }\n}\n\nconst MAXIMUM_COMPARISON_LINES = 10_000\n\nconst MAXIMUM_EDIT_LENGTH = 2_000\n\nconst comparisonTooLarge = () =>\n new DocumentHistoryComparisonTooLargeError({\n maximumEditLength: MAXIMUM_EDIT_LENGTH,\n maximumLines: MAXIMUM_COMPARISON_LINES,\n })\n\nconst compareLines = EffectRuntime.fn('Documents.history.compareLines')(function* (\n beforeMarkdown: string,\n afterMarkdown: string,\n) {\n const before = beforeMarkdown.split('\\n')\n const after = afterMarkdown.split('\\n')\n\n if (before.length > MAXIMUM_COMPARISON_LINES || after.length > MAXIMUM_COMPARISON_LINES) {\n return yield* comparisonTooLarge()\n }\n\n const diff = diffArrays(before, after, {\n maxEditLength: MAXIMUM_EDIT_LENGTH,\n oneChangePerToken: true,\n timeout: 100,\n })\n\n if (!diff) return yield* comparisonTooLarge()\n\n const changes: DocumentRevisionChange[] = []\n let beforeLine = 1\n let afterLine = 1\n\n for (const change of diff) {\n for (const line of change.value) {\n if (change.removed) {\n changes.push({ beforeLine, kind: 'removed', line })\n beforeLine += 1\n } else if (change.added) {\n changes.push({ afterLine, kind: 'added', line })\n afterLine += 1\n } else {\n changes.push({ afterLine, beforeLine, kind: 'equal', line })\n beforeLine += 1\n afterLine += 1\n }\n }\n }\n\n return changes\n})\n","import type { DocumentCatalog } from '@internal/document/DocumentEngine'\nimport type { DocumentConfiguration } from '@internal/protocol/Configuration'\nimport type {\n CompiledDocument,\n DocumentIssue,\n DocumentNavigationItem,\n DocumentNavigationQuery,\n DocumentQuerySort,\n DocumentQueryValue,\n DocumentSurround,\n PublishedDocumentLookup,\n PublishedDocumentNotFound,\n PublishedDocumentPage,\n PublishedDocumentQuery,\n PublishedDocumentSelection,\n PublishedDocumentSurroundQuery,\n} from '@internal/protocol/Documents'\nimport type { Effect } from 'effect'\nimport type { DocumentProjectionError } from './document-authoring'\nimport {\n DocumentNavigationItem as DocumentNavigationItemSchema,\n DocumentQueryScalar,\n DocumentSurround as DocumentSurroundSchema,\n PublishedDocumentNotFound as PublishedDocumentNotFoundError,\n PublishedDocumentPage as PublishedDocumentPageSchema,\n} from '@internal/protocol/Documents'\nimport { PublicPath } from '@internal/protocol/Documents'\nimport { Effect as EffectRuntime, Option, Schema } from 'effect'\n\ntype DocumentDeliveryError = DocumentProjectionError | PublishedDocumentNotFound\n\nexport interface DocumentDeliveryApi {\n readonly diagnostics: Effect.Effect<ReadonlyArray<DocumentIssue>, DocumentProjectionError>\n readonly navigation: (\n query: DocumentNavigationQuery,\n ) => Effect.Effect<ReadonlyArray<DocumentNavigationItem>, DocumentProjectionError>\n readonly query: (query: PublishedDocumentQuery) => Effect.Effect<PublishedDocumentPage, DocumentProjectionError>\n readonly read: (lookup: PublishedDocumentLookup) => Effect.Effect<CompiledDocument, DocumentDeliveryError>\n readonly surround: (\n lookup: PublishedDocumentLookup,\n query: PublishedDocumentSurroundQuery,\n ) => Effect.Effect<DocumentSurround, DocumentDeliveryError>\n}\n\nexport function documentDelivery(\n configuration: DocumentConfiguration,\n catalog: Effect.Effect<DocumentCatalog, DocumentProjectionError>,\n): DocumentDeliveryApi {\n const read = EffectRuntime.fn('Documents.delivery.read')(function* (lookup: PublishedDocumentLookup) {\n const current = yield* catalog\n const document = findDocument(current, lookup)\n\n return Option.isSome(document) ? document.value : yield* new PublishedDocumentNotFoundError({ lookup })\n })\n\n const query = EffectRuntime.fn('Documents.delivery.query')(function* (input: PublishedDocumentQuery) {\n return queryDocuments((yield* catalog).documents, input, { limit: input.limit, offset: input.offset ?? 0 })\n })\n\n const navigation = EffectRuntime.fn('Documents.delivery.navigation')(function* (input: DocumentNavigationQuery) {\n return createNavigation((yield* catalog).documents, input, configuration)\n })\n\n const surround = EffectRuntime.fn('Documents.delivery.surround')(function* (\n lookup: PublishedDocumentLookup,\n input: PublishedDocumentSurroundQuery,\n ) {\n const current = yield* catalog\n const document = findDocument(current, lookup)\n\n if (Option.isNone(document)) return yield* new PublishedDocumentNotFoundError({ lookup })\n\n const surroundQuery: PublishedDocumentSurroundQuery = Object.assign(\n {},\n { collection: input.collection ?? document.value.collection },\n input.locale === undefined && document.value.locale === undefined\n ? undefined\n : { locale: input.locale ?? document.value.locale },\n input.where === undefined ? undefined : { where: input.where },\n input.sort === undefined ? undefined : { sort: input.sort },\n )\n\n const page = queryDocuments(current.documents, surroundQuery)\n const index = page.items.findIndex((candidate) => candidate.id === document.value.id)\n\n return DocumentSurroundSchema.make({\n previous: index > 0 ? (page.items[index - 1] ?? null) : null,\n next: index >= 0 ? (page.items[index + 1] ?? null) : null,\n })\n })\n\n return {\n diagnostics: catalog.pipe(EffectRuntime.map((current) => current.issues)),\n navigation,\n query,\n read,\n surround,\n }\n}\n\nexport function findDocument(\n catalog: DocumentCatalog,\n lookup: PublishedDocumentLookup,\n): Option.Option<CompiledDocument> {\n switch (lookup.kind) {\n case 'id':\n return Option.fromNullishOr(catalog.documents.find((document) => document.id === lookup.documentId))\n case 'path':\n return catalog.findByPath(lookup.path)\n case 'key':\n return catalog\n .findByKey(lookup.key, lookup.locale)\n .pipe(Option.filter((document) => lookup.collection === undefined || document.collection === lookup.collection))\n }\n}\n\nfunction queryDocuments(\n documents: ReadonlyArray<CompiledDocument>,\n query: PublishedDocumentSelection,\n page?: { readonly limit: number; readonly offset: number },\n): PublishedDocumentPage {\n const filtered = documents.filter((document) => {\n if (query.collection !== undefined && document.collection !== query.collection) return false\n\n if (query.locale !== undefined && document.locale !== query.locale) return false\n\n return Object.entries(query.where ?? {}).every(([field, expected]) =>\n matchesValue(documentField(document, field), expected),\n )\n })\n\n const sorted = query.sort && query.sort.length > 0 ? sortDocuments(filtered, query.sort) : filtered\n const items = page ? sorted.slice(page.offset, page.offset + page.limit) : sorted\n\n return PublishedDocumentPageSchema.make({ items, total: filtered.length })\n}\n\nfunction createNavigation(\n documents: ReadonlyArray<CompiledDocument>,\n query: DocumentNavigationQuery,\n configuration: DocumentConfiguration,\n): ReadonlyArray<DocumentNavigationItem> {\n const locale = query.locale ?? configuration.locales?.defaultLocale\n\n const candidates = documents.filter(\n (document) =>\n (query.collection === undefined || document.collection === query.collection) &&\n (locale === undefined || document.locale === locale) &&\n document.data.navigation !== false,\n )\n\n const roots: MutableNavigationItem[] = []\n const itemsByKey = new Map<string, MutableNavigationItem>()\n const orderByItem = new Map<MutableNavigationItem, number>()\n\n for (const document of candidates) {\n if (document.key === '/') {\n const item = navigationItem(document)\n roots.push(item)\n orderByItem.set(item, Number.NEGATIVE_INFINITY)\n continue\n }\n\n const segments = document.key.slice(1).split('/')\n let parent: MutableNavigationItem | undefined\n\n for (let index = 0; index < segments.length; index += 1) {\n const key = PublicPath.make(`/${segments.slice(0, index + 1).join('/')}`)\n let item = itemsByKey.get(key)\n\n if (!item) {\n item = { children: [], key, title: titleFromSegment(segments[index] ?? '') }\n itemsByKey.set(key, item)\n\n if (parent) parent.children.push(item)\n else roots.push(item)\n }\n\n if (index === segments.length - 1) {\n const resolved = navigationItem(document)\n item.title = resolved.title\n item.path = resolved.path\n\n if (resolved.locale !== undefined) item.locale = resolved.locale\n else delete item.locale\n item.documentId = resolved.documentId\n orderByItem.set(item, navigationOrder(document))\n }\n\n parent = item\n }\n }\n\n sortNavigation(roots, orderByItem)\n\n return roots.map((item) => DocumentNavigationItemSchema.make(item))\n}\n\ninterface MutableNavigationItem {\n key: DocumentNavigationItem['key']\n title: string\n path?: DocumentNavigationItem['path']\n locale?: DocumentNavigationItem['locale']\n documentId?: DocumentNavigationItem['documentId']\n children: MutableNavigationItem[]\n}\n\nfunction navigationItem(document: CompiledDocument): MutableNavigationItem {\n const navigation = document.data.navigation\n const configuredTitle = Schema.is(Schema.JsonObject)(navigation) ? navigation.title : undefined\n\n return Object.assign(\n {\n children: [],\n documentId: document.id,\n key: document.key,\n path: document.path,\n title:\n Schema.is(Schema.String)(configuredTitle) && configuredTitle.trim() ? configuredTitle.trim() : document.title,\n },\n document.locale === undefined ? undefined : { locale: document.locale },\n )\n}\n\nfunction navigationOrder(document: CompiledDocument): number {\n const navigation = document.data.navigation\n const configuredOrder = Schema.is(Schema.JsonObject)(navigation) ? navigation.order : undefined\n const order = configuredOrder ?? document.data.order\n\n return Schema.is(Schema.Finite)(order) ? order : Number.POSITIVE_INFINITY\n}\n\nfunction sortNavigation(items: MutableNavigationItem[], orderByItem: Map<MutableNavigationItem, number>): void {\n items.sort((left, right) => {\n const byOrder =\n (orderByItem.get(left) ?? Number.POSITIVE_INFINITY) - (orderByItem.get(right) ?? Number.POSITIVE_INFINITY)\n\n return byOrder || left.title.localeCompare(right.title)\n })\n items.forEach((item) => sortNavigation(item.children, orderByItem))\n}\n\nfunction documentField(document: CompiledDocument, field: string): Schema.Json | undefined {\n switch (field) {\n case 'collection':\n return document.collection\n case 'description':\n return document.description\n case 'id':\n return document.id\n case 'key':\n return document.key\n case 'locale':\n return document.locale\n case 'path':\n return document.path\n case 'source.path':\n return document.source.path\n case 'title':\n return document.title\n default:\n return nestedValue(document.data, field.startsWith('data.') ? field.slice('data.'.length) : field)\n }\n}\n\nfunction nestedValue(value: Schema.JsonObject, path: string): Schema.Json | undefined {\n return path.split('.').reduce<Schema.Json | undefined>((current, segment) => {\n if (!Schema.is(Schema.JsonObject)(current)) return undefined\n\n return current[segment]\n }, value)\n}\n\nfunction matchesValue(actual: Schema.Json | undefined, expected: DocumentQueryValue): boolean {\n const expectedValues = Array.isArray(expected) ? expected : [expected]\n const actualValues = Array.isArray(actual) ? actual : [actual]\n\n return actualValues.some((value) => Schema.is(DocumentQueryScalar)(value) && expectedValues.includes(value))\n}\n\nfunction sortDocuments(\n documents: ReadonlyArray<CompiledDocument>,\n sorts: ReadonlyArray<DocumentQuerySort>,\n): ReadonlyArray<CompiledDocument> {\n return documents.toSorted((left, right) => {\n for (const sort of sorts) {\n const comparison = compareValues(documentField(left, sort.field), documentField(right, sort.field))\n\n if (comparison !== 0) return sort.direction === 'desc' ? -comparison : comparison\n }\n\n return 0\n })\n}\n\nfunction compareValues(left: Schema.Json | undefined, right: Schema.Json | undefined): number {\n if (left === right) return 0\n\n if (left === undefined || left === null) return 1\n\n if (right === undefined || right === null) return -1\n\n if (Schema.is(Schema.Finite)(left) && Schema.is(Schema.Finite)(right)) return left - right\n const leftText = Schema.is(Schema.String)(left) ? left : (JSON.stringify(left) ?? '')\n const rightText = Schema.is(Schema.String)(right) ? right : (JSON.stringify(right) ?? '')\n\n return leftText.localeCompare(rightText)\n}\n\nfunction titleFromSegment(segment: string): string {\n return segment.replace(/[-_]+/gu, ' ').replace(/^./u, (character) => character.toUpperCase())\n}\n","import type {\n DocumentEngineConfigurationInvalid,\n DocumentEngine,\n DocumentEngineOptions,\n} from '@internal/document/DocumentEngine'\nimport type { AccessDenied, DocumentAccessDecision, StudioRequestContext } from '@internal/protocol/AccessControl'\nimport type { ActivityContext } from '@internal/protocol/Activity'\nimport type { DocumentConfiguration } from '@internal/protocol/Configuration'\nimport type {\n DocumentBrowseQuery,\n DocumentSummary,\n DeletedDocument,\n DocumentIssue,\n DocumentMutationResult,\n CreateDocumentInput,\n MoveDocumentInput,\n DuplicateDocumentInput,\n UnpublishDocumentInput,\n PublishDocumentInput,\n RemoveDocumentInput,\n RestoreDocumentInput,\n UndeleteDocumentInput,\n UpdateDocumentInput,\n DocumentNotFound,\n DocumentSource,\n DocumentValidationResult,\n DocumentVersionConflict,\n CompiledDocument,\n} from '@internal/protocol/Documents'\nimport type { DocumentGeneration, DocumentId } from '@internal/protocol/Documents'\nimport type {\n ContentApplyInput,\n ContentApplyResult,\n ContentPlan,\n ContentSnapshot,\n ContentTransferInput,\n} from '@internal/protocol/ContentTransfer'\nimport type { MediaReference } from '@internal/protocol/Media'\nimport type {\n DocumentChangeSubscription,\n DocumentCreateError,\n DocumentMutationError,\n DocumentProjectionError,\n} from './document-authoring'\n\nexport type {\n DocumentChangeSubscription,\n DocumentCreateError,\n DocumentMutationError,\n DocumentProjectionError,\n} from './document-authoring'\n\nimport type { DocumentLifecycleCommand, DocumentLifecycleDependencies } from './document-lifecycle'\nimport type { DocumentStoreApi, DocumentStoreSnapshot } from './document-store'\nimport type { DocumentState } from './document-state'\nimport type { DocumentHistoryApi } from './document-history'\nimport type { DocumentDeliveryApi } from './document-delivery'\nimport { createDocumentEngine } from '@internal/document/DocumentEngine'\nimport { createInitialDocumentSource, planDocumentCreation } from '@internal/document/DocumentPlanning'\nimport { ActivityContext as ActivityContextSchema } from '@internal/protocol/Activity'\nimport {\n ContentApplyResult as ContentApplyResultSchema,\n ContentSnapshot as ContentSnapshotSchema,\n ContentTransferConflict,\n} from '@internal/protocol/ContentTransfer'\nimport {\n DocumentMediaUnavailable as DocumentMediaUnavailableError,\n DocumentNotFound as DocumentNotFoundError,\n DocumentValidationFailed,\n} from '@internal/protocol/Documents'\nimport { DocumentId as DocumentIdSchema } from '@internal/protocol/Documents'\nimport { Context, Crypto, Effect, Layer, PubSub, Ref, Schedule, Schema, Semaphore, Stream } from 'effect'\nimport type { Scope } from 'effect'\nimport { validateDocumentUpdate } from './document-lifecycle'\nimport { projectMediaReferences } from './document-media-references'\nimport { planContentTransfer } from './content-transfer'\nimport { commitApprovedDocumentPlans, commitDocumentMutation } from './document-mutation'\nimport { DocumentStore } from './document-store'\nimport { DocumentGenerationConflict, DocumentPersistenceError } from './document-failures'\nimport { authoringEntries, compileDocumentState, compileValidCatalog, deletedEntries } from './document-state'\nimport { AccessControl } from '../../AccessControl'\nimport { documentHistoryCapability } from './document-history'\nimport { documentDelivery } from './document-delivery'\n\nconst isDocumentGenerationConflict = Schema.is(DocumentGenerationConflict)\n\nconst isDocumentMediaUnavailable = Schema.is(DocumentMediaUnavailableError)\n\nconst CONTENT_MUTATION_BUFFER_CAPACITY = 16\n\ntype AuthorizedEffect<A, E> = Effect.Effect<A, AccessDenied | E>\n\nexport interface DocumentsApi {\n readonly contentSnapshot: (\n context: StudioRequestContext,\n ) => AuthorizedEffect<ContentSnapshot, DocumentProjectionError>\n readonly contentPlan: (\n context: StudioRequestContext,\n input: ContentTransferInput,\n ) => AuthorizedEffect<ContentPlan, DocumentProjectionError | ContentTransferConflict>\n readonly contentApply: (\n context: StudioRequestContext,\n input: ContentApplyInput,\n ) => AuthorizedEffect<ContentApplyResult, DocumentMutationError | ContentTransferConflict>\n readonly browse: (\n context: StudioRequestContext,\n query: DocumentBrowseQuery,\n ) => AuthorizedEffect<ReadonlyArray<DocumentSummary>, DocumentProjectionError>\n readonly create: (\n context: StudioRequestContext,\n input: CreateDocumentInput,\n ) => AuthorizedEffect<DocumentMutationResult, DocumentCreateError>\n readonly duplicate: (\n context: StudioRequestContext,\n input: DuplicateDocumentInput,\n ) => AuthorizedEffect<DocumentMutationResult, DocumentMutationError>\n readonly unpublish: (\n context: StudioRequestContext,\n input: UnpublishDocumentInput,\n ) => AuthorizedEffect<DocumentMutationResult, DocumentMutationError>\n readonly move: (\n context: StudioRequestContext,\n input: MoveDocumentInput,\n ) => AuthorizedEffect<DocumentMutationResult, DocumentMutationError>\n readonly publish: (\n context: StudioRequestContext,\n input: PublishDocumentInput,\n ) => AuthorizedEffect<DocumentMutationResult, DocumentMutationError>\n readonly read: (\n context: StudioRequestContext,\n documentId: DocumentId,\n ) => AuthorizedEffect<DocumentSource, DocumentNotFound | DocumentProjectionError>\n readonly remove: (\n context: StudioRequestContext,\n input: RemoveDocumentInput,\n ) => AuthorizedEffect<DocumentMutationResult, DocumentMutationError>\n readonly restore: (\n context: StudioRequestContext,\n input: RestoreDocumentInput,\n ) => AuthorizedEffect<DocumentMutationResult, DocumentMutationError>\n readonly trash: (\n context: StudioRequestContext,\n ) => AuthorizedEffect<ReadonlyArray<DeletedDocument>, DocumentProjectionError>\n readonly undelete: (\n context: StudioRequestContext,\n input: UndeleteDocumentInput,\n ) => AuthorizedEffect<DocumentMutationResult, DocumentMutationError>\n readonly update: (\n context: StudioRequestContext,\n input: UpdateDocumentInput,\n ) => AuthorizedEffect<DocumentMutationResult, DocumentMutationError>\n readonly validate: (\n context: StudioRequestContext,\n input: UpdateDocumentInput,\n ) => AuthorizedEffect<DocumentValidationResult, DocumentNotFound | DocumentProjectionError | DocumentVersionConflict>\n readonly historyCompare: DocumentHistoryApi['compare']\n readonly historyList: DocumentHistoryApi['list']\n readonly historyRead: DocumentHistoryApi['read']\n}\n\nexport class Documents extends Context.Service<Documents, DocumentsApi>()('@internal/server/Documents') {}\n\nexport type DocumentPreviewsApi = {\n readonly [Operation in keyof Omit<DocumentDeliveryApi, 'diagnostics'>]: (\n context: StudioRequestContext,\n ...args: Parameters<DocumentDeliveryApi[Operation]>\n ) => Effect.Effect<\n Effect.Success<ReturnType<DocumentDeliveryApi[Operation]>>,\n AccessDenied | Effect.Error<ReturnType<DocumentDeliveryApi[Operation]>>\n >\n}\n\nexport class DocumentPreviews extends Context.Service<DocumentPreviews, DocumentPreviewsApi>()(\n '@internal/server/DocumentPreviews',\n) {}\n\nexport interface PublishedDocumentsApi extends Omit<DocumentDeliveryApi, 'diagnostics'> {\n readonly snapshot: Effect.Effect<ReadonlyArray<CompiledDocument>, DocumentProjectionError>\n readonly diagnostics: (\n context: StudioRequestContext,\n ) => Effect.Effect<ReadonlyArray<DocumentIssue>, AccessDenied | DocumentProjectionError>\n}\n\nexport class PublishedDocuments extends Context.Service<PublishedDocuments, PublishedDocumentsApi>()(\n '@internal/server/PublishedDocuments',\n) {}\n\nexport interface DocumentMaintenanceApi {\n readonly mediaReferences: (\n documentId?: DocumentId,\n ) => Effect.Effect<ReadonlyArray<MediaReference>, DocumentProjectionError>\n readonly publish: (\n input: PublishDocumentInput,\n activity: ActivityContext,\n ) => Effect.Effect<DocumentMutationResult, DocumentMutationError>\n readonly read: (documentId: DocumentId) => Effect.Effect<DocumentSource, DocumentNotFound | DocumentProjectionError>\n readonly refresh: Effect.Effect<DocumentGeneration, DocumentProjectionError>\n readonly subscribeMutations: Effect.Effect<DocumentChangeSubscription, never, Scope.Scope>\n readonly validate: (\n input: UpdateDocumentInput,\n ) => Effect.Effect<DocumentValidationResult, DocumentNotFound | DocumentProjectionError | DocumentVersionConflict>\n}\n\nexport class DocumentMaintenance extends Context.Service<DocumentMaintenance, DocumentMaintenanceApi>()(\n '@internal/server/internal/DocumentMaintenance',\n) {}\n\nexport interface DocumentsOptions extends DocumentEngineOptions {}\n\nconst makeDocuments = Effect.fn('Documents.make')(function* (\n configuration: DocumentConfiguration,\n options: DocumentsOptions,\n) {\n const repository = yield* DocumentStore\n const accessControl = yield* AccessControl\n const crypto = yield* Crypto.Crypto\n const engine = yield* createDocumentEngine(configuration, options)\n const state = yield* Ref.make(yield* loadSynchronizedState(repository, engine))\n const semaphore = yield* Semaphore.make(1)\n\n const mutationEvents = yield* Effect.acquireRelease(\n PubSub.sliding<DocumentMutationResult>(CONTENT_MUTATION_BUFFER_CAPACITY),\n PubSub.shutdown,\n )\n\n const dependencies: DocumentLifecycleDependencies = {\n engine,\n configuration,\n repository,\n components: options.components,\n }\n\n const refreshUnlocked = Effect.fn('Documents.refreshUnlocked')(function* (force = false) {\n const current = yield* Ref.get(state)\n const snapshot = force ? yield* loadRequired(repository) : yield* repository.load(current.snapshot.generation)\n\n if (!snapshot || !generationIsAfter(snapshot.generation, current.snapshot.generation))\n return current.snapshot.generation\n // A snapshot can span multiple generations but carries neither their actions nor their order.\n // Updating the projection without inventing mutation events preserves exactly-once semantics.\n const refreshed = yield* compileDocumentState(engine, snapshot, current)\n yield* Ref.set(state, refreshed)\n\n return refreshed.snapshot.generation\n })\n\n const executeUnlocked = Effect.fn('Documents.execute')(function* (\n command: DocumentLifecycleCommand,\n activity: ActivityContext,\n ) {\n const attempt = Effect.gen(function* () {\n yield* refreshUnlocked()\n const current = yield* Ref.get(state)\n\n const outcome = yield* commitDocumentMutation(accessControl, dependencies, current, command, activity)\n\n if (outcome.kind === 'unchanged') return outcome.result\n\n yield* Ref.set(state, outcome.next)\n yield* PubSub.publish(mutationEvents, outcome.result)\n\n return outcome.result\n })\n\n return yield* attempt.pipe(\n Effect.tapError((error) => (isDocumentGenerationConflict(error) ? refreshUnlocked(true) : Effect.void)),\n Effect.retry({\n schedule: Schedule.recurs(3),\n while: isDocumentGenerationConflict,\n }),\n )\n })\n\n const runMutation = Effect.fn('Documents.runMutation')(function* (\n command: DocumentLifecycleCommand,\n activity: ActivityContext,\n reason: string | undefined,\n ) {\n const resolvedActivity = enrichActivity(activity, reason)\n\n return yield* semaphore.withPermits(1)(executeUnlocked(command, resolvedActivity))\n })\n\n const authored = semaphore\n .withPermits(1)(\n Effect.gen(function* () {\n yield* refreshUnlocked()\n\n return (yield* Ref.get(state)).authored\n }),\n )\n .pipe(Effect.withSpan('Documents.authored'))\n\n const browse = Effect.fn('Documents.browse')((query: DocumentBrowseQuery) =>\n semaphore.withPermits(1)(\n Effect.gen(function* () {\n yield* refreshUnlocked()\n\n return authoringEntries(yield* Ref.get(state), query)\n }),\n ),\n )\n\n const create = Effect.fn('Documents.create')(function* (input: CreateDocumentInput, activity: ActivityContext) {\n const collection = configuration.types.find((candidate) => candidate.collection === input.collection)\n\n if (collection && !collection.canCreate)\n return yield* new DocumentValidationFailed({\n issues: [\n {\n code: 'document.invalid',\n field: 'collection',\n message: `Document collection \"${input.collection}\" does not allow creation.`,\n severity: 'error',\n },\n ],\n })\n\n const plan = yield* Effect.fromResult(planDocumentCreation(configuration, input))\n const source = yield* createInitialDocumentSource(plan)\n const documentId = DocumentIdSchema.make(yield* crypto.randomUUIDv4.pipe(Effect.orDie))\n\n return yield* runMutation(\n {\n action: 'document.create',\n documentId,\n markdown: source.markdown,\n sourcePath: plan.sourcePath,\n },\n activity,\n input.reason,\n )\n })\n\n const duplicate = Effect.fn('Documents.duplicate')((input: DuplicateDocumentInput, activity: ActivityContext) =>\n runMutation(\n {\n action: 'document.duplicate',\n input,\n nextDocumentId: crypto.randomUUIDv4.pipe(\n Effect.orDie,\n Effect.map((value) => DocumentIdSchema.make(value)),\n ),\n },\n activity,\n input.reason,\n ),\n )\n\n const unpublish = Effect.fn('Documents.unpublish')((input: UnpublishDocumentInput, activity: ActivityContext) =>\n runMutation({ action: 'document.unpublish', input }, activity, input.reason),\n )\n\n const move = Effect.fn('Documents.move')((input: MoveDocumentInput, activity: ActivityContext) =>\n runMutation({ action: 'document.move', input }, activity, input.reason),\n )\n\n const subscribeMutations = Effect.gen(function* () {\n const subscription = yield* PubSub.subscribe(mutationEvents)\n\n const baseline = yield* semaphore.withPermits(1)(\n Ref.get(state).pipe(Effect.map((current) => current.snapshot.generation)),\n )\n\n return {\n baseline,\n mutations: Stream.fromSubscription(subscription).pipe(\n Stream.filter((mutation) => generationIsAfter(mutation.generation, baseline)),\n ),\n } satisfies DocumentChangeSubscription\n }).pipe(Effect.withSpan('Documents.subscribeMutations'))\n\n const publish = Effect.fn('Documents.publish')((input: PublishDocumentInput, activity: ActivityContext) =>\n runMutation({ action: 'document.publish', input }, activity, input.reason),\n )\n\n const published = semaphore\n .withPermits(1)(\n Effect.gen(function* () {\n yield* refreshUnlocked()\n\n return (yield* Ref.get(state)).published\n }),\n )\n .pipe(Effect.withSpan('Documents.published'))\n\n const read = Effect.fn('Documents.read')((documentId: DocumentId) =>\n semaphore.withPermits(1)(\n Effect.gen(function* () {\n yield* refreshUnlocked()\n const source = (yield* Ref.get(state)).activeById.get(documentId)\n\n return source || (yield* new DocumentNotFoundError({ documentId }))\n }),\n ),\n )\n\n const refresh = semaphore.withPermits(1)(refreshUnlocked()).pipe(Effect.withSpan('Documents.refresh'))\n\n const remove = Effect.fn('Documents.remove')((input: RemoveDocumentInput, activity: ActivityContext) =>\n runMutation({ action: 'document.remove', input }, activity, input.reason),\n )\n\n const restore = Effect.fn('Documents.restore')((input: RestoreDocumentInput, activity: ActivityContext) =>\n runMutation({ action: 'document.restore', input }, activity, input.reason),\n )\n\n const trash = semaphore\n .withPermits(1)(\n Effect.gen(function* () {\n yield* refreshUnlocked()\n\n return deletedEntries(yield* Ref.get(state))\n }),\n )\n .pipe(Effect.withSpan('Documents.trash'))\n\n const undelete = Effect.fn('Documents.undelete')((input: UndeleteDocumentInput, activity: ActivityContext) =>\n runMutation({ action: 'document.undelete', input }, activity, input.reason),\n )\n\n const update = Effect.fn('Documents.update')((input: UpdateDocumentInput, activity: ActivityContext) =>\n runMutation({ action: 'document.update', input }, activity, input.reason),\n )\n\n const validate = Effect.fn('Documents.validate')((input: UpdateDocumentInput) =>\n semaphore.withPermits(1)(\n Effect.gen(function* () {\n yield* refreshUnlocked()\n\n return yield* validateDocumentUpdate(engine, yield* Ref.get(state), input)\n }),\n ),\n )\n\n const history = documentHistoryCapability(accessControl, repository)\n const delivery = documentDelivery(configuration, published)\n const document = (documentId: DocumentId) => ({ documentId, kind: 'document' as const })\n\n const requireThen = <A, E>(\n context: StudioRequestContext,\n action: DocumentAccessDecision['action'],\n resource: DocumentAccessDecision['resource'],\n effect: () => Effect.Effect<A, E>,\n ) => accessControl.require(context, { action, resource }).pipe(Effect.andThen(effect))\n\n const requireContentTransfer = (context: StudioRequestContext) =>\n accessControl.require(context, { action: 'document.transfer', resource: { kind: 'catalog' } })\n\n const contentSnapshot = (context: StudioRequestContext) =>\n requireContentTransfer(context).pipe(\n Effect.andThen(\n semaphore.withPermits(1)(\n Effect.gen(function* () {\n yield* refreshUnlocked()\n const current = yield* Ref.get(state)\n\n return ContentSnapshotSchema.make({\n version: 1,\n sources: current.snapshot.active\n .map((source) => ({\n documentId: source.documentId,\n sourcePath: source.sourcePath,\n markdown: source.markdown,\n published: source.publishedVersion === source.version,\n }))\n .sort((left, right) => left.sourcePath.localeCompare(right.sourcePath)),\n })\n }),\n ),\n ),\n )\n\n const contentPlan = (context: StudioRequestContext, input: ContentTransferInput) =>\n requireContentTransfer(context).pipe(\n Effect.andThen(\n semaphore.withPermits(1)(\n Effect.gen(function* () {\n yield* refreshUnlocked()\n\n return (yield* planContentTransfer(engine, yield* Ref.get(state), input, crypto)).plan\n }),\n ),\n ),\n )\n\n const contentApply = (context: StudioRequestContext, input: ContentApplyInput) =>\n requireContentTransfer(context).pipe(\n Effect.andThen(\n semaphore.withPermits(1)(\n Effect.gen(function* () {\n yield* refreshUnlocked()\n const current = yield* Ref.get(state)\n\n if (current.snapshot.generation !== input.expectedGeneration)\n return yield* new ContentTransferConflict({\n message: 'Content changed since the plan. Run content plan again.',\n })\n const planned = yield* planContentTransfer(engine, current, input, crypto)\n\n if (planned.plan.entries.some((entry) => entry.action === 'conflict'))\n return yield* new ContentTransferConflict({\n message: 'Destination content differs. Use --overwrite after reviewing the plan.',\n })\n\n if (!planned.plan.valid) return yield* new DocumentValidationFailed({ issues: planned.plan.issues })\n\n if (planned.commitPlans.length === 0)\n return ContentApplyResultSchema.make({\n ...planned.counts,\n generation: current.snapshot.generation,\n })\n\n const authored = yield* compileValidCatalog(engine, planned.authoredSources, current.authored)\n const publishedCatalog = yield* compileValidCatalog(engine, planned.publishedSources, current.published)\n const [first, ...additionalPlans] = planned.commitPlans\n\n if (!first) throw new Error('Content import requires a commit plan.')\n\n const committed = yield* commitApprovedDocumentPlans({\n repository,\n current,\n plans: [first, ...additionalPlans],\n authored,\n published: publishedCatalog,\n activity: requestActivity(context, 'CMS content import'),\n }).pipe(\n Effect.mapError((error) =>\n isDocumentGenerationConflict(error)\n ? new ContentTransferConflict({ message: 'Content changed since the plan. Run content plan again.' })\n : error,\n ),\n )\n\n yield* Ref.set(state, yield* compileDocumentState(engine, committed.snapshot, current))\n yield* PubSub.publish(mutationEvents, committed.mutation)\n\n return ContentApplyResultSchema.make({\n ...planned.counts,\n generation: committed.snapshot.generation,\n })\n }),\n ),\n ),\n )\n\n const documents = Documents.of({\n contentSnapshot,\n contentPlan,\n contentApply,\n browse: (context, query) =>\n requireThen(\n context,\n 'document.browse',\n query.collection\n ? { collection: query.collection, kind: 'collection', locale: query.locale }\n : { kind: 'catalog' },\n () => browse(query),\n ),\n create: (context, input) =>\n requireThen(\n context,\n 'document.create',\n { collection: input.collection, kind: 'collection', locale: input.locale },\n () => create(input, requestActivity(context, input.reason)),\n ),\n historyCompare: history.compare,\n historyList: history.list,\n historyRead: history.read,\n duplicate: (context, input) =>\n requireThen(context, 'document.duplicate', document(input.documentId), () =>\n duplicate(input, requestActivity(context, input.reason)),\n ),\n unpublish: (context, input) =>\n requireThen(context, 'document.unpublish', document(input.documentId), () =>\n unpublish(input, requestActivity(context, input.reason)),\n ),\n move: (context, input) =>\n requireThen(context, 'document.move', document(input.documentId), () =>\n move(input, requestActivity(context, input.reason)),\n ),\n publish: (context, input) =>\n requireThen(context, 'document.publish', document(input.documentId), () =>\n publish(input, requestActivity(context, input.reason)),\n ),\n read: (context, documentId) => requireThen(context, 'document.read', document(documentId), () => read(documentId)),\n remove: (context, input) =>\n requireThen(context, 'document.remove', document(input.documentId), () =>\n remove(input, requestActivity(context, input.reason)),\n ),\n restore: (context, input) =>\n requireThen(context, 'document.restore', document(input.documentId), () =>\n restore(input, requestActivity(context, input.reason)),\n ),\n trash: (context) => requireThen(context, 'document.trash', { kind: 'catalog' }, () => trash),\n undelete: (context, input) =>\n requireThen(context, 'document.undelete', document(input.documentId), () =>\n undelete(input, requestActivity(context, input.reason)),\n ),\n update: (context, input) =>\n requireThen(context, 'document.update', document(input.documentId), () =>\n update(input, requestActivity(context, input.reason)),\n ),\n validate: (context, input) =>\n requireThen(context, 'document.validate', document(input.documentId), () => validate(input)),\n })\n\n const draftDelivery = documentDelivery(configuration, authored)\n\n const previews = DocumentPreviews.of({\n read: (context, lookup) =>\n requireThen(context, 'document.browse', { kind: 'catalog' }, () => draftDelivery.read(lookup)),\n query: (context, query) =>\n requireThen(context, 'document.browse', { kind: 'catalog' }, () => draftDelivery.query(query)),\n navigation: (context, query) =>\n requireThen(context, 'document.browse', { kind: 'catalog' }, () => draftDelivery.navigation(query)),\n surround: (context, lookup, query) =>\n requireThen(context, 'document.browse', { kind: 'catalog' }, () => draftDelivery.surround(lookup, query)),\n })\n\n const publishedService = PublishedDocuments.of({\n navigation: delivery.navigation,\n query: delivery.query,\n read: delivery.read,\n snapshot: published.pipe(Effect.map((catalog) => catalog.documents)),\n surround: delivery.surround,\n diagnostics: (context) =>\n accessControl\n .require(context, { action: 'document.browse', resource: { kind: 'catalog' } })\n .pipe(Effect.andThen(delivery.diagnostics)),\n })\n\n const maintenance = DocumentMaintenance.of({\n mediaReferences: (documentId) =>\n semaphore.withPermits(1)(\n Effect.gen(function* () {\n yield* refreshUnlocked()\n const current = yield* Ref.get(state)\n\n return projectMediaReferences(current.authored, current.published, documentId)\n }),\n ),\n publish,\n read,\n refresh,\n subscribeMutations,\n validate,\n })\n\n return { documents, maintenance, previews, publishedDocuments: publishedService }\n})\n\nexport function documentsLayer(\n configuration: DocumentConfiguration,\n options: DocumentsOptions,\n): Layer.Layer<\n Documents | DocumentMaintenance | DocumentPreviews | PublishedDocuments,\n DocumentEngineConfigurationInvalid | DocumentProjectionError,\n AccessControl | DocumentStore | Crypto.Crypto\n> {\n return Layer.effectContext(\n makeDocuments(configuration, options).pipe(\n Effect.map(({ documents, maintenance, previews, publishedDocuments }) =>\n Context.empty().pipe(\n Context.add(Documents, documents),\n Context.add(DocumentMaintenance, maintenance),\n Context.add(DocumentPreviews, previews),\n Context.add(PublishedDocuments, publishedDocuments),\n ),\n ),\n ),\n )\n}\n\nfunction loadRequired(repository: DocumentStoreApi): Effect.Effect<DocumentStoreSnapshot, DocumentPersistenceError> {\n return repository.load().pipe(\n Effect.filterOrFail(\n (snapshot) => snapshot !== undefined,\n () =>\n new DocumentPersistenceError({\n cause: new Error('DocumentStore returned no initial snapshot.'),\n operation: 'DocumentStore.load',\n }),\n ),\n )\n}\n\nfunction loadSynchronizedState(\n repository: DocumentStoreApi,\n engine: DocumentEngine,\n): Effect.Effect<DocumentState, DocumentProjectionError> {\n const attempt = Effect.gen(function* () {\n const snapshot = yield* loadRequired(repository)\n const state = yield* compileDocumentState(engine, snapshot)\n yield* repository.synchronizeMediaReferences({\n expectedGeneration: snapshot.generation,\n references: projectMediaReferences(state.authored, state.published),\n })\n\n return state\n })\n\n return attempt.pipe(\n Effect.retry({ schedule: Schedule.recurs(3), while: isDocumentGenerationConflict }),\n Effect.mapError((error) =>\n isDocumentGenerationConflict(error) || isDocumentMediaUnavailable(error)\n ? new DocumentPersistenceError({ cause: error, operation: 'Documents.synchronizeMediaReferences' })\n : error,\n ),\n )\n}\n\nfunction generationIsAfter(candidate: DocumentGeneration, current: DocumentGeneration): boolean {\n return BigInt(candidate) > BigInt(current)\n}\n\nfunction enrichActivity(activity: ActivityContext, reason: string | undefined): ActivityContext {\n return ActivityContextSchema.make(Object.assign({}, activity, reason === undefined ? undefined : { reason }))\n}\n\nfunction requestActivity(context: StudioRequestContext, reason: string | undefined): ActivityContext {\n return ActivityContextSchema.make(\n Object.assign(\n { actor: context.actor, requestId: context.requestId },\n reason === undefined ? undefined : { reason },\n ),\n )\n}\n","import type { ActivityContext } from '@internal/protocol/Activity'\nimport type {\n GlobalSeoSettings,\n SeoMediaUnavailable,\n SeoRevision,\n SeoVersion,\n SeoVersionConflict,\n} from '@internal/protocol/Seo'\nimport { Context, Effect, Schema } from 'effect'\n\nexport class SeoPersistenceError extends Schema.TaggedError<SeoPersistenceError>()('Seo.PersistenceError', {\n operation: Schema.NonEmptyString,\n cause: Schema.Defect(),\n}) {}\n\nexport interface SeoStoreSnapshot {\n readonly working: SeoRevision\n readonly published?: SeoRevision\n}\n\nexport interface SeoStoreSaveInput {\n readonly activity: ActivityContext\n readonly expectedVersion: SeoVersion\n readonly settings: GlobalSeoSettings\n}\n\nexport interface SeoStorePublishInput {\n readonly activity: ActivityContext\n readonly expectedVersion: SeoVersion\n}\n\nexport type SeoStoreMutationError = SeoMediaUnavailable | SeoPersistenceError | SeoVersionConflict\n\nexport interface SeoStoreApi {\n readonly initialize: (defaults: GlobalSeoSettings) => Effect.Effect<SeoStoreSnapshot, SeoPersistenceError>\n readonly load: Effect.Effect<SeoStoreSnapshot | undefined, SeoPersistenceError>\n readonly publish: (input: SeoStorePublishInput) => Effect.Effect<SeoStoreSnapshot, SeoStoreMutationError>\n readonly save: (input: SeoStoreSaveInput) => Effect.Effect<SeoStoreSnapshot, SeoStoreMutationError>\n}\n\nexport class SeoStore extends Context.Service<SeoStore, SeoStoreApi>()('@internal/server/SeoStore') {}\n","import type { AccessDenied, StudioRequestContext } from '@internal/protocol/AccessControl'\nimport type { ActivityContext } from '@internal/protocol/Activity'\nimport type {\n GlobalSeoSettings,\n PublishSeoInput,\n SaveSeoInput,\n SeoCapabilities,\n SeoConfirmationRequired,\n SeoMediaUnavailable,\n SeoMutationResult,\n SeoSnapshot,\n SeoState,\n SeoVersionConflict,\n SitemapEntry,\n} from '@internal/protocol/Seo'\nimport type { CompiledDocument } from '@internal/protocol/Documents'\nimport type { SeoPersistenceError } from './seo-store'\nimport {\n GlobalSeoSettings as GlobalSeoSettingsSchema,\n SeoCanonicalOrigin,\n SeoCapabilities as SeoCapabilitiesSchema,\n SeoConfirmationRequired as SeoConfirmationRequiredError,\n SeoMutationResult as SeoMutationResultSchema,\n SeoSnapshot as SeoSnapshotSchema,\n SeoState as SeoStateSchema,\n SitemapEntry as SitemapEntrySchema,\n} from '@internal/protocol/Seo'\nimport { CompiledDocument as CompiledDocumentSchema } from '@internal/protocol/Documents'\nimport { resolveDocumentSeo } from '@internal/document/Seo'\nimport { Context, Effect, Layer } from 'effect'\nimport { AccessControl } from '../../AccessControl'\nimport { PublishedDocuments } from '../documents/documents'\nimport type { DocumentProjectionError } from '../documents/document-authoring'\nimport { SeoStore } from './seo-store'\n\ntype SeoMutationError =\n | AccessDenied\n | SeoConfirmationRequired\n | SeoMediaUnavailable\n | SeoPersistenceError\n | SeoVersionConflict\n\nexport interface SeoApi {\n readonly publish: (\n context: StudioRequestContext,\n input: PublishSeoInput,\n ) => Effect.Effect<SeoMutationResult, SeoMutationError>\n readonly read: (context: StudioRequestContext) => Effect.Effect<SeoState, AccessDenied | SeoPersistenceError>\n readonly save: (\n context: StudioRequestContext,\n input: SaveSeoInput,\n ) => Effect.Effect<SeoMutationResult, Exclude<SeoMutationError, SeoConfirmationRequired>>\n}\n\nexport class Seo extends Context.Service<Seo, SeoApi>()('@internal/server/Seo') {}\n\nexport interface PublishedSeoApi {\n readonly read: Effect.Effect<SeoSnapshot, SeoPersistenceError>\n}\n\nexport class PublishedSeo extends Context.Service<PublishedSeo, PublishedSeoApi>()('@internal/server/PublishedSeo') {}\n\nexport interface PreviewSeoApi {\n readonly read: Effect.Effect<SeoSnapshot, SeoPersistenceError>\n}\n\nexport class PreviewSeo extends Context.Service<PreviewSeo, PreviewSeoApi>()('@internal/server/PreviewSeo') {}\n\nexport interface SeoDeliveryApi {\n readonly previewDocument: (\n document: CompiledDocument,\n ) => Effect.Effect<CompiledDocument, SeoPersistenceError | DocumentProjectionError>\n readonly publishedDocument: (\n document: CompiledDocument,\n ) => Effect.Effect<CompiledDocument, SeoPersistenceError | DocumentProjectionError>\n readonly sitemap: Effect.Effect<ReadonlyArray<SitemapEntry>, DocumentProjectionError | SeoPersistenceError>\n}\n\nexport class SeoDelivery extends Context.Service<SeoDelivery, SeoDeliveryApi>()('@internal/server/SeoDelivery') {}\n\nexport interface SeoOptions {\n readonly capabilities: SeoCapabilities\n readonly defaults: GlobalSeoSettings\n}\n\nexport function makeDefaultSeoOptions(baseUrl: string): SeoOptions {\n const url = new URL(baseUrl)\n\n return {\n capabilities: SeoCapabilitiesSchema.make({\n generatedSocialImageTemplateIds: [],\n identityTypes: ['Person', 'Organization', 'LocalBusiness'],\n structuredDataTypes: ['WebPage', 'Article'],\n }),\n defaults: GlobalSeoSettingsSchema.make({\n canonicalOrigin: SeoCanonicalOrigin.make(url.origin),\n follow: true,\n index: true,\n siteName: url.hostname,\n }),\n }\n}\n\nexport const seoLayer = (\n options: SeoOptions,\n): Layer.Layer<Seo | PublishedSeo | PreviewSeo, never, AccessControl | SeoStore> =>\n Layer.effectContext(\n Effect.gen(function* () {\n const accessControl = yield* AccessControl\n const store = yield* SeoStore\n\n const load = Effect.fn('Seo.load')(function* () {\n return (yield* store.load) ?? (yield* store.initialize(options.defaults))\n })\n\n const state = Effect.fn('Seo.state')(function* () {\n const snapshot = yield* load()\n\n return makeState(snapshot, options.capabilities)\n })\n\n const requireAdministrator = (context: StudioRequestContext, action: 'seo.read' | 'seo.save' | 'seo.publish') =>\n accessControl.require(context, { action, resource: { kind: 'seo' } })\n\n const read: SeoApi['read'] = Effect.fn('Seo.read')(function* (context) {\n yield* requireAdministrator(context, 'seo.read')\n\n return yield* state()\n })\n\n const save: SeoApi['save'] = Effect.fn('Seo.save')(function* (context, input) {\n yield* requireAdministrator(context, 'seo.save')\n\n const snapshot = yield* store.save({\n activity: requestActivity(context, input.reason),\n expectedVersion: input.expectedVersion,\n settings: input.settings,\n })\n\n return SeoMutationResultSchema.make({\n action: 'seo.save',\n state: makeState(snapshot, options.capabilities),\n })\n })\n\n const publish: SeoApi['publish'] = Effect.fn('Seo.publish')(function* (context, input) {\n yield* requireAdministrator(context, 'seo.publish')\n\n const snapshot = yield* load()\n\n const confirmationChanges = productionChanges(\n snapshot.published?.settings ?? options.defaults,\n snapshot.working.settings,\n )\n\n if (confirmationChanges.length > 0 && input.confirmedSiteWideChange !== true) {\n return yield* new SeoConfirmationRequiredError({ changes: confirmationChanges })\n }\n\n const published = yield* store.publish({\n activity: requestActivity(context, input.reason),\n expectedVersion: input.expectedVersion,\n })\n\n return SeoMutationResultSchema.make({\n action: 'seo.publish',\n state: makeState(published, options.capabilities),\n })\n })\n\n const seo = Seo.of({ publish, read, save })\n\n const publishedSeo = PublishedSeo.of({\n read: load().pipe(\n Effect.map((snapshot) =>\n SeoSnapshotSchema.make({\n capabilities: options.capabilities,\n revision: snapshot.published ?? snapshot.working,\n }),\n ),\n ),\n })\n\n const previewSeo = PreviewSeo.of({\n read: load().pipe(\n Effect.map((snapshot) =>\n SeoSnapshotSchema.make({ capabilities: options.capabilities, revision: snapshot.working }),\n ),\n ),\n })\n\n return Context.empty().pipe(\n Context.add(Seo, seo),\n Context.add(PublishedSeo, publishedSeo),\n Context.add(PreviewSeo, previewSeo),\n )\n }),\n )\n\nexport const seoDeliveryLayer: Layer.Layer<SeoDelivery, never, PreviewSeo | PublishedDocuments | PublishedSeo> =\n Layer.effect(\n SeoDelivery,\n Effect.gen(function* () {\n const previews = yield* PreviewSeo\n const published = yield* PublishedSeo\n const documents = yield* PublishedDocuments\n\n const alternatives = (document: CompiledDocument) =>\n documents.snapshot.pipe(\n Effect.map((snapshot) =>\n snapshot.flatMap((candidate) =>\n candidate.key === document.key && candidate.locale !== undefined\n ? [{ locale: candidate.locale, path: candidate.path }]\n : [],\n ),\n ),\n )\n\n const resolveWith = (\n document: CompiledDocument,\n snapshot: SeoSnapshot,\n localized: NonNullable<CompiledDocument['alternatives']>,\n ) =>\n CompiledDocumentSchema.make(\n Object.assign({}, document, {\n alternatives: localized,\n resolvedSeo: resolveDocumentSeo({\n capabilities: snapshot.capabilities,\n document,\n global: snapshot.revision.settings,\n }),\n }),\n )\n\n const publishedDocument: SeoDeliveryApi['publishedDocument'] = Effect.fn('SeoDelivery.publishedDocument')(\n (document) =>\n Effect.all({ snapshot: published.read, alternatives: alternatives(document) }).pipe(\n Effect.map(({ alternatives, snapshot }) => resolveWith(document, snapshot, alternatives)),\n ),\n )\n\n const previewDocument: SeoDeliveryApi['previewDocument'] = Effect.fn('SeoDelivery.previewDocument')((document) =>\n Effect.all({ snapshot: previews.read, alternatives: alternatives(document) }).pipe(\n Effect.map(({ alternatives, snapshot }) => resolveWith(document, snapshot, alternatives)),\n ),\n )\n\n const sitemap = Effect.gen(function* () {\n const snapshot = yield* published.read\n const all = yield* documents.snapshot\n\n const resolved = all.flatMap((document) => {\n const resolvedDocument = resolveWith(document, snapshot, [])\n\n return resolvedDocument.resolvedSeo?.index === true && resolvedDocument.source.publishedAt !== undefined\n ? [resolvedDocument]\n : []\n })\n\n const localesByKey = new Map<\n string,\n Array<{ readonly locale: NonNullable<CompiledDocument['locale']>; readonly loc: CompiledDocument['path'] }>\n >()\n\n for (const document of resolved) {\n if (document.locale === undefined) continue\n const alternatives = localesByKey.get(document.key) ?? []\n alternatives.push({ locale: document.locale, loc: document.path })\n localesByKey.set(document.key, alternatives)\n }\n\n return resolved\n .flatMap((document) => {\n const publishedAt = document.source.publishedAt\n\n if (publishedAt === undefined) return []\n const alternatives = localesByKey.get(document.key)\n\n const entry = {\n loc: document.path,\n lastmod: publishedAt,\n }\n\n return [\n SitemapEntrySchema.make(alternatives && alternatives.length > 1 ? { ...entry, alternatives } : entry),\n ]\n })\n .sort((left, right) => left.loc.localeCompare(right.loc))\n }).pipe(Effect.withSpan('SeoDelivery.sitemap'))\n\n return SeoDelivery.of({ previewDocument, publishedDocument, sitemap })\n }),\n )\n\nfunction makeState(\n snapshot: { readonly working: SeoState['working']; readonly published?: SeoState['published'] },\n capabilities: SeoCapabilities,\n) {\n return SeoStateSchema.make(\n snapshot.published === undefined\n ? { capabilities, working: snapshot.working }\n : { capabilities, published: snapshot.published, working: snapshot.working },\n )\n}\n\nfunction requestActivity(context: StudioRequestContext, reason?: string): ActivityContext {\n return {\n actor: context.actor,\n requestId: context.requestId,\n ...(reason === undefined ? undefined : { reason }),\n }\n}\n\nfunction productionChanges(previous: GlobalSeoSettings, next: GlobalSeoSettings) {\n const changes: Array<'canonicalOrigin' | 'indexability'> = []\n\n if (previous.canonicalOrigin !== next.canonicalOrigin) changes.push('canonicalOrigin')\n\n if (previous.index !== next.index || previous.follow !== next.follow) changes.push('indexability')\n\n return changes\n}\n","import type { ImageMimeType, MediaByteSize, MediaInvalid, MediaObjectKey } from '@internal/protocol/Media'\nimport type { MediaStorageError } from './media-failures'\nimport { Context, Effect, Option, Stream } from 'effect'\n\nexport const mediaObjectPrefix = 'media/'\n\nexport interface StoredMediaObject {\n readonly byteSize: MediaByteSize\n readonly mimeType?: ImageMimeType\n readonly objectKey: MediaObjectKey\n}\n\nexport interface MediaObjectWrite {\n readonly body: Stream.Stream<Uint8Array, MediaInvalid>\n readonly byteSize: MediaByteSize\n readonly mimeType: ImageMimeType\n readonly objectKey: MediaObjectKey\n}\n\nexport interface MediaObjectPromotion {\n readonly byteSize: MediaByteSize\n readonly destinationObjectKey: MediaObjectKey\n readonly mimeType: ImageMimeType\n readonly sourceObjectKey: MediaObjectKey\n}\n\nexport interface MediaObjectStoreApi {\n readonly list: Stream.Stream<StoredMediaObject, MediaStorageError>\n readonly promote: (input: MediaObjectPromotion) => Effect.Effect<StoredMediaObject, MediaStorageError>\n readonly put: (input: MediaObjectWrite) => Effect.Effect<StoredMediaObject, MediaInvalid | MediaStorageError>\n readonly remove: (objectKey: MediaObjectKey) => Effect.Effect<void, MediaStorageError>\n readonly stat: (objectKey: MediaObjectKey) => Effect.Effect<Option.Option<StoredMediaObject>, MediaStorageError>\n}\n\nexport class MediaObjectStore extends Context.Service<MediaObjectStore, MediaObjectStoreApi>()(\n '@internal/server/MediaObjectStore',\n) {}\n","import { Schema } from 'effect'\n\nexport class MediaPersistenceError extends Schema.TaggedError<MediaPersistenceError>()('Media.PersistenceError', {\n operation: Schema.NonEmptyString,\n cause: Schema.Defect(),\n}) {}\n\nexport class MediaStorageError extends Schema.TaggedError<MediaStorageError>()('Media.StorageError', {\n operation: Schema.NonEmptyString,\n cause: Schema.Defect(),\n}) {}\n","import {\n CreateBucketCommand,\n CopyObjectCommand,\n DeleteObjectCommand,\n HeadBucketCommand,\n HeadObjectCommand,\n ListObjectsV2Command,\n PutObjectCommand,\n S3Client,\n} from '@aws-sdk/client-s3'\nimport type { BucketLocationConstraint } from '@aws-sdk/client-s3'\nimport { NodeStream } from '@effect/platform-node-shared'\nimport type { MediaInvalid } from '@internal/protocol/Media'\nimport type { MediaStorageError } from '@internal/server/adapter/MediaObjectStore'\nimport { Effect, Redacted, Schema, Stream } from 'effect'\nimport type { S3MediaObjectStoreOptions } from '../S3MediaObjects'\n\nexport interface S3PutObjectInput {\n readonly body: Stream.Stream<Uint8Array, MediaInvalid | MediaStorageError>\n readonly bucket: string\n readonly cacheControl: string\n readonly contentLength: number\n readonly contentType: string\n readonly key: string\n}\n\nexport interface S3CopyObjectInput {\n readonly bucket: string\n readonly cacheControl: string\n readonly contentType: string\n readonly copySource: string\n readonly key: string\n}\n\nexport interface S3HeadObjectInput {\n readonly bucket: string\n readonly key: string\n}\n\nexport interface S3HeadObjectOutput {\n readonly contentLength?: number\n readonly contentType?: string\n}\n\nexport interface S3ListObjectsInput {\n readonly bucket: string\n readonly continuationToken?: string\n readonly prefix: string\n}\n\nexport interface S3ListedObject {\n readonly key?: string\n readonly size?: number\n}\n\nexport interface S3ListObjectsOutput {\n readonly isTruncated: boolean\n readonly nextContinuationToken?: string\n readonly objects: ReadonlyArray<S3ListedObject>\n}\n\nexport interface S3DeleteObjectInput {\n readonly bucket: string\n readonly key: string\n}\n\nexport interface S3HeadBucketInput {\n readonly bucket: string\n}\n\nexport interface S3CreateBucketInput {\n readonly bucket: string\n readonly locationConstraint?: string\n}\n\nexport class S3RequestError extends Schema.TaggedError<S3RequestError>()('S3.RequestError', {\n cause: Schema.Defect(),\n operation: Schema.NonEmptyString,\n}) {}\n\nexport interface S3MediaObjectClient {\n readonly copyObject: (input: S3CopyObjectInput) => Effect.Effect<void, S3RequestError>\n readonly createBucket: (input: S3CreateBucketInput) => Effect.Effect<void, S3RequestError>\n readonly deleteObject: (input: S3DeleteObjectInput) => Effect.Effect<void, S3RequestError>\n readonly headBucket: (input: S3HeadBucketInput) => Effect.Effect<void, S3RequestError>\n readonly headObject: (input: S3HeadObjectInput) => Effect.Effect<S3HeadObjectOutput, S3RequestError>\n readonly listObjects: (input: S3ListObjectsInput) => Effect.Effect<S3ListObjectsOutput, S3RequestError>\n readonly putObject: (input: S3PutObjectInput) => Effect.Effect<void, S3RequestError>\n}\n\nexport interface CloseableS3MediaObjectClient extends S3MediaObjectClient {\n readonly close: Effect.Effect<void>\n}\n\nexport function openAwsS3MediaObjectClient(options: S3MediaObjectStoreOptions): CloseableS3MediaObjectClient {\n const credentials = options.credentials\n ? {\n accessKeyId: options.credentials.accessKeyId,\n secretAccessKey: Redacted.value(options.credentials.secretAccessKey),\n sessionToken: options.credentials.sessionToken ? Redacted.value(options.credentials.sessionToken) : undefined,\n }\n : undefined\n\n const client = new S3Client({\n credentials,\n endpoint: options.endpoint,\n forcePathStyle: options.forcePathStyle,\n region: options.region,\n requestChecksumCalculation: 'WHEN_REQUIRED',\n })\n\n return makeAwsS3MediaObjectClient(client)\n}\n\nexport function makeAwsS3MediaObjectClient(client: S3Client): CloseableS3MediaObjectClient {\n const request = <A>(operation: string, send: (signal: AbortSignal) => Promise<A>) =>\n Effect.tryPromise({\n catch: (cause) => new S3RequestError({ cause, operation }),\n try: send,\n })\n\n return {\n close: Effect.sync(() => client.destroy()),\n copyObject: (input) =>\n request('MediaObjectStore.S3.copyObject', (signal) =>\n client.send(\n new CopyObjectCommand({\n Bucket: input.bucket,\n CacheControl: input.cacheControl,\n ContentType: input.contentType,\n CopySource: input.copySource,\n Key: input.key,\n MetadataDirective: 'REPLACE',\n }),\n { abortSignal: signal },\n ),\n ).pipe(Effect.asVoid),\n createBucket: (input) =>\n request('MediaObjectStore.S3.createBucket', (signal) =>\n client.send(\n new CreateBucketCommand({\n Bucket: input.bucket,\n // SAFETY: S3 accepts its configured region identifier; the SDK's generated union can lag new regions.\n CreateBucketConfiguration: input.locationConstraint\n ? { LocationConstraint: input.locationConstraint as BucketLocationConstraint }\n : undefined,\n }),\n { abortSignal: signal },\n ),\n ).pipe(Effect.asVoid),\n deleteObject: (input) =>\n request('MediaObjectStore.S3.deleteObject', (signal) =>\n client.send(new DeleteObjectCommand({ Bucket: input.bucket, Key: input.key }), { abortSignal: signal }),\n ).pipe(Effect.asVoid),\n headBucket: (input) =>\n request('MediaObjectStore.S3.headBucket', (signal) =>\n client.send(new HeadBucketCommand({ Bucket: input.bucket }), { abortSignal: signal }),\n ).pipe(Effect.asVoid),\n headObject: (input) =>\n request('MediaObjectStore.S3.headObject', (signal) =>\n client.send(new HeadObjectCommand({ Bucket: input.bucket, Key: input.key }), { abortSignal: signal }),\n ).pipe(Effect.map((output) => ({ contentLength: output.ContentLength, contentType: output.ContentType }))),\n listObjects: (input) =>\n request('MediaObjectStore.S3.listObjects', (signal) =>\n client.send(\n new ListObjectsV2Command({\n Bucket: input.bucket,\n ContinuationToken: input.continuationToken,\n Prefix: input.prefix,\n }),\n { abortSignal: signal },\n ),\n ).pipe(\n Effect.map((output) => ({\n isTruncated: output.IsTruncated === true,\n nextContinuationToken: output.NextContinuationToken,\n objects: (output.Contents ?? []).map((object) => ({ key: object.Key, size: object.Size })),\n })),\n ),\n putObject: (input) =>\n request('MediaObjectStore.S3.putObject', (signal) =>\n client.send(\n new PutObjectCommand({\n Body: NodeStream.toReadableNever(input.body),\n Bucket: input.bucket,\n CacheControl: input.cacheControl,\n ContentLength: input.contentLength,\n ContentType: input.contentType,\n Key: input.key,\n }),\n { abortSignal: signal },\n ),\n ).pipe(Effect.asVoid),\n }\n}\n","import { ImageMimeType, MediaByteSize, MediaInvalid, MediaObjectKey } from '@internal/protocol/Media'\nimport {\n MediaObjectStore,\n MediaStorageError,\n mediaObjectPrefix,\n type MediaObjectStoreApi,\n type MediaObjectWrite,\n type StoredMediaObject,\n} from '@internal/server/adapter/MediaObjectStore'\nimport { Effect, Layer, Option, Redacted, Ref, Schema, Stream } from 'effect'\nimport { maxS3SingleCopyBytes, type S3MediaObjectStoreOptions } from '../S3MediaObjects'\nimport {\n openAwsS3MediaObjectClient,\n type S3ListObjectsOutput,\n type S3ListedObject,\n type S3MediaObjectClient,\n type S3RequestError,\n} from './client'\n\ninterface ResolvedS3MediaObjectStoreOptions extends S3MediaObjectStoreOptions {\n readonly forcePathStyle: boolean\n readonly prefix: string\n readonly provisionBucket: boolean\n}\n\nconst replaceableMediaCacheControl = 'public, max-age=0, must-revalidate'\n\ninterface ListState {\n readonly continuationToken?: string\n readonly seenTokens: ReadonlySet<string>\n}\n\nconst isWriteBodyError = Schema.is(Schema.Union([MediaInvalid, MediaStorageError]))\n\nexport function s3MediaObjectStoreLayer(options: S3MediaObjectStoreOptions) {\n return Layer.effect(\n MediaObjectStore,\n resolveOptions(options).pipe(\n Effect.flatMap((resolved) =>\n Effect.acquireRelease(\n Effect.sync(() => openAwsS3MediaObjectClient(resolved)),\n (client) => client.close,\n ).pipe(\n Effect.tap((client) => provisionBucket(resolved, client)),\n Effect.map((client) => makeStore(resolved, client)),\n ),\n ),\n ),\n )\n}\n\nexport function s3MediaObjectStoreLayerWithClient(options: S3MediaObjectStoreOptions, client: S3MediaObjectClient) {\n return Layer.effect(\n MediaObjectStore,\n resolveOptions(options).pipe(\n Effect.tap((resolved) => provisionBucket(resolved, client)),\n Effect.map((resolved) => makeStore(resolved, client)),\n ),\n )\n}\n\nfunction makeStore(options: ResolvedS3MediaObjectStoreOptions, client: S3MediaObjectClient): MediaObjectStoreApi {\n return {\n list: listObjects(options.bucket, options.prefix, client),\n promote: (input) => promoteObject(options.bucket, options.prefix, input, client),\n put: (input) => putObject(options.bucket, options.prefix, input, client),\n remove: (objectKey) =>\n providerRequest(\n 'MediaObjectStore.S3.remove',\n client.deleteObject({ bucket: options.bucket, key: physicalKey(options.prefix, objectKey) }),\n ),\n stat: (objectKey) => statObject(options.bucket, options.prefix, objectKey, client),\n }\n}\n\nfunction promoteObject(\n bucket: string,\n prefix: string,\n input: Parameters<MediaObjectStoreApi['promote']>[0],\n client: S3MediaObjectClient,\n): Effect.Effect<StoredMediaObject, MediaStorageError> {\n if (input.byteSize > maxS3SingleCopyBytes) {\n return Effect.fail(storageError('MediaObjectStore.S3.promote', 'The object exceeds the S3 single-copy size limit.'))\n }\n\n return statObject(bucket, prefix, input.sourceObjectKey, client).pipe(\n Effect.flatMap((source) =>\n Option.isSome(source) && source.value.byteSize === input.byteSize && source.value.mimeType === input.mimeType\n ? Effect.void\n : Effect.fail(\n storageError('MediaObjectStore.S3.promote.source', 'The staged object metadata does not match its intent.'),\n ),\n ),\n Effect.flatMap(() =>\n providerRequest(\n 'MediaObjectStore.S3.promote.copy',\n client.copyObject({\n bucket,\n cacheControl: replaceableMediaCacheControl,\n contentType: input.mimeType,\n copySource: copySource(bucket, physicalKey(prefix, input.sourceObjectKey)),\n key: physicalKey(prefix, input.destinationObjectKey),\n }),\n ),\n ),\n Effect.flatMap(() => statObject(bucket, prefix, input.destinationObjectKey, client)),\n Effect.flatMap((destination) =>\n Option.isSome(destination) &&\n destination.value.byteSize === input.byteSize &&\n destination.value.mimeType === input.mimeType\n ? Effect.succeed(destination.value)\n : Effect.fail(\n storageError(\n 'MediaObjectStore.S3.promote.verify',\n 'The promoted object metadata does not match its intent.',\n ),\n ),\n ),\n )\n}\n\nfunction copySource(bucket: string, objectKey: string): string {\n return `/${encodeURIComponent(bucket)}/${objectKey.split('/').map(encodeURIComponent).join('/')}`\n}\n\nfunction putObject(\n bucket: string,\n prefix: string,\n input: MediaObjectWrite,\n client: S3MediaObjectClient,\n): Effect.Effect<StoredMediaObject, MediaInvalid | MediaStorageError> {\n return Effect.gen(function* () {\n const body = yield* validatedWriteBody(input)\n yield* client\n .putObject({\n body,\n bucket,\n cacheControl: replaceableMediaCacheControl,\n contentLength: input.byteSize,\n contentType: input.mimeType,\n key: physicalKey(prefix, input.objectKey),\n })\n .pipe(\n Effect.catch((failure) =>\n isWriteBodyError(failure.cause)\n ? Effect.fail(failure.cause)\n : Effect.fail(providerError('MediaObjectStore.S3.put', failure)),\n ),\n )\n\n return { byteSize: input.byteSize, mimeType: input.mimeType, objectKey: input.objectKey }\n })\n}\n\nconst validatedWriteBody = Effect.fn('MediaObjectStore.S3.validateWriteBody')(function* (input: MediaObjectWrite) {\n const byteLength = yield* Ref.make(0)\n\n return input.body.pipe(\n Stream.mapEffect((chunk) =>\n Effect.gen(function* () {\n const next = yield* Ref.updateAndGet(byteLength, (current) => current + chunk.byteLength)\n\n if (next > input.byteSize) {\n return yield* storageError('MediaObjectStore.S3.put.body', 'The object body exceeds its declared byte size.')\n }\n\n return chunk\n }),\n ),\n Stream.concat(\n Stream.fromEffect(\n Ref.get(byteLength).pipe(\n Effect.flatMap((actual) =>\n actual === input.byteSize\n ? Effect.void\n : Effect.fail(\n storageError(\n 'MediaObjectStore.S3.put.body',\n 'The object body does not match its declared byte size.',\n ),\n ),\n ),\n ),\n ).pipe(Stream.drain),\n ),\n )\n})\n\nfunction statObject(\n bucket: string,\n prefix: string,\n objectKey: MediaObjectKey,\n client: S3MediaObjectClient,\n): Effect.Effect<Option.Option<StoredMediaObject>, MediaStorageError> {\n return client.headObject({ bucket, key: physicalKey(prefix, objectKey) }).pipe(\n Effect.matchEffect({\n onFailure: (failure) =>\n isMissingObject(failure.cause)\n ? Effect.succeed(Option.none<StoredMediaObject>())\n : Effect.fail(providerError('MediaObjectStore.S3.stat', failure)),\n onSuccess: (output) =>\n decodeStoredObject('MediaObjectStore.S3.stat', objectKey, output.contentLength, output.contentType).pipe(\n Effect.asSome,\n ),\n }),\n )\n}\n\nfunction listObjects(\n bucket: string,\n prefix: string,\n client: S3MediaObjectClient,\n): Stream.Stream<StoredMediaObject, MediaStorageError> {\n return Stream.paginate<ListState, StoredMediaObject, MediaStorageError>({ seenTokens: new Set<string>() }, (state) =>\n providerRequest(\n 'MediaObjectStore.S3.list',\n client.listObjects({\n bucket,\n continuationToken: state.continuationToken,\n prefix: `${prefix}${mediaObjectPrefix}`,\n }),\n ).pipe(\n Effect.flatMap((page) =>\n Effect.gen(function* () {\n const items = yield* Effect.forEach(page.objects, (object) => decodeListedObject(object, prefix))\n const next = yield* nextListState(state, page)\n\n return [items, next] as const\n }),\n ),\n ),\n )\n}\n\nfunction decodeListedObject(\n object: S3ListedObject,\n prefix: string,\n): Effect.Effect<StoredMediaObject, MediaStorageError> {\n if (object.key === undefined) {\n return Effect.fail(storageError('MediaObjectStore.S3.list', 'The provider returned object metadata without a key.'))\n }\n\n return decodeStoredObject('MediaObjectStore.S3.list', object.key.slice(prefix.length), object.size)\n}\n\nfunction nextListState(\n state: ListState,\n page: S3ListObjectsOutput,\n): Effect.Effect<Option.Option<ListState>, MediaStorageError> {\n if (!page.isTruncated) return Effect.succeedNone\n const token = page.nextContinuationToken\n\n if (!token || token === state.continuationToken || state.seenTokens.has(token)) {\n return Effect.fail(storageError('MediaObjectStore.S3.list', 'The provider returned an invalid continuation token.'))\n }\n\n return Effect.succeedSome({ continuationToken: token, seenTokens: new Set([...state.seenTokens, token]) })\n}\n\nfunction decodeStoredObject(\n operation: string,\n objectKey: string,\n byteSize: number | undefined,\n contentType?: string,\n): Effect.Effect<StoredMediaObject, MediaStorageError> {\n const decodedObjectKey = Schema.decodeOption(MediaObjectKey)(objectKey)\n const decodedByteSize = Schema.decodeUnknownOption(MediaByteSize)(byteSize)\n\n if (Option.isNone(decodedObjectKey) || Option.isNone(decodedByteSize)) {\n return Effect.fail(storageError(operation, 'The provider returned invalid object metadata.'))\n }\n\n const decodedMimeType = Schema.decodeUnknownOption(ImageMimeType)(contentType)\n\n const storedObject: StoredMediaObject = {\n byteSize: decodedByteSize.value,\n objectKey: decodedObjectKey.value,\n }\n\n return Effect.succeed(\n Option.isSome(decodedMimeType) ? { ...storedObject, mimeType: decodedMimeType.value } : storedObject,\n )\n}\n\nfunction providerRequest<A>(\n operation: string,\n request: Effect.Effect<A, S3RequestError>,\n): Effect.Effect<A, MediaStorageError> {\n return request.pipe(Effect.mapError((failure) => providerError(operation, failure)))\n}\n\nfunction provisionBucket(\n options: ResolvedS3MediaObjectStoreOptions,\n client: S3MediaObjectClient,\n): Effect.Effect<void, MediaStorageError> {\n if (!options.provisionBucket) return Effect.void\n\n return client\n .headBucket({ bucket: options.bucket })\n .pipe(\n Effect.catch((failure) =>\n isMissingBucket(failure.cause)\n ? createMissingBucket(options, client)\n : Effect.fail(providerError('MediaObjectStore.S3.bucket.head', failure)),\n ),\n )\n}\n\nfunction createMissingBucket(\n options: ResolvedS3MediaObjectStoreOptions,\n client: S3MediaObjectClient,\n): Effect.Effect<void, MediaStorageError> {\n return client\n .createBucket({\n bucket: options.bucket,\n locationConstraint: options.endpoint || options.region === 'us-east-1' ? undefined : options.region,\n })\n .pipe(\n Effect.catch((failure) =>\n isBucketAlreadyOwned(failure.cause)\n ? providerRequest('MediaObjectStore.S3.bucket.verify', client.headBucket({ bucket: options.bucket }))\n : Effect.fail(providerError('MediaObjectStore.S3.bucket.create', failure)),\n ),\n )\n}\n\nconst ProviderFailureDetails = Schema.Struct({\n $metadata: Schema.optionalKey(\n Schema.Struct({\n attempts: Schema.optionalKey(Schema.Finite),\n httpStatusCode: Schema.optionalKey(Schema.Finite),\n }),\n ),\n name: Schema.optionalKey(Schema.String),\n})\n\nconst decodeProviderFailure = Schema.decodeUnknownOption(ProviderFailureDetails)\n\nfunction providerError(operation: string, failure: S3RequestError): MediaStorageError {\n const details = decodeProviderFailure(failure.cause)\n const diagnostics: Array<string> = []\n\n if (Option.isSome(details)) {\n if (details.value.name) diagnostics.push(`name=${details.value.name}`)\n\n if (details.value.$metadata?.httpStatusCode !== undefined) {\n diagnostics.push(`status=${details.value.$metadata.httpStatusCode}`)\n }\n\n if (details.value.$metadata?.attempts !== undefined) {\n diagnostics.push(`attempts=${details.value.$metadata.attempts}`)\n }\n }\n\n const suffix = diagnostics.length > 0 ? ` (${diagnostics.join(', ')}).` : '.'\n\n return storageError(operation, `The S3 provider request failed${suffix}`)\n}\n\nfunction isMissingObject(cause: unknown): boolean {\n const details = decodeProviderFailure(cause)\n\n if (Option.isNone(details)) return false\n\n return details.value.name === 'NoSuchKey' || details.value.name === 'NotFound'\n}\n\nfunction isMissingBucket(cause: unknown): boolean {\n const details = decodeProviderFailure(cause)\n\n if (Option.isNone(details)) return false\n\n return details.value.name === 'NoSuchBucket' || details.value.$metadata?.httpStatusCode === 404\n}\n\nfunction isBucketAlreadyOwned(cause: unknown): boolean {\n const details = decodeProviderFailure(cause)\n\n return Option.isSome(details) && details.value.name === 'BucketAlreadyOwnedByYou'\n}\n\nfunction resolveOptions(\n options: S3MediaObjectStoreOptions,\n): Effect.Effect<ResolvedS3MediaObjectStoreOptions, MediaStorageError> {\n const bucket = options.bucket.trim()\n const region = options.region.trim()\n const endpoint = options.endpoint?.trim()\n const prefix = options.prefix.trim()\n\n if (\n !bucket ||\n !region ||\n (options.endpoint !== undefined && !endpoint) ||\n !prefix ||\n prefix.startsWith('/') ||\n !prefix.endsWith('/') ||\n prefix.includes('..')\n ) {\n return Effect.fail(\n storageError(\n 'MediaObjectStore.S3.configure',\n 'The bucket, region, configured endpoint, and relative object prefix must be valid.',\n ),\n )\n }\n\n if (options.credentials) {\n const secretAccessKey = Redacted.value(options.credentials.secretAccessKey)\n const sessionToken = options.credentials.sessionToken && Redacted.value(options.credentials.sessionToken)\n\n if (!options.credentials.accessKeyId.trim() || !secretAccessKey || sessionToken === '') {\n return Effect.fail(storageError('MediaObjectStore.S3.configure', 'The configured credentials must be non-empty.'))\n }\n }\n\n return Effect.succeed({\n ...options,\n bucket,\n credentials: options.credentials\n ? { ...options.credentials, accessKeyId: options.credentials.accessKeyId.trim() }\n : undefined,\n endpoint,\n forcePathStyle: options.forcePathStyle ?? false,\n prefix,\n provisionBucket: options.provisionBucket ?? false,\n region,\n })\n}\n\nfunction physicalKey(prefix: string, objectKey: MediaObjectKey): string {\n return `${prefix}${objectKey}`\n}\n\nfunction storageError(operation: string, message: string): MediaStorageError {\n return new MediaStorageError({ cause: new Error(message), operation })\n}\n","import type { Redacted } from 'effect'\n\nexport const maxS3SingleCopyBytes = 5_000_000_000\n\nexport interface S3MediaObjectStoreOptions {\n readonly bucket: string\n readonly credentials?: {\n readonly accessKeyId: string\n readonly secretAccessKey: Redacted.Redacted<string>\n readonly sessionToken?: Redacted.Redacted<string>\n }\n readonly endpoint?: string\n readonly forcePathStyle?: boolean\n readonly provisionBucket?: boolean\n readonly prefix: string\n readonly region: string\n}\n\nexport { s3MediaObjectStoreLayer } from './internal/media-object-store'\n"],"mappings":";;;;;;;;;;;;;;;;;;AAKA,IAAa,mBAAb,cAAsC,OAAO,YAA8B,CAAC,CAAC,qBAAqB;CAChG,YAAY;CACZ,YAAY,OAAO,YAAY,UAAU;AAC3C,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa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