@bsv/create-dpp-app 0.0.0-stage → 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 (178) hide show
  1. package/LICENSE +203 -0
  2. package/NOTICE +2 -0
  3. package/PATENTS +12 -0
  4. package/README.md +93 -2
  5. package/dist/index.js +125 -0
  6. package/package.json +57 -4
  7. package/template/Dockerfile +37 -0
  8. package/template/README.md +389 -0
  9. package/template/_dockerignore +6 -0
  10. package/template/_env.example +122 -0
  11. package/template/_github/workflows/ci.yml +23 -0
  12. package/template/_gitignore +8 -0
  13. package/template/_prettierrc +6 -0
  14. package/template/apps/api/API.md +119 -0
  15. package/template/apps/api/package.json +39 -0
  16. package/template/apps/api/src/auth.ts +55 -0
  17. package/template/apps/api/src/bound-profiles.ts +590 -0
  18. package/template/apps/api/src/claims.ts +204 -0
  19. package/template/apps/api/src/cli.ts +99 -0
  20. package/template/apps/api/src/config.ts +180 -0
  21. package/template/apps/api/src/custody.ts +358 -0
  22. package/template/apps/api/src/dev-index.ts +120 -0
  23. package/template/apps/api/src/env-file.ts +55 -0
  24. package/template/apps/api/src/env.ts +14 -0
  25. package/template/apps/api/src/epcis/exchange.ts +434 -0
  26. package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
  27. package/template/apps/api/src/epcis/routes.ts +364 -0
  28. package/template/apps/api/src/epcis/sources.ts +142 -0
  29. package/template/apps/api/src/go-live.ts +226 -0
  30. package/template/apps/api/src/http-error.ts +15 -0
  31. package/template/apps/api/src/identifiers.ts +57 -0
  32. package/template/apps/api/src/index-client.ts +261 -0
  33. package/template/apps/api/src/index-projects.ts +53 -0
  34. package/template/apps/api/src/lifecycle-authority.ts +49 -0
  35. package/template/apps/api/src/lifecycle.ts +485 -0
  36. package/template/apps/api/src/main.ts +58 -0
  37. package/template/apps/api/src/parties.ts +68 -0
  38. package/template/apps/api/src/platform.ts +176 -0
  39. package/template/apps/api/src/portability/commands.ts +224 -0
  40. package/template/apps/api/src/portability/export.ts +708 -0
  41. package/template/apps/api/src/portability/package.ts +270 -0
  42. package/template/apps/api/src/portability/restore.ts +863 -0
  43. package/template/apps/api/src/profiles.ts +125 -0
  44. package/template/apps/api/src/reader.ts +265 -0
  45. package/template/apps/api/src/resolver.ts +159 -0
  46. package/template/apps/api/src/sector-examples.ts +390 -0
  47. package/template/apps/api/src/server.ts +613 -0
  48. package/template/apps/api/src/store.ts +426 -0
  49. package/template/apps/api/src/validation-engine.ts +172 -0
  50. package/template/apps/api/src/wallet.ts +359 -0
  51. package/template/apps/api/src/worker.ts +113 -0
  52. package/template/apps/api/src/writer.ts +603 -0
  53. package/template/apps/api/test/bound-http.test.ts +496 -0
  54. package/template/apps/api/test/bound-profiles.test.ts +547 -0
  55. package/template/apps/api/test/config.test.ts +160 -0
  56. package/template/apps/api/test/custody-journal.test.ts +415 -0
  57. package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
  58. package/template/apps/api/test/custom-profile.test.ts +167 -0
  59. package/template/apps/api/test/env-file.test.ts +53 -0
  60. package/template/apps/api/test/epcis-fixtures.ts +270 -0
  61. package/template/apps/api/test/epcis-http.test.ts +1179 -0
  62. package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
  63. package/template/apps/api/test/epcis-separation.test.ts +253 -0
  64. package/template/apps/api/test/epcis-web.test.ts +230 -0
  65. package/template/apps/api/test/exit-exercise.test.ts +1038 -0
  66. package/template/apps/api/test/external-index.test.ts +32 -0
  67. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
  68. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
  69. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
  70. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
  71. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
  72. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
  73. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
  74. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
  75. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
  76. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
  77. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
  78. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
  79. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
  80. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
  81. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
  82. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
  83. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
  84. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
  85. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
  86. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
  87. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
  88. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
  89. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
  90. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
  91. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
  92. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
  93. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
  94. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
  95. package/template/apps/api/test/go-live.test.ts +179 -0
  96. package/template/apps/api/test/gs1-global-setup.ts +33 -0
  97. package/template/apps/api/test/gs1-test-env.ts +5 -0
  98. package/template/apps/api/test/identifier-host.test.ts +256 -0
  99. package/template/apps/api/test/index-projects.test.ts +81 -0
  100. package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
  101. package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
  102. package/template/apps/api/test/lifecycle.test.ts +147 -0
  103. package/template/apps/api/test/manifest-notice.test.ts +36 -0
  104. package/template/apps/api/test/network-guard.ts +113 -0
  105. package/template/apps/api/test/portability.test.ts +655 -0
  106. package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
  107. package/template/apps/api/test/retired-profiles.test.ts +216 -0
  108. package/template/apps/api/test/sector-cutover.test.ts +95 -0
  109. package/template/apps/api/test/sector-forms.test.ts +420 -0
  110. package/template/apps/api/test/unjoined-index.test.ts +62 -0
  111. package/template/apps/api/test/validation-engine.test.ts +328 -0
  112. package/template/apps/api/test/wallet-monitor.test.ts +38 -0
  113. package/template/apps/api/test/writer-journal.test.ts +327 -0
  114. package/template/apps/api/tsconfig.json +9 -0
  115. package/template/apps/api/vitest.config.ts +12 -0
  116. package/template/apps/web/components.json +21 -0
  117. package/template/apps/web/index.html +12 -0
  118. package/template/apps/web/package.json +33 -0
  119. package/template/apps/web/src/app.tsx +55 -0
  120. package/template/apps/web/src/components/bits.tsx +188 -0
  121. package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
  122. package/template/apps/web/src/components/bound/field-view.tsx +237 -0
  123. package/template/apps/web/src/components/bound/pieces.tsx +169 -0
  124. package/template/apps/web/src/components/bound/readings.tsx +152 -0
  125. package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
  126. package/template/apps/web/src/components/claim-dialog.tsx +344 -0
  127. package/template/apps/web/src/components/epcis-events.tsx +119 -0
  128. package/template/apps/web/src/components/layout.tsx +135 -0
  129. package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
  130. package/template/apps/web/src/components/passport-form.tsx +244 -0
  131. package/template/apps/web/src/components/read-passport.tsx +49 -0
  132. package/template/apps/web/src/components/reading.tsx +150 -0
  133. package/template/apps/web/src/components/ui/alert.tsx +65 -0
  134. package/template/apps/web/src/components/ui/badge.tsx +47 -0
  135. package/template/apps/web/src/components/ui/button.tsx +63 -0
  136. package/template/apps/web/src/components/ui/card.tsx +91 -0
  137. package/template/apps/web/src/components/ui/dialog.tsx +156 -0
  138. package/template/apps/web/src/components/ui/input.tsx +20 -0
  139. package/template/apps/web/src/components/ui/label.tsx +21 -0
  140. package/template/apps/web/src/components/ui/select.tsx +189 -0
  141. package/template/apps/web/src/components/ui/separator.tsx +25 -0
  142. package/template/apps/web/src/components/ui/table.tsx +115 -0
  143. package/template/apps/web/src/components/ui/tabs.tsx +90 -0
  144. package/template/apps/web/src/components/ui/textarea.tsx +17 -0
  145. package/template/apps/web/src/index.css +81 -0
  146. package/template/apps/web/src/lib/api.ts +396 -0
  147. package/template/apps/web/src/lib/auth.ts +10 -0
  148. package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
  149. package/template/apps/web/src/lib/bound/display.ts +122 -0
  150. package/template/apps/web/src/lib/bound/fields.ts +128 -0
  151. package/template/apps/web/src/lib/bound/form-model.ts +521 -0
  152. package/template/apps/web/src/lib/bound/forms.ts +15 -0
  153. package/template/apps/web/src/lib/bound/identity.ts +48 -0
  154. package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
  155. package/template/apps/web/src/lib/bound/units.ts +37 -0
  156. package/template/apps/web/src/lib/epcis.ts +345 -0
  157. package/template/apps/web/src/lib/format.ts +87 -0
  158. package/template/apps/web/src/lib/lifecycle.ts +350 -0
  159. package/template/apps/web/src/lib/session.tsx +92 -0
  160. package/template/apps/web/src/lib/use-load.ts +46 -0
  161. package/template/apps/web/src/main.tsx +18 -0
  162. package/template/apps/web/src/pages/accept.tsx +113 -0
  163. package/template/apps/web/src/pages/brand.tsx +94 -0
  164. package/template/apps/web/src/pages/brands.tsx +104 -0
  165. package/template/apps/web/src/pages/events.tsx +388 -0
  166. package/template/apps/web/src/pages/home.tsx +51 -0
  167. package/template/apps/web/src/pages/new-passport.tsx +137 -0
  168. package/template/apps/web/src/pages/operations.tsx +169 -0
  169. package/template/apps/web/src/pages/passport.tsx +632 -0
  170. package/template/apps/web/src/pages/public-passport.tsx +64 -0
  171. package/template/apps/web/src/pages/sign-in.tsx +93 -0
  172. package/template/apps/web/src/pages/verify.tsx +30 -0
  173. package/template/apps/web/src/pages/wallet.tsx +141 -0
  174. package/template/apps/web/tsconfig.json +29 -0
  175. package/template/apps/web/vite.config.ts +23 -0
  176. package/template/deploy/compose.yml +38 -0
  177. package/template/package.json +48 -0
  178. package/template/tsconfig.base.json +13 -0
@@ -0,0 +1,420 @@
1
+ // The web client's sector forms, exercised here because the web app has no
2
+ // test runner of its own and these modules touch neither the page nor the
3
+ // network. What is tested is the part that decides what gets written: the
4
+ // document a form builds from what was entered, and where a validator's
5
+ // finding is shown. The pages around it are type-checked by the build.
6
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'
7
+ import { describeProduct, describeValue, humaniseName } from '../../web/src/lib/bound/display'
8
+ import { buildDocument, codeClasses, emptyState, fieldPointerFor, labelsOf, parseDocument, splitPreview, stripComments, tierOf, topLevelFields, type FormState, type Json, type SectorForm } from '../../web/src/lib/bound/form-model'
9
+ import { sectorFormFor } from '../../web/src/lib/bound/forms'
10
+ import { identityFromDocument, mintIdentity } from '../../web/src/lib/bound/identity'
11
+ import type { ViewCheck } from '../src/bound-profiles.js'
12
+ import { loadConfig } from '../src/config.js'
13
+ import { mintGtin, mintPassportId } from '../src/identifiers.js'
14
+ import { openPlatform, type Platform } from '../src/platform.js'
15
+ import { sectorExamples } from '../src/sector-examples.js'
16
+ import { WriteRefused } from '../src/writer.js'
17
+
18
+ const config = loadConfig({ NETWORK: 'main', PASSPORT_HOST: 'passports.example.com', GS1_PREFIX: '952', LIVE_PUBLISHING: 'false' })
19
+ const policy = { host: config.passportHost, prefix: config.gs1Prefix }
20
+ const brandId = 'brand-forms-1'
21
+ let platform: Platform
22
+
23
+ beforeAll(async () => {
24
+ platform = await openPlatform({ config, mode: 'test', log: () => {} })
25
+ })
26
+ afterAll(async () => {
27
+ await platform.close()
28
+ })
29
+
30
+ const formFor = (profile: string): SectorForm => {
31
+ const form = sectorFormFor(profile)
32
+ if (form == null) throw new Error(`no form for ${profile}`)
33
+ return form
34
+ }
35
+ /** The addresses the registered binding lists for the form's context files, as the page receives them from the API. */
36
+ const contextsFor = (form: SectorForm): string[] => {
37
+ const described = platform.profiles.describe(platform.profiles.get(form.profile)!)
38
+ return form.contexts.map((path) => described.contexts.find((context) => context.path === path)!.uri)
39
+ }
40
+ const minted = (itemReference: string, serial: string) => {
41
+ const identity = mintIdentity(policy, itemReference, serial)
42
+ if (!identity.ok) throw new Error(identity.problem)
43
+ return identity
44
+ }
45
+
46
+ describe('the identifier the form writes', () => {
47
+ it('is the one the API mints, with the same GTIN and serial in the document', () => {
48
+ for (const [itemReference, serial] of [
49
+ ['100200300', 'HC48-2026-000117'],
50
+ ['000000001', 'A/B+C 1'.replace(' ', '_')],
51
+ ['999999999', "it's:<ok>"],
52
+ ]) {
53
+ const identity = minted(itemReference, serial)
54
+ expect(identity.passportId).toBe(mintPassportId(policy, itemReference, serial))
55
+ expect(identity.gtin).toBe(mintGtin(policy.prefix, itemReference))
56
+ for (const profile of ['eu-battery@2', 'eu-textile@2']) {
57
+ const form = formFor(profile)
58
+ const { product } = buildDocument(form, emptyState(), identity, contextsFor(form))
59
+ // One serial and one GTIN go in, and every member that states either is written from them.
60
+ expect(product.id).toBe(identity.passportId)
61
+ expect(product['gs1:gtin']).toBe(identity.gtin)
62
+ for (const member of form.serialMembers) expect(product[member]).toBe(serial)
63
+ }
64
+ }
65
+ })
66
+
67
+ it('refuses an item reference or a serial the API would refuse', () => {
68
+ expect(mintIdentity(policy, '12345', 'A1')).toMatchObject({ ok: false })
69
+ expect(mintIdentity(policy, '12345678x', 'A1')).toMatchObject({ ok: false })
70
+ expect(mintIdentity(policy, '100200300', '')).toMatchObject({ ok: false })
71
+ expect(mintIdentity(policy, '100200300', 'has a space')).toMatchObject({ ok: false })
72
+ expect(mintIdentity(policy, '100200300', 'x'.repeat(21))).toMatchObject({ ok: false })
73
+ })
74
+
75
+ it('reads the item reference and serial back from a loaded document under this prefix, and refuses another prefix', () => {
76
+ expect(identityFromDocument(policy, 'https://id.example/01/09521002003000/21/HC48-2026-000117')).toEqual({ itemReference: '100200300', serial: 'HC48-2026-000117' })
77
+ // The same document on a platform with another prefix is not that platform's to write.
78
+ expect(identityFromDocument({ host: policy.host, prefix: '9539' }, 'https://id.example/01/09521002003000/21/HC48-2026-000117')).toHaveProperty('problem')
79
+ expect(identityFromDocument(policy, 'https://id.example/01/09521002003000')).toHaveProperty('problem')
80
+ expect(identityFromDocument(policy, undefined)).toHaveProperty('problem')
81
+ })
82
+ })
83
+
84
+ describe('an empty form', () => {
85
+ it('writes the identity and nothing else: no identifier, classification, date or unit is made up', () => {
86
+ const identity = minted('100200300', 'EMPTY-0001')
87
+ const battery = formFor('eu-battery@2')
88
+ expect(buildDocument(battery, emptyState(), identity, contextsFor(battery))).toMatchObject({
89
+ problems: [],
90
+ product: { '@context': contextsFor(battery), id: identity.passportId, type: ['gs1:Product', 'eubat:Battery'], 'oec:granularityLevel': 'item', 'gs1:gtin': identity.gtin, 'gs1:hasSerialNumber': 'EMPTY-0001' },
91
+ })
92
+ expect(Object.keys(buildDocument(battery, emptyState(), identity, contextsFor(battery)).product)).toEqual(['@context', 'id', 'type', 'oec:granularityLevel', 'gs1:gtin', 'gs1:hasSerialNumber'])
93
+ const textile = formFor('eu-textile@2')
94
+ expect(Object.keys(buildDocument(textile, emptyState(), identity, contextsFor(textile)).product)).toEqual(['@context', 'id', 'type', 'oec:granularityLevel', 'gs1:gtin', 'schema:serialNumber'])
95
+ })
96
+
97
+ it('writes nothing for fields that were touched and left empty, and no node for a group with only its fixed members', () => {
98
+ const identity = minted('100200300', 'EMPTY-0002')
99
+ const form = formFor('eu-battery@2')
100
+ const state: FormState = {
101
+ ...emptyState(),
102
+ values: {
103
+ 'eubat:batteryModelIdentifier': ' ',
104
+ 'gs1:productName': [{ value: '', language: 'en' }],
105
+ 'gs1:netWeight': { value: '', unit: '' },
106
+ 'gs1:manufacturer': { 'gs1:organizationName': '', 'gs1:address': { 'gs1:streetAddress': '' }, 'gs1:contactPoint': {} },
107
+ 'eubat:hasCarbonFootprintDeclaration': { 'oea:hasIndicator': { 'oea:hasCategoricalValue': '' } },
108
+ 'eubat:hasMaterialComposition': [{}, { 'schema:name': { value: '', language: '' } }],
109
+ 'eubat:ceMarkingIndicator': undefined,
110
+ },
111
+ }
112
+ const built = buildDocument(form, state, identity, contextsFor(form))
113
+ expect(built.problems).toEqual([])
114
+ expect(Object.keys(built.product)).toEqual(['@context', 'id', 'type', 'oec:granularityLevel', 'gs1:gtin', 'gs1:hasSerialNumber'])
115
+ })
116
+ })
117
+
118
+ describe('what a field writes', () => {
119
+ const identity = () => minted('100200300', 'FIELD-0001')
120
+ const build = (values: FormState['values']) => {
121
+ const form = formFor('eu-battery@2')
122
+ return buildDocument(form, { ...emptyState(), values }, identity(), contextsFor(form))
123
+ }
124
+
125
+ it('keeps the digits of a number as typed, and a measurement as a value with its unit', () => {
126
+ const { product, problems } = build({
127
+ 'gs1:netWeight': { value: '41.50', unit: 'KGM' },
128
+ 'eubat:numberOfCells': '16',
129
+ 'eubat:hasTechnicalSpecifications': { 'eubat:cRate': '0.50', 'eubat:hasTemperatureRangeCharging': { 'eubat:hasMinimumTemperature': { value: '-0', unit: 'CEL' } } },
130
+ })
131
+ expect(problems).toEqual([])
132
+ expect(product['gs1:netWeight']).toEqual({ type: 'gs1:QuantitativeValue', 'gs1:value': '41.50', 'gs1:unitCode': 'KGM' })
133
+ expect(product['eubat:numberOfCells']).toBe(16)
134
+ expect(product['eubat:hasTechnicalSpecifications']).toEqual({
135
+ type: 'eubat:TechnicalSpecification',
136
+ 'eubat:cRate': '0.50',
137
+ 'eubat:hasTemperatureRangeCharging': { type: 'eubat:TemperatureRange', 'eubat:hasMinimumTemperature': { type: 'gs1:QuantitativeValue', 'gs1:value': '-0', 'gs1:unitCode': 'CEL' } },
138
+ })
139
+ })
140
+
141
+ it('stops, and writes nothing in its place, for a measurement with no unit, a unit with no value, or a number that is not one', () => {
142
+ const { problems, product } = build({
143
+ 'gs1:netWeight': { value: '41.5', unit: '' },
144
+ 'gs1:grossWeight': { value: '', unit: 'KGM' },
145
+ 'eubat:numberOfCells': '16.5',
146
+ 'eubat:hasTechnicalSpecifications': { 'eubat:cRate': 'half' },
147
+ 'gs1:productionDate': '18/09/2026',
148
+ 'oec:lastUpdated': '2026-11-02 09:30',
149
+ 'gs1:countryOfOrigin': 'Australia',
150
+ 'eubat:warrantyConditions': 'see the box',
151
+ })
152
+ expect(problems.map((p) => p.pointer).sort()).toEqual(
153
+ ['/eubat:hasTechnicalSpecifications/eubat:cRate', '/eubat:numberOfCells', '/eubat:warrantyConditions', '/gs1:countryOfOrigin', '/gs1:grossWeight', '/gs1:netWeight', '/gs1:productionDate', '/oec:lastUpdated'].sort()
154
+ )
155
+ for (const key of ['gs1:netWeight', 'gs1:grossWeight', 'eubat:numberOfCells', 'gs1:productionDate', 'oec:lastUpdated', 'gs1:countryOfOrigin', 'eubat:warrantyConditions']) expect(product[key]).toBeUndefined()
156
+ })
157
+
158
+ it('writes text with its language, or as plain text when no language was chosen, and a code as a reference', () => {
159
+ const { product } = build({
160
+ 'gs1:productName': [
161
+ { value: 'Harbour module', language: 'en' },
162
+ { value: 'Module Harbour', language: 'fr' },
163
+ { value: '', language: 'de' },
164
+ ],
165
+ 'schema:model': { value: 'Harbour 48-100', language: '' },
166
+ 'schema:category': 'eubat:StationaryBattery',
167
+ 'oec:passportStatus': 'draft',
168
+ 'eubat:ceMarkingIndicator': false,
169
+ })
170
+ expect(product['gs1:productName']).toEqual([
171
+ { '@value': 'Harbour module', '@language': 'en' },
172
+ { '@value': 'Module Harbour', '@language': 'fr' },
173
+ ])
174
+ expect(product['schema:model']).toBe('Harbour 48-100')
175
+ expect(product['schema:category']).toEqual({ '@id': 'eubat:StationaryBattery' })
176
+ expect(product['oec:passportStatus']).toBe('draft')
177
+ expect(product['eubat:ceMarkingIndicator']).toBe(false)
178
+ })
179
+
180
+ it('keeps the manufacturer\'s identifiers apart from display names', () => {
181
+ const fields = topLevelFields(formFor('eu-battery@2'))
182
+ const keys = fields.map((field) => field.key)
183
+ for (const key of ['eubat:batteryModelIdentifier', 'gs1:productName', 'schema:model', 'eubat:manufacturerIdentifier', 'eubat:operatorIdentifier', 'eubat:facilityIdentifier', 'gs1:manufacturer', 'eubat:hasOperatorInformation', 'eubat:hasManufacturingPlace']) expect(keys).toContain(key)
184
+ // No field writes the serial or the GTIN: they come from the passport identifier alone.
185
+ for (const profile of ['eu-battery@2', 'eu-textile@2']) {
186
+ const all = JSON.stringify(formFor(profile).sections)
187
+ for (const member of ['gs1:gtin', 'gs1:hasSerialNumber', 'schema:serialNumber', 'gs1:productID']) expect(all).not.toContain(`"key":"${member}"`)
188
+ }
189
+ })
190
+
191
+ it('writes a fibre share as a typed number and the five care symbols as codes', () => {
192
+ const form = formFor('eu-textile@2')
193
+ const { product, problems } = buildDocument(
194
+ form,
195
+ {
196
+ ...emptyState(),
197
+ values: {
198
+ 'gs1:textileMaterial': [{ 'gs1:textileMaterialPercentage': '87.5', 'gs1:textileMaterialDescription': { value: 'Wool', language: 'en' }, 'eutex:fiberOrigin': 'NZ', 'eutex:isRecycledFiber': false }],
199
+ 'eutex:hasCareInstructions': { 'eutex:hasWashingSymbol': 'eutex:Wash30', 'eutex:hasDryingSymbol': 'eutex:DryFlat' },
200
+ 'eutex:hasDurabilityInfo': { 'oea:hasSubAssessment': [{ 'oea:hasMethod': 'eutex:PillingTest', 'oea:hasResult': { 'oea:hasObservedParameter': 'eutex:PillingResistance', 'oea:hasMeasuredValue': { value: '4', unit: 'C62' } } }] },
201
+ },
202
+ },
203
+ minted('100200400', 'FIELD-0002'),
204
+ contextsFor(form)
205
+ )
206
+ expect(problems).toEqual([])
207
+ expect(product['gs1:textileMaterial']).toEqual([
208
+ { type: 'gs1:TextileMaterialDetails', 'gs1:textileMaterialPercentage': { '@value': '87.5', '@type': 'xsd:decimal' }, 'gs1:textileMaterialDescription': { '@value': 'Wool', '@language': 'en' }, 'eutex:fiberOrigin': 'NZ', 'eutex:isRecycledFiber': false },
209
+ ])
210
+ expect(product['eutex:hasCareInstructions']).toEqual({ type: 'eutex:CareInstruction', 'eutex:hasWashingSymbol': { '@id': 'eutex:Wash30' }, 'eutex:hasDryingSymbol': { '@id': 'eutex:DryFlat' } })
211
+ expect(product['eutex:hasDurabilityInfo']).toEqual({
212
+ type: 'eutex:DurabilityInfo',
213
+ 'oea:hasSubAssessment': [
214
+ {
215
+ type: 'oea:TestExecution',
216
+ 'oea:hasMethod': { '@id': 'eutex:PillingTest' },
217
+ 'oea:hasResult': { type: 'oea:MeasurementResult', 'oea:hasObservedParameter': { '@id': 'eutex:PillingResistance' }, 'oea:hasMeasuredValue': { type: 'gs1:QuantitativeValue', 'gs1:value': '4', 'gs1:unitCode': 'C62' } },
218
+ },
219
+ ],
220
+ })
221
+ })
222
+ })
223
+
224
+ describe.each(['eu-battery@1', 'eu-textile@1', 'eu-battery@2', 'eu-textile@2'])('the %s form and its example', (profile) => {
225
+ it('holds every property of the example in a field, and builds the same document back', () => {
226
+ const form = formFor(profile)
227
+ const example = sectorExamples(platform.profiles.get(profile)!, policy)[0]
228
+ const parsed = parseDocument(form, example.product)
229
+ expect(parsed.kept).toEqual([])
230
+ expect(parsed.stated).toEqual({ id: example.passportId, gtin: mintGtin(policy.prefix, example.itemReference), serial: example.serial })
231
+ expect(identityFromDocument(policy, parsed.stated.id)).toEqual({ itemReference: example.itemReference, serial: example.serial })
232
+ const built = buildDocument(form, parsed.state, minted(example.itemReference, example.serial), contextsFor(form))
233
+ expect(built.problems).toEqual([])
234
+ expect(built.product).toEqual(example.product)
235
+ })
236
+
237
+ it('builds a document the writer accepts, and labels each property with the tier the binding gives it', async () => {
238
+ const form = formFor(profile)
239
+ const bound = platform.profiles.get(profile)!
240
+ const example = sectorExamples(bound, policy)[0]
241
+ const identity = minted(example.itemReference, `FORM-${profile.slice(3, 6).toUpperCase()}-${bound.version}`)
242
+ const { product } = buildDocument(form, parseDocument(form, example.product).state, identity, contextsFor(form))
243
+ const prepared = await platform.profiles.prepare({ profile: bound, product, passportId: identity.passportId })
244
+ if (!prepared.ok) throw new Error(prepared.detail)
245
+ if (bound.version === 2) {
246
+ const issued = await platform.writer.issue({ brandId, brand: platform.parties.brand(brandId), passportId: identity.passportId, profile, product })
247
+ expect(issued.entry.index).toBe('admitted')
248
+ expect(JSON.parse(issued.state.payloadPublic)).toEqual({ notice: 'This demonstration record describes no real product.', ...JSON.parse(prepared.payloadPublic) })
249
+ }
250
+
251
+ const access = platform.profiles.describe(bound).access
252
+ const preview = splitPreview(product, access)
253
+ const written = JSON.parse(prepared.payloadPublic) as { product: Json }
254
+ // What the page says is public is exactly what went on chain.
255
+ expect(preview.public).toEqual(Object.keys(written.product))
256
+ expect(preview.restricted.length).toBeGreaterThan(0)
257
+ for (const name of preview.restricted) expect(Object.hasOwn(written.product, name)).toBe(false)
258
+ expect(tierOf(access, 'gs1:gtin')).toBe('public')
259
+ expect(tierOf(access, 'a-property:nobody-heard-of')).toBe('restricted')
260
+ expect(tierOf(undefined, 'anything')).toBe('public')
261
+ })
262
+
263
+ it('asks the API for code lists the profile\'s vocabulary has', async () => {
264
+ const lists = await platform.profiles.codeLists(platform.profiles.get(profile)!, codeClasses(formFor(profile)))
265
+ for (const [name, codes] of Object.entries(lists)) expect(codes.length, name).toBeGreaterThan(0)
266
+ })
267
+ })
268
+
269
+ describe('a loaded document', () => {
270
+ it('loses nothing: what the form cannot hold exactly is kept as it came', () => {
271
+ const form = formFor('eu-battery@2')
272
+ const example = sectorExamples(platform.profiles.get('eu-battery@2')!, policy)[0]
273
+ const loaded = stripComments({
274
+ _comment_architecture: ['a note'],
275
+ ...example.product,
276
+ 'schema:serialNumber': example.serial,
277
+ // A number where the form would write text, a nested member the form has no field for, and a property it has never heard of.
278
+ 'gs1:netWeight': { type: 'gs1:QuantitativeValue', 'gs1:value': 132, 'gs1:unitCode': 'KGM' },
279
+ 'eubat:hasBatteryChemistry': { type: 'eubat:BatteryChemistry', 'schema:name': 'LFP', _comment: 'nested note', 'eubat:somethingNew': 1 },
280
+ 'eubat:hasBatteryState': { ...(example.product['eubat:hasBatteryState'] as Json), 'oea:hasSubAssessment': [{ type: 'oea:TestExecution' }] },
281
+ 'gs1:regulatoryInformation': [{ type: 'gs1:RegulatoryInformation', 'gs1:regulatoryAct': 'An act' }],
282
+ }) as Json
283
+ expect(JSON.stringify(loaded)).not.toContain('_comment')
284
+ const parsed = parseDocument(form, loaded)
285
+ expect(parsed.kept.sort()).toEqual(['eubat:hasBatteryChemistry', 'eubat:hasBatteryState', 'gs1:regulatoryInformation'])
286
+ // The number stays a number in its field.
287
+ expect(parsed.state.values['gs1:netWeight']).toEqual({ value: 132, unit: 'KGM' })
288
+ const built = buildDocument(form, parsed.state, minted(example.itemReference, example.serial), contextsFor(form))
289
+ expect(built.problems).toEqual([])
290
+ expect(built.product).toEqual(loaded)
291
+ // Both serial members the document carried are written from the one serial.
292
+ expect(built.product['schema:serialNumber']).toBe(example.serial)
293
+ expect(built.product['gs1:hasSerialNumber']).toBe(example.serial)
294
+ })
295
+
296
+ it('keeps a node\'s own identifier and the spelling of a reference, in their fields', () => {
297
+ const form = formFor('eu-battery@2')
298
+ const example = sectorExamples(platform.profiles.get('eu-battery@2')!, policy)[0]
299
+ const loaded: Json = {
300
+ ...example.product,
301
+ // A reference spelled with id, and nodes that carry identifiers of their own: both are as the document wrote them.
302
+ 'oec:hasReportingGranularity': { id: 'oec:ItemLevel' },
303
+ 'eubat:hasBatteryChemistry': { id: `${example.passportId}#chemistry`, ...(example.product['eubat:hasBatteryChemistry'] as Json) },
304
+ 'gs1:manufacturer': { ...(example.product['gs1:manufacturer'] as Json), 'gs1:contactPoint': { type: 'gs1:ContactPoint', 'gs1:email': 'info@harbour-cells.example', 'schema:url': { id: 'https://harbour-cells.example/' } } },
305
+ }
306
+ const parsed = parseDocument(form, loaded)
307
+ expect(parsed.kept).toEqual([])
308
+ expect(parsed.state.values['oec:hasReportingGranularity']).toEqual({ code: 'oec:ItemLevel', spelled: 'id' })
309
+ const built = buildDocument(form, parsed.state, minted(example.itemReference, example.serial), contextsFor(form))
310
+ expect(built.product).toEqual(loaded)
311
+ expect(JSON.stringify(built.product['oec:hasReportingGranularity'])).toBe('{"id":"oec:ItemLevel"}')
312
+ // A document the form builds from typed values never carries an identifier nobody entered.
313
+ const typed = buildDocument(form, { ...emptyState(), values: { 'eubat:hasBatteryChemistry': { 'schema:alternateName': 'LFP' }, 'oec:hasReportingGranularity': 'oec:ItemLevel' } }, minted(example.itemReference, example.serial), contextsFor(form))
314
+ expect(typed.product['eubat:hasBatteryChemistry']).toEqual({ type: 'eubat:BatteryChemistry', 'schema:alternateName': 'LFP' })
315
+ expect(typed.product['oec:hasReportingGranularity']).toEqual({ '@id': 'oec:ItemLevel' })
316
+ })
317
+
318
+ it('says so when the JSON area repeats a property a field writes', () => {
319
+ const form = formFor('eu-textile@2')
320
+ const built = buildDocument(form, { ...emptyState(), values: { 'eutex:garmentType': 'Jacket' }, others: { 'eutex:garmentType': 'Coat' } }, minted('100200400', 'DUP-0001'), contextsFor(form))
321
+ expect(built.problems).toEqual([{ pointer: '/~others', message: expect.stringContaining('eutex:garmentType') }])
322
+ expect(built.product['eutex:garmentType']).toBe('Jacket')
323
+ })
324
+
325
+ it('does not let the JSON area state a second serial, GTIN or identifier', () => {
326
+ for (const profile of ['eu-battery@2', 'eu-textile@2']) {
327
+ const form = formFor(profile)
328
+ const identity = minted('100200400', 'ONE-SERIAL-1')
329
+ for (const member of ['schema:serialNumber', 'gs1:hasSerialNumber', 'gs1:gtin', 'id', '@id']) {
330
+ const built = buildDocument(form, { ...emptyState(), others: { [member]: 'ANOTHER-ITEM' } }, identity, contextsFor(form))
331
+ expect(built.problems, `${profile} ${member}`).toHaveLength(1)
332
+ expect(JSON.stringify(built.product)).not.toContain('ANOTHER-ITEM')
333
+ }
334
+ }
335
+ })
336
+ })
337
+
338
+ describe('where a finding is shown', () => {
339
+ it('is the field it concerns, by the row the entry was typed in', async () => {
340
+ const form = formFor('eu-battery@2')
341
+ const example = sectorExamples(platform.profiles.get('eu-battery@2')!, policy)[0]
342
+ const state = parseDocument(form, example.product).state
343
+ // An empty row before the materials, so the second written material is the third row of the form.
344
+ state.values['eubat:hasMaterialComposition'] = [{}, ...(state.values['eubat:hasMaterialComposition'] as Array<Record<string, unknown>>)] as FormState['values'][string]
345
+ ;((state.values['eubat:hasMaterialComposition'] as Array<Record<string, unknown>>)[2] as Record<string, unknown>)['schema:name'] = undefined
346
+ // A unit the rules do not allow for this measurement, and a missing required property.
347
+ ;((state.values['eubat:hasTechnicalSpecifications'] as Record<string, unknown>)['eubat:hasRatedCapacity'] as Record<string, unknown>).unit = 'KWH'
348
+ state.values['oec:passportStatus'] = undefined
349
+ state.others = { 'gs1:regulatoryInformation': [{ type: 'gs1:QuantitativeValue', 'gs1:value': '1' }] }
350
+ const identity = minted(example.itemReference, 'FIND-0001')
351
+ const built = buildDocument(form, state, identity, contextsFor(form))
352
+ expect(built.problems).toEqual([])
353
+
354
+ let refused: WriteRefused | undefined
355
+ try {
356
+ await platform.writer.issue({ brandId, brand: platform.parties.brand(brandId), passportId: identity.passportId, profile: 'eu-battery@2', product: built.product })
357
+ } catch (cause) {
358
+ refused = cause as WriteRefused
359
+ }
360
+ expect(refused?.code).toBe('product-invalid')
361
+ const findings = (refused!.data!.validation as ViewCheck).findings
362
+ const shownAt = findings.map((finding) => (finding.pointer == null ? undefined : fieldPointerFor(form, state, built.rows, finding.pointer)))
363
+ expect(shownAt).toContain('/eubat:hasMaterialComposition/2/schema:name')
364
+ expect(shownAt).toContain('/eubat:hasTechnicalSpecifications/eubat:hasRatedCapacity')
365
+ expect(shownAt).toContain('/oec:passportStatus')
366
+ expect(shownAt).toContain('/~others')
367
+ // A finding about the document's own identity is shown with the identifier inputs.
368
+ expect(fieldPointerFor(form, state, built.rows, '/gs1:gtin')).toBe('/~identity')
369
+ expect(fieldPointerFor(form, state, built.rows, '/oec:granularityLevel')).toBe('/~identity')
370
+ expect(fieldPointerFor(form, state, built.rows, '/not:there')).toBeUndefined()
371
+ })
372
+ })
373
+
374
+ describe('what a reader is shown', () => {
375
+ it('draws a measurement, text in a language, a code, a list and a nested object as what they are', () => {
376
+ expect(describeValue({ type: 'gs1:QuantitativeValue', 'gs1:value': '98.50', 'gs1:unitCode': 'P1' })).toEqual({ kind: 'quantity', value: '98.50', unitCode: 'P1', unitName: 'per cent' })
377
+ expect(describeValue({ type: 'gs1:QuantitativeValue', 'gs1:value': 132, 'gs1:unitCode': 'XYZ' })).toEqual({ kind: 'quantity', value: '132', unitCode: 'XYZ', unitName: 'XYZ' })
378
+ expect(describeValue({ '@value': 'Laine', '@language': 'fr' })).toEqual({ kind: 'langText', text: 'Laine', language: 'fr' })
379
+ expect(describeValue({ '@value': '88', '@type': 'xsd:decimal' })).toEqual({ kind: 'typed', text: '88', type: 'xsd:decimal' })
380
+ expect(describeValue({ '@id': 'eutex:TumbleDryLow' })).toEqual({ kind: 'reference', id: 'eutex:TumbleDryLow', label: 'Tumble dry low' })
381
+ expect(describeValue('2026-09-18')).toEqual({ kind: 'date', text: '2026-09-18' })
382
+ expect(describeValue('2026-11-02T09:30:00Z')).toEqual({ kind: 'date', text: '2026-11-02T09:30:00Z' })
383
+ expect(describeValue(false)).toEqual({ kind: 'boolean', value: false })
384
+ expect(describeValue([1, 'two'])).toEqual({ kind: 'list', items: [{ kind: 'number', text: '1' }, { kind: 'text', text: 'two' }] })
385
+ const nested = describeValue({ type: 'gs1:Organization', id: 'https://id.example/417/9520000000011', 'gs1:organizationName': 'Harbour Cells', 'x:unknownThing': { deep: [true] } }, new Map([['gs1:organizationName', 'Name']]))
386
+ expect(nested).toEqual({
387
+ kind: 'object',
388
+ type: 'gs1:Organization',
389
+ id: 'https://id.example/417/9520000000011',
390
+ entries: [
391
+ { key: 'gs1:organizationName', label: 'Name', value: { kind: 'text', text: 'Harbour Cells' } },
392
+ { key: 'x:unknownThing', label: 'Unknown thing', value: { kind: 'object', entries: [{ key: 'deep', label: 'Deep', value: { kind: 'list', items: [{ kind: 'boolean', value: true }] } }] } },
393
+ ],
394
+ })
395
+ expect(humaniseName('eubat:hasBatteryState')).toBe('Battery state')
396
+ expect(humaniseName('gs1:TargetConsumerGenderCode-UNISEX')).toBe('Unisex')
397
+ })
398
+
399
+ it('lists every top-level property with its tier, including ones the page has no label for', () => {
400
+ const form = formFor('eu-textile@2')
401
+ const shown = describeProduct(
402
+ {
403
+ publicProduct: { '@context': ['x'], id: 'https://passports.example.com/01/09521002004007/21/A1', 'eutex:garmentType': 'Jacket', 'eutex:hasWaterUsage': { type: 'gs1:QuantitativeValue', 'gs1:value': '5', 'gs1:unitCode': 'LTR' }, 'x:brandNew': 1 },
404
+ restrictedProduct: { id: 'https://passports.example.com/01/09521002004007/21/A1', 'eutex:productionWastePercentage': '6.5', 'x:alsoNew': { a: 1 } },
405
+ access: { public: ['@context', 'id', 'eutex:garmentType'] },
406
+ },
407
+ labelsOf(form)
408
+ )
409
+ expect(shown.map((p) => [p.key, p.label, p.tier, p.disclosed ?? false])).toEqual([
410
+ ['@context', 'Contexts', 'public', false],
411
+ ['id', 'Identifier', 'public', false],
412
+ ['eutex:garmentType', 'Garment', 'public', false],
413
+ // In the public payload although the binding does not list it: shown, and flagged.
414
+ ['eutex:hasWaterUsage', 'Water used in production', 'public', true],
415
+ ['x:brandNew', 'Brand new', 'public', true],
416
+ ['eutex:productionWastePercentage', 'Production waste', 'restricted', false],
417
+ ['x:alsoNew', 'Also new', 'restricted', false],
418
+ ])
419
+ })
420
+ })
@@ -0,0 +1,62 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { PrivateKey, ProtoWallet } from '@bsv/sdk'
3
+ import { INDEX_REGISTRATION_FORMAT, signRegistration } from '@bsv/dpp-protocol'
4
+ import { loadConfig } from '../src/config.js'
5
+ import { startDevIndex } from '../src/dev-index.js'
6
+ import { openPlatform } from '../src/platform.js'
7
+
8
+ /**
9
+ * Before go-live, an index address with no tokens is one this app has not
10
+ * joined: the platform keeps the in-process index and says so, naming the
11
+ * command. The in-process index itself can run registration open, for the
12
+ * go-live test, and reports the network it was started on.
13
+ */
14
+ describe('an index the app has not joined', () => {
15
+ it('starts the in-process index and names go-live, instead of announcing to an index that would refuse', async () => {
16
+ const lines: string[] = []
17
+ const platform = await openPlatform({ config: loadConfig({ INDEX_URL: 'https://dpp-overlay-testnet.bsvb.net', NETWORK: 'test' }), mode: 'live', log: (line) => lines.push(line) })
18
+ try {
19
+ expect(platform.index.url).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/)
20
+ expect(lines.some((line) => /^This app has not joined https:\/\/dpp-overlay-testnet\.bsvb\.net yet .* npm run go-live /.test(line))).toBe(true)
21
+ expect(await platform.index.health()).toMatchObject({ status: 'ok', network: 'test' })
22
+ } finally {
23
+ await platform.close()
24
+ }
25
+ })
26
+
27
+ it('opens the test wallet on the configured root key when DPP_TEST_WALLET=1, so the registered key is the key in .env', async () => {
28
+ const rootKey = '77'.repeat(32)
29
+ const lines: string[] = []
30
+ const platform = await openPlatform({ config: loadConfig({ WALLET_ROOT_KEY: rootKey, DPP_TEST_WALLET: '1', NETWORK: 'test' }), mode: 'live', log: (line) => lines.push(line) })
31
+ try {
32
+ expect(platform.wallet.kind).toBe('test')
33
+ expect(platform.wallet.identityKey).toBe(PrivateKey.fromHex(rootKey).toPublicKey().toString())
34
+ expect(lines.some((line) => line.includes('DPP_TEST_WALLET'))).toBe(true)
35
+ } finally {
36
+ await platform.close()
37
+ }
38
+ })
39
+ })
40
+
41
+ describe('the in-process index with registration open', () => {
42
+ it('registers a wallet-signed request and names the key afterwards', async () => {
43
+ const app = PrivateKey.fromHex('78'.repeat(32))
44
+ const index = await startDevIndex({ publisherKey: PrivateKey.fromHex('79'.repeat(32)).toPublicKey().toString(), network: 'test', registration: 'open' })
45
+ try {
46
+ const request = await signRegistration(
47
+ { registrationFormat: INDEX_REGISTRATION_FORMAT, indexUrl: index.url, publisherKey: app.toPublicKey().toString(), network: 'test', custodyProfile: 'managed-custody@2', label: 'test app', requestedAt: new Date().toISOString() },
48
+ new ProtoWallet(app)
49
+ )
50
+ const response = await fetch(`${index.url}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(request) })
51
+ expect(response.status).toBe(201)
52
+ const body = (await response.json()) as { tokens: { submit: string; callback: string } }
53
+ expect(body.tokens.submit).toMatch(/^[0-9a-f]{64}$/)
54
+ const capabilities = (await (await fetch(`${index.url}/capabilities`)).json()) as { publisherPolicy: { publisherKeys: string[] }; profiles: Array<{ kind: string; id: string; version: string; options?: Record<string, unknown> }> }
55
+ expect(capabilities.publisherPolicy.publisherKeys).toContain(app.toPublicKey().toString())
56
+ expect(capabilities.profiles.find((p) => p.kind === 'operator')?.options?.registration).toBe('open')
57
+ expect(capabilities.profiles.find((p) => p.kind === 'custody')).toMatchObject({ id: 'managed-custody', version: '2' })
58
+ } finally {
59
+ await index.close()
60
+ }
61
+ })
62
+ })