Skip to content

Repository files navigation

URLSearchParams Parser

npm GitHub Actions

Parses URLSearchParams to JavaScript objects according to Zod schemas.

Description

The set of allowed Zod schemas is restricted to ensure the parsing is unambiguous. This parser may be used as a true inverse operation to @seamapi/url-search-params-serializer.

Strict Parsing

By default, or when passing strict: true, the parser only parses the expected output of @url-search-params-serializer, making the parser a true inverse of the serializer:

  • Parses z.array() only in the repeated format foo=1&foo=2.
    • Array values may contain a , and are never split, e.g., foo=a,b&foo=c is parsed as ['a,b', 'c'].
    • There is no bracket array format: since the serializer never outputs it, a param named foo[] is unrelated to the param foo and is parsed as a param literally named foo[].
  • For z.boolean(), only the strings true and false are parsed.
  • Whitespace is significant and is never trimmed: only a completely empty value is parsed as null (or as the empty array for z.array()).

Generous Parsing

When passing strict: false, additional input cases are handled at the cost of some limitations, e.g., array string values containing a , are not supported:

  • For z.number(), z.boolean(), z.date(), z.object(), and z.record(), whitespace only values are parsed as null.
  • For z.number(), z.boolean(), z.date(), starting and ending whitespace is trimmed before parsing.
  • For z.boolean(), the following strings are parsed as true: true, True, TRUE, yes, Yes, YES, and 1.
  • For z.boolean(), the following values are parsed as false: false, False, FALSE, no, No, NO, and 0.
  • Parses z.array() in the following formats. In order to support unambiguous parsing, array string values containing a , are not supported.
    • foo=1&foo=2
    • foo[]=1&foo[]=2
    • foo=1,2

Parsing in Both Modes

These rules apply in strict and generous mode alike:

  • For z.number(), z.boolean(), and z.date(), values that cannot be parsed as the expected type are passed through unchanged as strings, e.g., foo=a is parsed as 'a' for z.number(). Validating the parsed output is left to the schema.
  • For z.string(), an empty value is parsed as null, since the serializer treats the empty string as undefined. Whitespace is significant and is never trimmed for z.string().
  • For z.object() and z.record(), a non-empty value is passed through unchanged as a string, e.g., foo=a is parsed as 'a'.
  • Search params not present in the schema are ignored.

Unparseable Search Params

Some inputs are ambiguous and cannot be parsed unambiguously. These throw an UnparseableSearchParamError:

  • A non-array param with repeated values, e.g., foo=1&foo=2 for z.number().
  • An array param that mixes empty values with other values, e.g., foo=&foo=1 or foo=&foo=.
  • An object or record param that conflicts with its own nested params, e.g., foo.bar=&foo.bar.a=1, since this would be a null object containing a value.
  • A param nested inside a record param, e.g., foo.a.b=1 for z.record(z.string(), z.number()).
  • In generous mode (strict: false):
    • An array param that mixes array formats, e.g., foo=1&foo[]=2 or foo=1,2&foo=3.
    • An array param that repeats a value containing a ,, e.g., foo=a,b&foo=c,d.
    • An array param using the bracket format with a value containing a ,, e.g., foo[]=a,b.
    • An array param using the comma format with empty values, e.g., foo=a,,b.

Schemas that do not obey these rules throw an UnparseableSchemaError.

  • The top-level schema must be an z.object() or z.union() of z.object().
  • Properties may be a z.object() or z.union() of objects.
  • All union object types must flatten to a parseable object schema with non-conflicting property types.
    • Properties present in only some union options are parsed as optional.
    • Using z.discriminatedUnion() is allowed and equivalent to z.union().
  • Primitive properties must be a z.string(), z.number(), z.boolean() or z.date().
    • Properties must be a single-value type.
    • The primitives z.bigint() and z.symbol() are not supported.
    • Strings with zero length are not allowed. If not specified, a z.string() is always assumed to be z.string().min(1).
    • Using z.enum() is allowed and equivalent to z.string().
    • Using z.nativeEnum() is allowed when all its values are strings or all its values are numbers.
  • Any property may be z.optional() or z.never().
  • Any property may be z.null(), which is always parsed as null.
  • No property may z.void(), z.undefined(), z.any(), or z.unknown().
  • Any property may be z.nullable() except z.array().
  • Properties that are z.literal() are allowed and must still obey all of these rules.
  • The z.default() and z.readonly() wrappers are allowed and ignored. Defaults are not applied by this parser: applying them is left to the schema.
  • A z.array() must be of a single value-type.
    • The value-types must obey all the same basic rules for primitive object, union, and property types.
    • A union value-type must resolve to a single value-type, e.g., a z.union() of z.literal() strings.
    • Value-types may not be z.nullable() or z.undefined().
    • The value-type cannot be a z.object().
    • The value-type cannot be an z.array() or contain a nested z.array() at any level.
    • The value-type cannot be a z.boolean(). This restriction is not strictly necessary, but a deliberate choice not to support such schemas in this version.
  • A z.record() has less-strict schema constraints but weaker parsing guarantees:
    • They keys must be z.string() or a z.enum().
    • The value-type may be a single primitive type.
    • The value-type may be z.nullable().
    • The value-type may not be a z.record(), z.array(), or z.object(). This restriction is not strictly necessary, but a deliberate choice not to support such schemas in this version.
    • The value-type may be a union of primitive types, but this union must include z.string() and all values will be parsed as z.string(). For schemas of this type, the parser is no longer a true inverse of the serialization.

Installation

Add this as a dependency to your project using npm with

$ npm install @seamapi/url-search-params-parser

Usage

import { parseUrlSearchParams } from '@seamapi/url-search-params-parser'

parseUrlSearchParams(
  'age=27&isAdmin=true&name=Dax&tags=cars&tags=planes',
  z.object({
    name: z.string().min(1),
    age: z.number(),
    isAdmin: z.boolean(),
    tags: z.array(z.string()),
  }),
) // => { name: 'Dax', age: 27, isAdmin: true, tags: ['cars', 'planes'] }

Pass strict: false to enable generous parsing, which accepts additional input formats at the cost of no longer being a true inverse of the serializer.

parseUrlSearchParams(
  'isAdmin=yes&tags=cars,planes',
  z.object({
    isAdmin: z.boolean(),
    tags: z.array(z.string()),
  }),
  { strict: false },
) // => { isAdmin: true, tags: ['cars', 'planes'] }

This parser does not validate its output: pass the parsed params to the schema to both validate and type them.

const schema = z.object({ name: z.string().min(1), age: z.number() })

schema.parse(parseUrlSearchParams('age=27&name=Dax', schema))

Parsing throws an UnparseableSchemaError when the schema is not supported, and an UnparseableSearchParamError when the query string is ambiguous.

import {
  parseUrlSearchParams,
  UnparseableSchemaError,
  UnparseableSearchParamError,
} from '@seamapi/url-search-params-parser'

Development and Testing

Quickstart

$ git clone https://github.com/seamapi/url-search-params-parser.git
$ cd url-search-params-parser
$ nvm install
$ npm install
$ npm run test:watch

Primary development tasks are defined under scripts in package.json and available via npm run. View them with

$ npm run

Source code

The source code is hosted on GitHub. Clone the project with

$ git clone git@github.com:seamapi/url-search-params-parser.git

Requirements

You will need Node.js with npm and a Node.js debugging client.

Be sure that all commands run under the correct Node version, e.g., if using nvm, install the correct version with

$ nvm install

Set the active version for each shell session with

$ nvm use

Install the development dependencies with

$ npm install

Publishing

Automatic

New versions are released automatically with semantic-release as long as commits follow the Angular Commit Message Conventions.

Manual

Publish a new version by triggering a version workflow_dispatch on GitHub Actions. The version input will be passed as the first argument to npm-version.

This may be done on the web or using the GitHub CLI with

$ gh workflow run version.yml --raw-field version=<version>

GitHub Actions

GitHub Actions should already be configured: this section is for reference only.

The following repository secrets must be set on GitHub Actions:

  • NPM_TOKEN: npm token for installing and publishing packages.
  • GH_TOKEN: A personal access token for the bot user with packages:write and contents:write permission.
  • GIT_USER_NAME: The GitHub bot user's real name.
  • GIT_USER_EMAIL: The GitHub bot user's email.
  • GPG_PRIVATE_KEY: The GitHub bot user's GPG private key.
  • GPG_PASSPHRASE: The GitHub bot user's GPG passphrase.

Contributing

If using squash merge, edit and ensure the commit message follows the Angular Commit Message Conventions specification. Otherwise, each individual commit must follow the Angular Commit Message Conventions specification.

  1. Create your feature branch (git checkout -b my-new-feature).
  2. Make changes.
  3. Commit your changes (git commit -am 'Add some feature').
  4. Push to the branch (git push origin my-new-feature).
  5. Create a new draft pull request.
  6. Ensure all checks pass.
  7. Mark your pull request ready for review.
  8. Wait for the required approval from the code owners.
  9. Merge when ready.

License

This npm package is licensed under the MIT license.

Warranty

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.

About

Parses URLSearchParams to JavaScript objects according to Zod schemas.

Resources

Stars

0 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages