@bsv/create-dpp-app 0.1.0-beta.1 → 0.1.0-beta.2

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 (143) hide show
  1. package/NOTICE +2 -0
  2. package/PATENTS +12 -0
  3. package/README.md +26 -6
  4. package/dist/index.js +36 -8
  5. package/package.json +9 -5
  6. package/template/Dockerfile +4 -2
  7. package/template/README.md +297 -42
  8. package/template/_env.example +82 -13
  9. package/template/_github/workflows/ci.yml +3 -3
  10. package/template/apps/api/API.md +86 -16
  11. package/template/apps/api/package.json +9 -4
  12. package/template/apps/api/src/bound-profiles.ts +590 -0
  13. package/template/apps/api/src/claims.ts +175 -56
  14. package/template/apps/api/src/cli.ts +64 -7
  15. package/template/apps/api/src/config.ts +124 -10
  16. package/template/apps/api/src/custody.ts +241 -69
  17. package/template/apps/api/src/dev-index.ts +58 -9
  18. package/template/apps/api/src/env-file.ts +55 -0
  19. package/template/apps/api/src/epcis/exchange.ts +434 -0
  20. package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
  21. package/template/apps/api/src/epcis/routes.ts +364 -0
  22. package/template/apps/api/src/epcis/sources.ts +142 -0
  23. package/template/apps/api/src/go-live.ts +226 -0
  24. package/template/apps/api/src/http-error.ts +15 -0
  25. package/template/apps/api/src/identifiers.ts +1 -1
  26. package/template/apps/api/src/index-client.ts +131 -6
  27. package/template/apps/api/src/index-projects.ts +53 -0
  28. package/template/apps/api/src/lifecycle-authority.ts +49 -0
  29. package/template/apps/api/src/lifecycle.ts +485 -0
  30. package/template/apps/api/src/main.ts +10 -2
  31. package/template/apps/api/src/parties.ts +2 -2
  32. package/template/apps/api/src/platform.ts +72 -17
  33. package/template/apps/api/src/portability/commands.ts +224 -0
  34. package/template/apps/api/src/portability/export.ts +708 -0
  35. package/template/apps/api/src/portability/package.ts +270 -0
  36. package/template/apps/api/src/portability/restore.ts +863 -0
  37. package/template/apps/api/src/profiles.ts +38 -13
  38. package/template/apps/api/src/reader.ts +172 -3
  39. package/template/apps/api/src/resolver.ts +159 -0
  40. package/template/apps/api/src/sector-examples.ts +390 -0
  41. package/template/apps/api/src/server.ts +253 -60
  42. package/template/apps/api/src/store.ts +198 -21
  43. package/template/apps/api/src/validation-engine.ts +172 -0
  44. package/template/apps/api/src/wallet.ts +30 -17
  45. package/template/apps/api/src/worker.ts +20 -13
  46. package/template/apps/api/src/writer.ts +383 -131
  47. package/template/apps/api/test/bound-http.test.ts +496 -0
  48. package/template/apps/api/test/bound-profiles.test.ts +547 -0
  49. package/template/apps/api/test/config.test.ts +148 -3
  50. package/template/apps/api/test/custody-journal.test.ts +415 -0
  51. package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
  52. package/template/apps/api/test/custom-profile.test.ts +167 -0
  53. package/template/apps/api/test/env-file.test.ts +53 -0
  54. package/template/apps/api/test/epcis-fixtures.ts +270 -0
  55. package/template/apps/api/test/epcis-http.test.ts +1179 -0
  56. package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
  57. package/template/apps/api/test/epcis-separation.test.ts +253 -0
  58. package/template/apps/api/test/epcis-web.test.ts +230 -0
  59. package/template/apps/api/test/exit-exercise.test.ts +1038 -0
  60. package/template/apps/api/test/external-index.test.ts +3 -2
  61. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
  62. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
  63. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
  64. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
  65. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
  66. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
  67. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
  68. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
  69. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
  70. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
  71. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
  72. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
  73. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
  74. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
  75. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
  76. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
  77. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
  78. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
  79. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
  80. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
  81. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
  82. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
  83. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
  84. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
  85. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
  86. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
  87. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
  88. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
  89. package/template/apps/api/test/go-live.test.ts +179 -0
  90. package/template/apps/api/test/gs1-global-setup.ts +33 -0
  91. package/template/apps/api/test/gs1-test-env.ts +5 -0
  92. package/template/apps/api/test/identifier-host.test.ts +256 -0
  93. package/template/apps/api/test/index-projects.test.ts +81 -0
  94. package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
  95. package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
  96. package/template/apps/api/test/lifecycle.test.ts +17 -6
  97. package/template/apps/api/test/manifest-notice.test.ts +36 -0
  98. package/template/apps/api/test/network-guard.ts +113 -0
  99. package/template/apps/api/test/portability.test.ts +655 -0
  100. package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
  101. package/template/apps/api/test/retired-profiles.test.ts +216 -0
  102. package/template/apps/api/test/sector-cutover.test.ts +95 -0
  103. package/template/apps/api/test/sector-forms.test.ts +420 -0
  104. package/template/apps/api/test/unjoined-index.test.ts +62 -0
  105. package/template/apps/api/test/validation-engine.test.ts +328 -0
  106. package/template/apps/api/test/wallet-monitor.test.ts +38 -0
  107. package/template/apps/api/test/writer-journal.test.ts +327 -0
  108. package/template/apps/api/vitest.config.ts +3 -0
  109. package/template/apps/web/src/app.tsx +8 -4
  110. package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
  111. package/template/apps/web/src/components/bound/field-view.tsx +237 -0
  112. package/template/apps/web/src/components/bound/pieces.tsx +169 -0
  113. package/template/apps/web/src/components/bound/readings.tsx +152 -0
  114. package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
  115. package/template/apps/web/src/components/claim-dialog.tsx +344 -0
  116. package/template/apps/web/src/components/epcis-events.tsx +119 -0
  117. package/template/apps/web/src/components/layout.tsx +17 -0
  118. package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
  119. package/template/apps/web/src/components/passport-form.tsx +2 -2
  120. package/template/apps/web/src/components/read-passport.tsx +4 -3
  121. package/template/apps/web/src/components/reading.tsx +32 -39
  122. package/template/apps/web/src/lib/api.ts +136 -26
  123. package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
  124. package/template/apps/web/src/lib/bound/display.ts +122 -0
  125. package/template/apps/web/src/lib/bound/fields.ts +128 -0
  126. package/template/apps/web/src/lib/bound/form-model.ts +521 -0
  127. package/template/apps/web/src/lib/bound/forms.ts +15 -0
  128. package/template/apps/web/src/lib/bound/identity.ts +48 -0
  129. package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
  130. package/template/apps/web/src/lib/bound/units.ts +37 -0
  131. package/template/apps/web/src/lib/epcis.ts +345 -0
  132. package/template/apps/web/src/lib/format.ts +27 -4
  133. package/template/apps/web/src/lib/lifecycle.ts +350 -0
  134. package/template/apps/web/src/pages/accept.tsx +8 -3
  135. package/template/apps/web/src/pages/events.tsx +388 -0
  136. package/template/apps/web/src/pages/new-passport.tsx +25 -2
  137. package/template/apps/web/src/pages/operations.tsx +22 -3
  138. package/template/apps/web/src/pages/passport.tsx +226 -162
  139. package/template/apps/web/src/pages/public-passport.tsx +50 -10
  140. package/template/apps/web/src/pages/wallet.tsx +1 -1
  141. package/template/apps/web/vite.config.ts +12 -4
  142. package/template/deploy/compose.yml +14 -2
  143. package/template/package.json +9 -3
@@ -0,0 +1,434 @@
1
+ // EPCIS exchange for this application: file import, a configured pull and
2
+ // exact export. Every one of them is a call into
3
+ // `@bsv/dpp-credentials/epcis-exchange`. Nothing here parses, validates,
4
+ // classifies or pages: this file chooses the storage, provisions the GS1
5
+ // files, runs recovery, and hands the module what it asks for.
6
+ //
7
+ // What an import is not: it changes no custody, signs nothing, writes nothing
8
+ // on chain and never reaches the wallet. An event that is retained is data
9
+ // someone supplied. A document that passes validation says nothing about who
10
+ // wrote it or whether its events happened. This file and the two beside it
11
+ // import no wallet, writer or index code, and a test holds them to that.
12
+ import { lookup } from 'node:dns/promises'
13
+ import { dirname, isAbsolute, resolve } from 'node:path'
14
+ import { fileURLToPath } from 'node:url'
15
+ import type { Db } from 'mongodb'
16
+ import { provisionGs1Artefacts, verifyGs1Artefacts, type Gs1ProvisionReport } from '@bsv/dpp-credentials'
17
+ import {
18
+ EpcisStorageError,
19
+ createMemoryEpcisStorage,
20
+ deriveEpcisEventProjection,
21
+ exportEpcisSource,
22
+ findEpcisAssociations,
23
+ getEpcisConflict,
24
+ getEpcisImport,
25
+ getEpcisPull,
26
+ importEpcisSource,
27
+ openFileEpcisStorage,
28
+ listEpcisImports,
29
+ listEpcisPullPages,
30
+ pullEpcisEvents,
31
+ recoverEpcisExchange,
32
+ resolveEpcisConflict,
33
+ type EpcisAssociationGranularity,
34
+ type EpcisAssociationRecord,
35
+ type EpcisConflict,
36
+ type EpcisExchangeStorage,
37
+ type EpcisImportEvent,
38
+ type EpcisImportOutcome,
39
+ type EpcisImportPolicy,
40
+ type EpcisImportRecord,
41
+ type EpcisOriginalExport,
42
+ type EpcisPullOutcome,
43
+ type EpcisPullPageRecord,
44
+ type EpcisPullQueryInput,
45
+ type EpcisPullRecord,
46
+ type EpcisRecoveryReport,
47
+ type EpcisResolutionDisposition,
48
+ type EpcisResolutionOutcome,
49
+ type FileEpcisStorage,
50
+ } from '@bsv/dpp-credentials/epcis-exchange'
51
+ import { openMongoEpcisStorage, type MongoEpcisStorage } from './mongo-storage.js'
52
+ import { describeEpcisSource, type EpcisSourceConfig, type EpcisSourceDescription } from './sources.js'
53
+
54
+ const PROJECT_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../../..')
55
+
56
+ /** The operator policy every import and pull of this application is read under: the module's default limits, under a name of this application's own. */
57
+ export const EPCIS_POLICY: EpcisImportPolicy = { policyId: 'starter-default@1' }
58
+ /** The source scope a file is imported under when the request names none. */
59
+ export const EPCIS_UPLOAD_SOURCE = 'upload'
60
+ /** How many imports the conflict listing reads before it says it stopped. */
61
+ const CONFLICT_SCAN_LIMIT = 2000
62
+
63
+ /** Which adapter holds the exchange's records: the configuration's `EPCIS_STORAGE`. */
64
+ export type EpcisStorageSetting = { kind: 'mongodb' } | { kind: 'file'; dir: string }
65
+
66
+ export interface OpenedExchangeStorage {
67
+ storage: EpcisExchangeStorage
68
+ kind: 'mongodb' | 'file' | 'memory'
69
+ close(): Promise<void>
70
+ }
71
+
72
+ /**
73
+ * Open the store the configuration chose. `mongodb` is the application
74
+ * database, or memory when there is none. `file` is the module's file-system
75
+ * adapter over a folder of this deployment. Both are handed to the module as
76
+ * the same six methods, and the module does not know which it was given.
77
+ * The exchange opens its store through this, and so do the export and the
78
+ * restore of this application, which run when the API does not.
79
+ */
80
+ export async function openExchangeStorage(options: { setting?: EpcisStorageSetting; db?: Db; log: (line: string) => void }): Promise<OpenedExchangeStorage> {
81
+ const { log } = options
82
+ if (options.setting?.kind === 'file') {
83
+ const folder = isAbsolute(options.setting.dir) ? options.setting.dir : resolve(PROJECT_ROOT, options.setting.dir)
84
+ const file: FileEpcisStorage = await openFileEpcisStorage(folder)
85
+ log(`EPCIS store: the file-system adapter over ${folder}.`)
86
+ if (file.reopened.journalsApplied > 0) log('EPCIS store: a batch that was committed before the last stop was applied.')
87
+ return { storage: file, kind: 'file', close: () => file.close() }
88
+ }
89
+ if (options.db != null) {
90
+ const mongo: MongoEpcisStorage = await openMongoEpcisStorage(options.db)
91
+ if (mongo.reopened.batchesApplied > 0) log('EPCIS store: a batch that was committed before the last stop was applied.')
92
+ return { storage: mongo, kind: 'mongodb', close: () => mongo.close() }
93
+ }
94
+ log('EPCIS store: no MongoDB, so imports are held in memory and are gone when this process ends.')
95
+ return { storage: createMemoryEpcisStorage(), kind: 'memory', close: async () => undefined }
96
+ }
97
+
98
+ /**
99
+ * A call to the store did not complete: the database did not answer, a write
100
+ * failed, the disk is full. It is not a refusal of a document and not a fault
101
+ * in a request, and the routes answer it by its own name, as something that
102
+ * may be tried again. `cause` is the store's own error, which is logged for
103
+ * the operator and never sent to a caller: an error from a database driver
104
+ * can name hosts and paths.
105
+ */
106
+ export class EpcisStoreFailure extends Error {
107
+ constructor(
108
+ /** The storage method that failed. */
109
+ readonly method: keyof EpcisExchangeStorage,
110
+ cause: unknown
111
+ ) {
112
+ super(`the EPCIS store did not complete ${method}`, { cause })
113
+ this.name = 'EpcisStoreFailure'
114
+ }
115
+ }
116
+
117
+ /**
118
+ * The same store, with every failure of one of its six methods named as a
119
+ * store failure. The module hands on whatever a store throws, unchanged, so
120
+ * this is the one place that can say for certain that an error came from the
121
+ * store and not from the module or a request. An `EpcisStorageError` passes
122
+ * as it is: it is already the store's own named refusal of a call or of a
123
+ * store it cannot use, and the routes read its code.
124
+ */
125
+ export function namingStoreFailures(inner: EpcisExchangeStorage, log: (line: string) => void): EpcisExchangeStorage {
126
+ const named = <A extends unknown[], T>(method: keyof EpcisExchangeStorage, run: (...args: A) => Promise<T>) => async (...args: A): Promise<T> => {
127
+ try {
128
+ return await run(...args)
129
+ } catch (error) {
130
+ if (error instanceof EpcisStorageError) throw error
131
+ // For the operator: which call, and what the store said. No record, byte or credential is part of it.
132
+ log(`EPCIS store: ${method} did not complete (${error instanceof Error ? `${error.name}: ${error.message}` : String(error)}).`)
133
+ throw new EpcisStoreFailure(method, error)
134
+ }
135
+ }
136
+ return {
137
+ putBytes: named('putBytes', (sha256: string, bytes: Uint8Array) => inner.putBytes(sha256, bytes)),
138
+ getBytes: named('getBytes', (sha256: string) => inner.getBytes(sha256)),
139
+ deleteBytes: named('deleteBytes', (sha256: string) => inner.deleteBytes(sha256)),
140
+ get: named('get', (kind: string, key: string) => inner.get(kind, key)),
141
+ list: named('list', (kind: string, options: Parameters<EpcisExchangeStorage['list']>[1]) => inner.list(kind, options)),
142
+ commit: named('commit', (writes: Parameters<EpcisExchangeStorage['commit']>[0]) => inner.commit(writes)),
143
+ }
144
+ }
145
+
146
+ export interface EpcisExchangeOptions {
147
+ config: { gs1Dir: string; gs1Offline: boolean; sources: EpcisSourceConfig[]; storage?: EpcisStorageSetting }
148
+ /** The application database. Without one, and without a folder chosen as the store, imports are held in memory and are gone when the process ends. */
149
+ db?: Db
150
+ /** A store to use in place of the one this would open. A test hands in one that stops where a crash would. */
151
+ storage?: EpcisExchangeStorage
152
+ /** One line per thing start-up did, and one per step of a pull. No line carries a credential. */
153
+ log: (line: string) => void
154
+ /** The transport, for the GS1 files at start-up and for every page of a pull. The platform's by default. */
155
+ fetch?: typeof globalThis.fetch
156
+ now?: () => string
157
+ }
158
+
159
+ /** What start-up found when it provisioned the pinned GS1 files. */
160
+ export interface EpcisArtefactState {
161
+ dir: string
162
+ /** `present`: every file was already in the folder. `fetched`: at least one was obtained from GS1 and checked. `unavailable`: at least one is missing or wrong, and every import and pull is refused until it is provided. */
163
+ state: 'present' | 'fetched' | 'unavailable'
164
+ files: Array<{ fileName: string; outcome: 'present' | 'fetched' | 'failed'; reason?: string }>
165
+ /** How to provide the files, when they are unavailable. */
166
+ remedy?: string
167
+ }
168
+
169
+ /** One relationship between an identifier and a retained event, with where the event came from and whether its document was valid. */
170
+ export interface EpcisEventEntry {
171
+ association: EpcisAssociationRecord
172
+ /** The import that holds the event: its source, its validity and how it arrived. */
173
+ source: { importId: string; sourceId: string; receivedAt: string; documentValidity: 'valid' | 'invalid'; state: EpcisImportRecord['state']; provenance: EpcisImportRecord['sourceLocation']; sha256: string }
174
+ /** What the import record says about this event. */
175
+ event?: EpcisImportEvent
176
+ /** The event as the retained document holds it, extension members included. Generated from the retained bytes by the module's projection. */
177
+ body?: unknown
178
+ }
179
+
180
+ /** One retained event, read from the bytes as they were received. Reading it changes nothing: the import, its bytes and its records stay as they were. */
181
+ export interface RetainedEvent {
182
+ record: EpcisImportRecord
183
+ event: EpcisImportEvent
184
+ /** The event object, exactly as the received document holds it. */
185
+ body: Record<string, unknown>
186
+ /** The document's inline `@context` objects whose every value is a namespace IRI: the prefixes its extension members are read under. */
187
+ inlineContexts: Array<Record<string, string>>
188
+ }
189
+
190
+ /** The value an RFC 6901 pointer names in a parsed document. */
191
+ function atPointer(document: unknown, pointer: string): unknown {
192
+ if (pointer === '') return document
193
+ let at: unknown = document
194
+ for (const raw of pointer.split('/').slice(1)) {
195
+ const token = raw.replace(/~1/g, '/').replace(/~0/g, '~')
196
+ if (Array.isArray(at) && /^(0|[1-9][0-9]*)$/.test(token)) at = at[Number(token)]
197
+ else if (at != null && typeof at === 'object' && !Array.isArray(at) && Object.hasOwn(at, token)) at = (at as Record<string, unknown>)[token]
198
+ else return undefined
199
+ }
200
+ return at
201
+ }
202
+
203
+ export interface EpcisExchange {
204
+ readonly storage: EpcisExchangeStorage
205
+ readonly storageKind: 'mongodb' | 'file' | 'memory' | 'supplied'
206
+ /** The folder the pinned GS1 files are read from. */
207
+ readonly artefactsDir: string
208
+ /** What start-up found. `status()` looks at the folder again. */
209
+ readonly artefacts: EpcisArtefactState
210
+ readonly recovery: EpcisRecoveryReport
211
+ readonly sources: EpcisSourceConfig[]
212
+ status(): { storage: EpcisExchange['storageKind']; artefacts: EpcisArtefactState; recovery: EpcisRecoveryReport; sources: EpcisSourceDescription[]; policy: string }
213
+ importDocument(input: { sourceId: string; requestId: string; bytes: Uint8Array; mediaType: string; filename?: string }): Promise<EpcisImportOutcome>
214
+ listImports(options: { after?: string; limit?: number }): Promise<EpcisImportRecord[]>
215
+ getImport(importId: string): Promise<EpcisImportRecord | undefined>
216
+ exportOriginal(importId: string): Promise<EpcisOriginalExport | undefined>
217
+ /** One bounded run against a configured source. Undefined when no source has that identifier. */
218
+ pull(input: { sourceId: string; queryId: string; query: EpcisPullQueryInput; window?: 'watermark' | 'query-bounds' }): Promise<EpcisPullOutcome | undefined>
219
+ getPull(sourceId: string, queryId: string): Promise<{ pull: EpcisPullRecord; pages: EpcisPullPageRecord[] } | undefined>
220
+ eventsFor(query: { identifier: string; granularity: EpcisAssociationGranularity; sourceId?: string; after?: string; limit?: number }): Promise<{ events: EpcisEventEntry[]; next?: string }>
221
+ /** One retained event as the original document holds it, read from the retained bytes, with the import record and the document's inline context declarations. Undefined when no import or no event is there. */
222
+ retainedEvent(importId: string, pointer: string): Promise<RetainedEvent | undefined>
223
+ listConflicts(): Promise<{ conflicts: EpcisConflict[]; importsRead: number; truncated: boolean }>
224
+ getConflict(conflictId: string): Promise<EpcisConflict | undefined>
225
+ resolveConflict(input: { conflictId: string; decision: string; disposition: EpcisResolutionDisposition; selectedBodyDigest?: string; decidedAt?: string; decidedBy?: string }): Promise<EpcisResolutionOutcome>
226
+ close(): Promise<void>
227
+ }
228
+
229
+ const remedyFor = (dir: string): string =>
230
+ `Start the API again with network access to https://ref.gs1.org, or run "npx dpp-gs1-artefacts fetch --dir ${dir}", or place the files GS1 publishes in ${dir} under the names "npx dpp-gs1-artefacts verify --dir ${dir}" prints.`
231
+
232
+ function artefactState(report: Pick<Gs1ProvisionReport, 'dir' | 'files' | 'ok'>): EpcisArtefactState {
233
+ const files = report.files.map((file) => ({ fileName: file.fileName, outcome: file.outcome, ...(file.reason == null ? {} : { reason: file.reason }) }))
234
+ if (!report.ok) return { dir: report.dir, state: 'unavailable', files, remedy: remedyFor(report.dir) }
235
+ return { dir: report.dir, state: files.some((file) => file.outcome === 'fetched') ? 'fetched' : 'present', files }
236
+ }
237
+
238
+ /**
239
+ * Start the exchange: provision the GS1 files, open the store, run recovery.
240
+ * It resolves before the API accepts a request, so no import meets a store
241
+ * that still holds unfinished work.
242
+ */
243
+ export async function startEpcisExchange(options: EpcisExchangeOptions): Promise<EpcisExchange> {
244
+ const { log } = options
245
+ const clock = options.now ?? (() => new Date().toISOString())
246
+ const transport = options.fetch ?? globalThis.fetch
247
+ const dir = isAbsolute(options.config.gs1Dir) ? options.config.gs1Dir : resolve(PROJECT_ROOT, options.config.gs1Dir)
248
+
249
+ // The GS1 files are obtained here, once and by name. Nothing fetches them later, and an import never does.
250
+ const artefacts = artefactState(await provisionGs1Artefacts({ dir, offline: options.config.gs1Offline, fetch: transport }))
251
+ if (artefacts.state === 'present') log(`GS1 files for EPCIS validation: present in ${dir}.`)
252
+ else if (artefacts.state === 'fetched') log(`GS1 files for EPCIS validation: fetched from GS1 into ${dir} and checked against their pinned digests.`)
253
+ else {
254
+ const failed = artefacts.files.filter((file) => file.outcome === 'failed').map((file) => `${file.fileName} (${file.reason ?? 'unavailable'})`)
255
+ log(`GS1 files for EPCIS validation: unavailable in ${dir}: ${failed.join(', ')}. The API runs, and every EPCIS import and pull is refused until they are provided. ${artefacts.remedy}`)
256
+ }
257
+
258
+ let held: EpcisExchangeStorage
259
+ let storageKind: EpcisExchange['storageKind']
260
+ let opened: OpenedExchangeStorage | undefined
261
+ if (options.storage != null) {
262
+ held = options.storage
263
+ storageKind = 'supplied'
264
+ } else {
265
+ opened = await openExchangeStorage({ ...(options.config.storage == null ? {} : { setting: options.config.storage }), ...(options.db == null ? {} : { db: options.db }), log })
266
+ held = opened.storage
267
+ storageKind = opened.kind
268
+ }
269
+ // One object for every call of this process, recovery included: the module takes calls on one storage object in turn.
270
+ const storage = namingStoreFailures(held, log)
271
+
272
+ // Recovery finishes or discards what a stopped process left. It runs alone, before any request.
273
+ const recovery = await recoverEpcisExchange(storage, { now: clock })
274
+ if (recovery.actions.length === 0) log('EPCIS recovery: nothing was left unfinished.')
275
+ else {
276
+ const counts = new Map<string, number>()
277
+ for (const action of recovery.actions) counts.set(action.action, (counts.get(action.action) ?? 0) + 1)
278
+ log(`EPCIS recovery: ${[...counts].map(([action, count]) => `${action} x${count}`).join(', ')}; ${recovery.remaining} left unfinished.`)
279
+ }
280
+
281
+ const sources = options.config.sources
282
+ /** A name is checked against the addresses it resolves to, so one that leads to a private address is refused outside the local-test option. */
283
+ const resolveHost = async (hostname: string): Promise<string[]> => (await lookup(hostname, { all: true })).map((entry) => entry.address)
284
+
285
+ return {
286
+ storage,
287
+ storageKind,
288
+ artefactsDir: dir,
289
+ artefacts,
290
+ recovery,
291
+ sources,
292
+
293
+ status() {
294
+ // The folder is read again, without the network, so files an operator placed since the start are seen.
295
+ const now = verifyGs1Artefacts({ dir })
296
+ const current: EpcisArtefactState = now.ok
297
+ ? { dir, state: artefacts.state === 'unavailable' ? 'present' : artefacts.state, files: now.files.map((file) => ({ fileName: file.fileName, outcome: 'present' as const })) }
298
+ : { dir, state: 'unavailable', files: now.files.map((file) => (file.status === 'ok' ? { fileName: file.fileName, outcome: 'present' as const } : { fileName: file.fileName, outcome: 'failed' as const, reason: file.status })), remedy: remedyFor(dir) }
299
+ return { storage: storageKind, artefacts: current, recovery, sources: sources.map(describeEpcisSource), policy: EPCIS_POLICY.policyId }
300
+ },
301
+
302
+ importDocument: (input) =>
303
+ importEpcisSource({
304
+ storage,
305
+ sourceId: input.sourceId,
306
+ requestId: input.requestId,
307
+ bytes: input.bytes,
308
+ mediaType: input.mediaType,
309
+ receivedAt: clock(),
310
+ provenance: { kind: 'file', ...(input.filename == null ? {} : { filename: input.filename }) },
311
+ policy: EPCIS_POLICY,
312
+ artefactsDir: dir,
313
+ now: clock,
314
+ }),
315
+
316
+ listImports: (page) => listEpcisImports(storage, page),
317
+ getImport: (importId) => getEpcisImport(storage, importId),
318
+ exportOriginal: (importId) => exportEpcisSource(storage, importId),
319
+
320
+ async pull(input) {
321
+ const source = sources.find((candidate) => candidate.sourceId === input.sourceId)
322
+ if (source == null) return undefined
323
+ return await pullEpcisEvents({
324
+ storage,
325
+ source: {
326
+ sourceId: source.sourceId,
327
+ baseUrl: source.baseUrl,
328
+ permittedOrigins: source.permittedOrigins,
329
+ policy: EPCIS_POLICY,
330
+ localTest: source.localTest,
331
+ repeatListParameters: source.repeatListParameters,
332
+ ...(source.credentials == null ? {} : { credentials: source.credentials }),
333
+ },
334
+ queryId: input.queryId,
335
+ query: input.query,
336
+ ...(input.window == null ? {} : { window: input.window }),
337
+ fetch: (url, init) => transport(url, init),
338
+ artefactsDir: dir,
339
+ now: clock,
340
+ resolveHost,
341
+ // The module's entries name addresses, counts and outcomes. It searches each for the credential before it hands one over.
342
+ log: (entry) => log(`EPCIS pull ${source.sourceId}/${input.queryId}: ${JSON.stringify(entry)}`),
343
+ })
344
+ },
345
+
346
+ async getPull(sourceId, queryId) {
347
+ const pull = await getEpcisPull(storage, sourceId, queryId)
348
+ return pull == null ? undefined : { pull, pages: await listEpcisPullPages(storage, pull.pullId, { limit: 1000 }) }
349
+ },
350
+
351
+ async eventsFor(query) {
352
+ const page = await findEpcisAssociations(storage, query)
353
+ const imports = new Map<string, EpcisImportRecord | undefined>()
354
+ const bodies = new Map<string, Map<string, unknown>>()
355
+ const events: EpcisEventEntry[] = []
356
+ for (const association of page.associations) {
357
+ if (!imports.has(association.importId)) {
358
+ imports.set(association.importId, await getEpcisImport(storage, association.importId))
359
+ // The event as it was received is read from the retained bytes by the module's projection, which says it is derived.
360
+ const projection = await deriveEpcisEventProjection(storage, association.importId)
361
+ const parsed = projection == null ? undefined : (JSON.parse(new TextDecoder().decode(projection.bytes)) as { events: Array<{ pointer: string; event: unknown }> })
362
+ bodies.set(association.importId, new Map((parsed?.events ?? []).map((entry) => [entry.pointer, entry.event])))
363
+ }
364
+ const record = imports.get(association.importId)
365
+ if (record == null) continue
366
+ const event = record.events.find((candidate) => candidate.pointer === association.pointer)
367
+ const body = bodies.get(association.importId)?.get(association.pointer)
368
+ events.push({
369
+ association,
370
+ source: { importId: record.importId, sourceId: record.sourceId, receivedAt: record.receivedAt, documentValidity: record.documentValidity, state: record.state, provenance: record.sourceLocation, sha256: record.sha256 },
371
+ ...(event == null ? {} : { event }),
372
+ ...(body === undefined ? {} : { body }),
373
+ })
374
+ }
375
+ return { events, ...(page.next == null ? {} : { next: page.next }) }
376
+ },
377
+
378
+ async retainedEvent(importId, pointer) {
379
+ const record = await getEpcisImport(storage, importId)
380
+ const event = record?.events.find((candidate) => candidate.pointer === pointer)
381
+ if (record == null || event == null) return undefined
382
+ const original = await exportEpcisSource(storage, importId)
383
+ if (original == null) return undefined
384
+ const document = JSON.parse(new TextDecoder().decode(original.bytes)) as Record<string, unknown>
385
+ const body = atPointer(document, pointer)
386
+ if (body == null || typeof body !== 'object' || Array.isArray(body)) return undefined
387
+ const contexts = Array.isArray(document['@context']) ? document['@context'] : [document['@context']]
388
+ const inlineContexts = contexts.filter((entry): entry is Record<string, string> => entry != null && typeof entry === 'object' && !Array.isArray(entry) && Object.keys(entry).length > 0 && Object.values(entry).every((value) => typeof value === 'string'))
389
+ return { record, event, body: body as Record<string, unknown>, inlineContexts }
390
+ },
391
+
392
+ async listConflicts() {
393
+ // The module names a conflict on each event that is part of one. Reading the import records finds them all.
394
+ const ids = new Set<string>()
395
+ let after: string | undefined
396
+ let importsRead = 0
397
+ let truncated = false
398
+ for (;;) {
399
+ const page = await listEpcisImports(storage, { ...(after == null ? {} : { after }), limit: 100 })
400
+ for (const record of page) for (const event of record.events) if (event.conflict != null) ids.add(event.conflict.conflictId)
401
+ importsRead += page.length
402
+ if (page.length < 100) break
403
+ if (importsRead >= CONFLICT_SCAN_LIMIT) {
404
+ truncated = true
405
+ break
406
+ }
407
+ after = page[page.length - 1]!.importId
408
+ }
409
+ const conflicts: EpcisConflict[] = []
410
+ for (const conflictId of ids) {
411
+ const conflict = await getEpcisConflict(storage, conflictId)
412
+ if (conflict != null) conflicts.push(conflict)
413
+ }
414
+ return { conflicts, importsRead, truncated }
415
+ },
416
+
417
+ getConflict: (conflictId) => getEpcisConflict(storage, conflictId),
418
+
419
+ resolveConflict: (input) =>
420
+ resolveEpcisConflict(storage, {
421
+ conflictId: input.conflictId,
422
+ decision: input.decision,
423
+ disposition: input.disposition,
424
+ ...(input.selectedBodyDigest == null ? {} : { selectedBodyDigest: input.selectedBodyDigest }),
425
+ decidedAt: input.decidedAt ?? clock(),
426
+ ...(input.decidedBy == null ? {} : { decidedBy: input.decidedBy }),
427
+ now: clock,
428
+ }),
429
+
430
+ async close() {
431
+ await opened?.close()
432
+ },
433
+ }
434
+ }