@nuasite/cms-sidecar 0.70.5 → 0.71.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.ts CHANGED
@@ -33,7 +33,7 @@ import type {
33
33
  MediaTypeFilter,
34
34
  MutationResult,
35
35
  } from '@nuasite/cms-types'
36
- import { hashContent, hashSource, KeyedMutex, SharedRun } from './concurrency.ts'
36
+ import { hashSource, KeyedMutex, SharedRun } from './concurrency.ts'
37
37
  import {
38
38
  type AddArrayItemBody,
39
39
  type ApiError,
@@ -41,6 +41,7 @@ import {
41
41
  type ConflictResponse,
42
42
  type CreateEntryBody,
43
43
  type CreateFolderBody,
44
+ type DeleteEntryBody,
44
45
  type EntriesListResult,
45
46
  type EntriesQuery,
46
47
  type ErrorCode,
@@ -161,6 +162,28 @@ async function parseJson<T>(req: Request): Promise<{ ok: true; value: T } | { ok
161
162
  }
162
163
  }
163
164
 
165
+ /** A body that may be absent: no body reads as `undefined`, anything else must be JSON. */
166
+ async function parseOptionalJson<T>(req: Request): Promise<{ ok: true; value: T | undefined } | { ok: false; response: Response }> {
167
+ const text = await req.text()
168
+ if (text.trim() === '') return { ok: true, value: undefined }
169
+ try {
170
+ // See `parseJson`: the route validates every field it reads.
171
+ const value: T = JSON.parse(text)
172
+ return { ok: true, value }
173
+ } catch {
174
+ return { ok: false, response: error('validation', 'Invalid JSON body') }
175
+ }
176
+ }
177
+
178
+ function isOptionalHash(value: unknown): value is string | undefined {
179
+ return value === undefined || (typeof value === 'string' && value !== '')
180
+ }
181
+
182
+ /** A JSON object, the only shape a request body takes. */
183
+ function isBodyObject(value: unknown): value is object {
184
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
185
+ }
186
+
164
187
  function parseEntriesQuery(url: URL): EntriesQuery {
165
188
  const fields = url.searchParams.get('fields') ?? undefined
166
189
  const rawDraft = url.searchParams.get('draft')
@@ -660,6 +683,7 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
660
683
  frontmatter,
661
684
  body: result.content,
662
685
  bodyStartLine: 0,
686
+ sourceHash: result.sourceHash,
663
687
  }
664
688
  return json(entry)
665
689
  }
@@ -687,26 +711,10 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
687
711
  const existing = await core.getEntry(collection, slug)
688
712
  if (!existing) return error('not_found', `Entry not found: ${collection}/${slug}`)
689
713
  const sourcePath = existing.sourcePath
690
- const existingFrontmatter = existing.frontmatter
691
-
692
- /** The 409 with the entry as it is now, so the client can offer "use server" vs "use ours". */
693
- async function conflictResponse(serverHash: string): Promise<Response> {
694
- const current = await core.getEntry(collection, slug)
695
- const conflict: ConflictResponse = {
696
- code: 'conflict',
697
- serverHash,
698
- serverFrontmatter: current?.frontmatter ?? existingFrontmatter,
699
- }
700
- if (current && current.content !== '') conflict.serverBody = current.content
701
- return json(conflict, STATUS_BY_CODE.conflict)
702
- }
703
714
 
704
715
  return mutex.runExclusive(sourcePath, async () => {
705
716
  // Re-hash under the lock so a concurrent writer cannot slip in between.
706
- const serverHash = await hashSource(fs, sourcePath)
707
- if (body.baseHash !== undefined && serverHash !== null && body.baseHash !== serverHash) {
708
- return conflictResponse(serverHash)
709
- }
717
+ if (await isStale(sourcePath, body.baseHash)) return conflictResponse(collection, slug)
710
718
 
711
719
  let result: MutationResult
712
720
  try {
@@ -719,20 +727,39 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
719
727
  } catch (cause) {
720
728
  // The core's commit found the file changed by a writer outside this server's lock.
721
729
  if (!(cause instanceof CmsCommitConflictError)) throw cause
722
- const currentHash = await hashSource(fs, sourcePath)
723
730
  // Removed meanwhile: there is no server version to offer, only the plain conflict.
724
- if (currentHash === null) throw cause
725
- return conflictResponse(currentHash)
731
+ if (await hashSource(fs, sourcePath) === null) throw cause
732
+ return conflictResponse(collection, slug)
726
733
  }
727
- if (!result.success) return mutationResponse(result)
728
-
729
- const newHash = await hashSource(fs, result.sourcePath ?? sourcePath)
730
- const enriched: MutationResult = { ...result }
731
- if (newHash !== null) enriched.sourceHash = newHash
732
- return json(enriched)
734
+ // The result carries the hash of the bytes the core wrote; hashing the file again here
735
+ // could pick up a write that landed after it.
736
+ return mutationResponse(result)
733
737
  })
734
738
  }
735
739
 
740
+ /** Whether `baseHash` was given and no longer matches the file. Call under the file's lock. */
741
+ async function isStale(sourcePath: string, baseHash: string | undefined): Promise<boolean> {
742
+ if (baseHash === undefined) return false
743
+ const serverHash = await hashSource(fs, sourcePath)
744
+ return serverHash !== null && serverHash !== baseHash
745
+ }
746
+
747
+ /**
748
+ * The 409 with the entry as it is now, so the client can offer "use server" vs "use ours". The
749
+ * hash and the version come from one read, so they always describe the same bytes.
750
+ */
751
+ async function conflictResponse(collection: string, slug: string): Promise<Response> {
752
+ const current = await core.getEntry(collection, slug)
753
+ if (current === null) return error('conflict', `Entry changed and was removed meanwhile: ${collection}/${slug}`)
754
+ const conflict: ConflictResponse = {
755
+ code: 'conflict',
756
+ serverHash: current.sourceHash,
757
+ serverFrontmatter: current.frontmatter,
758
+ }
759
+ if (current.content !== '') conflict.serverBody = current.content
760
+ return json(conflict, STATUS_BY_CODE.conflict)
761
+ }
762
+
736
763
  async function fetchHandler(req: Request): Promise<Response> {
737
764
  const url = new URL(req.url)
738
765
  let pathname = url.pathname
@@ -841,7 +868,7 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
841
868
  if (action === undefined) {
842
869
  if (method === 'GET') return entryDetail(collection, slug)
843
870
  if (method === 'PATCH') return updateEntryRoute(collection, slug, req)
844
- if (method === 'DELETE') return deleteEntryRoute(collection, slug)
871
+ if (method === 'DELETE') return deleteEntryRoute(collection, slug, req)
845
872
  return error('unsupported', `Unsupported: ${method} /collections/${collection}/entries/${slug}`)
846
873
  }
847
874
 
@@ -896,12 +923,8 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
896
923
  body: body.body,
897
924
  fileExtension: body.fileExtension,
898
925
  })
899
- if (!result.success) return mutationResponse(result)
900
-
901
- const newHash = result.sourcePath ? await hashSource(fs, result.sourcePath) : null
902
- const enriched: MutationResult = { ...result }
903
- if (newHash !== null) enriched.sourceHash = newHash
904
- return json(enriched)
926
+ // The result carries the hash of the bytes the core wrote.
927
+ return mutationResponse(result)
905
928
  }
906
929
 
907
930
  async function updateEntryRoute(collection: string, slug: string, req: Request): Promise<Response> {
@@ -910,10 +933,16 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
910
933
  return patchEntry(collection, slug, parsed.value)
911
934
  }
912
935
 
913
- async function deleteEntryRoute(collection: string, slug: string): Promise<Response> {
936
+ async function deleteEntryRoute(collection: string, slug: string, req: Request): Promise<Response> {
937
+ // The body is optional: a client that sends no `baseHash` deletes unchecked, as before.
938
+ const parsed = await parseOptionalJson<DeleteEntryBody>(req)
939
+ if (!parsed.ok) return parsed.response
940
+ if (parsed.value !== undefined && !isBodyObject(parsed.value)) return error('validation', 'The body must be a JSON object')
941
+ if (!isOptionalHash(parsed.value?.baseHash)) return error('validation', '"baseHash" must be a non-empty string')
914
942
  const existing = await core.getEntry(collection, slug)
915
943
  if (!existing) return error('not_found', `Entry not found: ${collection}/${slug}`)
916
944
  return mutex.runExclusive(existing.sourcePath, async () => {
945
+ if (await isStale(existing.sourcePath, parsed.value?.baseHash)) return conflictResponse(collection, slug)
917
946
  const result = await core.deleteEntry(collection, slug)
918
947
  return mutationResponse(result)
919
948
  })
@@ -925,15 +954,13 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
925
954
  if (typeof parsed.value.to !== 'string' || parsed.value.to.trim() === '') {
926
955
  return error('validation', 'A non-empty "to" slug is required')
927
956
  }
957
+ if (!isOptionalHash(parsed.value.baseHash)) return error('validation', '"baseHash" must be a non-empty string')
928
958
  const existing = await core.getEntry(collection, slug)
929
959
  if (!existing) return error('not_found', `Entry not found: ${collection}/${slug}`)
930
960
  return mutex.runExclusive(existing.sourcePath, async () => {
931
- const result = await core.renameEntry(collection, slug, parsed.value.to)
932
- if (!result.success) return mutationResponse(result)
933
- const newHash = result.sourcePath ? await hashSource(fs, result.sourcePath) : null
934
- const enriched: MutationResult = { ...result }
935
- if (newHash !== null) enriched.sourceHash = newHash
936
- return json(enriched)
961
+ if (await isStale(existing.sourcePath, parsed.value.baseHash)) return conflictResponse(collection, slug)
962
+ // The result carries the hash of the bytes the core wrote at the new path.
963
+ return mutationResponse(await core.renameEntry(collection, slug, parsed.value.to))
937
964
  })
938
965
  }
939
966
 
package/src/types.ts CHANGED
@@ -40,8 +40,8 @@ export const STATUS_BY_CODE: Record<ErrorCode, number> = {
40
40
  }
41
41
 
42
42
  /**
43
- * Returned with `409` when a `PATCH`'s `baseHash` no longer matches the file on
44
- * disk (an agent or a human wrote in between). Carries the current server
43
+ * Returned with `409` when a write's `baseHash` (`PATCH`, `DELETE`, rename) no longer
44
+ * matches the file on disk (an agent or a human wrote in between). Carries the current server
45
45
  * version so the client can offer "use server" vs "use ours".
46
46
  */
47
47
  export interface ConflictResponse {
@@ -73,6 +73,13 @@ export interface CreateEntryBody {
73
73
 
74
74
  export interface RenameEntryBody {
75
75
  to: string
76
+ /** Hash of the entry source the client saw; `409` on drift. Without it the rename is unchecked. */
77
+ baseHash?: string
78
+ }
79
+
80
+ export interface DeleteEntryBody {
81
+ /** Hash of the entry source the client saw; `409` on drift. Without it the delete is unchecked. */
82
+ baseHash?: string
76
83
  }
77
84
 
78
85
  export interface AddArrayItemBody {