@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,521 @@
1
+ // The model behind the sector forms: a form is a tree of fields, each field
2
+ // names the property it writes, and the product document is built from what
3
+ // the user entered and from nothing else.
4
+ //
5
+ // The rules the model keeps:
6
+ //
7
+ // - a field left empty is absent from the document. Nothing is defaulted:
8
+ // no identifier, classification, date, unit or precision is made up;
9
+ // - a number is written with the digits that were typed. A decimal goes
10
+ // into the document as text, so 98.50 stays 98.50;
11
+ // - a measurement is a value and a unit together, or it is nothing;
12
+ // - a document that was loaded is rebuilt value for value. A top-level
13
+ // property the form cannot hold exactly is kept as it came, as JSON,
14
+ // and is never dropped or reshaped.
15
+ //
16
+ // Nothing here touches the page or the network, so the API's tests exercise
17
+ // this module directly.
18
+
19
+ export type Json = Record<string, unknown>
20
+
21
+ export const isObject = (value: unknown): value is Json => value !== null && typeof value === 'object' && !Array.isArray(value)
22
+
23
+ /** Where a code field's choices come from: a short fixed list, or a class of the profile's own vocabulary, which the API serves. */
24
+ export type CodeSource = { options: Array<{ value: string; label: string }> } | { class: string; prefix?: string; only?: string }
25
+
26
+ interface Base {
27
+ /** The property the field writes, as documents write it. */
28
+ key: string
29
+ label: string
30
+ help?: string
31
+ /** The profile's rules require a value here. The form marks it, and the validator is what enforces it. */
32
+ required?: boolean
33
+ }
34
+
35
+ export type ScalarField =
36
+ | (Base & { kind: 'text' | 'longText' | 'date' | 'dateTime' | 'integer' | 'boolean' })
37
+ /** A web address. `as: 'reference'` writes it as a link to the thing at that address; otherwise it is written as text. */
38
+ | (Base & { kind: 'url'; as?: 'reference' })
39
+ /** `typed` writes the number as a value with the decimal type beside it, for a property the profile's contexts give no number type. */
40
+ | (Base & { kind: 'decimal'; typed?: boolean })
41
+ /** Text with its language. With no language chosen it is written as plain text. */
42
+ | (Base & { kind: 'langText' })
43
+ /** A measurement: the value and its UN/CEFACT unit code. */
44
+ | (Base & { kind: 'quantity'; units: string[] })
45
+ /** A coded value. `as: 'text'` writes the code itself; otherwise it is written as a reference. */
46
+ | (Base & { kind: 'code'; codes: CodeSource; as?: 'text' })
47
+ /** A country by its two-letter code. `as: 'text'` writes the code itself; otherwise a country node. */
48
+ | (Base & { kind: 'country'; as?: 'text' })
49
+
50
+ /** A member a group always carries once it carries anything: the kind of an indicator, for example. It is never written alone. */
51
+ export interface FixedField {
52
+ kind: 'fixed'
53
+ key: string
54
+ value: unknown
55
+ }
56
+
57
+ export interface GroupField extends Base {
58
+ kind: 'group'
59
+ /** The node's type, written first whenever the group has any value. */
60
+ type?: string
61
+ fields: Array<Field | FixedField>
62
+ }
63
+
64
+ export interface ListField extends Base {
65
+ kind: 'list'
66
+ /** What one entry is called, for the add button. */
67
+ itemLabel: string
68
+ item: ScalarField | GroupField
69
+ }
70
+
71
+ export type Field = ScalarField | GroupField | ListField
72
+
73
+ export interface FormSection {
74
+ title: string
75
+ description?: string
76
+ fields: Field[]
77
+ }
78
+
79
+ export interface SectorForm {
80
+ /** `id@version` of the profile the form writes. */
81
+ profile: string
82
+ /** The contexts a document names, by the file name the binding gives each. */
83
+ contexts: string[]
84
+ type: string[]
85
+ /** The members that state the serial. They are written from the one serial the passport identifier is made of. */
86
+ serialMembers: string[]
87
+ sections: FormSection[]
88
+ }
89
+
90
+ export interface LangValue {
91
+ value: string
92
+ language: string
93
+ }
94
+ export interface QuantityValue {
95
+ /** Text as typed, or the number a loaded document carried. */
96
+ value: string | number
97
+ unit: string
98
+ }
99
+ /** A reference a loaded document spelled with `id` where this form writes `@id`. The two mean the same, and the spelling is kept. */
100
+ export interface ReferenceValue {
101
+ code: string
102
+ spelled: 'id'
103
+ }
104
+ export type Value = string | number | boolean | LangValue | QuantityValue | ReferenceValue | { [key: string]: Value } | Value[] | undefined
105
+
106
+ /** The member of a group's values that holds the node's own identifier, where the group has no field for one. Only a loaded document sets it. */
107
+ export const NODE_ID = '~id'
108
+
109
+ const isReference = (value: unknown): value is ReferenceValue => isObject(value) && typeof value.code === 'string' && value.spelled === 'id'
110
+ /** The code or address a reference field holds, whichever way it is spelled. */
111
+ export const referenceText = (value: Value): string => (typeof value === 'string' ? value : isReference(value) ? value.code : '')
112
+ /** A reference field's value after an edit: the new text, in the spelling the value already had. */
113
+ export const withReferenceText = (value: Value, text: string): Value => (isReference(value) ? { code: text, spelled: 'id' } : text)
114
+ const writeReference = (value: Value): unknown => (isReference(value) ? { id: value.code } : { '@id': value })
115
+ const readReference = (json: unknown): Value | typeof UNFIT => {
116
+ if (!isObject(json)) return UNFIT
117
+ if (hasOnly(json, ['@id']) && typeof json['@id'] === 'string') return json['@id']
118
+ if (hasOnly(json, ['id']) && typeof json.id === 'string') return { code: json.id, spelled: 'id' }
119
+ return UNFIT
120
+ }
121
+
122
+ export interface FormState {
123
+ /** What the user entered, by top-level property. */
124
+ values: Record<string, Value>
125
+ /** Top-level properties the form has no field for, or could not hold exactly: kept as JSON, written as they are. */
126
+ others: Json
127
+ /** Whether the document states its granularity. A new document does; a loaded one keeps what it had. */
128
+ granularity: boolean
129
+ /** What a loaded document carried where the form would otherwise write its own. */
130
+ loaded?: { context?: unknown; type?: unknown; serialMembers?: string[] }
131
+ }
132
+
133
+ export const emptyState = (): FormState => ({ values: {}, others: {}, granularity: true })
134
+
135
+ /** The identity every document of the form carries: the passport identifier, and the GTIN and serial it is made of. */
136
+ export interface Identity {
137
+ passportId: string
138
+ gtin: string
139
+ serial: string
140
+ }
141
+
142
+ export interface FormProblem {
143
+ /** The field, as a pointer into the form's values. */
144
+ pointer: string
145
+ message: string
146
+ }
147
+
148
+ const DECIMAL = /^[+-]?(\d+(\.\d+)?|\.\d+)$/
149
+ const INTEGER = /^[+-]?\d+$/
150
+ const DATE = /^\d{4}-\d{2}-\d{2}$/
151
+ const DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/
152
+ const XSD_DECIMAL = 'xsd:decimal'
153
+ const QUANTITY_TYPE = 'gs1:QuantitativeValue'
154
+ const COUNTRY_TYPE = 'gs1:Country'
155
+
156
+ export const escapePointer = (segment: string): string => segment.replace(/~/g, '~0').replace(/\//g, '~1')
157
+ const unescapePointer = (segment: string): string => segment.replace(/~1/g, '/').replace(/~0/g, '~')
158
+ const UNFIT = Symbol('a value the field cannot hold exactly')
159
+ const hasOnly = (value: Json, names: string[]): boolean => Object.keys(value).length === names.length && names.every((name) => Object.hasOwn(value, name))
160
+ const isBlank = (value: unknown): boolean => value === undefined || value === null || (typeof value === 'string' && value.trim() === '')
161
+
162
+ interface Emission {
163
+ problems: FormProblem[]
164
+ /** For each list that was written: the form row each written entry came from. */
165
+ rows: Map<string, number[]>
166
+ }
167
+
168
+ /** The JSON a field writes for a value, or nothing when the value is empty. `formPointer` and `docPointer` say where the field sits. */
169
+ function emit(field: Field, value: Value, formPointer: string, docPointer: string, out: Emission): unknown {
170
+ const problem = (message: string): undefined => {
171
+ out.problems.push({ pointer: formPointer, message })
172
+ return undefined
173
+ }
174
+ switch (field.kind) {
175
+ case 'text':
176
+ case 'longText':
177
+ return typeof value === 'string' && !isBlank(value) ? value : undefined
178
+ case 'url': {
179
+ const address = field.as === 'reference' ? referenceText(value) : value
180
+ if (typeof address !== 'string' || isBlank(address)) return undefined
181
+ try {
182
+ new URL(address)
183
+ } catch {
184
+ return problem('Enter a complete web address, starting with https://.')
185
+ }
186
+ return field.as === 'reference' ? writeReference(value) : address
187
+ }
188
+ case 'date':
189
+ if (typeof value !== 'string' || isBlank(value)) return undefined
190
+ return DATE.test(value) ? value : problem('Write the date as YYYY-MM-DD.')
191
+ case 'dateTime':
192
+ if (typeof value !== 'string' || isBlank(value)) return undefined
193
+ return DATE_TIME.test(value) ? value : problem('Write the date and time with its zone, for example 2026-11-02T09:30:00Z.')
194
+ case 'integer':
195
+ if (typeof value === 'number') return value
196
+ if (typeof value !== 'string' || isBlank(value)) return undefined
197
+ return INTEGER.test(value.trim()) && Number.isSafeInteger(Number(value.trim())) ? Number(value.trim()) : problem('Enter a whole number.')
198
+ case 'decimal':
199
+ if (typeof value === 'number') return value
200
+ if (typeof value !== 'string' || isBlank(value)) return undefined
201
+ if (!DECIMAL.test(value.trim())) return problem('Enter a number, with a point for the decimals.')
202
+ // The digits as typed: nothing is rounded and no precision is added.
203
+ return field.typed === true ? { '@value': value.trim(), '@type': XSD_DECIMAL } : value.trim()
204
+ case 'boolean':
205
+ return typeof value === 'boolean' ? value : undefined
206
+ case 'langText': {
207
+ const text = isObject(value) ? (value as unknown as LangValue) : undefined
208
+ if (text == null || isBlank(text.value)) return undefined
209
+ return isBlank(text.language) ? text.value : { '@value': text.value, '@language': text.language.trim() }
210
+ }
211
+ case 'quantity': {
212
+ const quantity = isObject(value) ? (value as unknown as QuantityValue) : undefined
213
+ if (quantity == null || (isBlank(quantity.value) && isBlank(quantity.unit))) return undefined
214
+ if (isBlank(quantity.value)) return problem('Enter the value, or clear the unit.')
215
+ if (isBlank(quantity.unit)) return problem('Choose the unit. A measurement is a value and its unit together.')
216
+ if (typeof quantity.value === 'string' && !DECIMAL.test(quantity.value.trim())) return problem('Enter a number, with a point for the decimals.')
217
+ return { type: QUANTITY_TYPE, 'gs1:value': typeof quantity.value === 'string' ? quantity.value.trim() : quantity.value, 'gs1:unitCode': quantity.unit }
218
+ }
219
+ case 'code':
220
+ if (isBlank(referenceText(value))) return undefined
221
+ return field.as === 'text' ? referenceText(value) : writeReference(value)
222
+ case 'country':
223
+ if (typeof value !== 'string' || isBlank(value)) return undefined
224
+ if (!/^[A-Z]{2}$/.test(value)) return problem('Enter the two-letter country code in capitals, for example AU.')
225
+ return field.as === 'text' ? value : { type: COUNTRY_TYPE, 'gs1:countryCode': value }
226
+ case 'group': {
227
+ const group = isObject(value) ? (value as { [key: string]: Value }) : {}
228
+ const members: Array<[string, unknown]> = []
229
+ let entered = false
230
+ // An identifier a loaded node carried, where the group has no field for one.
231
+ if (typeof group[NODE_ID] === 'string' && !isBlank(group[NODE_ID])) {
232
+ members.push(['id', group[NODE_ID]])
233
+ entered = true
234
+ }
235
+ for (const child of field.fields) {
236
+ if (child.kind === 'fixed') {
237
+ members.push([child.key, child.value])
238
+ continue
239
+ }
240
+ const written = emit(child, group[child.key], `${formPointer}/${escapePointer(child.key)}`, `${docPointer}/${escapePointer(child.key)}`, out)
241
+ if (written === undefined) continue
242
+ members.push([child.key, written])
243
+ entered = true
244
+ }
245
+ // A type and fixed members alone say nothing the user entered, so they are not written alone.
246
+ if (!entered) return undefined
247
+ return Object.fromEntries([...(field.type == null ? [] : [['type', field.type] as [string, unknown]]), ...members])
248
+ }
249
+ case 'list': {
250
+ const entries = Array.isArray(value) ? value : []
251
+ const written: unknown[] = []
252
+ const rows: number[] = []
253
+ entries.forEach((entry, row) => {
254
+ const item = emit({ ...field.item, key: field.key } as Field, entry, `${formPointer}/${row}`, `${docPointer}/${written.length}`, out)
255
+ if (item === undefined) return
256
+ written.push(item)
257
+ rows.push(row)
258
+ })
259
+ if (written.length === 0) return undefined
260
+ out.rows.set(docPointer, rows)
261
+ return written
262
+ }
263
+ }
264
+ }
265
+
266
+
267
+ /** The form value for a piece of a document, or `UNFIT` when the field would not write it back the same. */
268
+ function read(field: Field, json: unknown): Value | typeof UNFIT {
269
+ switch (field.kind) {
270
+ case 'url':
271
+ if (field.as === 'reference') return readReference(json)
272
+ return typeof json === 'string' ? json : UNFIT
273
+ case 'text':
274
+ case 'longText':
275
+ case 'date':
276
+ case 'dateTime':
277
+ return typeof json === 'string' ? json : UNFIT
278
+ case 'integer':
279
+ return typeof json === 'number' && Number.isSafeInteger(json) ? json : UNFIT
280
+ case 'decimal':
281
+ if (typeof json === 'number') return json
282
+ if (field.typed === true) return isObject(json) && hasOnly(json, ['@value', '@type']) && typeof json['@value'] === 'string' && json['@type'] === XSD_DECIMAL ? json['@value'] : UNFIT
283
+ return typeof json === 'string' ? json : UNFIT
284
+ case 'boolean':
285
+ return typeof json === 'boolean' ? json : UNFIT
286
+ case 'langText':
287
+ if (typeof json === 'string') return { value: json, language: '' }
288
+ return isObject(json) && hasOnly(json, ['@value', '@language']) && typeof json['@value'] === 'string' && typeof json['@language'] === 'string' ? { value: json['@value'], language: json['@language'] } : UNFIT
289
+ case 'quantity': {
290
+ if (!isObject(json) || !hasOnly(json, ['type', 'gs1:value', 'gs1:unitCode']) || json.type !== QUANTITY_TYPE || typeof json['gs1:unitCode'] !== 'string') return UNFIT
291
+ const value = json['gs1:value']
292
+ return typeof value === 'string' || typeof value === 'number' ? { value, unit: json['gs1:unitCode'] } : UNFIT
293
+ }
294
+ case 'code':
295
+ if (field.as === 'text') return typeof json === 'string' ? json : UNFIT
296
+ return readReference(json)
297
+ case 'country':
298
+ if (field.as === 'text') return typeof json === 'string' ? json : UNFIT
299
+ return isObject(json) && hasOnly(json, ['type', 'gs1:countryCode']) && json.type === COUNTRY_TYPE && typeof json['gs1:countryCode'] === 'string' ? json['gs1:countryCode'] : UNFIT
300
+ case 'group': {
301
+ if (!isObject(json)) return UNFIT
302
+ const group: { [key: string]: Value } = {}
303
+ for (const [key, member] of Object.entries(json)) {
304
+ if (key === 'type' && field.type != null) {
305
+ if (member !== field.type) return UNFIT
306
+ continue
307
+ }
308
+ const child = field.fields.find((candidate) => candidate.key === key)
309
+ if (child == null) {
310
+ if (key !== 'id' || typeof member !== 'string') return UNFIT
311
+ group[NODE_ID] = member
312
+ continue
313
+ }
314
+ if (child.kind === 'fixed') {
315
+ if (!sameJson(member, child.value)) return UNFIT
316
+ continue
317
+ }
318
+ const value = read(child, member)
319
+ if (value === UNFIT) return UNFIT
320
+ group[key] = value
321
+ }
322
+ return group
323
+ }
324
+ case 'list': {
325
+ if (!Array.isArray(json)) return UNFIT
326
+ const entries: Value[] = []
327
+ for (const entry of json) {
328
+ const value = read({ ...field.item, key: field.key } as Field, entry)
329
+ if (value === UNFIT) return UNFIT
330
+ entries.push(value)
331
+ }
332
+ return entries
333
+ }
334
+ }
335
+ }
336
+
337
+ /** Whether two JSON values are the same, whatever order their members are written in. */
338
+ export function sameJson(a: unknown, b: unknown): boolean {
339
+ if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((entry, index) => sameJson(entry, b[index]))
340
+ if (isObject(a) || isObject(b)) {
341
+ if (!isObject(a) || !isObject(b)) return false
342
+ const keys = Object.keys(a)
343
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && sameJson(a[key], b[key]))
344
+ }
345
+ return a === b
346
+ }
347
+
348
+ /** The members that state which item a document is about. A form writes them from the passport identifier and takes them from nowhere else. */
349
+ const STATED_IDENTITY = ['id', '@id', 'gs1:gtin', 'gs1:hasSerialNumber', 'schema:serialNumber']
350
+
351
+ export const topLevelFields = (form: SectorForm): Field[] => form.sections.flatMap((section) => section.fields)
352
+
353
+ /** The members the form writes from the identity, never from a field. */
354
+ export function identityMembers(form: SectorForm, state?: FormState): string[] {
355
+ return ['@context', 'id', '@id', 'type', '@type', 'oec:granularityLevel', 'gs1:gtin', ...new Set([...form.serialMembers, ...(state?.loaded?.serialMembers ?? [])])]
356
+ }
357
+
358
+ export interface BuiltDocument {
359
+ /** The complete product document, as it will be sent. */
360
+ product: Json
361
+ /** What stops the document being sent: a measurement with no unit, a number that is not one. */
362
+ problems: FormProblem[]
363
+ rows: Map<string, number[]>
364
+ }
365
+
366
+ /**
367
+ * The product document for what the form holds. The identity members come
368
+ * from the one passport identifier, so the document's GTIN and serial cannot
369
+ * disagree with it. `contexts` are the addresses the registered binding
370
+ * lists for the form's context files.
371
+ */
372
+ export function buildDocument(form: SectorForm, state: FormState, identity: Identity, contexts: string[]): BuiltDocument {
373
+ const out: Emission = { problems: [], rows: new Map() }
374
+ const product: Json = {
375
+ '@context': state.loaded?.context ?? contexts,
376
+ id: identity.passportId,
377
+ type: state.loaded?.type ?? form.type,
378
+ ...(state.granularity ? { 'oec:granularityLevel': 'item' } : {}),
379
+ 'gs1:gtin': identity.gtin,
380
+ }
381
+ for (const member of state.loaded?.serialMembers ?? form.serialMembers) product[member] = identity.serial
382
+ for (const field of topLevelFields(form)) {
383
+ const written = emit(field, state.values[field.key], `/${escapePointer(field.key)}`, `/${escapePointer(field.key)}`, out)
384
+ if (written !== undefined) product[field.key] = written
385
+ }
386
+ const reserved = new Set(Object.keys(product))
387
+ for (const [key, value] of Object.entries(state.others)) {
388
+ // The identifier, GTIN and serial have one source, the passport identifier, so they cannot be stated a second time here and disagree with it.
389
+ if (STATED_IDENTITY.includes(key)) out.problems.push({ pointer: '/~others', message: `Other properties state ${key}. The form writes the identifier, GTIN and serial from the passport identifier, so remove it here.` })
390
+ else if (reserved.has(key)) out.problems.push({ pointer: '/~others', message: `Other properties repeat ${key}, which the form already writes. Remove it from one of the two.` })
391
+ else product[key] = value
392
+ }
393
+ return { product, problems: out.problems, rows: out.rows }
394
+ }
395
+
396
+ /** A document without its note members: any member whose name starts with `_comment`, at any depth. A profile's contexts do not define them, so a document that carries one is refused. */
397
+ export function stripComments<T>(value: T): T {
398
+ if (Array.isArray(value)) return value.map(stripComments) as T
399
+ if (!isObject(value)) return value
400
+ return Object.fromEntries(
401
+ Object.entries(value)
402
+ .filter(([name]) => !name.startsWith('_comment'))
403
+ .map(([name, member]) => [name, stripComments(member)])
404
+ ) as T
405
+ }
406
+
407
+ export interface ParsedDocument {
408
+ state: FormState
409
+ /** The top-level properties that went to the JSON area, because the form has no field for them or could not hold their value exactly. */
410
+ kept: string[]
411
+ /** What the document says of itself, for the identifier inputs. */
412
+ stated: { id?: string; gtin?: string; serial?: string }
413
+ }
414
+
415
+ /** A product document as form values. Every top-level property ends up in a field or, unchanged, in `others`: none is dropped. */
416
+ export function parseDocument(form: SectorForm, product: Json): ParsedDocument {
417
+ const state: FormState = { values: {}, others: {}, granularity: Object.hasOwn(product, 'oec:granularityLevel') }
418
+ const kept: string[] = []
419
+ const fields = new Map(topLevelFields(form).map((field) => [field.key, field]))
420
+ const serialMembers = ['gs1:hasSerialNumber', 'schema:serialNumber'].filter((member) => Object.hasOwn(product, member))
421
+ const stated: ParsedDocument['stated'] = {}
422
+ const id = [product.id, product['@id']].find((value): value is string => typeof value === 'string')
423
+ if (id != null) stated.id = id
424
+ if (typeof product['gs1:gtin'] === 'string') stated.gtin = product['gs1:gtin']
425
+ const serial = serialMembers.map((member) => product[member]).find((value): value is string => typeof value === 'string')
426
+ if (serial != null) stated.serial = serial
427
+
428
+ const loaded: NonNullable<FormState['loaded']> = {}
429
+ if (Object.hasOwn(product, '@context')) loaded.context = product['@context']
430
+ const type = product.type ?? product['@type']
431
+ if (type !== undefined && !sameJson(type, form.type)) loaded.type = type
432
+ if (serialMembers.length > 0 && !sameJson(serialMembers, form.serialMembers)) loaded.serialMembers = serialMembers
433
+ if (Object.keys(loaded).length > 0) state.loaded = loaded
434
+
435
+ const identity = new Set(['@context', 'id', '@id', 'type', '@type', 'oec:granularityLevel', 'gs1:gtin', ...serialMembers])
436
+ for (const [key, value] of Object.entries(product)) {
437
+ if (identity.has(key)) continue
438
+ const field = fields.get(key)
439
+ const read_ = field == null ? UNFIT : read(field, value)
440
+ // The value is taken into the field only if the field writes it back the same. Anything else stays as it came.
441
+ if (field != null && read_ !== UNFIT && sameJson(emit(field, read_, '', '', { problems: [], rows: new Map() }), value)) {
442
+ state.values[key] = read_
443
+ } else {
444
+ state.others[key] = value
445
+ kept.push(key)
446
+ }
447
+ }
448
+ return { state, kept, stated }
449
+ }
450
+
451
+ /**
452
+ * The field a place in the product document belongs to, as a pointer into
453
+ * the form: the deepest field on the way to it. A finding is shown there.
454
+ * `rows` is from the build that made the document, and maps a written list
455
+ * entry back to its row. Nothing is returned for a place outside the form.
456
+ */
457
+ export function fieldPointerFor(form: SectorForm, state: FormState, rows: Map<string, number[]>, docPointer: string): string | undefined {
458
+ const segments = docPointer.split('/').slice(1).map(unescapePointer)
459
+ if (segments.length === 0) return undefined
460
+ if (identityMembers(form, state).includes(segments[0])) return '/~identity'
461
+ let field: Field | undefined = topLevelFields(form).find((candidate) => candidate.key === segments[0])
462
+ if (field == null) return Object.hasOwn(state.others, segments[0]) ? '/~others' : undefined
463
+ let formPointer = `/${escapePointer(field.key)}`
464
+ let docWalked = formPointer
465
+ for (let at = 1; at < segments.length; at++) {
466
+ const segment = segments[at]
467
+ if (field.kind === 'list') {
468
+ const index = Number(segment)
469
+ if (!Number.isInteger(index)) break
470
+ const row = rows.get(docWalked)?.[index]
471
+ if (row == null) break
472
+ formPointer = `${formPointer}/${row}`
473
+ docWalked = `${docWalked}/${index}`
474
+ field = { ...field.item, key: field.key } as Field
475
+ } else if (field.kind === 'group') {
476
+ const child: Field | FixedField | undefined = field.fields.find((candidate) => candidate.key === segment)
477
+ if (child == null || child.kind === 'fixed') break
478
+ formPointer = `${formPointer}/${escapePointer(child.key)}`
479
+ docWalked = `${docWalked}/${escapePointer(segment)}`
480
+ field = child
481
+ } else break
482
+ }
483
+ return formPointer
484
+ }
485
+
486
+ export type Tier = 'public' | 'restricted'
487
+
488
+ /** The tier of a top-level property under a binding's split: public if the binding lists it, restricted otherwise. Without a split everything is public. */
489
+ export const tierOf = (access: { public: string[] } | undefined, property: string): Tier => (access == null || access.public.includes(property) ? 'public' : 'restricted')
490
+
491
+ /** The top-level properties of a document, by the tier each will be written to. */
492
+ export function splitPreview(product: Json, access: { public: string[] } | undefined): { public: string[]; restricted: string[] } {
493
+ const names = Object.keys(product)
494
+ return { public: names.filter((name) => tierOf(access, name) === 'public'), restricted: names.filter((name) => tierOf(access, name) === 'restricted') }
495
+ }
496
+
497
+ /** Every class of the profile's vocabulary the form's code fields draw on, for one request to the API. */
498
+ export function codeClasses(form: SectorForm): string[] {
499
+ const classes = new Set<string>()
500
+ const visit = (field: Field | FixedField): void => {
501
+ if (field.kind === 'code' && 'class' in field.codes) classes.add(field.codes.class)
502
+ else if (field.kind === 'group') field.fields.forEach(visit)
503
+ else if (field.kind === 'list') visit(field.item)
504
+ }
505
+ topLevelFields(form).forEach(visit)
506
+ return [...classes].sort()
507
+ }
508
+
509
+ /** A label for every property the form knows, by the name documents write, for a reader's page. The first field to name a property wins. */
510
+ export function labelsOf(form: SectorForm): Map<string, string> {
511
+ const labels = new Map<string, string>()
512
+ const visit = (field: Field | FixedField): void => {
513
+ if (field.kind === 'fixed') return
514
+ // A list entry has no property of its own, and a node's own identifier is labelled by the page.
515
+ if (field.key !== '' && field.key !== 'id' && !labels.has(field.key)) labels.set(field.key, field.label)
516
+ if (field.kind === 'group') field.fields.forEach(visit)
517
+ else if (field.kind === 'list' && field.item.kind === 'group') field.item.fields.forEach(visit)
518
+ }
519
+ topLevelFields(form).forEach(visit)
520
+ return labels
521
+ }
@@ -0,0 +1,15 @@
1
+ // The sector forms this application has, by the profile each writes. A
2
+ // profile held by a binding that has no form here is written as a JSON
3
+ // document instead.
4
+ import { BATTERY_FORM } from './battery-form'
5
+ import type { SectorForm } from './form-model'
6
+ import { TEXTILE_FORM } from './textile-form'
7
+
8
+ const FORMS: SectorForm[] = [
9
+ BATTERY_FORM,
10
+ TEXTILE_FORM,
11
+ { ...BATTERY_FORM, profile: 'eu-battery@2' },
12
+ { ...TEXTILE_FORM, profile: 'eu-textile@2' },
13
+ ]
14
+
15
+ export const sectorFormFor = (profile: string): SectorForm | undefined => FORMS.find((form) => form.profile === profile)
@@ -0,0 +1,48 @@
1
+ // The passport identifier a form's document is written for: a GS1 Digital
2
+ // Link made of the platform's host, a GTIN under its GS1 prefix and the
3
+ // item's serial. The API mints the identifier itself and refuses a document
4
+ // that names any other item, so this is for the page: it lets the form show
5
+ // the identifier and put the same GTIN and serial into the document.
6
+
7
+ export interface IdentifierPolicy {
8
+ host: string
9
+ prefix: string
10
+ }
11
+
12
+ /** The GS1 check digit for a run of digits: weights of three and one from the right. */
13
+ export function gs1CheckDigit(digits: string): string {
14
+ let sum = 0
15
+ for (let at = 0; at < digits.length; at++) sum += Number(digits[digits.length - 1 - at]) * (at % 2 === 0 ? 3 : 1)
16
+ return String((10 - (sum % 10)) % 10)
17
+ }
18
+
19
+ export type MintedIdentity = { ok: true; passportId: string; gtin: string; serial: string } | { ok: false; problem: string }
20
+
21
+ /** The identifier, GTIN and serial for an item reference and a serial, or what is wrong with them. */
22
+ export function mintIdentity(policy: IdentifierPolicy, itemReference: string, serial: string): MintedIdentity {
23
+ const digits = 12 - policy.prefix.length
24
+ if (!/^\d+$/.test(itemReference) || itemReference.length !== digits) return { ok: false, problem: `The item reference is ${digits} digits: the ones after the GS1 prefix ${policy.prefix}.` }
25
+ if (!/^[A-Za-z0-9!"%&'()*+,\-./:;<=>?_]{1,20}$/.test(serial)) return { ok: false, problem: 'A serial is 1 to 20 characters: letters, digits and the punctuation GS1 allows.' }
26
+ const body = `0${policy.prefix}${itemReference}`
27
+ const gtin = body + gs1CheckDigit(body)
28
+ return { ok: true, passportId: `https://${policy.host}/01/${gtin}/21/${encodeURIComponent(serial)}`, gtin, serial }
29
+ }
30
+
31
+ /**
32
+ * The item reference and serial a loaded document's own identifier names,
33
+ * when its GTIN is under this platform's prefix. A document about a product
34
+ * under another prefix cannot be written here, and the form says so.
35
+ */
36
+ export function identityFromDocument(policy: IdentifierPolicy, id: string | undefined): { itemReference: string; serial: string } | { problem: string } {
37
+ const match = id == null ? null : /\/01\/(\d{14})\/21\/([^/?#]+)$/.exec(id)
38
+ if (match == null) return { problem: 'The document does not name a serialised item: its identifier is not a GS1 Digital Link with a GTIN and a serial.' }
39
+ const gtin = match[1]
40
+ if (!gtin.startsWith(`0${policy.prefix}`)) return { problem: `The document's GTIN ${gtin} is not under this platform's GS1 prefix ${policy.prefix}, so it cannot be written here.` }
41
+ let serial = match[2]
42
+ try {
43
+ serial = decodeURIComponent(serial)
44
+ } catch {
45
+ // Left as written.
46
+ }
47
+ return { itemReference: gtin.slice(1 + policy.prefix.length, 13), serial }
48
+ }