@antelopejs/dms-media 0.5.1 → 0.6.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.
Files changed (135) hide show
  1. package/README.md +3 -3
  2. package/dist/db/models/mediaFolders.model.d.ts +0 -3
  3. package/dist/db/models/mediaFolders.model.js +0 -29
  4. package/dist/db/models/mediaFolders.model.js.map +1 -1
  5. package/dist/db/tables/mediaDeclarations.table.d.ts +0 -4
  6. package/dist/db/tables/mediaDeclarations.table.js +0 -16
  7. package/dist/db/tables/mediaDeclarations.table.js.map +1 -1
  8. package/dist/declared/assets.d.ts +0 -2
  9. package/dist/declared/assets.js +12 -140
  10. package/dist/declared/assets.js.map +1 -1
  11. package/dist/declared/folders.d.ts +1 -5
  12. package/dist/declared/folders.js +14 -80
  13. package/dist/declared/folders.js.map +1 -1
  14. package/dist/declared/index.d.ts +0 -2
  15. package/dist/declared/index.js +0 -2
  16. package/dist/declared/index.js.map +1 -1
  17. package/dist/declared/records.d.ts +2 -30
  18. package/dist/declared/records.js +3 -33
  19. package/dist/declared/records.js.map +1 -1
  20. package/dist/derivatives.js +5 -17
  21. package/dist/derivatives.js.map +1 -1
  22. package/dist/frontend-module.d.ts +4 -0
  23. package/dist/frontend-module.js +24 -0
  24. package/dist/frontend-module.js.map +1 -0
  25. package/dist/implementations/interface-dms-media/index.d.ts +1 -3
  26. package/dist/implementations/interface-dms-media/index.js +0 -2
  27. package/dist/implementations/interface-dms-media/index.js.map +1 -1
  28. package/dist/index.d.ts +1 -3
  29. package/dist/index.js +3 -19
  30. package/dist/index.js.map +1 -1
  31. package/dist/library/realtime.js +8 -1
  32. package/dist/library/realtime.js.map +1 -1
  33. package/dist/pages/activity.d.ts +1 -0
  34. package/dist/pages/activity.js +3 -0
  35. package/dist/pages/activity.js.map +1 -1
  36. package/dist/pages/overview.d.ts +1 -0
  37. package/dist/pages/overview.js +3 -2
  38. package/dist/pages/overview.js.map +1 -1
  39. package/dist/pages/toolbar.d.ts +3 -0
  40. package/dist/pages/toolbar.js +19 -0
  41. package/dist/pages/toolbar.js.map +1 -0
  42. package/dist/pages/uploads.d.ts +1 -0
  43. package/dist/pages/uploads.js +4 -0
  44. package/dist/pages/uploads.js.map +1 -1
  45. package/dist/routes/media/delivery-stream.js +7 -21
  46. package/dist/routes/media/delivery-stream.js.map +1 -1
  47. package/dist/routes/media/manage.d.ts +23 -0
  48. package/dist/routes/media/manage.js +7 -4
  49. package/dist/routes/media/manage.js.map +1 -1
  50. package/dist/routes/media/upload.js +2 -5
  51. package/dist/routes/media/upload.js.map +1 -1
  52. package/dist/test/antelope.test.js +9 -4
  53. package/dist/test/antelope.test.js.map +1 -1
  54. package/dist/test/integration/media-activity-overview.test.js +6 -0
  55. package/dist/test/integration/media-activity-overview.test.js.map +1 -1
  56. package/dist/test/integration/media-declared-content.test.js +17 -317
  57. package/dist/test/integration/media-declared-content.test.js.map +1 -1
  58. package/dist/test/integration/media-linked-subfolders.test.js +2 -2
  59. package/dist/test/integration/media-linked-subfolders.test.js.map +1 -1
  60. package/dist/test/integration/media-storage-origin-unreachable.test.js +79 -0
  61. package/dist/test/integration/media-storage-origin-unreachable.test.js.map +1 -0
  62. package/dist/test/unit/declared.test.js +0 -66
  63. package/dist/test/unit/declared.test.js.map +1 -1
  64. package/dist/test/unit/library/realtime.test.d.ts +1 -0
  65. package/dist/test/unit/library/realtime.test.js +44 -0
  66. package/dist/test/unit/library/realtime.test.js.map +1 -0
  67. package/dist/test/unit/pages/toolbar.test.d.ts +1 -0
  68. package/dist/test/unit/pages/toolbar.test.js +64 -0
  69. package/dist/test/unit/pages/toolbar.test.js.map +1 -0
  70. package/dist/test/unit/routes/preset-row.test.d.ts +1 -0
  71. package/dist/test/unit/routes/preset-row.test.js +36 -0
  72. package/dist/test/unit/routes/preset-row.test.js.map +1 -0
  73. package/dist/validation/declared.schema.d.ts +7 -36
  74. package/dist/validation/declared.schema.js +1 -12
  75. package/dist/validation/declared.schema.js.map +1 -1
  76. package/frontend-vue/app/components/Explorer.vue +2 -0
  77. package/frontend-vue/app/components/FirstRun.vue +3 -1
  78. package/frontend-vue/app/components/PresetCards.vue +28 -5
  79. package/frontend-vue/app/components/RecentFiles.vue +11 -5
  80. package/frontend-vue/app/components/UploadQueue.vue +3 -1
  81. package/frontend-vue/app/components/UploadStrip.vue +3 -1
  82. package/frontend-vue/app/components/explorer/ExplorerDetailsDrawer.vue +10 -0
  83. package/frontend-vue/app/components/explorer/ExplorerInspector.vue +19 -14
  84. package/frontend-vue/app/components/explorer/ExplorerShell.vue +1 -11
  85. package/frontend-vue/app/composables/library/useExplorerCommands.ts +7 -1
  86. package/frontend-vue/app/composables/library/useExplorerDetailsDrawer.ts +75 -0
  87. package/frontend-vue/i18n/locales/media-en-GB.json +9 -2
  88. package/frontend-vue/i18n/locales/media-fr-FR.json +9 -2
  89. package/frontend-vue/package.json +1 -1
  90. package/frontend-vue/tests/detailsDrawer.test.ts +150 -0
  91. package/frontend-vue/tests/fixtures/serverRender.ts +70 -0
  92. package/frontend-vue/tests/locales.test.ts +17 -0
  93. package/frontend-vue/tests/serverRender.test.ts +47 -2
  94. package/package.json +10 -9
  95. package/skills/dms-media/SKILL.md +17 -24
  96. package/src/db/models/mediaFolders.model.ts +0 -44
  97. package/src/db/tables/mediaDeclarations.table.ts +3 -19
  98. package/src/declared/assets.ts +19 -210
  99. package/src/declared/folders.ts +22 -135
  100. package/src/declared/index.ts +0 -2
  101. package/src/declared/records.ts +8 -82
  102. package/src/derivatives.ts +7 -17
  103. package/src/frontend-module.ts +35 -0
  104. package/src/implementations/interface-dms-media/index.ts +1 -8
  105. package/src/index.ts +4 -28
  106. package/src/library/realtime.ts +12 -3
  107. package/src/pages/activity.ts +4 -0
  108. package/src/pages/overview.ts +4 -3
  109. package/src/pages/toolbar.ts +28 -0
  110. package/src/pages/uploads.ts +5 -0
  111. package/src/routes/media/delivery-stream.ts +12 -28
  112. package/src/routes/media/manage.ts +17 -4
  113. package/src/routes/media/upload.ts +4 -6
  114. package/src/test/antelope.test.ts +13 -4
  115. package/src/test/integration/media-activity-overview.test.ts +5 -0
  116. package/src/test/integration/media-declared-content.test.ts +17 -360
  117. package/src/test/integration/media-linked-subfolders.test.ts +2 -2
  118. package/src/test/integration/media-storage-origin-unreachable.test.ts +110 -0
  119. package/src/test/unit/declared.test.ts +0 -87
  120. package/src/test/unit/library/realtime.test.ts +55 -0
  121. package/src/test/unit/pages/toolbar.test.ts +92 -0
  122. package/src/test/unit/routes/preset-row.test.ts +39 -0
  123. package/src/validation/declared.schema.ts +0 -13
  124. package/dist/declared/readiness.d.ts +0 -2
  125. package/dist/declared/readiness.js +0 -52
  126. package/dist/declared/readiness.js.map +0 -1
  127. package/dist/declared/retire.d.ts +0 -3
  128. package/dist/declared/retire.js +0 -118
  129. package/dist/declared/retire.js.map +0 -1
  130. package/dist/test/integration/media-declared-retire.test.js +0 -186
  131. package/dist/test/integration/media-declared-retire.test.js.map +0 -1
  132. package/src/declared/readiness.ts +0 -64
  133. package/src/declared/retire.ts +0 -206
  134. package/src/test/integration/media-declared-retire.test.ts +0 -257
  135. /package/dist/test/integration/{media-declared-retire.test.d.ts → media-storage-origin-unreachable.test.d.ts} +0 -0
@@ -1,14 +1,17 @@
1
1
  import { defineComponent, h } from 'vue'
2
2
  import { describe, expect, it } from 'vitest'
3
- import { serverRender, type BackendRead } from './fixtures/serverRender'
3
+ import { serverRender, suspendedMount, type BackendRead } from './fixtures/serverRender'
4
4
  import AssetValue from '../app/components/field/AssetValue.vue'
5
5
  import Explorer from '../app/components/Explorer.vue'
6
6
  import FileHeader from '../app/components/FileHeader.vue'
7
7
  import FilePreview from '../app/components/FilePreview.vue'
8
8
  import FileProperties from '../app/components/FileProperties.vue'
9
+ import FirstRun from '../app/components/FirstRun.vue'
9
10
  import ImageEditor from '../app/components/ImageEditor.vue'
10
11
  import PresetCards from '../app/components/PresetCards.vue'
11
12
  import RecentFiles from '../app/components/RecentFiles.vue'
13
+ import UploadQueue from '../app/components/UploadQueue.vue'
14
+ import UploadStrip from '../app/components/UploadStrip.vue'
12
15
  import { useFieldFolders } from '../app/composables/useFieldFolders'
13
16
  import type { MediaAsset, MediaFolder } from '../app/types/media'
14
17
 
@@ -84,7 +87,7 @@ function backend({ url }: BackendRead): unknown {
84
87
  return { assets: FILES }
85
88
  case '/api/media/presets':
86
89
  return {
87
- presets: [{ id: 'thumb', width: 300, height: 300, fit: 'cover', cacheKey: 'thumb.1', rendered: 1, urlPattern: '', exampleUrl: null }],
90
+ presets: [{ id: 'thumb', width: 300, height: 300, fit: 'cover', cacheKey: 'thumb.1', rendered: 1, urlPattern: '', exampleUrl: null, examplePreviewUrl: null }],
88
91
  cache: { schedule: '', lastSweepAt: null, lastSweepRemoved: null, publicTtlSeconds: 0, privateTtlSeconds: 0 },
89
92
  isDefault: true,
90
93
  example: null,
@@ -122,6 +125,21 @@ describe('server render: the blocks read with the page and hand it over', () =>
122
125
  expect(page.html).toContain('thumb')
123
126
  })
124
127
 
128
+ it('image sizes: the example loads on the dashboard origin, the copied link stays absolute', async () => {
129
+ const exampleUrl = 'https://api.example.com/media/a1/thumb/lighthouse.png'
130
+ const examplePreviewUrl = '/media/a1/thumb/lighthouse.png'
131
+ const presets = {
132
+ presets: [{ id: 'thumb', width: 300, height: 300, fit: 'cover', cacheKey: 'thumb.1', rendered: 1, urlPattern: '', exampleUrl, examplePreviewUrl }],
133
+ cache: { schedule: '', lastSweepAt: null, lastSweepRemoved: null, publicTtlSeconds: 0, privateTtlSeconds: 0 },
134
+ isDefault: false,
135
+ example: { id: 'a1', name: 'lighthouse.png', width: 1200, height: 800 },
136
+ }
137
+ const page = await serverRender(PresetCards, {}, { respond: (read) => (read.url === '/api/media/presets' ? presets : backend(read)) })
138
+ expect(page.html).toContain(`src="${examplePreviewUrl}"`)
139
+ expect(page.html).not.toContain(`src="${exampleUrl}"`)
140
+ expect(page.html).toContain(exampleUrl)
141
+ })
142
+
125
143
  it('file page: one read of the file and its neighbours for the three blocks, and the image read URL', async () => {
126
144
  const page = await render(FilePage, {}, '/modules/media/file?asset=a2')
127
145
  expect(page.reads.sort()).toEqual(
@@ -214,3 +232,30 @@ describe('server render: the blocks read with the page and hand it over', () =>
214
232
  expect(page.html).toContain('Demo covers')
215
233
  })
216
234
  })
235
+
236
+ // A page block that waits for its reads in `setup` is part of the page's
237
+ // Suspense: a client navigation shows it with its data, never a skeleton that
238
+ // the data then pushes around.
239
+ const PAGE_BLOCKS: [string, Parameters<typeof serverRender>[0], string[], string][] = [
240
+ ['image sizes', PresetCards, ['GET /api/media/presets'], 'thumb'],
241
+ ['recent files', RecentFiles, ['GET /api/media/stats/recent', 'GET /api/media/tree'], 'lighthouse.png'],
242
+ ['upload strip', UploadStrip, ['GET /api/media/tree'], 'dms_media.upload_strip.choose'],
243
+ ['upload queue', UploadQueue, ['GET /api/media/tree'], 'dms_media.queue.empty_description_drop'],
244
+ ['first run', FirstRun, ['GET /api/media/tree'], ''],
245
+ ['library', Explorer, ['GET /api/media/tree'], 'Catalog'],
246
+ ]
247
+
248
+ describe('page blocks: shown with the page, without a skeleton', () => {
249
+ it.each(PAGE_BLOCKS)('%s: a client navigation waits for its reads', async (_, block, reads) => {
250
+ const mounted = await suspendedMount(block, { respond: backend })
251
+ expect(mounted.waited).toBe(true)
252
+ expect(mounted.readsBeforeShown).toEqual(expect.arrayContaining(reads))
253
+ })
254
+
255
+ it.each(PAGE_BLOCKS)('%s: the server render shows its data, no skeleton', async (_, block, reads, shown) => {
256
+ const page = await render(block)
257
+ expect(page.reads).toEqual(expect.arrayContaining(reads))
258
+ expect(page.html).toContain(shown)
259
+ expect(page.html).not.toContain('data-stub="USkeleton"')
260
+ })
261
+ })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@antelopejs/dms-media",
3
- "version": "0.5.1",
3
+ "version": "0.6.1",
4
4
  "description": "Media library for the AntelopeJS DMS: uploads, folders with per-folder permissions, image sizes and light editing, with a Finder-style explorer.",
5
5
  "keywords": [
6
6
  "antelopejs",
@@ -66,19 +66,19 @@
66
66
  "@antelopejs/interface-api": ">=0.0.15 <1.0.0",
67
67
  "@antelopejs/interface-api-util": ">=0.1.3 <1.0.0",
68
68
  "@antelopejs/interface-core": ">=0.2.4 <1.0.0",
69
- "@antelopejs/interface-database": ">=0.1.10 <1.0.0",
70
- "@antelopejs/interface-database-decorators": ">=0.1.9 <1.0.0",
71
- "@antelopejs/interface-dms": ">=0.7.2 <1.0.0",
69
+ "@antelopejs/interface-database": ">=0.1.11 <1.0.0",
70
+ "@antelopejs/interface-database-decorators": ">=0.1.10 <1.0.0",
71
+ "@antelopejs/interface-dms": ">=0.9.0 <1.0.0",
72
72
  "@antelopejs/interface-dms-media": ">=0.3.0 <0.4.0",
73
- "@antelopejs/interface-file-storage": ">=0.1.4 <1.0.0",
73
+ "@antelopejs/interface-file-storage": ">=0.1.6 <1.0.0",
74
74
  "node-cron": "^4.2.1",
75
75
  "sharp": "^0.34.4",
76
76
  "zod": "~3.24.2"
77
77
  },
78
78
  "devDependencies": {
79
- "@antelopejs/core": ">=1.16.0 <2",
80
- "@antelopejs/dms": ">=0.9.3 <1.0.0",
81
- "@antelopejs/dms-frontend": "0.6.3",
79
+ "@antelopejs/core": ">=1.17.1 <2",
80
+ "@antelopejs/dms": ">=0.11.0 <1.0.0",
81
+ "@antelopejs/dms-frontend": "0.9.0",
82
82
  "@antelopejs/tooling-configs": ">=0.0.9 <1.0.0",
83
83
  "@types/chai": "^4.3.20",
84
84
  "@types/mocha": "^10",
@@ -106,5 +106,6 @@
106
106
  "skills": [
107
107
  "./skills"
108
108
  ]
109
- }
109
+ },
110
+ "dmsFrontend": "dist/frontend-module.js"
110
111
  }
@@ -12,6 +12,10 @@ Asset library: folders with per-folder ACL, direct-to-storage uploads, stable `/
12
12
  Owner pages under `/modules/media` (overview, files, uploads, file, editor, activity, presets). Members never open them:
13
13
  they reach media through `AssetType` fields on project pages. User docs: `docs/` of this package, published at
14
14
  https://dms.antelopejs.com/docs/modules/media.
15
+ Overview, uploads and activity are `live` pages (shared `rememberKey: "media"`) opening on the DMS `pageToolbar({ period: false })`
16
+ (last read + Direct / Pause, block id `toolbar`); the upload history table is `liveHold`. Needs interface-dms with `base/page-toolbar`.
17
+ Every data block carries `realtimeTopic: MEDIA_LIBRARY_TOPIC`; custom components refresh through `onLibraryChange` (DMS
18
+ `usePageLiveRefresh`, so Pause holds them). Announcements are coalesced and carry `payload.count` (changes they stand for).
15
19
 
16
20
  ## Setup
17
21
 
@@ -53,10 +57,11 @@ static form = Form({
53
57
  ## Ship content as code
54
58
 
55
59
  ```typescript
60
+ import { Hook, RegisterHook } from "@antelopejs/interface-dms/hooks";
56
61
  import { EnsureMediaFolder, ImportMediaAsset } from "@antelopejs/interface-dms-media";
57
62
 
58
- // Called by the application's lifecycle with a trusted, explicit tenant.
59
- export async function declareMedia(tenantId: string): Promise<void> {
63
+ // Once per tenant, when it is created (registered from construct()).
64
+ RegisterHook(Hook.TENANT_BEING_PROVISIONED, async ({ tenantId }) => {
60
65
  await EnsureMediaFolder({ tenantId, key: "helio.procedures", name: "Procedures", visibility: "private" });
61
66
  await ImportMediaAsset({
62
67
  tenantId,
@@ -65,31 +70,17 @@ export async function declareMedia(tenantId: string): Promise<void> {
65
70
  name: "Roof safety checklist.pdf",
66
71
  mimetype: "application/pdf",
67
72
  source: { filePath: "/abs/path.pdf" }, // or { bytes: buffer }, or { load: () => bytes }
68
- version: "2026-10-17", // optional: while unchanged, the source is not read
69
73
  });
70
- }
74
+ });
71
75
  ```
72
76
 
73
- - Required `tenantId` in types and runtime: omitted/empty/whitespace-only rejects before writes. No fallback;
74
- an explicitly chosen `DEFAULT_TENANT_ID` remains valid. Idempotent per tenant + kind + key. Returns
75
- `{ status: "created" | "updated" | "unchanged" | "preserved" | "deleted", id? }`.
76
- - New SaaS tenants: the application registers `RegisterWorkspaceLifecycleConsumer` from
77
- `@antelopejs/interface-dms-saas/workspace-lifecycle` for `created` before startup reconciliation.
78
- Delivery follows preparation/payment and is at least once: deduplicate `operationId`, persist resource links
79
- before returning a receipt, and recover incomplete attempts. Media does not register it or depend on SaaS.
80
- - `start()` is process-global: use it for registration or explicitly scoped global work, not implicit default content.
81
- Never await declarations in `construct()`. A required tenant does not prove authorization or committed provisioning.
82
- The prepayment `TENANT_BEING_PROVISIONED` hook has no automatic replay/compensation and is not durable `created`.
83
- - Deployment refresh/backfill is separate: enumerate trusted tenants, require `IsWorkspaceProvisioningCommitted(tenantId)`,
84
- fail closed on lookup errors, and coordinate writers. Idempotent APIs do not make all effects exactly-once.
85
- See the [canonical lifecycle guidance](https://dms.antelopejs.com/docs/modules/media/reference#new-saas-tenants-application-owned-durable-lifecycle).
86
- - Generated files: `source: { load }` is called only when the bytes are needed; with a `version` changed whenever the
87
- bytes change, an unchanged file is not read or generated again on reload. Files a member changed or deleted are never read.
88
- - Dropped content: `PruneMediaDeclarations({ tenantId, prefix: "helio.", keep: declaredKeys })` after declaring retires
89
- the namespace's other keys (files, then deepest folders); `RetireMediaDeclaration({ tenantId, kind, key })` one key.
90
- Removed only while still as declared (folders only when empty), else `preserved` and handed to members; never a cascade.
91
- - Never undoes a member: a row changed since its last declaration is `preserved`, a deleted one stays `deleted`;
92
- only a row still exactly as declared is refreshed. Parents before children, folders before files (await each).
77
+ - Required `tenantId` in types and runtime: omitted/empty/whitespace-only rejects before writes. No fallback.
78
+ Idempotent per tenant + kind + key. Returns `{ status: "created" | "kept", id }`.
79
+ - Call from `Hook.TENANT_BEING_PROVISIONED` (the DMS fires it for `default` on the start that creates it, after
80
+ `DATABASE_INITIALIZED`; dms-saas for each workspace). Never from `start()` / `DATABASE_INITIALIZED`, never awaited in `construct()`.
81
+ - Written once: a key declared before is `kept` without reading its source. No refresh, no retirement, no `version`:
82
+ the content belongs to the members. Parents before children, folders before files (await each).
83
+ - `source: { load }` is called only when the file is created. Bytes are written with `WriteFile` (no HTTP round trip).
93
84
  - Same rules as the dashboard (names, unique sibling folders, allowed and field types, quota, decodable images); errors
94
85
  name the key (`Media file 'helio.x': ...`). Never write `media_folders` / `media_assets` directly.
95
86
 
@@ -100,6 +91,8 @@ export async function declareMedia(tenantId: string): Promise<void> {
100
91
  - The module declares `/media/**` to the frontend server (`backendProxies`, `auth: "session"`): the same links work on
101
92
  the dashboard's origin, a private file opening for a signed-in member. Copied links start with `publicBaseUrl`.
102
93
  - Authenticated: `GET /api/media/assets/:id/read-url?preset=`.
94
+ - An image the dashboard shows uses a relative `/media/...` path or a signed read URL, never a `publicBaseUrl` link:
95
+ the API's origin carries no session cookie, so a private file answers 401 there.
103
96
 
104
97
  ## Gotchas
105
98
 
@@ -1,54 +1,10 @@
1
1
  import { BasicDataModel } from "@antelopejs/interface-database-decorators";
2
- import { triggerEvent } from "@antelopejs/interface-database-decorators/modifiers/common";
3
2
  import { MEDIA_FOLDERS_TABLE_NAME, MediaFolder } from "../tables";
4
3
 
5
4
  export class MediaFolderModel extends BasicDataModel(
6
5
  MediaFolder,
7
6
  MEDIA_FOLDERS_TABLE_NAME,
8
7
  ) {
9
- /** The row of `expected` while its editable state and path are still as observed. */
10
- private whileAsObserved(expected: MediaFolder) {
11
- return this.table.filter((row) =>
12
- row
13
- .key("_id")
14
- .eq(expected._id)
15
- .and(row.key("name").eq(expected.name))
16
- .and(
17
- row
18
- .key("parentId")
19
- .default("")
20
- .eq(expected.parentId || ""),
21
- )
22
- .and(row.key("path").eq(expected.path))
23
- .and(row.key("visibility").eq(expected.visibility))
24
- .and(
25
- row
26
- .key("json_acl")
27
- .default("")
28
- .eq(expected.json_acl || ""),
29
- ),
30
- );
31
- }
32
-
33
- /** Applies a declaration only while the observed editable state and path still match. */
34
- async compareDeclared(
35
- expected: MediaFolder,
36
- patch: Partial<MediaFolder>,
37
- ): Promise<boolean> {
38
- const instance = MediaFolderModel.fromPlainData(patch);
39
- triggerEvent(instance, "update");
40
- const count = await this.whileAsObserved(expected)
41
- .update(MediaFolderModel.toDatabase(instance))
42
- .run();
43
- return count === 1;
44
- }
45
-
46
- /** Deletes a retired declaration's folder only while the observed editable state and path still match. */
47
- async deleteDeclared(expected: MediaFolder): Promise<boolean> {
48
- const count = await this.whileAsObserved(expected).delete().run();
49
- return count === 1;
50
- }
51
-
52
8
  async getChildren(parentId: string): Promise<MediaFolder[]> {
53
9
  return this.getBy("parentId", parentId);
54
10
  }
@@ -13,9 +13,9 @@ export const MEDIA_DECLARATIONS_TABLE_NAME = "media_declarations";
13
13
  export type MediaDeclarationKind = "folder" | "asset";
14
14
 
15
15
  /**
16
- * A folder or file a module declared as code, by the key it chose: what it
17
- * last declared, and the state it left the row in, to tell a member's change
18
- * from content still as declared.
16
+ * A folder or file a module declared as code, by the key it chose: what lets
17
+ * a later declaration name it (a declared parent folder) and a repeated
18
+ * declaration leave it as it is.
19
19
  */
20
20
  @RegisterTable(MEDIA_DECLARATIONS_TABLE_NAME, TENANT_SCHEMA_NAME)
21
21
  export class MediaDeclaration extends Table {
@@ -40,20 +40,4 @@ export class MediaDeclaration extends Table {
40
40
  /** Id of the declared folder or asset row. */
41
41
  @Field("string")
42
42
  declare targetId: string;
43
-
44
- /** Hash of the last declaration applied. */
45
- @Field("string")
46
- declare declaredHash: string;
47
-
48
- /** Hash of the row's member-editable state right after that declaration was applied. */
49
- @Field("string")
50
- declare appliedHash: string;
51
-
52
- /** Hash of the declared file's bytes; absent for a folder. */
53
- @Field("string")
54
- declare contentHash?: string;
55
-
56
- /** Caller's version of those bytes; empty when the last declaration gave none. */
57
- @Field("string")
58
- declare version?: string;
59
43
  }
@@ -5,10 +5,9 @@ import type {
5
5
  MediaAssetDeclaration,
6
6
  MediaDeclarationResult,
7
7
  } from "@antelopejs/interface-dms-media";
8
- import { cleanupAssetFiles, updateAssetMedia } from "../asset-lifecycle";
9
8
  import { feedingBinding } from "../bindings";
10
9
  import { getMediaConfig } from "../config";
11
- import type { MediaAsset, MediaDeclaration, MediaFolder } from "../db";
10
+ import type { MediaAsset, MediaFolder } from "../db";
12
11
  import { uploadStorageBytes } from "../derivatives";
13
12
  import { recordMediaEvent } from "../library/events";
14
13
  import {
@@ -27,18 +26,13 @@ import {
27
26
  describeDeclarationIssues,
28
27
  } from "../validation/declared.schema";
29
28
  import { findBoundFolder, findDeclaredFolder } from "./folders";
30
- import { waitForTenant, writeWhenReachable } from "./readiness";
31
29
  import {
32
30
  DECLARED_CONTENT_AUTHOR,
33
31
  type DeclaredModels,
34
32
  declaredModels,
35
- hashBytes,
36
- hashState,
37
- judgeDeclaredRow,
38
- judgeMemberChange,
39
33
  MediaDeclarationError,
40
34
  parseDeclaration,
41
- saveDeclaration,
35
+ rememberDeclaration,
42
36
  withDeclarationLock,
43
37
  } from "./records";
44
38
 
@@ -57,38 +51,8 @@ interface PreparedFile {
57
51
  image: ImageProbe;
58
52
  }
59
53
 
60
- interface AssetHashes {
61
- declaredHash: string;
62
- contentHash: string;
63
- }
64
-
65
54
  type Fail = (reason: string) => never;
66
55
 
67
- /** The member-editable state of a file: its name, folder, alt text, visibility and content. */
68
- export function assetStateHash(asset: MediaAsset): string {
69
- return hashState({
70
- name: asset.name,
71
- folderId: asset.folderId,
72
- alt: asset.alt || null,
73
- visibility: asset.visibility,
74
- storageKey: asset.storageKey,
75
- });
76
- }
77
-
78
- function assetHashes(
79
- declaration: DeclaredAssetInput,
80
- contentHash: string,
81
- ): AssetHashes {
82
- const declaredHash = hashState({
83
- name: declaration.name,
84
- folder: declaration.folder,
85
- alt: declaration.alt ?? null,
86
- mimetype: declaration.mimetype,
87
- content: contentHash,
88
- });
89
- return { declaredHash, contentHash };
90
- }
91
-
92
56
  function describeError(error: unknown): string {
93
57
  return error instanceof Error ? error.message : String(error);
94
58
  }
@@ -124,33 +88,6 @@ async function readSource(
124
88
  return bytes;
125
89
  }
126
90
 
127
- /**
128
- * A declared file's bytes, read at most once and only when a decision needs
129
- * them: generating or reading content every boot is what `version` and lazy
130
- * sources let callers avoid.
131
- */
132
- class DeclaredContent {
133
- private bytes?: Promise<Buffer>;
134
-
135
- constructor(
136
- private readonly declaration: DeclaredAssetInput,
137
- private readonly fail: Fail,
138
- ) {}
139
-
140
- read(): Promise<Buffer> {
141
- this.bytes ??= readSource(this.declaration, this.fail);
142
- return this.bytes;
143
- }
144
-
145
- /** The bytes' hash, taken from the last declaration while the caller's version still matches it. */
146
- async hash(record: MediaDeclaration | undefined): Promise<string> {
147
- const { version } = this.declaration;
148
- if (version && record?.contentHash && record.version === version)
149
- return record.contentHash;
150
- return hashBytes(await this.read());
151
- }
152
- }
153
-
154
91
  /** The binding whose field the folder feeds, through its linked ancestors when it has no binding itself. */
155
92
  async function fieldBindingOf(
156
93
  models: DeclaredModels,
@@ -172,23 +109,19 @@ async function findTargetFolder(
172
109
  models: DeclaredModels,
173
110
  declaration: DeclaredAssetInput,
174
111
  fail: Fail,
175
- ): Promise<MediaFolder | undefined> {
112
+ ): Promise<MediaFolder> {
176
113
  const target = declaration.folder;
177
114
  if ("binding" in target) return findBoundFolder(models, target.binding, fail);
178
- return (await findDeclaredFolder(models, target.key, fail)).folder;
115
+ return findDeclaredFolder(models, target.key, fail);
179
116
  }
180
117
 
181
118
  /** The checks of the upload routes: type, field type, quota and image decoding. */
182
119
  async function prepareFile(
183
120
  { models, declaration, fieldBinding }: AssetTarget,
184
121
  bytes: Buffer,
185
- replacedSize: number,
186
122
  ): Promise<PreparedFile> {
187
123
  assertUploadTypeAllowed(fieldBinding, declaration.name, declaration.mimetype);
188
- await assertWithinQuota(
189
- models.assetModel,
190
- Math.max(bytes.byteLength - replacedSize, 0),
191
- );
124
+ await assertWithinQuota(models.assetModel, bytes.byteLength);
192
125
  const image = await probeImageBytes(
193
126
  async () => bytes,
194
127
  declaration.mimetype,
@@ -206,14 +139,12 @@ function writeFile(
206
139
  { models, declaration, folder }: AssetTarget,
207
140
  file: PreparedFile,
208
141
  ): Promise<string> {
209
- return writeWhenReachable(() =>
210
- uploadStorageBytes(
211
- file.bytes,
212
- declaration.name,
213
- file.mimetype,
214
- `media/${models.tenantId}/${folder._id}`,
215
- getMediaConfig().storage,
216
- ),
142
+ return uploadStorageBytes(
143
+ file.bytes,
144
+ declaration.name,
145
+ file.mimetype,
146
+ `media/${models.tenantId}/${folder._id}`,
147
+ getMediaConfig().storage,
217
148
  );
218
149
  }
219
150
 
@@ -274,151 +205,29 @@ async function createAsset(
274
205
  return asset;
275
206
  }
276
207
 
277
- /** Publishes metadata and optional new bytes together, only while the file is untouched. */
278
- async function refreshAsset(
279
- target: AssetTarget,
280
- asset: MediaAsset,
281
- content: DeclaredContent,
282
- isContentChanged: boolean,
283
- ): Promise<MediaAsset | undefined> {
284
- const { models, declaration, folder, fieldBinding } = target;
285
- const { assetModel } = models;
286
- const patch: Partial<MediaAsset> = {
287
- name: declaration.name,
288
- folderId: folder._id,
289
- alt: declaration.alt ?? "",
290
- };
291
- let storageKey: string | undefined;
292
- if (isContentChanged) {
293
- const file = await prepareFile(target, await content.read(), asset.size);
294
- storageKey = await writeFile(target, file);
295
- Object.assign(patch, {
296
- storageKey,
297
- mimetype: file.mimetype,
298
- size: file.bytes.byteLength,
299
- width: file.image.width,
300
- height: file.image.height,
301
- json_derivatives: "",
302
- });
303
- } else {
304
- assertUploadTypeAllowed(fieldBinding, declaration.name, asset.mimetype);
305
- }
306
- for (;;) {
307
- const fresh = await assetModel.get(asset._id);
308
- const isStillAsDeclared =
309
- fresh !== undefined &&
310
- !fresh.isDeleting &&
311
- assetStateHash(fresh) === assetStateHash(asset);
312
- if (!isStillAsDeclared) {
313
- if (storageKey)
314
- await DeleteFile(storageKey, getMediaConfig().storage).catch(
315
- () => undefined,
316
- );
317
- return undefined;
318
- }
319
- if (
320
- await updateAssetMedia(assetModel, fresh, patch, {
321
- preserveDetails: true,
322
- })
323
- )
324
- break;
325
- }
326
- if (storageKey) await cleanupAssetFiles(assetModel, asset._id);
327
- // A concurrent edit after publication must not become our new baseline.
328
- return Object.assign(asset, patch);
329
- }
330
-
331
- function rememberAsset(
332
- target: AssetTarget,
333
- record: MediaDeclaration | undefined,
334
- asset: MediaAsset,
335
- hashes: AssetHashes,
336
- ): Promise<void> {
337
- return saveDeclaration(target.models.declarationModel, record, {
338
- kind: "asset",
339
- key: target.declaration.key,
340
- targetId: asset._id,
341
- appliedHash: assetStateHash(asset),
342
- version: target.declaration.version ?? "",
343
- ...hashes,
344
- });
345
- }
346
-
347
- /** Remembers a new caller version of unchanged bytes, so the next boot does not read them again. */
348
- async function rememberVersion(
349
- models: DeclaredModels,
350
- record: MediaDeclaration,
351
- version: string | undefined,
352
- ): Promise<void> {
353
- if (!version || record.version === version) return;
354
- await models.declarationModel.update(record._id, { version });
355
- }
356
-
357
208
  async function applyAssetDeclaration(
358
209
  declaration: DeclaredAssetInput,
359
210
  ): Promise<MediaDeclarationResult> {
360
- const fail: Fail = (reason) => {
361
- throw new MediaDeclarationError("asset", declaration.key, reason);
362
- };
363
- const content = new DeclaredContent(declaration, fail);
364
- await waitForTenant(declaration.tenantId);
365
211
  const models = declaredModels(declaration.tenantId);
366
212
  const record = await models.declarationModel.findByKey(
367
213
  "asset",
368
214
  declaration.key,
369
215
  );
370
- const stored = record && (await models.assetModel.get(record.targetId));
371
- const asset = stored && !stored.isDeleting ? stored : undefined;
372
- // Deleted or changed by a member: the new content cannot matter, so it is not read.
373
- const change =
374
- record && judgeMemberChange(record, asset, asset && assetStateHash(asset));
375
- if (change) return change;
376
- const hashes = assetHashes(declaration, await content.hash(record));
377
- const verdict =
378
- record &&
379
- judgeDeclaredRow(
380
- record,
381
- asset,
382
- asset && assetStateHash(asset),
383
- hashes.declaredHash,
384
- );
385
- if (verdict) {
386
- if (record) await rememberVersion(models, record, declaration.version);
387
- return verdict;
388
- }
216
+ if (record) return { status: "kept", id: record.targetId };
217
+ const fail: Fail = (reason) => {
218
+ throw new MediaDeclarationError("asset", declaration.key, reason);
219
+ };
389
220
  const folder = await findTargetFolder(models, declaration, fail);
390
- // A file whose declared folder a member deleted went with it, or never came.
391
- if (!folder)
392
- return asset
393
- ? { status: "preserved", id: asset._id }
394
- : { status: "deleted" };
395
221
  const target: AssetTarget = {
396
222
  models,
397
223
  declaration,
398
224
  folder,
399
225
  fieldBinding: await fieldBindingOf(models, folder),
400
226
  };
401
- if (!record || !asset) {
402
- const file = await prepareFile(target, await content.read(), 0);
403
- const created = await createAsset(target, file);
404
- await rememberAsset(target, record, created, hashes);
405
- return { status: "created", id: created._id };
406
- }
407
- const isContentChanged = record.contentHash !== hashes.contentHash;
408
- const refreshed = await refreshAsset(
409
- target,
410
- asset,
411
- content,
412
- isContentChanged,
413
- );
414
- if (!refreshed) {
415
- const current = await models.assetModel.get(asset._id);
416
- return current && !current.isDeleting
417
- ? { status: "preserved", id: asset._id }
418
- : { status: "deleted" };
419
- }
420
- await rememberAsset(target, record, refreshed, hashes);
421
- return { status: "updated", id: refreshed._id };
227
+ const file = await prepareFile(target, await readSource(declaration, fail));
228
+ const asset = await createAsset(target, file);
229
+ await rememberDeclaration(models, "asset", declaration.key, asset._id);
230
+ return { status: "created", id: asset._id };
422
231
  }
423
232
 
424
233
  /** Implements `ImportMediaAsset`. */