From 2a2b6fc5e6ae6ee65c9b68e1a99071b54e98e825 Mon Sep 17 00:00:00 2001 From: Vladimir Gorej Date: Thu, 26 Nov 2026 10:39:50 +0100 Subject: [PATCH 01/11] fix(types): provide CommonJS declarations for all entry points The require export condition reused ES module declarations, so CommonJS consumers with node16/nodenext module resolution failed with TS1479. Declarations are now copied to .d.cts at build time, with relative .js specifiers rewritten to .cjs, and referenced via separate types under import and require conditions. Refs #269 --- .gitignore | 1 + CLAUDE.md | 2 +- package-lock.json | 376 +++++++++++++++++++++++++++++ package.json | 44 +++- scripts/build-types.cjs | 38 +++ test/artifacts/types/consumer.cts | 12 + test/artifacts/types/consumer.mts | 12 + types/evaluate/realms/json.d.ts | 2 +- types/evaluate/realms/map-set.d.ts | 2 +- 9 files changed, 473 insertions(+), 16 deletions(-) create mode 100644 scripts/build-types.cjs create mode 100644 test/artifacts/types/consumer.cts create mode 100644 test/artifacts/types/consumer.mts diff --git a/.gitignore b/.gitignore index b557097..0c60160 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ node_modules/ /es /dist /swaggerexpert-json-pointer-*.tgz +/types/**/*.d.cts diff --git a/CLAUDE.md b/CLAUDE.md index a12e5ac..2e9bcbf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -72,4 +72,4 @@ The build produces three formats: - `cjs/` - CommonJS (.cjs) - `dist/` - UMD browser bundles (json-pointer.browser.js, json-pointer.browser.min.js) -TypeScript types are in `types/index.d.ts`. +TypeScript types are in `types/`; the build generates gitignored `.d.cts` copies for the `require` export conditions. diff --git a/package-lock.json b/package-lock.json index e55b4ff..190412d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,6 +38,7 @@ "prettier": "^3.10.1", "semantic-release": "^26.0.1", "terser-webpack-plugin": "^5.6.1", + "typescript": "^7.0.2", "webpack": "^5.113.0", "webpack-cli": "^7.3.1" }, @@ -2936,6 +2937,346 @@ "dev": true, "license": "MIT" }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, "node_modules/@webassemblyjs/ast": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.14.1.tgz", @@ -12244,6 +12585,41 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, "node_modules/uglify-js": { "version": "3.19.3", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz", diff --git a/package.json b/package.json index d7cfc1f..aba8102 100644 --- a/package.json +++ b/package.json @@ -11,19 +11,34 @@ "types": "./types/index.d.ts", "exports": { ".": { - "types": "./types/index.d.ts", - "import": "./es/index.mjs", - "require": "./cjs/index.cjs" + "import": { + "types": "./types/index.d.ts", + "default": "./es/index.mjs" + }, + "require": { + "types": "./types/index.d.cts", + "default": "./cjs/index.cjs" + } }, "./evaluate/realms/json": { - "types": "./types/evaluate/realms/json.d.ts", - "import": "./es/evaluate/realms/json/index.mjs", - "require": "./cjs/evaluate/realms/json/index.cjs" + "import": { + "types": "./types/evaluate/realms/json.d.ts", + "default": "./es/evaluate/realms/json/index.mjs" + }, + "require": { + "types": "./types/evaluate/realms/json.d.cts", + "default": "./cjs/evaluate/realms/json/index.cjs" + } }, "./evaluate/realms/map-set": { - "types": "./types/evaluate/realms/map-set.d.ts", - "import": "./es/evaluate/realms/map-set/index.mjs", - "require": "./cjs/evaluate/realms/map-set/index.cjs" + "import": { + "types": "./types/evaluate/realms/map-set.d.ts", + "default": "./es/evaluate/realms/map-set/index.mjs" + }, + "require": { + "types": "./types/evaluate/realms/map-set.d.cts", + "default": "./cjs/evaluate/realms/map-set/index.cjs" + } }, "./package.json": "./package.json" }, @@ -33,12 +48,14 @@ "scripts": { "prepublishOnly": "npm run build", "grammar:compile": "node ./scripts/apg-js.js --lite --in=./src/grammar.bnf --out=./src/grammar.js && cd ./src", - "build": "npm run grammar:compile && npm run build:es && npm run build:cjs && npm run build:cjs:apg-lite && npm run build:umd:browser", + "build": "npm run grammar:compile && npm run build:es && npm run build:cjs && npm run build:cjs:apg-lite && npm run build:types && npm run build:umd:browser", "build:es": "cross-env BABEL_ENV=es babel src --out-dir es --extensions '.js' --out-file-extension '.mjs'", "build:cjs": "cross-env BABEL_ENV=cjs babel src --out-dir cjs --extensions '.js' --out-file-extension '.cjs'", "build:cjs:apg-lite": "cross-env BABEL_ENV=cjs babel node_modules/apg-lite/lib/parser.js --out-file ./cjs/apg-lite.cjs", + "build:types": "node ./scripts/build-types.cjs", "build:umd:browser": "cross-env BABEL_ENV=browser webpack --config config/webpack/browser.config.js --progress", "test": "cross-env NODE_OPTIONS='--import ./test/loader.js' mocha", + "test:types": "tsc --noEmit --strict --skipLibCheck false --module node16 --moduleResolution node16 --target es2020 test/artifacts/types/consumer.cts test/artifacts/types/consumer.mts && tsc --noEmit --strict --module esnext --moduleResolution bundler --target es2020 test/artifacts/types/consumer.mts", "test:watch": "npm-watch test", "watch": "npm-watch" }, @@ -86,14 +103,14 @@ "@babel/preset-env": "=8.0.7", "@commitlint/cli": "=21.2.4", "@commitlint/config-conventional": "=21.2.4", - "@speclynx/apidom-datamodel": "^7.1.0", - "@speclynx/apidom-core": "^7.1.0", - "@speclynx/apidom-ns-openapi-3-0": "^7.1.0", "@semantic-release/commit-analyzer": "^13.0.1", "@semantic-release/git": "^11.0.1", "@semantic-release/github": "^12.0.11", "@semantic-release/npm": "^13.2.0", "@semantic-release/release-notes-generator": "^14.1.1", + "@speclynx/apidom-core": "^7.1.0", + "@speclynx/apidom-datamodel": "^7.1.0", + "@speclynx/apidom-ns-openapi-3-0": "^7.1.0", "apg-js": "^4.4.0", "babel-loader": "^10.1.1", "babel-plugin-module-resolver": "^5.0.3", @@ -107,6 +124,7 @@ "prettier": "^3.10.1", "semantic-release": "^26.0.1", "terser-webpack-plugin": "^5.6.1", + "typescript": "^7.0.2", "webpack": "^5.113.0", "webpack-cli": "^7.3.1" } diff --git a/scripts/build-types.cjs b/scripts/build-types.cjs new file mode 100644 index 0000000..a83c9f9 --- /dev/null +++ b/scripts/build-types.cjs @@ -0,0 +1,38 @@ +/** + * The package is "type": "module", so TypeScript treats types/**\/*.d.ts as ES module declarations. + * CommonJS consumers (moduleResolution node16/nodenext) need CommonJS declarations, + * otherwise they fail with TS1479. This script generates a .d.cts copy of every .d.ts file, + * rewriting relative references of .js declarations to .cjs declarations. + */ +const fs = require('node:fs'); +const path = require('node:path'); + +const typesDir = path.join(__dirname, '..', 'types'); + +const collect = (dir, suffix) => + fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const entryPath = path.join(dir, entry.name); + if (entry.isDirectory()) return collect(entryPath, suffix); + return entry.name.endsWith(suffix) ? [entryPath] : []; + }); + +// relative specifier ending with .js in quotes, e.g. '../../index.js' +const relativeJSSpecifier = /(['"])(\.{1,2}\/[^'"]*)\.js\1/g; + +// stale declarations of removed .d.ts files must not be published +collect(typesDir, '.d.cts').forEach((file) => fs.rmSync(file)); + +collect(typesDir, '.d.ts').forEach((file) => { + const source = fs.readFileSync(file, 'utf8'); + // covers import/export ... from, import(), require(), side-effect imports and declare module + const output = source.replace(relativeJSSpecifier, '$1$2.cjs$1'); + const unresolved = output.match(/(['"])\.{1,2}\/[^'"]*\1/g)?.filter((s) => !/\.cjs['"]$/.test(s)); + + if (unresolved?.length) { + throw new Error( + `${path.relative(typesDir, file)}: relative specifiers must end with .js: ${unresolved}`, + ); + } + + fs.writeFileSync(file.replace(/\.d\.ts$/, '.d.cts'), output); +}); diff --git a/test/artifacts/types/consumer.cts b/test/artifacts/types/consumer.cts new file mode 100644 index 0000000..95f4d81 --- /dev/null +++ b/test/artifacts/types/consumer.cts @@ -0,0 +1,12 @@ +// CommonJS consumer: resolved through the "require" export conditions +import { parse, evaluate, compile, JSONPointerError } from '@swaggerexpert/json-pointer'; +import JSONEvaluationRealm = require('@swaggerexpert/json-pointer/evaluate/realms/json'); +import MapSetEvaluationRealm = require('@swaggerexpert/json-pointer/evaluate/realms/map-set'); + +const { tree } = parse('/a/b'); +const pointer: string = compile(tree ?? []); +const value = evaluate({ a: { b: 1 } }, pointer, { realm: new JSONEvaluationRealm.default() }); +const realm = new MapSetEvaluationRealm.default(); +const error: Error = new JSONPointerError('message'); + +export { value, realm, error }; diff --git a/test/artifacts/types/consumer.mts b/test/artifacts/types/consumer.mts new file mode 100644 index 0000000..abcfc50 --- /dev/null +++ b/test/artifacts/types/consumer.mts @@ -0,0 +1,12 @@ +// ES module consumer: resolved through the "import" export conditions +import { parse, evaluate, compile, JSONPointerError } from '@swaggerexpert/json-pointer'; +import JSONEvaluationRealm from '@swaggerexpert/json-pointer/evaluate/realms/json'; +import MapSetEvaluationRealm from '@swaggerexpert/json-pointer/evaluate/realms/map-set'; + +const { tree } = parse('/a/b'); +const pointer: string = compile(tree ?? []); +const value = evaluate({ a: { b: 1 } }, pointer, { realm: new JSONEvaluationRealm() }); +const realm = new MapSetEvaluationRealm(); +const error: Error = new JSONPointerError('message'); + +export { value, realm, error }; diff --git a/types/evaluate/realms/json.d.ts b/types/evaluate/realms/json.d.ts index a2da6c8..f2b4923 100644 --- a/types/evaluate/realms/json.d.ts +++ b/types/evaluate/realms/json.d.ts @@ -1,4 +1,4 @@ -import type { EvaluationRealm } from '../../index.ts'; +import type { EvaluationRealm } from '../../index.js'; export type JSONPrimitive = string | number | boolean | null; diff --git a/types/evaluate/realms/map-set.d.ts b/types/evaluate/realms/map-set.d.ts index 0fb61fc..5d09aa7 100644 --- a/types/evaluate/realms/map-set.d.ts +++ b/types/evaluate/realms/map-set.d.ts @@ -1,4 +1,4 @@ -import type { EvaluationRealm } from '../../index.ts'; +import type { EvaluationRealm } from '../../index.js'; declare class MapSetEvaluationRealm extends EvaluationRealm { public readonly name: 'map-set'; From fe3410fcf3fcd03948120c8f9cd2f3eb14806dba Mon Sep 17 00:00:00 2001 From: Vladimir Gorej Date: Thu, 26 Nov 2026 10:40:23 +0100 Subject: [PATCH 02/11] fix(types): declare Grammar as class with construct signature Grammar was declared as function without construct signature, so `new Grammar()` (as documented) failed with TS7009 under --strict. Refs #269 --- test/artifacts/types/consumer.mts | 8 ++++++++ types/index.d.ts | 5 ++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/test/artifacts/types/consumer.mts b/test/artifacts/types/consumer.mts index abcfc50..276b44f 100644 --- a/test/artifacts/types/consumer.mts +++ b/test/artifacts/types/consumer.mts @@ -10,3 +10,11 @@ const realm = new MapSetEvaluationRealm(); const error: Error = new JSONPointerError('message'); export { value, realm, error }; + +// Grammar is constructed with new, as documented +import { Grammar } from '@swaggerexpert/json-pointer'; + +const grammar: Grammar = new Grammar(); +const abnf: string = grammar.toString(); + +export { abnf }; diff --git a/types/index.d.ts b/types/index.d.ts index 31bdd88..b123f86 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -169,9 +169,8 @@ export declare const URIFragmentIdentifier: URIFragmentIdentifier; /** * Grammar */ -export function Grammar(): Grammar; - -export interface Grammar { +export declare class Grammar { + constructor(); grammarObject: string; // Internal identifier rules: Rule[]; // List of grammar rules udts: UDT[]; // User-defined terminals (empty in this grammar) From ff8a1c360b9c5ca55452a0964051a2afab7bfafe Mon Sep 17 00:00:00 2001 From: Vladimir Gorej Date: Thu, 26 Nov 2026 10:40:42 +0100 Subject: [PATCH 03/11] fix(types): return boolean from JSON Pointer and token test functions testJSONPointer and testReferenceToken used type predicates targeting aliases of string, which narrowed invalid input to never in the false branch. testArrayLocation, testArrayIndex and testArrayDash keep their predicates, as they narrow to literal types. Refs #269 --- test/artifacts/types/consumer.mts | 15 +++++++++++++++ types/index.d.ts | 4 ++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/test/artifacts/types/consumer.mts b/test/artifacts/types/consumer.mts index 276b44f..d8b0499 100644 --- a/test/artifacts/types/consumer.mts +++ b/test/artifacts/types/consumer.mts @@ -18,3 +18,18 @@ const grammar: Grammar = new Grammar(); const abnf: string = grammar.toString(); export { abnf }; + +// invalid input is not narrowed to never +import { testJSONPointer, testReferenceToken } from '@swaggerexpert/json-pointer'; + +declare const candidate: string; + +if (!testJSONPointer(candidate)) { + const invalidPointer: string = candidate; + // @ts-expect-error invalid JSON Pointer is still a string + const impossible: never = candidate; +} +if (!testReferenceToken(candidate)) { + // @ts-expect-error invalid reference token is still a string + const impossible: never = candidate; +} diff --git a/types/index.d.ts b/types/index.d.ts index b123f86..b7cce6d 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -83,8 +83,8 @@ export interface Trace { /** * Testing */ -export function testJSONPointer(jsonPointer: string): jsonPointer is JSONPointer; -export function testReferenceToken(referenceToken: string): referenceToken is ReferenceToken; +export function testJSONPointer(jsonPointer: string): boolean; +export function testReferenceToken(referenceToken: string): boolean; export function testArrayLocation(referenceToken: string): referenceToken is ArrayLocation; export function testArrayIndex(referenceToken: string): referenceToken is ArrayIndex; export function testArrayDash(referenceToken: string): referenceToken is ArrayDash; From 16b53315a100b3ea4660ad1449e1e407789ba40e Mon Sep 17 00:00:00 2001 From: Vladimir Gorej Date: Thu, 26 Nov 2026 10:41:05 +0100 Subject: [PATCH 04/11] fix(errors): keep error names in minified browser bundle Error classes derived their names from this.constructor.name, which Terser mangles in dist/*.min.js (e.g. JSONPointerKeyError became Z). Names are now defined explicitly on the error classes. Refs #269 --- src/errors/JSONPointerCompileError.js | 2 ++ src/errors/JSONPointerError.js | 5 ++++ src/errors/JSONPointerEvaluateError.js | 2 ++ src/errors/JSONPointerIndexError.js | 2 ++ src/errors/JSONPointerKeyError.js | 2 ++ src/errors/JSONPointerParseError.js | 2 ++ src/errors/JSONPointerTypeError.js | 2 ++ test/errors.js | 36 ++++++++++++++++++++++++++ 8 files changed, 53 insertions(+) create mode 100644 test/errors.js diff --git a/src/errors/JSONPointerCompileError.js b/src/errors/JSONPointerCompileError.js index d5b9e9b..7d0a9f2 100644 --- a/src/errors/JSONPointerCompileError.js +++ b/src/errors/JSONPointerCompileError.js @@ -2,4 +2,6 @@ import JSONPointerError from './JSONPointerError.js'; class JSONPointerCompileError extends JSONPointerError {} +Object.defineProperty(JSONPointerCompileError, 'name', { value: 'JSONPointerCompileError' }); + export default JSONPointerCompileError; diff --git a/src/errors/JSONPointerError.js b/src/errors/JSONPointerError.js index 469f1b1..50217d9 100644 --- a/src/errors/JSONPointerError.js +++ b/src/errors/JSONPointerError.js @@ -39,4 +39,9 @@ class JSONPointerError extends Error { } } +/** + * Class names are not reliable at runtime, as minifiers mangle them. + */ +Object.defineProperty(JSONPointerError, 'name', { value: 'JSONPointerError' }); + export default JSONPointerError; diff --git a/src/errors/JSONPointerEvaluateError.js b/src/errors/JSONPointerEvaluateError.js index 2da9d4f..3604b5a 100644 --- a/src/errors/JSONPointerEvaluateError.js +++ b/src/errors/JSONPointerEvaluateError.js @@ -2,4 +2,6 @@ import JSONPointerError from './JSONPointerError.js'; class JSONPointerEvaluateError extends JSONPointerError {} +Object.defineProperty(JSONPointerEvaluateError, 'name', { value: 'JSONPointerEvaluateError' }); + export default JSONPointerEvaluateError; diff --git a/src/errors/JSONPointerIndexError.js b/src/errors/JSONPointerIndexError.js index 7a631c8..9c7a6f5 100644 --- a/src/errors/JSONPointerIndexError.js +++ b/src/errors/JSONPointerIndexError.js @@ -2,4 +2,6 @@ import JSONPointerEvaluateError from './JSONPointerEvaluateError.js'; class JSONPointerIndexError extends JSONPointerEvaluateError {} +Object.defineProperty(JSONPointerIndexError, 'name', { value: 'JSONPointerIndexError' }); + export default JSONPointerIndexError; diff --git a/src/errors/JSONPointerKeyError.js b/src/errors/JSONPointerKeyError.js index f14831d..678550e 100644 --- a/src/errors/JSONPointerKeyError.js +++ b/src/errors/JSONPointerKeyError.js @@ -2,4 +2,6 @@ import JSONPointerEvaluateError from './JSONPointerEvaluateError.js'; class JSONPointerKeyError extends JSONPointerEvaluateError {} +Object.defineProperty(JSONPointerKeyError, 'name', { value: 'JSONPointerKeyError' }); + export default JSONPointerKeyError; diff --git a/src/errors/JSONPointerParseError.js b/src/errors/JSONPointerParseError.js index 3ce6d8d..c984d59 100644 --- a/src/errors/JSONPointerParseError.js +++ b/src/errors/JSONPointerParseError.js @@ -2,4 +2,6 @@ import JSONPointerError from './JSONPointerError.js'; class JSONPointerParseError extends JSONPointerError {} +Object.defineProperty(JSONPointerParseError, 'name', { value: 'JSONPointerParseError' }); + export default JSONPointerParseError; diff --git a/src/errors/JSONPointerTypeError.js b/src/errors/JSONPointerTypeError.js index 52a09a7..3b03c7e 100644 --- a/src/errors/JSONPointerTypeError.js +++ b/src/errors/JSONPointerTypeError.js @@ -2,4 +2,6 @@ import JSONPointerEvaluateError from './JSONPointerEvaluateError.js'; class JSONPointerTypeError extends JSONPointerEvaluateError {} +Object.defineProperty(JSONPointerTypeError, 'name', { value: 'JSONPointerTypeError' }); + export default JSONPointerTypeError; diff --git a/test/errors.js b/test/errors.js new file mode 100644 index 0000000..7dbfeaa --- /dev/null +++ b/test/errors.js @@ -0,0 +1,36 @@ +import { assert } from 'chai'; + +import { + JSONPointerError, + JSONPointerParseError, + JSONPointerCompileError, + JSONPointerEvaluateError, + JSONPointerTypeError, + JSONPointerKeyError, + JSONPointerIndexError, +} from '../src/index.js'; + +describe('errors', function () { + const errorClasses = { + JSONPointerError, + JSONPointerParseError, + JSONPointerCompileError, + JSONPointerEvaluateError, + JSONPointerTypeError, + JSONPointerKeyError, + JSONPointerIndexError, + }; + + Object.entries(errorClasses).forEach(([name, ErrorClass]) => { + specify(`${name} should have explicit name`, function () { + assert.strictEqual(ErrorClass.name, name); + assert.strictEqual(new ErrorClass('message').name, name); + }); + }); + + specify('should name instances of subclasses after the subclass', function () { + class CustomError extends JSONPointerKeyError {} + + assert.strictEqual(new CustomError('message').name, 'CustomError'); + }); +}); From 50b4f086b9fb21f5a75c296b53d28fa224c0e651 Mon Sep 17 00:00:00 2001 From: Vladimir Gorej Date: Thu, 26 Nov 2026 10:41:41 +0100 Subject: [PATCH 05/11] fix(build): make UMD bundles loadable via require webpack's default globalObject for web target is self, which is not defined in Node.js, so requiring the bundles threw ReferenceError. The bundles now use self or this as global object. Adds smoke test of built artifacts (npm run test:artifacts). Refs #269 --- config/webpack/browser.config.js | 4 ++ package.json | 1 + test/artifacts/smoke.cjs | 107 +++++++++++++++++++++++++++++++ 3 files changed, 112 insertions(+) create mode 100644 test/artifacts/smoke.cjs diff --git a/config/webpack/browser.config.js b/config/webpack/browser.config.js index 6908f51..ba6f8ab 100644 --- a/config/webpack/browser.config.js +++ b/config/webpack/browser.config.js @@ -10,6 +10,8 @@ const browser = { filename: 'json-pointer.browser.js', libraryTarget: 'umd', library: 'JSONPointer', + // works in browsers, web workers and CommonJS (where self is not defined) + globalObject: "typeof self !== 'undefined' ? self : this", }, resolve: { extensions: ['.js'], @@ -40,6 +42,8 @@ const browserMin = { filename: 'json-pointer.browser.min.js', libraryTarget: 'umd', library: 'JSONPointer', + // works in browsers, web workers and CommonJS (where self is not defined) + globalObject: "typeof self !== 'undefined' ? self : this", }, resolve: { extensions: ['.js'], diff --git a/package.json b/package.json index aba8102..0a1f6a2 100644 --- a/package.json +++ b/package.json @@ -55,6 +55,7 @@ "build:types": "node ./scripts/build-types.cjs", "build:umd:browser": "cross-env BABEL_ENV=browser webpack --config config/webpack/browser.config.js --progress", "test": "cross-env NODE_OPTIONS='--import ./test/loader.js' mocha", + "test:artifacts": "node ./test/artifacts/smoke.cjs", "test:types": "tsc --noEmit --strict --skipLibCheck false --module node16 --moduleResolution node16 --target es2020 test/artifacts/types/consumer.cts test/artifacts/types/consumer.mts && tsc --noEmit --strict --module esnext --moduleResolution bundler --target es2020 test/artifacts/types/consumer.mts", "test:watch": "npm-watch test", "watch": "npm-watch" diff --git a/test/artifacts/smoke.cjs b/test/artifacts/smoke.cjs new file mode 100644 index 0000000..c427d71 --- /dev/null +++ b/test/artifacts/smoke.cjs @@ -0,0 +1,107 @@ +/** + * Smoke test of the built artifacts, as consumers load them: CommonJS, ES module, UMD (require and browser global). + * Resolves the package by its name, so it runs both inside this repository (self-reference) + * and in a project the packed tarball is installed into. + * Written in syntax supported by the oldest supported Node.js version (see engines in package.json). + */ +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const vm = require('vm'); + +const name = '@swaggerexpert/json-pointer'; +const root = path.dirname(require.resolve(`${name}/package.json`)); + +// values created in a different realm (vm context) have different prototypes, so compare their JSON +const assertJSONEqual = (actual, expected) => + assert.strictEqual(JSON.stringify(actual), JSON.stringify(expected)); + +const errorNames = [ + 'JSONPointerError', + 'JSONPointerParseError', + 'JSONPointerCompileError', + 'JSONPointerEvaluateError', + 'JSONPointerTypeError', + 'JSONPointerKeyError', + 'JSONPointerIndexError', +]; + +const check = (label, JSONPointer) => { + assertJSONEqual(JSONPointer.parse('/a~1b/c~0d').tree, ['a/b', 'c~d']); + assert.strictEqual(JSONPointer.testJSONPointer('/a'), true); + assert.strictEqual(JSONPointer.testJSONPointer('a'), false); + assert.strictEqual(JSONPointer.compile(['a/b', 'c~d']), '/a~1b/c~0d'); + assert.strictEqual(JSONPointer.evaluate({ a: [1, 2] }, '/a/1'), 2); + + errorNames.forEach((errorName) => { + assert.strictEqual(JSONPointer[errorName].name, errorName); + assert.strictEqual(new JSONPointer[errorName]('message').name, errorName); + }); + + assert.throws( + () => JSONPointer.evaluate({}, '/a'), + (error) => error.name === 'JSONPointerKeyError', + ); + assert.throws( + () => JSONPointer.evaluate({}, '/a~'), + (error) => error.name === 'JSONPointerParseError', + ); + + assert.strictEqual(typeof new JSONPointer.Grammar().toString(), 'string'); + + console.log(`ok ${label}`); +}; + +const checkRealms = (label, JSONRealm, MapSetRealm) => { + assert.strictEqual(new JSONRealm().name, 'json'); + assert.strictEqual(new MapSetRealm().name, 'map-set'); + + console.log(`ok ${label}`); +}; + +const main = async () => { + check('CommonJS', require(name)); + check('ES module', await import(name)); + + checkRealms( + 'CommonJS realms', + require(`${name}/evaluate/realms/json`).default, + require(`${name}/evaluate/realms/map-set`).default, + ); + checkRealms( + 'ES module realms', + (await import(`${name}/evaluate/realms/json`)).default, + (await import(`${name}/evaluate/realms/map-set`)).default, + ); + + // UMD bundles target browsers (browser-production in .browserslistrc) and use private class + // methods, so Node.js >= 14.6 can require them + const [major, minor] = process.versions.node.split('.').map(Number); + if (major < 14 || (major === 14 && minor < 6)) { + console.log('skip UMD bundles on Node.js < 14.6'); + } else { + // dist/ is not exported, so the bundles are required as consumers vendoring them do: + // copied into a CommonJS context (the package itself is "type": "module") + const vendorDir = fs.mkdtempSync(path.join(os.tmpdir(), 'json-pointer-')); + + ['json-pointer.browser.js', 'json-pointer.browser.min.js'].forEach((file) => { + const bundlePath = path.join(root, 'dist', file); + const vendoredPath = path.join(vendorDir, file.replace(/\.js$/, '.cjs')); + + fs.copyFileSync(bundlePath, vendoredPath); + check(`UMD require ${file}`, require(vendoredPath)); + + const context = {}; + context.self = context; + vm.createContext(context); + vm.runInContext(fs.readFileSync(bundlePath, 'utf8'), context); + check(`UMD browser global ${file}`, context.JSONPointer); + }); + } +}; + +main().catch((error) => { + console.error(error); + process.exitCode = 1; +}); From 4337a8b6a6d045288f9f35bcd1549f84f46ed269 Mon Sep 17 00:00:00 2001 From: Vladimir Gorej Date: Thu, 26 Nov 2026 10:41:58 +0100 Subject: [PATCH 06/11] fix(build): resolve apg-lite path independently of cwd and platform The CommonJS build rewrote apg-lite imports relative to the current working directory and used raw path.relative() output, producing wrong paths when run from another directory, backslashes on Windows and bare specifiers for files directly under src/. Refs #269 --- babel.config.cjs | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/babel.config.cjs b/babel.config.cjs index 8c2caa3..d895050 100644 --- a/babel.config.cjs +++ b/babel.config.cjs @@ -1,5 +1,28 @@ const path = require('node:path'); +/** + * apg-lite is an ES module, so the CommonJS build (kept for backward compatibility) + * bundles its own copy at cjs/apg-lite.cjs. Imports of apg-lite are rewritten to a relative path + * to that copy, mirroring src/ layout in the output directory, independent of the current working + * directory and platform path separators. + */ +const resolveApgLite = (extension) => [ + 'module-resolver', + { + resolvePath(sourcePath, currentFile) { + if (sourcePath !== 'apg-lite') return sourcePath; + + const apgLite = path.join(__dirname, 'src', `apg-lite.${extension}`); + const relativePath = path + .relative(path.dirname(currentFile), apgLite) + .split(path.sep) + .join('/'); + + return relativePath.startsWith('.') ? relativePath : `./${relativePath}`; + }, + }, +]; + module.exports = { env: { cjs: { @@ -21,19 +44,7 @@ module.exports = { path.join(__dirname, './scripts/babel-plugin-add-import-extension.cjs'), { extension: 'cjs' }, ], - [ - 'module-resolver', - { - resolvePath(sourcePath, currentFile) { - if (sourcePath === 'apg-lite') { - const apgLiteCJS = path.resolve('./src/apg-lite.cjs'); - const currentDir = path.dirname(currentFile); - return path.relative(currentDir, apgLiteCJS); - } - return sourcePath; - }, - }, - ], + resolveApgLite('cjs'), ], }, es: { From 6f3f40fa16610c8792a03a7801f2e76b66eeba6e Mon Sep 17 00:00:00 2001 From: Vladimir Gorej Date: Thu, 26 Nov 2026 10:42:32 +0100 Subject: [PATCH 07/11] fix(parse): infer expectations at furthest offset only inferExpectations collected failed terminals from offsets earlier than the furthest one and considered TLS terminals only, so e.g. "/a~" reported "0", "1", "/". Failed TLS, TBS and TRG terminals are now recorded with their offsets and only those at the furthest offset are reported, or none when the parser matched past them. Refs #269 --- src/parse/trace/Trace.js | 94 +++++++++++++++++++++++++++++----------- test/parse/trace.js | 25 +++++++++++ 2 files changed, 94 insertions(+), 25 deletions(-) diff --git a/src/parse/trace/Trace.js b/src/parse/trace/Trace.js index 17661b6..251de85 100644 --- a/src/parse/trace/Trace.js +++ b/src/parse/trace/Trace.js @@ -1,35 +1,79 @@ -import { Trace as BaseTrace } from 'apg-lite'; +import { Trace as BaseTrace, identifiers } from 'apg-lite'; import Expectations from './Expectations.js'; +const terminalOperators = [identifiers.TLS, identifiers.TBS, identifiers.TRG]; + +const failures = new WeakMap(); + +/** + * Printable ASCII characters are shown as they are, except for `"` and `\`, which would be + * ambiguous in quoted expectations (see Expectations.toString). Other characters are shown + * as `\xHH` (up to 0xFF) or `\u{H...}`. + */ +const describeCharacter = (code) => { + if (code >= 0x21 && code <= 0x7e && code !== 0x22 && code !== 0x5c) { + return String.fromCharCode(code); + } + if (code <= 0xff) return `\\x${code.toString(16).toUpperCase().padStart(2, '0')}`; + return `\\u{${code.toString(16).toUpperCase()}}`; +}; + +const describeTerminal = (operator) => { + if (operator.type === identifiers.TRG) { + return `${describeCharacter(operator.min)}-${describeCharacter(operator.max)}`; + } + + return operator.string.map(describeCharacter).join(''); +}; + class Trace extends BaseTrace { - inferExpectations() { - const lines = this.displayTrace().split('\n'); - const expectations = new Set(); - let collecting = false; - let lastMatchedIndex = -1; - - for (let i = 0; i < lines.length; i++) { - const line = lines[i]; - - // capture the max match line (first one that ends in a single character match) - if (!collecting && line.includes('M|')) { - const textMatch = line.match(/]'(.*)'$/); - if (textMatch && textMatch[1]) { - lastMatchedIndex = i; - } - } + constructor() { + super(); + + const state = { terminals: [], furthestMatchEnd: 0 }; + const { up } = this; - // begin collecting after the deepest successful match - if (i > lastMatchedIndex) { - const terminalFailMatch = line.match(/N\|\[TLS\(([^)]+)\)]/); - if (terminalFailMatch) { - expectations.add(terminalFailMatch[1]); - } + failures.set(this, state); + + /** + * Records terminals (literal strings, binary strings, ranges) that failed to match + * with their offsets, and the furthest offset any operator matched up to. + */ + this.up = (operator, operatorState, offset, phraseLength) => { + if (operatorState === identifiers.NOMATCH && terminalOperators.includes(operator.type)) { + state.terminals.push({ operator, offset }); + } else if (operatorState === identifiers.MATCH) { + state.furthestMatchEnd = Math.max(state.furthestMatchEnd, offset + phraseLength); } - } + up(operator, operatorState, offset, phraseLength); + }; + } + + /** + * Infers what the parser expected at the furthest offset it reached: + * terminals that failed to match at that offset. + * + * Unlike grammars where repetitions stop at the end of the source without trying their children, + * every failing JSON Pointer ends with a failed terminal at the furthest offset + * ("/" at the start, or "0" / "1" after "~"), so re-parsing with a sentinel is not needed. + * + * Terminals failing before the furthest matched offset did not stop the parser + * (e.g. alternatives tried during a successful parse), so nothing is expected then. + */ + inferExpectations() { + const { terminals, furthestMatchEnd } = failures.get(this); + const furthestOffset = terminals.reduce((max, { offset }) => Math.max(max, offset), -1); + + if (furthestOffset < furthestMatchEnd) return new Expectations(); + + const expectations = new Set( + terminals + .filter(({ offset }) => offset === furthestOffset) + .map(({ operator }) => describeTerminal(operator)), + ); - return new Expectations(...expectations); + return Expectations.from(expectations); } } diff --git a/test/parse/trace.js b/test/parse/trace.js index 2c4b82d..8198835 100644 --- a/test/parse/trace.js +++ b/test/parse/trace.js @@ -59,5 +59,30 @@ describe('parse', function () { 'Invalid JSON Pointer: "1". Syntax error at position 0, expected "/"', ); }); + + specify('should infer expectations at the end of the source', function () { + const { result, trace } = parse('/a~', { trace: true }); + + assert.isFalse(result.success); + assert.strictEqual(result.maxMatched, 3); + assert.deepEqual(Array.from(trace.inferExpectations()), ['0', '1']); + }); + + specify('should infer expectations only at the furthest offset', function () { + const { result, trace } = parse('/a/~2', { trace: true }); + + assert.isFalse(result.success); + assert.strictEqual(result.maxMatched, 4); + assert.deepEqual(Array.from(trace.inferExpectations()), ['0', '1']); + }); + + specify('should infer no expectations for valid JSON Pointer', function () { + ['', '/', '/a', '/a~0/b~1', '/a/b/c'].forEach((jsonPointer) => { + const { result, trace } = parse(jsonPointer, { trace: true }); + + assert.isTrue(result.success); + assert.lengthOf(Array.from(trace.inferExpectations()), 0, jsonPointer); + }); + }); }); }); From 716dc731379c39e116437b766f210a4d075fd27e Mon Sep 17 00:00:00 2001 From: Vladimir Gorej Date: Thu, 26 Nov 2026 10:43:18 +0100 Subject: [PATCH 08/11] test(parse): cover escaping of XML special characters XMLTranslator produced malformed XML for JSON Pointers containing < or & because apg-lite's toXml() did not escape texts. apg-lite fixed this in 1.0.7, and the minimum required version is ^1.0.8 since #282. Refs #269 --- test/parse/translators/XMLTranslator.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/test/parse/translators/XMLTranslator.js b/test/parse/translators/XMLTranslator.js index 231079f..0c40f89 100644 --- a/test/parse/translators/XMLTranslator.js +++ b/test/parse/translators/XMLTranslator.js @@ -32,6 +32,17 @@ describe('parse', function () { '\n', ); }); + + specify('should escape XML special characters', function () { + const parseResult = parse('/&"\'', { translator: new XMLTranslator() }); + + assert.isTrue(parseResult.result.success); + assert.include(parseResult.tree, '</node><x>&"''); + assert.notInclude(parseResult.tree, ''); + // & is allowed in XML comments, e.g. in the caveat comment of apg-lite + const withoutComments = parseResult.tree.replace(//g, ''); + assert.notMatch(withoutComments, /&(?!amp;|lt;|gt;|quot;|apos;)/); + }); }); }); }); From 69f7dcbf3588691ad1018a04d0c668d7149e4906 Mon Sep 17 00:00:00 2001 From: Vladimir Gorej Date: Thu, 26 Nov 2026 10:43:23 +0100 Subject: [PATCH 09/11] chore(scripts): watch nested files in test:watch The npm-watch pattern {src,test}/*.js matched top-level files only, so editing e.g. src/parse/index.js did not re-run tests. Refs #269 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 0a1f6a2..1453600 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,7 @@ "./package.json": "./package.json" }, "watch": { - "test": "{src,test}/*.js" + "test": "{src,test}/**/*.js" }, "scripts": { "prepublishOnly": "npm run build", From fa523b1093ce6a2cb1200704c8fdddb1ae01eb50 Mon Sep 17 00:00:00 2001 From: Vladimir Gorej Date: Thu, 26 Nov 2026 10:43:34 +0100 Subject: [PATCH 10/11] docs(NOTICE): add apg-lite copyright and license The CommonJS build bundles apg-lite (cjs/apg-lite.cjs) and src/grammar.js is generated by apg-js. The BSD-2-Clause license requires reproducing the copyright notice and license in binary distributions. Refs #269 --- NOTICE | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/NOTICE b/NOTICE index 73993de..c2856a1 100644 --- a/NOTICE +++ b/NOTICE @@ -9,3 +9,30 @@ https://datatracker.ietf.org/doc/html/rfc6901 Majority of ABNF grammar (grammar.bnf) and certain texts within the README.md file are licensed under Revised BSD License - https://spdx.org/licenses/BSD-3-Clause.html. +apg-lite +Copyright (c) 2023 Lowell D. Thomas +https://github.com/ldthomas/apg-lite +The CommonJS build (cjs/apg-lite.cjs) and the UMD browser bundles (dist/) bundle apg-lite, +and src/grammar.js is generated by apg-js. +apg-lite is licensed under 2-Clause BSD License - https://spdx.org/licenses/BSD-2-Clause.html: + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. From 318413efb8272f10f36ad170783838bccbef9f1c Mon Sep 17 00:00:00 2001 From: Vladimir Gorej Date: Thu, 26 Nov 2026 10:44:25 +0100 Subject: [PATCH 11/11] ci: test built artifacts, typings and installed tarball Runs the artifact smoke test and type checks after the build, verifies the tarball contains the generated declarations, and installs it into a new project on every Node.js version from engines up. Refs #269 --- .github/workflows/release.yml | 6 ++++ .github/workflows/test.yml | 55 +++++++++++++++++++++++++++++++++++ .gitignore | 1 + CLAUDE.md | 4 ++- 4 files changed, 65 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0a1c125..e6f22c5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -39,6 +39,12 @@ jobs: - name: Execute tests run: npm test + - name: Test artifacts + run: npm run test:artifacts + + - name: Test typings + run: npm run test:types + - name: Semantic Release env: GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1f35e11..ab92cd7 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -23,3 +23,58 @@ jobs: run: npm ci - name: Execute tests run: npm test + - name: Build artifacts + run: npm run build + - name: Test artifacts + run: npm run test:artifacts + - name: Test typings + run: npm run test:types + - name: Pack tarball + run: | + mkdir -p pack + npm pack --pack-destination ./pack + - name: Verify tarball contains generated declarations + run: | + # generated files are gitignored, so make sure they are published + contents="$(tar -tzf pack/*.tgz)" + for file in types/index.d.cts types/evaluate/realms/json.d.cts types/evaluate/realms/map-set.d.cts; do + echo "$contents" | grep -qx "package/$file" || { echo "missing $file"; exit 1; } + done + - name: Upload tarball + uses: actions/upload-artifact@v7 + with: + name: tarball + path: | + pack/*.tgz + test/artifacts/smoke.cjs + + compatibility: + needs: test + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + # oldest supported version (engines in package.json) and maintained versions + node-version: [ 12.20.0, 14, 16, 18, 20, 22, 24, 26 ] + + steps: + - name: Download tarball + uses: actions/download-artifact@v8 + with: + name: tarball + - name: Use Node.js + uses: actions/setup-node@v7 + with: + node-version: ${{ matrix.node-version }} + - name: Install tarball into a new project + run: | + mkdir consumer + cd consumer + npm init -y + npm install ../pack/*.tgz + # the package is resolved relative to the script, so the script must be inside the project + cp ../test/artifacts/smoke.cjs . + - name: Test installed package + working-directory: consumer + run: node smoke.cjs diff --git a/.gitignore b/.gitignore index 0c60160..40abc79 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ node_modules/ /dist /swaggerexpert-json-pointer-*.tgz /types/**/*.d.cts +/pack diff --git a/CLAUDE.md b/CLAUDE.md index 2e9bcbf..49ac883 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,6 +19,8 @@ npm run grammar:compile # Compile ABNF grammar to parser (src/grammar.bnf → s npm test # Run all tests with Mocha npm test -- --grep "pattern" # Run specific tests matching pattern npm test -- test/parse/index.js # Run a single test file +npm run test:artifacts # Smoke test built artifacts (es/, cjs/, dist/), run after npm run build +npm run test:types # Type check typings as CommonJS and ES module consumers, run after npm run build ``` ## Architecture @@ -57,7 +59,7 @@ Located in `src/parse/translators/`: ### Error Hierarchy -All errors extend `JSONPointerError`: +All errors extend `JSONPointerError`. Error classes define their `name` explicitly, as minifiers mangle class names: - `JSONPointerParseError` - Invalid pointer syntax - `JSONPointerCompileError` - Invalid reference tokens during compilation - `JSONPointerEvaluateError` - Base for evaluation errors