@uniweb/build 1.20.10 → 1.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/src/schema.js CHANGED
@@ -23,6 +23,7 @@ import { normalizeData, schemaDeclarationOf } from '@uniweb/schemas/foundation'
23
23
  import { rootListSection } from '@uniweb/schemas/conform'
24
24
  import { SECTION_PARAMS, SECTION_KEYS, stickyDeclaration, underHeaderDeclaration, heightDeclaration } from '@uniweb/schemas/section'
25
25
  import { collectSchemaRefs, buildDataSchemaMap, ownSchemaRefs } from './resolve-data-schema.js'
26
+ import { buildMappingMap } from './foundation/mappings.js'
26
27
  import {
27
28
  composeSupports,
28
29
  deriveRecordsSupport,
@@ -88,6 +89,12 @@ async function loadMetaFile(filePath) {
88
89
  /**
89
90
  * Find and load meta file for a component directory
90
91
  * Returns null if no meta file found
92
+ *
93
+ * ⭐ A `meta.js` that does not load STOPS THE BUILD, naming the file and the error [Diego,
94
+ * 2026-11-11: "It's okay for the foundation build to fail if it has problems in any `meta.js` or
95
+ * elsewhere."]. ⛔ Until then it warned and went on as if the file were not there: a type at the
96
+ * root of `sections/` lost everything its `meta.js` declares, its name, params, presets, labels and
97
+ * data keys (so it was given no records), and a nested one vanished, under a green build.
91
98
  */
92
99
  export async function loadComponentMeta(componentDir) {
93
100
  const filePath = join(componentDir, META_FILE_NAME)
@@ -98,8 +105,7 @@ export async function loadComponentMeta(componentDir) {
98
105
  const meta = await loadMetaFile(filePath)
99
106
  return { meta, fileName: META_FILE_NAME, filePath }
100
107
  } catch (error) {
101
- console.warn(`Warning: Failed to load ${filePath}:`, error.message)
102
- return null
108
+ throw new Error(`[uniweb] ${filePath} could not be loaded: ${error.message}`, { cause: error })
103
109
  }
104
110
  }
105
111
 
@@ -231,8 +237,9 @@ export async function loadPackageJson(srcDir) {
231
237
  ...normalizeSupports(pkg.uniweb?.supports, packagePath),
232
238
  }
233
239
  } catch (error) {
234
- console.warn(`Warning: Failed to load package.json:`, error.message)
235
- return {}
240
+ // A package.json that is there and cannot be read stops the build, as a `meta.js` does
241
+ // (`loadComponentMeta`): it holds the foundation's identity, and an empty one is a quiet lie.
242
+ throw new Error(`[uniweb] ${packagePath} could not be read: ${error.message}`, { cause: error })
236
243
  }
237
244
  }
238
245
 
@@ -1219,43 +1226,73 @@ function reportSupports(srcDir, authored, derived, emitted) {
1219
1226
  }
1220
1227
 
1221
1228
  /**
1222
- * Warn of a `data:` value `register` will refuse — one the normalized form it sends cannot
1223
- * write (`@uniweb/schemas/foundation`): an inline field map that is not a valid data schema.
1224
- * The build goes on; the site renders the map as before. `register` is where it stops, since
1225
- * a registered schema is written in one spelling per meaning or not at all.
1229
+ * Stop the build on a `data:` value `register` will refuse — one the normalized form it sends
1230
+ * cannot write (`@uniweb/schemas/foundation`): an inline field map that is not a valid data schema.
1231
+ * Every such value is named at once. ⛔ Until 2026-11-11 the build warned and went on, since the
1232
+ * site renders the map as before, and `register` was where it stopped; a foundation build now fails
1233
+ * on a problem in its declarations [Diego, 2026-11-11], as it already did for the other `data:`
1234
+ * declarations it cannot read.
1226
1235
  *
1227
1236
  * @param {Object} components - discovered section types, by name
1228
1237
  * @param {Object} [layouts] - discovered layouts, by name
1229
1238
  * @param {Object} [foundationConfig] - the foundation's `main.js`, whose `data:` reaches every section
1230
1239
  */
1231
- export function reportUnregistrableData(components, layouts = {}, foundationConfig = {}) {
1240
+ export function reportUnregistrableData(components, layouts = {}, foundationConfig = {}, { strict = true } = {}) {
1232
1241
  const owners = [
1233
1242
  ...Object.entries(components).map(([name, entry]) => [`${name} (meta.js)`, entry?.data]),
1234
1243
  ...Object.entries(layouts || {}).map(([name, entry]) => [`layout ${name} (meta.js)`, entry?.data]),
1235
1244
  ['the foundation (main.js)', foundationConfig?.data],
1236
1245
  ]
1246
+ const problems = []
1237
1247
  for (const [owner, data] of owners) {
1238
1248
  try {
1239
1249
  normalizeData(data, { owner })
1240
1250
  } catch (err) {
1241
- console.warn(`Warning: ${err.message} \`uniweb register\` refuses it until it is one.`)
1251
+ problems.push(`${err.message} \`uniweb register\` refuses it too.`)
1242
1252
  }
1243
1253
  }
1254
+ stopOrWarn(problems, strict)
1244
1255
  }
1245
1256
 
1246
1257
  /**
1247
- * Warn about `content` and `children` declarations an editor cannot use — what lowering
1248
- * them could not read (`@uniweb/schemas`, the grammar the editor reads them with). The
1249
- * entry is emitted lowered either way; these are warnings, never refusals.
1258
+ * One error naming every declaration problem the build found, so a developer fixes them in one
1259
+ * pass rather than one build at a time.
1260
+ *
1261
+ * @param {string[]} problems - each a sentence that names its owner (`Hero (meta.js): …`)
1262
+ */
1263
+ function declarationsError(problems) {
1264
+ return [`[uniweb] The foundation declares what its build cannot use:`, ...problems.map((p) => ` - ${p}`)].join('\n')
1265
+ }
1266
+
1267
+ /**
1268
+ * The foundation's build stops on them; a site reading its foundation warns of each and goes on
1269
+ * (`buildSchema`'s `strict`).
1270
+ *
1271
+ * @param {string[]} problems
1272
+ * @param {boolean} strict
1273
+ */
1274
+ function stopOrWarn(problems, strict) {
1275
+ if (!problems.length) return
1276
+ if (strict) throw new Error(declarationsError(problems))
1277
+ for (const problem of problems) console.warn(`Warning: ${problem} The foundation's build stops on it.`)
1278
+ }
1279
+
1280
+ /**
1281
+ * Stop the build on `content`, `children` and `params` declarations a section type cannot use:
1282
+ * what lowering them could not read (`@uniweb/schemas`, the grammar the editor reads them with),
1283
+ * and a param the component is never given. Every one is named at once [Diego, 2026-11-11: "It's
1284
+ * okay for the foundation build to fail if it has problems in any `meta.js` or elsewhere."]. ⛔ Until
1285
+ * then these were warnings under a green build, and a foundation registered with them.
1250
1286
  *
1251
1287
  * ⭐ A `children.types` entry must name one of this foundation's section types. A hidden
1252
1288
  * one is not a section type at all, and a child of a type nothing provides renders
1253
- * "Component not found". The one false alarm is a type an extension provides, which
1254
- * this foundation cannot see — the message says so.
1289
+ * "Component not found". It stays a WARNING, since it has one false alarm: a type an extension
1290
+ * provides, which this foundation cannot see — the message says so.
1255
1291
  *
1256
1292
  * @param {Object} components - discovered section types, by name
1257
1293
  */
1258
- export function reportPlacementDeclarations(components) {
1294
+ export function reportPlacementDeclarations(components, { strict = true } = {}) {
1295
+ const errors = []
1259
1296
  for (const [name, entry] of Object.entries(components)) {
1260
1297
  // An entry built here was lowered, and kept what it could not read aside; one handed
1261
1298
  // in as written is read now. (A lowered entry reads as itself, with no problems.)
@@ -1266,7 +1303,7 @@ export function reportPlacementDeclarations(components) {
1266
1303
  ...children.problems,
1267
1304
  ]
1268
1305
  for (const problem of problems) {
1269
- console.warn(`Warning: ${name} (meta.js): ${problem}`)
1306
+ errors.push(`${name} (meta.js): ${problem}`)
1270
1307
  }
1271
1308
  for (const type of children.types || []) {
1272
1309
  if (components[type]) continue
@@ -1284,8 +1321,8 @@ export function reportPlacementDeclarations(components) {
1284
1321
  const params = entry.params && typeof entry.params === 'object' ? entry.params : {}
1285
1322
  for (const [param, reserved] of Object.entries(SECTION_PARAMS)) {
1286
1323
  if (reserved.component || !Object.hasOwn(params, param)) continue
1287
- console.warn(
1288
- `Warning: ${name} (meta.js): params declares "${param}", a setting of the section, not of its ` +
1324
+ errors.push(
1325
+ `${name} (meta.js): params declares "${param}", a setting of the section, not of its ` +
1289
1326
  `component — framework applies an author's ${param}: to the section and never passes it to the ` +
1290
1327
  `component, and an editor offers it for every section (@uniweb/schemas/section). Remove it from params:.` +
1291
1328
  (param === 'grid'
@@ -1297,12 +1334,13 @@ export function reportPlacementDeclarations(components) {
1297
1334
  // takes it out before the params are stored, so a param of that name is never given one.
1298
1335
  for (const [key, { is }] of Object.entries(SECTION_KEYS)) {
1299
1336
  if (!Object.hasOwn(params, key)) continue
1300
- console.warn(
1301
- `Warning: ${name} (meta.js): params declares "${key}", a key a section's frontmatter keeps for ` +
1337
+ errors.push(
1338
+ `${name} (meta.js): params declares "${key}", a key a section's frontmatter keeps for ` +
1302
1339
  `itself — ${is} — so the component is never given it (@uniweb/schemas/section). Remove it from params:.`
1303
1340
  )
1304
1341
  }
1305
1342
  }
1343
+ stopOrWarn(errors, strict)
1306
1344
  }
1307
1345
 
1308
1346
  /**
@@ -1318,8 +1356,14 @@ export function reportPlacementDeclarations(components) {
1318
1356
  * @param {{services: string[], blind: boolean}} [derivedSupports] - what the
1319
1357
  * module graph says this foundation reaches for (`foundation/derive-supports.js`).
1320
1358
  * Omitted on a dev rebuild, where nothing reads the result.
1359
+ * @param {Object} [options]
1360
+ * @param {boolean} [options.strict=true] - stop on a declaration the build cannot use (the
1361
+ * foundation's own build, `register`). ⭐ A SITE reading its foundation's declarations passes
1362
+ * false (`foundationSections`, `validate`): it warns as it always did and keeps reading, since
1363
+ * the foundation's build is what stops, and a site step that threw would lose every
1364
+ * declaration in silence (it falls back to a schema.json, or to none).
1321
1365
  */
1322
- export async function buildSchema(srcDir, sectionPaths, derivedSupports = null) {
1366
+ export async function buildSchema(srcDir, sectionPaths, derivedSupports = null, { strict = true } = {}) {
1323
1367
  // Load identity from package.json
1324
1368
  const identity = await loadPackageJson(srcDir)
1325
1369
 
@@ -1330,7 +1374,7 @@ export async function buildSchema(srcDir, sectionPaths, derivedSupports = null)
1330
1374
 
1331
1375
  // Discover section types
1332
1376
  const components = await discoverComponents(srcDir, sectionPaths)
1333
- reportPlacementDeclarations(components)
1377
+ reportPlacementDeclarations(components, { strict })
1334
1378
 
1335
1379
  // Resolve the data schemas the foundation DEFINES — every file in its `schemas/`
1336
1380
  // folder (`ownSchemaRefs`) — and the ones its section bindings reference, carried
@@ -1342,6 +1386,10 @@ export async function buildSchema(srcDir, sectionPaths, derivedSupports = null)
1342
1386
  { srcDir },
1343
1387
  )
1344
1388
 
1389
+ // The mappings it defines — every file in its `mappings/` folder (`foundation/mappings.js`),
1390
+ // registered beside its data schemas. Editor-time: `_mappings`, never on a page.
1391
+ const mappings = await buildMappingMap(srcDir, { ownTypes: ownSchemaRefs(srcDir) })
1392
+
1345
1393
  // Discover layouts from src/layouts/
1346
1394
  const layouts = await discoverLayoutsInPath(srcDir)
1347
1395
  // The layout a page that names none renders with — the entry gets the same answer
@@ -1356,7 +1404,7 @@ export async function buildSchema(srcDir, sectionPaths, derivedSupports = null)
1356
1404
  dataSchemas,
1357
1405
  srcDir,
1358
1406
  )
1359
- reportUnregistrableData(components, layouts, foundationConfig)
1407
+ reportUnregistrableData(components, layouts, foundationConfig, { strict })
1360
1408
 
1361
1409
  // Determine extension role
1362
1410
  const isExtension = !!foundationConfig.extension
@@ -1423,6 +1471,7 @@ export async function buildSchema(srcDir, sectionPaths, derivedSupports = null)
1423
1471
  },
1424
1472
  // Layout metadata (full, for editor)
1425
1473
  ...(Object.keys(dataSchemas).length > 0 && { dataSchemas }),
1474
+ ...(Object.keys(mappings).length > 0 && { _mappings: mappings }),
1426
1475
  ...(Object.keys(layouts).length > 0 && { _layouts: layouts }),
1427
1476
  ...components,
1428
1477
  }
@@ -334,7 +334,10 @@ export async function defineSiteConfig(options = {}) {
334
334
  await generateEntryPoint(srcDir, entryPath)
335
335
  server.ws.send({ type: 'full-reload' })
336
336
  } catch (err) {
337
+ // The last good entry stays, and the page shows why it did not move: a `meta.js` that
338
+ // does not load, or a declaration the build cannot use, stops the build (schema.js).
337
339
  console.warn('[site] Failed to regenerate foundation entry:', err.message)
340
+ server.ws.send({ type: 'error', err: { message: err.message, stack: '' } })
338
341
  }
339
342
  }
340
343
  })
@@ -53,6 +53,7 @@ import { refuseUnreadableAddress } from './site-address.js'
53
53
  import { warnOutsideVocabulary } from './vocabulary-warnings.js'
54
54
  import { warnPlacementsNotOffered } from './placement-warnings.js'
55
55
  import { atomicPageConfig, isAtomicPageKey, warnPageKeysNamingParams } from './page-settings.js'
56
+ import { noteParamsNamedForContent } from './params-named-for-content.js'
56
57
  import { markdownToProseMirror } from '@uniweb/content-reader'
57
58
 
58
59
  /**
@@ -1307,8 +1308,12 @@ async function processMarkdownFile(filePath, id, siteRoot, defaultStableId = nul
1307
1308
  const warnHere = (message) => console.warn(`[content-collector] ${relative(siteRoot, filePath)}: ${message}`)
1308
1309
  const proseMirrorContent = markdownToProseMirror(markdown, { onWarning: warnHere })
1309
1310
  warnOutsideVocabulary(proseMirrorContent, warnHere)
1310
- warnPlacementsNotOffered(proseMirrorContent, type || null, sectionTypes, warnHere)
1311
- if (pageConfig) warnPageKeysNamingParams(pageConfig, type || null, sectionTypes, warnHere)
1311
+ // ⭐ The foundation's section types only for a file of the site being collected: the push reads its
1312
+ // files through this function too, after a collect of another site may have left that one's here.
1313
+ const typesHere = collectRoot === siteRoot ? sectionTypes : null
1314
+ warnPlacementsNotOffered(proseMirrorContent, type || null, typesHere, warnHere)
1315
+ if (pageConfig) warnPageKeysNamingParams(pageConfig, type || null, typesHere, warnHere)
1316
+ noteParamsNamedForContent({ ...params, ...props }, type || null, typesHere, { file: filePath, warn: warnHere })
1312
1317
 
1313
1318
  // `query: team` → `fetch: { query: team }`; a list, one config per name, each under
1314
1319
  // its own `as` — the one helper every level uses. Unrelated to a section type's
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Say, with the file in hand, each param a section's frontmatter names like a field of its content —
3
+ * `title:`, `items:` — when its section type declares no param of that name.
4
+ *
5
+ * ⭐ A section's frontmatter reaches its component as `params`, and its body as `content`, and
6
+ * neither is copied into the other (`@uniweb/runtime`, `BlockRenderer.jsx`). So a `title:` in the
7
+ * frontmatter never titles the section: the title is the body's heading. ⛔ Until 2026-11-11 the
8
+ * runtime spread every param over `content` too, so a `title:` there replaced the heading, and a
9
+ * site written for that loses its title without a word — this is the word.
10
+ *
11
+ * A param its type declares is one its component reads, and is not said: the name is the
12
+ * developer's to choose. A type this foundation doesn't have, or a foundation not at hand, says
13
+ * nothing either. A note, never a failure, since the page renders. Said once per file and key in a
14
+ * process: `uniweb dev` collects the site again on every edit, and a push builds its document more
15
+ * than once.
16
+ */
17
+
18
+ /**
19
+ * The fields of a section's content its body gives: what the content parser returns
20
+ * (`@uniweb/semantic-parser`), less `raw`, which no author writes, and `data`, which a frontmatter
21
+ * refuses (`SECTION_KEYS`, `@uniweb/schemas/section`). `math` and `tables` arrive only when the body
22
+ * has one. `tests/params-named-for-content.test.js` holds it to the parser.
23
+ */
24
+ export const BODY_FIELDS = Object.freeze([
25
+ 'title', 'pretitle', 'subtitle', 'paragraphs', 'links', 'images', 'icons', 'videos', 'documents',
26
+ 'insets', 'media', 'lists', 'quotes', 'snippets', 'headings', 'items', 'sequence', 'math', 'tables',
27
+ ])
28
+
29
+ const FIELDS = new Set(BODY_FIELDS)
30
+
31
+ /** How the body gives each field of the headline, for the note to say. */
32
+ const HEADLINE = {
33
+ title: (v) => `its heading: write \`# ${v}\` at the top of the body`,
34
+ subtitle: (v) => `a heading straight after the title, one level smaller: \`## ${v}\``,
35
+ pretitle: (v) => `the label line above the title: \`#> ${v}\``,
36
+ }
37
+
38
+ const said = new Set()
39
+
40
+ /**
41
+ * The params a section's frontmatter names like a field of its content that its section type
42
+ * declares no param of, or `[]` when the type, or the foundation, is not at hand.
43
+ *
44
+ * @param {object} params - the section's params, as stored
45
+ * @param {string|null} type - the section's `type:`; with none, the foundation's `defaultSection`
46
+ * @param {Object|null} sectionTypes - the foundation's schema, each section type's entry by name
47
+ * @returns {{ key: string, type: string }[]}
48
+ */
49
+ export function paramsNamedForContent(params, type, sectionTypes) {
50
+ if (!params || typeof params !== 'object') return []
51
+ const name = type || sectionTypes?._self?.defaultSection || null
52
+ const entry = name && !name.startsWith('_') ? sectionTypes?.[name] : null
53
+ if (!entry || typeof entry !== 'object') return []
54
+ const declared = entry.params && typeof entry.params === 'object' ? entry.params : {}
55
+ return Object.keys(params)
56
+ .filter((key) => FIELDS.has(key) && !Object.prototype.hasOwnProperty.call(declared, key))
57
+ .map((key) => ({ key, type: name }))
58
+ }
59
+
60
+ /**
61
+ * Say each of `paramsNamedForContent`, once per file and key in this process.
62
+ *
63
+ * @param {object} params - the section's params, as stored
64
+ * @param {string|null} type - the section's `type:`
65
+ * @param {Object|null} sectionTypes - the foundation's schema, each section type's entry by name
66
+ * @param {{ file: string, warn: (message: string) => void }} where - the section's file, and how to
67
+ * print one message, prefixed with it
68
+ */
69
+ export function noteParamsNamedForContent(params, type, sectionTypes, { file, warn }) {
70
+ for (const { key, type: name } of paramsNamedForContent(params, type, sectionTypes)) {
71
+ const once = `${file}\u0000${key}`
72
+ if (said.has(once)) continue
73
+ said.add(once)
74
+ const value = params[key]
75
+ const shown = typeof value === 'string' && value.trim() && !value.includes('\n') ? value.trim() : '…'
76
+ const how = HEADLINE[key]
77
+ warn(
78
+ `\`${key}:\` is a param, and ${name} declares no \`${key}\` param, so it doesn't set the section's ` +
79
+ (how ? `${key} (\`content.${key}\`), which is ${how(shown)}.` : `\`content.${key}\`, which comes from the body.`)
80
+ )
81
+ }
82
+ }
@@ -245,6 +245,16 @@ import { refuseSearchOption } from './search-declared.js'
245
245
  import { mountDevApi } from '../dev/api-mount.js'
246
246
  import { mountDevSubmit } from '../dev/submit-mount.js'
247
247
 
248
+ /**
249
+ * The pre-paint appearance script for a shell, the runtime's own (`@uniweb/runtime/ssr`, which a
250
+ * prerendered page's seam writes too), or '' for a site with no dark scheme. Loaded once.
251
+ */
252
+ let bootScriptOf = null
253
+ async function appearanceBootScript(appearance) {
254
+ bootScriptOf ||= import('@uniweb/runtime/ssr').then((runtime) => runtime.renderAppearanceBootScript)
255
+ return (await bootScriptOf)(appearance)
256
+ }
257
+
248
258
  /**
249
259
  * Create the site content plugin
250
260
  *
@@ -1155,6 +1165,14 @@ export function siteContentPlugin(options = {}) {
1155
1165
  headInjection += ` <style id="uniweb-theme">\n${contentToInject.theme.css}\n </style>\n`
1156
1166
  }
1157
1167
 
1168
+ // ⭐ THE PRE-PAINT APPEARANCE SCRIPT, so a page the browser renders itself — every page under
1169
+ // `uniweb dev`, and a build that doesn't prerender — shows the site's look before the bundle
1170
+ // boots. A prerendered page keeps this one: its render adds none where the shell has it
1171
+ // (`injectPageContent`). ⛔ Until 2026-11-11 only a prerendered page had it, so a dark site
1172
+ // under `uniweb dev` painted light for about 0.4 s on every load.
1173
+ const bootScript = await appearanceBootScript(contentToInject.theme?.appearance)
1174
+ if (bootScript) headInjection += ` ${bootScript}\n`
1175
+
1158
1176
  // ⛔ No page's head tags — canonical, Open Graph, hreflang — go into the shell, which every
1159
1177
  // page is rendered into: the prerender writes each page's own (`injectPageContent`), and the
1160
1178
  // browser keeps them (`useHeadMeta`). Until 2026-10-25 the home page's were written here.
@@ -1196,7 +1214,8 @@ export function siteContentPlugin(options = {}) {
1196
1214
  if (!headInjection) return result
1197
1215
 
1198
1216
  // Insert before </head>
1199
- return result.replace('</head>', headInjection + ' </head>')
1217
+ // A replacer function: `$$` or `$&` in the content, the theme or head.html is text, not a pattern.
1218
+ return result.replace('</head>', () => headInjection + ' </head>')
1200
1219
  },
1201
1220
 
1202
1221
  async generateBundle() {
@@ -459,7 +459,9 @@ export async function foundationSections(siteRoot, siteYml = null) {
459
459
  const srcDir = localFoundationSrcDir(siteRoot, yml)
460
460
  if (srcDir) {
461
461
  try {
462
- return await buildSchema(srcDir)
462
+ // Not strict: a declaration the foundation's build stops on is warned of here, and read
463
+ // (`buildSchema`'s `strict`).
464
+ return await buildSchema(srcDir, undefined, null, { strict: false })
463
465
  } catch {
464
466
  // a foundation whose source does not read is reported by the build that builds it
465
467
  }
@@ -23,7 +23,7 @@ import { YAML_OPTIONS } from '../utils/yaml-schema.js'
23
23
  export const BLUEPRINT_FILE = 'blueprint.yml'
24
24
 
25
25
  /** What the file holds, in the order a pull writes it. */
26
- export const BLUEPRINT_KEYS = Object.freeze(['signup', 'teams', 'access', 'publicQueries'])
26
+ export const BLUEPRINT_KEYS = Object.freeze(['signup', 'teams', 'access', 'publicQueries', 'integrations'])
27
27
 
28
28
  /** The two keys whose entries are types. */
29
29
  export const TYPE_KEYS = Object.freeze(['access', 'publicQueries'])
@@ -34,6 +34,23 @@ const ACCESS_KEYS = Object.freeze(['add', 'all'])
34
34
  const QUERY_KEYS = Object.freeze(['whole', 'where', 'sort', 'limit'])
35
35
  const TEAM_KEYS = Object.freeze(['label'])
36
36
 
37
+ /**
38
+ * An integration line, as a backend takes it. Refused here exactly as a backend refuses them, and no
39
+ * more: a line this takes, a backend takes.
40
+ */
41
+ const INTEGRATION_KEYS = Object.freeze(['label', 'mapping', 'channel', 'trigger', 'filter', 'enabled'])
42
+ const CHANNELS = Object.freeze(['file', 'feed', 'email', 'http'])
43
+ const TRIGGERS = Object.freeze(['manual', 'on_fetch', 'on_create', 'on_match'])
44
+ /** Each channel → the triggers it pairs with. */
45
+ const PAIRS = Object.freeze({
46
+ file: ['manual'],
47
+ feed: ['on_fetch'],
48
+ email: ['on_create', 'on_match', 'manual'],
49
+ http: ['on_create', 'on_match', 'manual'],
50
+ })
51
+ /** The channels a line may switch on with `enabled: true`. */
52
+ const ENABLEABLE = Object.freeze(['file', 'feed'])
53
+
37
54
  /** In `all`, every member of the home org: the one name there that is not a team. */
38
55
  const MEMBERS = 'members'
39
56
 
@@ -133,6 +150,7 @@ export function blueprintProblems(blueprint) {
133
150
  if (teams !== undefined) found.push(...teamProblems(teams))
134
151
  if (blueprint.access !== undefined) found.push(...accessProblems(blueprint.access, teamIds))
135
152
  if (blueprint.publicQueries !== undefined) found.push(...publicQueryProblems(blueprint.publicQueries))
153
+ if (blueprint.integrations !== undefined) found.push(...integrationProblems(blueprint.integrations))
136
154
  return found
137
155
  }
138
156
 
@@ -269,6 +287,79 @@ function publicQueryProblems(queries) {
269
287
  return found
270
288
  }
271
289
 
290
+ function integrationProblems(integrations) {
291
+ if (!isMap(integrations)) {
292
+ return [
293
+ `\`integrations\` is a map of integrations by id — \`integrations: { meta-catalog: { mapping: '@/vehicle-to-meta', channel: feed, trigger: on_fetch } }\` — not ${described(integrations)}.`,
294
+ ]
295
+ }
296
+ const found = []
297
+ for (const [id, line] of Object.entries(integrations)) {
298
+ const at = `integrations.${id}`
299
+ if (!TEAM_ID.test(id)) {
300
+ found.push(`\`${at}\`: an integration's id is lowercase letters, digits and dashes — its name goes in its \`label\`.`)
301
+ continue
302
+ }
303
+ if (!isMap(line)) {
304
+ found.push(`\`${at}\` is a map of ${listed(INTEGRATION_KEYS)} — not ${described(line)}.`)
305
+ continue
306
+ }
307
+ for (const key of Object.keys(line)) {
308
+ if (!INTEGRATION_KEYS.includes(key)) {
309
+ found.push(
310
+ `\`${at}.${key}\` is not one of an integration's keys, which are ${listed(INTEGRATION_KEYS)}. ` +
311
+ 'An address, a URL or a key is the owner\'s to give in the admin app, never the file\'s.'
312
+ )
313
+ }
314
+ }
315
+ if ('label' in line && (typeof line.label !== 'string' || !line.label.trim())) {
316
+ found.push(`\`${at}.label\` is the integration's name — not ${described(line.label)}.`)
317
+ }
318
+ if (!('mapping' in line)) {
319
+ found.push(`\`${at}\` names no \`mapping\`: one of the foundation's own is \`mapping: '@/<name>'\`.`)
320
+ } else {
321
+ const name = refNameProblem(`${at}.mapping`, line.mapping, 'mapping')
322
+ if (name) found.push(name)
323
+ }
324
+ const channelOk = CHANNELS.includes(line.channel)
325
+ const triggerOk = TRIGGERS.includes(line.trigger)
326
+ if (!channelOk) found.push(`\`${at}.channel\` is one of ${listed(CHANNELS)} — not ${described(line.channel)}.`)
327
+ if (!triggerOk) found.push(`\`${at}.trigger\` is one of ${listed(TRIGGERS)} — not ${described(line.trigger)}.`)
328
+ if (channelOk && triggerOk && !PAIRS[line.channel].includes(line.trigger)) {
329
+ found.push(`\`${at}\`: a \`${line.channel}\` integration's trigger is one of ${listed(PAIRS[line.channel])} — not \`${line.trigger}\`.`)
330
+ }
331
+ if ('filter' in line && !isMap(line.filter)) {
332
+ found.push(`\`${at}.filter\` is a map — \`filter: { where: { status: sold } }\` — not ${described(line.filter)}.`)
333
+ }
334
+ if ('enabled' in line) {
335
+ if (line.enabled !== true) {
336
+ found.push(
337
+ typeof line.enabled === 'string' && SWITCH_WORDS.test(line.enabled.trim())
338
+ ? `\`${at}.enabled\` is the text \`${line.enabled}\` — YAML reads yes, no, on and off as words. Write \`enabled: true\`, or leave it out.`
339
+ : `\`${at}.enabled\` is \`true\`, or left out — not ${described(line.enabled)}.`
340
+ )
341
+ } else if (channelOk && !ENABLEABLE.includes(line.channel)) {
342
+ found.push(
343
+ `\`${at}.enabled\`: a \`${line.channel}\` integration is switched on by its owner in the admin app, ` +
344
+ 'once its address is given. Leave `enabled` out.'
345
+ )
346
+ }
347
+ }
348
+ }
349
+ return found
350
+ }
351
+
352
+ /** A name that must be `@/x` or `@scope/x`, or null. */
353
+ function refNameProblem(at, ref, what) {
354
+ try {
355
+ parseSchemaRef(ref)
356
+ return null
357
+ } catch {
358
+ const bare = String(ref).replace(/^@?\/?/, '')
359
+ return `\`${at}\` names no ${what}: one of the foundation's own is \`'@/${bare}'\`, and any other is named in full, \`'@scope/${bare}'\`.`
360
+ }
361
+ }
362
+
272
363
  /** A type's name is `@/x` or `@scope/x` (`parseSchemaRef`), or null. */
273
364
  function typeNameProblem(at, type) {
274
365
  try {