~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
50 lines · 2.2 KB Raw History
// The pages' components' layers, atomic design's: atoms, molecules built of
// atoms, organisms of those, and templates laying organisms out
// (web/AGENTS.md). A component uses its own layer and those below it,
// never one above, so each layer can be understood, and changed, knowing
// only what is under it. Nothing in web/src/lib uses a view: views, in
// web/src/views, fill templates with the page's data.
//
//   node harness/layers.mjs
//
// Prints each import that reaches up as `file:line: what`, failing if any.

import { existsSync, readdirSync, readFileSync } from 'node:fs'
import { dirname, join, relative, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const src = join(root, 'web/src')
const lib = join(src, 'lib')
const layers = ['atoms', 'molecules', 'organisms', 'templates']

const files = (d) =>
  existsSync(d)
    ? readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? files(join(d, e.name)) : [join(d, e.name)]))
    : []

/// What `path`, imported from `file`, names, as a path under web/src, or null for a package.
const target = (file, path) =>
  path.startsWith('#lib/') ? join(lib, path.slice('#lib/'.length)) : path.startsWith('.') ? resolve(dirname(file), path) : null

const problems = []
for (const file of files(lib)) {
  const rank = layers.indexOf(relative(lib, file).split('/')[0])
  readFileSync(file, 'utf8')
    .split('\n')
    .forEach((line, i) => {
      for (const [, path] of line.matchAll(/(?:from|import)\s+['"]([^'"]+)['"]/g)) {
        const t = target(file, path)
        if (!t) continue
        const where = relative(src, t)
        if (where.startsWith('views')) problems.push(`${relative(root, file)}:${i + 1}: web/src/lib uses no view`)
        const used = layers.indexOf(relative(lib, t).split('/')[0])
        if (rank !== -1 && used > rank)
          problems.push(`${relative(root, file)}:${i + 1}: ${layers[rank]} use only ${layers.slice(0, rank + 1).join(', ')}, not ${layers[used]}`)
      }
    })
}

for (const p of problems) console.log(p)
if (problems.length) process.exit(1)
console.log(`web: ${layers.join(' < ')}, each using only its own layer and those below, and none a view`)