@crombolo/schema 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/schema",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "description": "Schema-as-code for crombolo: TOML document, media and member type definitions.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -28,7 +28,7 @@
28
28
  "access": "public"
29
29
  },
30
30
  "dependencies": {
31
- "@crombolo/core": "0.21.0",
32
- "@crombolo/data": "0.21.0"
31
+ "@crombolo/core": "0.22.0",
32
+ "@crombolo/data": "0.22.0"
33
33
  }
34
34
  }
package/src/builtin.ts CHANGED
@@ -25,7 +25,7 @@ export const BUILTIN_DATA_TYPES: readonly SchemaDataType[] = ALL_SEEDED_DATA_TYP
25
25
  )
26
26
 
27
27
  /** The `property_value` column family an editor stores into; Umbraco's ValueStorageType. */
28
- /** Folder, Image and File: always present, never deleted, alias fixed. */
28
+ /** Folder, Image, File and Caching: always present, never deleted, alias fixed. */
29
29
  export const SYSTEM_MEDIA_TYPE_ALIASES: ReadonlySet<string> = new Set(
30
30
  SYSTEM_MEDIA_TYPES.map((t) => t.alias),
31
31
  )
@@ -44,7 +44,7 @@ export function builtInMediaTypeSchema(
44
44
  alias: def.alias,
45
45
  name: def.name,
46
46
  icon: def.icon,
47
- allowAtRoot: true,
47
+ allowAtRoot: !def.composition,
48
48
  isElement: false,
49
49
  allowInLibrary: false,
50
50
  variesByCulture: false,
@@ -97,8 +97,8 @@ export function builtInContentTypeSchema(def: BuiltInContentType): SchemaContent
97
97
  description: def.description,
98
98
  icon: def.icon,
99
99
  allowAtRoot: false,
100
- isElement: false,
101
- allowInLibrary: false,
100
+ isElement: def.isElement === true,
101
+ allowInLibrary: def.allowedInLibrary === true,
102
102
  variesByCulture: false,
103
103
  variesBySegment: false,
104
104
  compositions: [],
@@ -147,8 +147,12 @@ export function checkSystemContentTypeFile(t: SchemaContentType): string[] {
147
147
  const findings: string[] = []
148
148
  if (t.key && t.key.toLowerCase() !== def.key)
149
149
  findings.push(`"${t.alias}" is provided by Crombolo; its key must be ${def.key}`)
150
- if (t.isElement)
151
- findings.push(`"${t.alias}" is provided by Crombolo and cannot be an element type`)
150
+ if (t.isElement !== (def.isElement === true))
151
+ findings.push(
152
+ def.isElement
153
+ ? `"${t.alias}" is provided by Crombolo and must stay an element type`
154
+ : `"${t.alias}" is provided by Crombolo and cannot be an element type`,
155
+ )
152
156
  const declared = declaredProperties(t)
153
157
  for (const shipped of def.properties) {
154
158
  const found = declared.find((p) => p.alias === shipped.alias)
@@ -0,0 +1,242 @@
1
+ /**
2
+ * `crombolo generate --delivery`: TypeScript for the JSON a site's Delivery API
3
+ * writes, one properties interface per content, element and media type, typed
4
+ * for `@crombolo/delivery-client`. docs/delivery-api.md, "Typed apps".
5
+ *
6
+ * A sibling of `generateTypes`, which types what a server-rendered view
7
+ * receives; the two describe the same schema in two different shapes.
8
+ */
9
+ import { BUILT_IN_MEDIA_TYPES } from '@crombolo/data'
10
+ import { storageTypeFor } from './builtin.ts'
11
+ import { blockElements, dataTypeOf, effectiveProperties, pascal } from './generate.ts'
12
+ import type { SchemaContentType, SchemaSet } from './model.ts'
13
+
14
+ export interface DeliveryTypesOptions {
15
+ /** Whether the API serves a content type: the site's allow and disallow lists. */
16
+ serves?: (alias: string) => boolean
17
+ }
18
+
19
+ /** The module the generated file imports its shapes from. */
20
+ export const DELIVERY_CLIENT_MODULE = '@crombolo/delivery-client'
21
+
22
+ /** An alias as an object key: bare when it is an identifier, quoted otherwise. */
23
+ const key = (alias: string) => (/^[A-Za-z_$][\w$]*$/.test(alias) ? alias : `'${alias}'`)
24
+
25
+ const byAlias = (a: { alias: string }, b: { alias: string }) => a.alias.localeCompare(b.alias)
26
+
27
+ const keyAliases = (set: SchemaSet, keys: string): string[] =>
28
+ keys
29
+ .split(',')
30
+ .map((key) => key.trim().toLowerCase())
31
+ .filter(Boolean)
32
+ .flatMap((key) => set.contentTypes.find((t) => t.key?.toLowerCase() === key)?.alias ?? [])
33
+
34
+ export function generateDeliveryTypes(set: SchemaSet, options: DeliveryTypesOptions = {}): string {
35
+ const serves = options.serves ?? (() => true)
36
+ const pages = set.contentTypes.filter((t) => !t.isElement && serves(t.alias)).sort(byAlias)
37
+ const elements = set.contentTypes.filter((t) => t.isElement).sort(byAlias)
38
+ const media = mediaTypes(set)
39
+
40
+ const name = (type: SchemaContentType) => `${pascal(type.alias)}Properties`
41
+ const mediaName = (alias: string) => `${pascal(alias)}MediaProperties`
42
+ const elementType = (alias: string) => {
43
+ const type = elements.find((t) => t.alias === alias)
44
+ return type ? `ApiElement<${JSON.stringify(alias)}, ${name(type)}>` : undefined
45
+ }
46
+ const elementUnion = (aliases: string[]) => {
47
+ const types = aliases.flatMap((alias) => elementType(alias) ?? [])
48
+ return types.length === 0 ? 'Element' : types.join(' | ')
49
+ }
50
+ const pageReferences = (aliases?: string[]) => {
51
+ const chosen = aliases ? pages.filter((t) => aliases.includes(t.alias)) : pages
52
+ return chosen.length === 0 || !aliases
53
+ ? 'ContentReference'
54
+ : chosen.map((t) => `ApiContentReference<${JSON.stringify(t.alias)}, ${name(t)}>`).join(' | ')
55
+ }
56
+
57
+ /** The JSON the Delivery API writes for a property of this data type; null when empty. */
58
+ const typeFor = (dataTypeAlias: string): string => {
59
+ const { editor, config } = dataTypeOf(set, dataTypeAlias)
60
+ switch (editor) {
61
+ case undefined:
62
+ return 'unknown'
63
+ case 'Umbraco.MemberPicker':
64
+ return "'(unsupported)'"
65
+ case 'Umbraco.TrueFalse':
66
+ return 'boolean'
67
+ case 'Umbraco.RichText':
68
+ return 'ApiRichText'
69
+ case 'Umbraco.ContentPicker':
70
+ return 'ContentReference'
71
+ case 'Umbraco.MultiNodeTreePicker': {
72
+ const startNode = config.startNode as { type?: unknown } | undefined
73
+ const filter = typeof config.filter === 'string' ? config.filter : ''
74
+ const aliases = filter
75
+ .split(',')
76
+ .map((alias) => alias.trim())
77
+ .filter(Boolean)
78
+ const content = pageReferences(aliases.length ? aliases : undefined)
79
+ if (startNode?.type === 'media') return 'MediaReference[]'
80
+ if (startNode?.type === 'content') return `Array<${content}>`
81
+ return `Array<${content} | MediaReference>`
82
+ }
83
+ case 'Umbraco.MediaPicker3':
84
+ return 'Array<MediaWithCrops>'
85
+ case 'Umbraco.MultiUrlPicker':
86
+ return 'ApiLink[]'
87
+ case 'Umbraco.BlockList': {
88
+ const { content, settings } = blockElements(set, config)
89
+ return `ApiBlockList<${elementUnion(content)}, ${elementUnion(settings)}>`
90
+ }
91
+ case 'Umbraco.BlockGrid': {
92
+ const { content, settings } = blockElements(set, config)
93
+ return `ApiBlockGrid<${elementUnion(content)}, ${elementUnion(settings)}>`
94
+ }
95
+ case 'Umbraco.ElementPicker': {
96
+ const allowed =
97
+ typeof config.allowedContentTypes === 'string' ? config.allowedContentTypes : ''
98
+ return `Array<${elementUnion([...new Set(keyAliases(set, allowed))])}>`
99
+ }
100
+ case 'Umbraco.DropDown.Flexible':
101
+ return config.multiple === true ? 'string[]' : 'string'
102
+ case 'Umbraco.CheckBoxList':
103
+ case 'Umbraco.MultipleTextstring':
104
+ case 'Umbraco.Tags':
105
+ return 'string[]'
106
+ case 'Umbraco.DateTime':
107
+ return 'string'
108
+ case 'Umbraco.ColorPicker':
109
+ return 'ApiColor'
110
+ case 'Umbraco.ImageCropper':
111
+ return 'ApiImageCropper'
112
+ case 'Umbraco.UploadField':
113
+ case 'Umbraco.TextBox':
114
+ case 'Umbraco.TextArea':
115
+ case 'Umbraco.EmailAddress':
116
+ return 'string'
117
+ }
118
+ switch (storageTypeFor(editor)) {
119
+ case 'Integer':
120
+ case 'Decimal':
121
+ return 'number'
122
+ case 'Date':
123
+ case 'Nvarchar':
124
+ return 'string'
125
+ default:
126
+ return 'unknown'
127
+ }
128
+ }
129
+
130
+ const body = (
131
+ properties: ReturnType<typeof effectiveProperties>,
132
+ skip?: (alias: string) => boolean,
133
+ ) => {
134
+ const lines: string[] = []
135
+ const unique = new Map(properties.map((p) => [p.alias, p]))
136
+ for (const p of [...unique.values()].sort(byAlias)) {
137
+ if (skip?.(p.alias)) continue
138
+ if (p.description) lines.push(` /** ${p.description} */`)
139
+ lines.push(` ${key(p.alias)}: ${typeFor(p.type)} | null`)
140
+ }
141
+ return lines
142
+ }
143
+
144
+ const out: string[] = [
145
+ '// Generated by `crombolo generate --delivery` from schema/*.toml. Do not edit.',
146
+ '',
147
+ '',
148
+ '/** Every type the Delivery API serves, by alias: pass it to `createDeliveryClient`. */',
149
+ 'export interface DeliveryTypes {',
150
+ ' content: {',
151
+ ...pages.map((t) => ` ${key(t.alias)}: ${name(t)}`),
152
+ ' }',
153
+ ' elements: {',
154
+ ...elements.map((t) => ` ${key(t.alias)}: ${name(t)}`),
155
+ ' }',
156
+ ' media: {',
157
+ ...media.map((t) => ` ${key(t.alias)}: ${mediaName(t.alias)}`),
158
+ ' }',
159
+ '}',
160
+ '',
161
+ '/** Any page, as the item, query and search endpoints answer it. */',
162
+ 'export type Content = ContentItem<DeliveryTypes>',
163
+ '',
164
+ '/** Any media item, as the media endpoints answer it. */',
165
+ 'export type Media = MediaItem<DeliveryTypes>',
166
+ '',
167
+ '/** A page a picker or link holds; its properties are there only when expanded. */',
168
+ `export type ContentReference = ${
169
+ pages.length === 0
170
+ ? 'ApiContentReference'
171
+ : pages
172
+ .map((t) => `ApiContentReference<${JSON.stringify(t.alias)}, ${name(t)}>`)
173
+ .join(' | ')
174
+ }`,
175
+ '',
176
+ '/** Media a picker holds; its own properties are there only when expanded. */',
177
+ `export type MediaReference = ${media
178
+ .map((t) => `ApiMediaReference<${JSON.stringify(t.alias)}, ${mediaName(t.alias)}>`)
179
+ .join(' | ')}`,
180
+ '',
181
+ '/** Media picked with the media picker, with its crops. */',
182
+ `export type MediaWithCrops = ${media
183
+ .map((t) => `ApiMediaWithCrops<${JSON.stringify(t.alias)}, ${mediaName(t.alias)}>`)
184
+ .join(' | ')}`,
185
+ '',
186
+ '/** Any element, as a block or an element picker holds it. */',
187
+ `export type Element = ${
188
+ elements.length === 0
189
+ ? 'ApiElement'
190
+ : elements.map((t) => `ApiElement<${JSON.stringify(t.alias)}, ${name(t)}>`).join(' | ')
191
+ }`,
192
+ '',
193
+ ]
194
+ for (const type of [...pages, ...elements]) {
195
+ out.push(`/** ${type.name}${type.description ? ` — ${type.description}` : ''} */`)
196
+ out.push(`export interface ${name(type)} {`, ...body(effectiveProperties(set, type)), '}', '')
197
+ }
198
+ for (const type of media) {
199
+ out.push(`/** ${type.name} (media) */`)
200
+ out.push(
201
+ `export interface ${mediaName(type.alias)} {`,
202
+ ...body(type.properties, (alias) => alias.toLowerCase().startsWith('umbraco')),
203
+ '}',
204
+ '',
205
+ )
206
+ }
207
+
208
+ const text = out.join('\n')
209
+ const shapes = [
210
+ 'ApiBlockGrid',
211
+ 'ApiBlockList',
212
+ 'ApiColor',
213
+ 'ApiContentReference',
214
+ 'ApiElement',
215
+ 'ApiImageCropper',
216
+ 'ApiLink',
217
+ 'ApiMediaReference',
218
+ 'ApiMediaWithCrops',
219
+ 'ApiRichText',
220
+ 'ContentItem',
221
+ 'MediaItem',
222
+ ].filter((shape) => new RegExp(`\\b${shape}\\b`).test(text))
223
+ out[2] = `import type { ${shapes.join(', ')} } from '${DELIVERY_CLIENT_MODULE}'\n`
224
+ return `${out.join('\n').trimEnd()}\n`
225
+ }
226
+
227
+ /** The site's media types, and the built-in ones it has no file for. */
228
+ function mediaTypes(set: SchemaSet): Array<{
229
+ alias: string
230
+ name: string
231
+ properties: ReturnType<typeof effectiveProperties>
232
+ }> {
233
+ const own = (set.mediaTypes ?? []).map((t) => ({
234
+ alias: t.alias,
235
+ name: t.name,
236
+ properties: effectiveProperties(set, t),
237
+ }))
238
+ const builtIn = BUILT_IN_MEDIA_TYPES.filter(
239
+ (b) => !b.composition && !own.some((t) => t.alias === b.alias),
240
+ ).map((b) => ({ alias: b.alias, name: b.name, properties: [] }))
241
+ return [...own, ...builtIn].sort(byAlias)
242
+ }
package/src/generate.ts CHANGED
@@ -3,11 +3,16 @@
3
3
  * view can name a property and have the compiler check it. Umbraco's
4
4
  * ModelsBuilder, minus the DLL.
5
5
  */
6
- import { SYSTEM_CONTENT_TYPES } from '@crombolo/data'
7
- import { BUILTIN_DATA_TYPES, builtInContentTypeSchema, storageTypeFor } from './builtin.ts'
6
+ import { BUILT_IN_MEDIA_TYPES, SYSTEM_CONTENT_TYPES } from '@crombolo/data'
7
+ import {
8
+ BUILTIN_DATA_TYPES,
9
+ builtInContentTypeSchema,
10
+ builtInMediaTypeSchema,
11
+ storageTypeFor,
12
+ } from './builtin.ts'
8
13
  import { allProperties, type SchemaContentType, type SchemaSet } from './model.ts'
9
14
 
10
- function pascal(alias: string): string {
15
+ export function pascal(alias: string): string {
11
16
  const cleaned = alias.replace(/[^A-Za-z0-9]+(.)?/g, (_, next: string | undefined) =>
12
17
  next ? next.toUpperCase() : '',
13
18
  )
@@ -15,7 +20,7 @@ function pascal(alias: string): string {
15
20
  }
16
21
 
17
22
  /** The element types a block data type allows, by alias, for its content and its settings. */
18
- function blockElements(set: SchemaSet, config: Record<string, unknown>) {
23
+ export function blockElements(set: SchemaSet, config: Record<string, unknown>) {
19
24
  const blocks = Array.isArray(config.blocks)
20
25
  ? (config.blocks as Array<Record<string, unknown>>)
21
26
  : []
@@ -33,12 +38,22 @@ const elementUnion = (aliases: string[]) =>
33
38
  ? 'PublishedElement'
34
39
  : aliases.map((a) => `TypedElement<${pascal(a)}>`).join(' | ')
35
40
 
41
+ /** A data type's editor and configuration, the site's own or a built-in one. */
42
+ export function dataTypeOf(
43
+ set: SchemaSet,
44
+ dataTypeAlias: string,
45
+ ): { editor: string | undefined; config: Record<string, unknown> } {
46
+ const custom = set.dataTypes.find((d) => d.alias === dataTypeAlias)
47
+ const builtIn = BUILTIN_DATA_TYPES.find((b) => b.alias === dataTypeAlias)
48
+ return {
49
+ editor: custom?.editor ?? builtIn?.editor,
50
+ config: (custom?.config ?? builtIn?.config ?? {}) as Record<string, unknown>,
51
+ }
52
+ }
53
+
36
54
  /** What a template receives for a property of this data type (see `@crombolo/render` values). */
37
55
  function tsTypeFor(set: SchemaSet, dataTypeAlias: string): string {
38
- const custom = set.dataTypes.find((d) => d.alias === dataTypeAlias)
39
- const editor = custom?.editor ?? BUILTIN_DATA_TYPES.find((b) => b.alias === dataTypeAlias)?.editor
40
- const config =
41
- custom?.config ?? BUILTIN_DATA_TYPES.find((b) => b.alias === dataTypeAlias)?.config ?? {}
56
+ const { editor, config } = dataTypeOf(set, dataTypeAlias)
42
57
  if (!editor) return 'unknown'
43
58
  switch (editor) {
44
59
  case 'Umbraco.TrueFalse':
@@ -96,16 +111,23 @@ function tsTypeFor(set: SchemaSet, dataTypeAlias: string): string {
96
111
  }
97
112
 
98
113
  /** Every property a type carries, including those from its compositions. */
99
- function effectiveProperties(set: SchemaSet, type: SchemaContentType, seen = new Set<string>()) {
114
+ export function effectiveProperties(
115
+ set: SchemaSet,
116
+ type: SchemaContentType,
117
+ seen = new Set<string>(),
118
+ ) {
100
119
  if (seen.has(type.alias)) return []
101
120
  seen.add(type.alias)
102
121
  const out = [...allProperties(type)]
103
122
  for (const alias of type.compositions) {
104
123
  // A built-in type such as `seoFields` has no file until a site extends it.
105
124
  const shipped = SYSTEM_CONTENT_TYPES.find((t) => t.alias === alias)
125
+ const shippedMedia = BUILT_IN_MEDIA_TYPES.find((t) => t.alias === alias)
106
126
  const composed =
107
127
  set.contentTypes.find((t) => t.alias === alias) ??
108
- (shipped ? builtInContentTypeSchema(shipped) : undefined)
128
+ set.mediaTypes?.find((t) => t.alias === alias) ??
129
+ (shipped ? builtInContentTypeSchema(shipped) : undefined) ??
130
+ (shippedMedia ? builtInMediaTypeSchema(shippedMedia) : undefined)
109
131
  if (composed) out.push(...effectiveProperties(set, composed, seen))
110
132
  }
111
133
  return out
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@ export * from './check.ts'
3
3
  export * from './export.ts'
4
4
  export * from './forms.ts'
5
5
  export * from './generate.ts'
6
+ export * from './generate-delivery.ts'
6
7
  export * from './load.ts'
7
8
  export * from './model.ts'
8
9
  export * from './parse.ts'