npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@deconz-community/ddf-validator

v2.31.1

Published

Validating DDF files for deconz

Downloads

239

Readme

DDF validator

The complete solution for validating DDF File.

Installation

npm install @deconz-community/ddf-validator

Quick Start

You can validate all DDF in a specefic directory using the example below. The validate method will return the validated data or will throw a Zod Error. You can use the package zod-validation-error to format the error for the user.

Example :

import { readFile } from 'node:fs/promises'
import glob from 'fast-glob'
import { fromZodError } from 'zod-validation-error'
import { createValidator } from '@deconz-community/ddf-validator'

(async () => {
  const validator = createValidator()

  const genericFiles = await glob('test-data/generic/**/*.json')
  const ddfFiles = await glob('test-data/**/*.json', {
    ignore: '**/generic/**',
  })

  const genericFilesData = await Promise.all(genericFiles.map(
    async (filePath) => {
      const data = await readFile(filePath, 'utf-8')
      const decoded = JSON.parse(data)
      return { path: filePath, data: decoded }
    },
  ))

  // Sort to load consts first
  genericFilesData.sort((a, b) => a.data.schema.localeCompare(b.data.schema))

  genericFilesData.forEach((file) => {
    try {
      const result = validator.loadGeneric(file.data)
      console.log(`Loaded generic file${file.path}`)
    }
    catch (error) {
      console.error(`Error while loading file ${file.path} : ${fromZodError(error).message}`)
    }
  })

  ddfFiles.forEach((filePath) => {
    const data = await readFile(filePath, 'utf-8')
    const decoded = JSON.parse(data)
    try {
      const result = validator.validate(decoded)
      console.log(`Validated file ${file.path}`)
    }
    catch (error) {
      console.error(`Error while validating file ${file.path} : ${fromZodError(error).message}`)
    }
  })
})()

API

createValidator()

Main function to validate the DDF data object.

Arguments

  • generics - : GenericsData; Base generic data to validate DDF.

Return

Return a new validator instance.

Example

import { createValidator } from '@deconz-community/ddf-validator'

const validator = createValidator({
  attributes: ['attr/id']
  manufacturers: { "$MF_FOO": "Foo inc." }
  deviceTypes: { "$TYPE_COLOR_LIGHT": "Color light" }
})

validator.generics

Currently loaded generics.

Return

  • generics - : GenericsData; Generic data to validate DDF.

validator.loadGeneric()

Load generic data from an object. Support files with schema constants1.schema.json, constants2.schema.json, resourceitem1.schema.json and subdevice1.schema.json.

Arguments

  • data - : object; File data.

Return

  • data - : object; File data.

Or throw Zod Error

Example

import { createValidator } from '@deconz-community/ddf-validator'

const validator = createValidator()
validator.loadGeneric({
  "schema": "constants1.schema.json",
  "manufacturers" : {
    "$MF_FOO": "Foo inc."
  },
  "device-types": {
    "$TYPE_COLOR_LIGHT": "Color light"
  }
})

validator.validate()

Validate DDF data from an object. Support files with schema constants1.schema.json, constants2.schema.json, resourceitem1.schema.json, subdevice1.schema.json and devcap1.schema.json. Make sure to load any need generic first.

Arguments

  • data - : object; File data.

Return

  • data - : object; File data.

Or throw Zod Error

Example

import { createValidator } from '@deconz-community/ddf-validator'

const validator = createValidator()
validator.validate({
  "schema": "constants1.schema.json",
  "manufacturers" : {
    "$MF_FOO": "Foo inc."
  },
  "device-types": {
    "$TYPE_COLOR_LIGHT": "Color light"
  }
})

validator.bulkValidate()

Validate both generic and DDF data from two arrays

Arguments

  • genericFiles - : FileDefinition[]; Generic files data.
  • ddfFiles - : FileDefinition[]; DDF files data.
  • callbacks - : object; Options.
    • onSectionStart - : function; Called when a section start.
    • onSectionProgress - : function; Called when a section progress.
    • onSectionEnd - : function; Called when a section end.

Return

  • errors - : FileDefinitionWithError[]; File definition with errors.

Example

validator.bulkValidate(genericFiles, ddfFiles, {
  onSectionStart: (type, total) => {
    spinner.start(chalk.blue(`Parsing ${typeFilesText(type, total)} 1 of ${total}`))
  },
  onSectionProgress: (type, current, total) => {
    spinner.text = chalk.blue(`Parsing ${typeFilesText(type, total)} ${current} of ${total}`)
    spinner.render()
  },
  onSectionEnd(type, total, errorFiles) {
    if (errorFiles.length === 0)
      return spinner.succeed(chalk.green(`No errors found in ${files.length} ${typeFilesText(type, total)}`))

    spinner.fail(chalk.red(`Found ${errorFiles.length} ${plural('error', 'errors', errorFiles.length)} in ${files.length} ${typeFilesText(type, total)}`))

    errorFiles.forEach(({ path, error }) => {
      let message = ''
      try {
        message = fromZodError(error, {
          issueSeparator: '\n    ',
          prefix: null,
        }).message
      }
      catch (e) {
        message = error.toString()
      }
      console.log(`  ${chalk.cyan('File:')}`, path)
      console.log(`    ${chalk.red(message)}`)
    })
  },
})

validator.getSchema()

Return Zod schema with loaded generic data.

Return

  • schema - : ZodType; Zod Schema.

Example

import { createValidator } from '@deconz-community/ddf-validator'
import { zodToJsonSchema } from 'zod-to-json-schema'

const validator = createValidator()
const schemaJson = zodToJsonSchema(validator.getSchema(), 'DDF')

Type definition

DDF

The type definition of a valid DDF file. Contain union type for constants1.schema.json, resourceitem1.schema.json, subdevice1.schema.json and devcap1.schema.json.

Example

import type { DDF } from '@deconz-community/ddf-validator'

const data = {} as DDF