Skip to content

Commit

Permalink
fix: fix AJV runtime validation code ESM compatibility (#261)
Browse files Browse the repository at this point in the history
This is a different approach to the fix in #256 because that was not playing nicely with Rollup bundler.
  • Loading branch information
gmaclennan authored Sep 16, 2024
1 parent 74a3d0d commit cc8722f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
7 changes: 4 additions & 3 deletions scripts/lib/generate-validations.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import Ajv from 'ajv'
import standaloneCode from 'ajv/dist/standalone/index.js'

const ucs2lengthCode = 'require("ajv/dist/runtime/ucs2length").default'

/**
* Returns generated code for validation functions
*
Expand Down Expand Up @@ -31,8 +33,7 @@ export function generateValidations(config, jsonSchemas) {
// AJV has [a bug when generating ESM code][0]: it includes `require` in the
// output. We should be able to remove this once the bug is fixed.
// [0]: https://github.com/ajv-validator/ajv/issues/2209
"import { createRequire } from 'node:module';",
'const require = createRequire(import.meta.url);',
standaloneCode(ajv, schemaExports),
"import ucs2length from './lib/ucs2length.js';",
standaloneCode(ajv, schemaExports).replace(ucs2lengthCode, 'ucs2length'),
].join('\n')
}
16 changes: 16 additions & 0 deletions src/lib/ucs2length.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export default function ucs2length(str: string): number {
const len = str.length
let length = 0
let pos = 0
let value
while (pos < len) {
length++
value = str.charCodeAt(pos++)
if (value >= 0xd800 && value <= 0xdbff && pos < len) {
// high surrogate, and there is a next character
value = str.charCodeAt(pos)
if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate
}
}
return length
}

0 comments on commit cc8722f

Please sign in to comment.