@graffiti-garden/wrapper-synchronize 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -0
- package/dist/cjs/index.js +2 -0
- package/dist/cjs/index.js.map +7 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +7 -0
- package/dist/index.browser.js +42 -0
- package/dist/index.browser.js.map +7 -0
- package/dist/index.d.ts +134 -0
- package/dist/index.d.ts.map +1 -0
- package/package.json +63 -0
- package/src/index.spec.ts +408 -0
- package/src/index.ts +315 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../node_modules/ajv/lib/compile/codegen/code.ts", "../node_modules/ajv/lib/compile/codegen/scope.ts", "../node_modules/ajv/lib/compile/codegen/index.ts", "../node_modules/ajv/lib/compile/util.ts", "../node_modules/ajv/lib/compile/names.ts", "../node_modules/ajv/lib/compile/errors.ts", "../node_modules/ajv/lib/compile/validate/boolSchema.ts", "../node_modules/ajv/lib/compile/rules.ts", "../node_modules/ajv/lib/compile/validate/applicability.ts", "../node_modules/ajv/lib/compile/validate/dataType.ts", "../node_modules/ajv/lib/compile/validate/defaults.ts", "../node_modules/ajv/lib/vocabularies/code.ts", "../node_modules/ajv/lib/compile/validate/keyword.ts", "../node_modules/ajv/lib/compile/validate/subschema.ts", "../node_modules/fast-deep-equal/index.js", "../node_modules/json-schema-traverse/index.js", "../node_modules/ajv/lib/compile/resolve.ts", "../node_modules/ajv/lib/compile/validate/index.ts", "../node_modules/ajv/lib/runtime/validation_error.ts", "../node_modules/ajv/lib/compile/ref_error.ts", "../node_modules/ajv/lib/compile/index.ts", "../node_modules/ajv/dist/refs/data.json", "../node_modules/fast-uri/lib/scopedChars.js", "../node_modules/fast-uri/lib/utils.js", "../node_modules/fast-uri/lib/schemes.js", "../node_modules/fast-uri/index.js", "../node_modules/ajv/lib/runtime/uri.ts", "../node_modules/ajv/lib/core.ts", "../node_modules/ajv/lib/vocabularies/core/ref.ts", "../node_modules/ajv-draft-04/src/vocabulary/core.ts", "../node_modules/ajv-draft-04/src/vocabulary/validation/limitNumber.ts", "../node_modules/ajv-draft-04/src/vocabulary/validation/limitNumberExclusive.ts", "../node_modules/ajv/lib/vocabularies/validation/multipleOf.ts", "../node_modules/ajv/lib/runtime/ucs2length.ts", "../node_modules/ajv/lib/vocabularies/validation/limitLength.ts", "../node_modules/ajv/lib/vocabularies/validation/pattern.ts", "../node_modules/ajv/lib/vocabularies/validation/limitProperties.ts", "../node_modules/ajv/lib/vocabularies/validation/required.ts", "../node_modules/ajv/lib/vocabularies/validation/limitItems.ts", "../node_modules/ajv/lib/runtime/equal.ts", "../node_modules/ajv/lib/vocabularies/validation/uniqueItems.ts", "../node_modules/ajv/lib/vocabularies/validation/const.ts", "../node_modules/ajv/lib/vocabularies/validation/enum.ts", "../node_modules/ajv-draft-04/src/vocabulary/validation/index.ts", "../node_modules/ajv/lib/vocabularies/applicator/additionalItems.ts", "../node_modules/ajv/lib/vocabularies/applicator/items.ts", "../node_modules/ajv/lib/vocabularies/applicator/prefixItems.ts", "../node_modules/ajv/lib/vocabularies/applicator/items2020.ts", "../node_modules/ajv/lib/vocabularies/applicator/contains.ts", "../node_modules/ajv/lib/vocabularies/applicator/dependencies.ts", "../node_modules/ajv/lib/vocabularies/applicator/propertyNames.ts", "../node_modules/ajv/lib/vocabularies/applicator/additionalProperties.ts", "../node_modules/ajv/lib/vocabularies/applicator/properties.ts", "../node_modules/ajv/lib/vocabularies/applicator/patternProperties.ts", "../node_modules/ajv/lib/vocabularies/applicator/not.ts", "../node_modules/ajv/lib/vocabularies/applicator/anyOf.ts", "../node_modules/ajv/lib/vocabularies/applicator/oneOf.ts", "../node_modules/ajv/lib/vocabularies/applicator/allOf.ts", "../node_modules/ajv/lib/vocabularies/applicator/if.ts", "../node_modules/ajv/lib/vocabularies/applicator/thenElse.ts", "../node_modules/ajv/lib/vocabularies/applicator/index.ts", "../node_modules/ajv/lib/vocabularies/format/format.ts", "../node_modules/ajv/lib/vocabularies/format/index.ts", "../node_modules/ajv-draft-04/src/vocabulary/draft4.ts", "../node_modules/ajv/lib/vocabularies/discriminator/types.ts", "../node_modules/ajv/lib/vocabularies/discriminator/index.ts", "../node_modules/ajv-draft-04/dist/refs/json-schema-draft-04.json", "../node_modules/ajv-draft-04/src/index.ts", "../src/index.ts", "../node_modules/@graffiti-garden/api/src/1-api.ts", "../node_modules/@graffiti-garden/api/src/3-errors.ts", "../node_modules/@repeaterjs/repeater/repeater.js", "../node_modules/fast-json-patch/module/core.mjs", "../node_modules/fast-json-patch/module/helpers.mjs", "../node_modules/fast-json-patch/module/duplex.mjs", "../node_modules/fast-json-patch/index.mjs", "../node_modules/@graffiti-garden/implementation-local/node_modules/@graffiti-garden/api/src/1-api.ts", "../node_modules/@graffiti-garden/implementation-local/node_modules/@graffiti-garden/api/src/3-errors.ts", "../node_modules/@graffiti-garden/implementation-local/src/utilities.ts"],
|
|
4
|
+
"sourcesContent": ["// eslint-disable-next-line @typescript-eslint/no-extraneous-class\nexport abstract class _CodeOrName {\n abstract readonly str: string\n abstract readonly names: UsedNames\n abstract toString(): string\n abstract emptyStr(): boolean\n}\n\nexport const IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i\n\nexport class Name extends _CodeOrName {\n readonly str: string\n constructor(s: string) {\n super()\n if (!IDENTIFIER.test(s)) throw new Error(\"CodeGen: name must be a valid identifier\")\n this.str = s\n }\n\n toString(): string {\n return this.str\n }\n\n emptyStr(): boolean {\n return false\n }\n\n get names(): UsedNames {\n return {[this.str]: 1}\n }\n}\n\nexport class _Code extends _CodeOrName {\n readonly _items: readonly CodeItem[]\n private _str?: string\n private _names?: UsedNames\n\n constructor(code: string | readonly CodeItem[]) {\n super()\n this._items = typeof code === \"string\" ? [code] : code\n }\n\n toString(): string {\n return this.str\n }\n\n emptyStr(): boolean {\n if (this._items.length > 1) return false\n const item = this._items[0]\n return item === \"\" || item === '\"\"'\n }\n\n get str(): string {\n return (this._str ??= this._items.reduce((s: string, c: CodeItem) => `${s}${c}`, \"\"))\n }\n\n get names(): UsedNames {\n return (this._names ??= this._items.reduce((names: UsedNames, c) => {\n if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1\n return names\n }, {}))\n }\n}\n\nexport type CodeItem = Name | string | number | boolean | null\n\nexport type UsedNames = Record<string, number | undefined>\n\nexport type Code = _Code | Name\n\nexport type SafeExpr = Code | number | boolean | null\n\nexport const nil = new _Code(\"\")\n\ntype CodeArg = SafeExpr | string | undefined\n\nexport function _(strs: TemplateStringsArray, ...args: CodeArg[]): _Code {\n const code: CodeItem[] = [strs[0]]\n let i = 0\n while (i < args.length) {\n addCodeArg(code, args[i])\n code.push(strs[++i])\n }\n return new _Code(code)\n}\n\nconst plus = new _Code(\"+\")\n\nexport function str(strs: TemplateStringsArray, ...args: (CodeArg | string[])[]): _Code {\n const expr: CodeItem[] = [safeStringify(strs[0])]\n let i = 0\n while (i < args.length) {\n expr.push(plus)\n addCodeArg(expr, args[i])\n expr.push(plus, safeStringify(strs[++i]))\n }\n optimize(expr)\n return new _Code(expr)\n}\n\nexport function addCodeArg(code: CodeItem[], arg: CodeArg | string[]): void {\n if (arg instanceof _Code) code.push(...arg._items)\n else if (arg instanceof Name) code.push(arg)\n else code.push(interpolate(arg))\n}\n\nfunction optimize(expr: CodeItem[]): void {\n let i = 1\n while (i < expr.length - 1) {\n if (expr[i] === plus) {\n const res = mergeExprItems(expr[i - 1], expr[i + 1])\n if (res !== undefined) {\n expr.splice(i - 1, 3, res)\n continue\n }\n expr[i++] = \"+\"\n }\n i++\n }\n}\n\nfunction mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined {\n if (b === '\"\"') return a\n if (a === '\"\"') return b\n if (typeof a == \"string\") {\n if (b instanceof Name || a[a.length - 1] !== '\"') return\n if (typeof b != \"string\") return `${a.slice(0, -1)}${b}\"`\n if (b[0] === '\"') return a.slice(0, -1) + b.slice(1)\n return\n }\n if (typeof b == \"string\" && b[0] === '\"' && !(a instanceof Name)) return `\"${a}${b.slice(1)}`\n return\n}\n\nexport function strConcat(c1: Code, c2: Code): Code {\n return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`\n}\n\n// TODO do not allow arrays here\nfunction interpolate(x?: string | string[] | number | boolean | null): SafeExpr | string {\n return typeof x == \"number\" || typeof x == \"boolean\" || x === null\n ? x\n : safeStringify(Array.isArray(x) ? x.join(\",\") : x)\n}\n\nexport function stringify(x: unknown): Code {\n return new _Code(safeStringify(x))\n}\n\nexport function safeStringify(x: unknown): string {\n return JSON.stringify(x)\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\")\n}\n\nexport function getProperty(key: Code | string | number): Code {\n return typeof key == \"string\" && IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`\n}\n\n//Does best effort to format the name properly\nexport function getEsmExportName(key: Code | string | number): Code {\n if (typeof key == \"string\" && IDENTIFIER.test(key)) {\n return new _Code(`${key}`)\n }\n throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`)\n}\n\nexport function regexpCode(rx: RegExp): Code {\n return new _Code(rx.toString())\n}\n", "import {_, nil, Code, Name} from \"./code\"\n\ninterface NameGroup {\n prefix: string\n index: number\n}\n\nexport interface NameValue {\n ref: ValueReference // this is the reference to any value that can be referred to from generated code via `globals` var in the closure\n key?: unknown // any key to identify a global to avoid duplicates, if not passed ref is used\n code?: Code // this is the code creating the value needed for standalone code wit_out closure - can be a primitive value, function or import (`require`)\n}\n\nexport type ValueReference = unknown // possibly make CodeGen parameterized type on this type\n\nclass ValueError extends Error {\n readonly value?: NameValue\n constructor(name: ValueScopeName) {\n super(`CodeGen: \"code\" for ${name} not defined`)\n this.value = name.value\n }\n}\n\ninterface ScopeOptions {\n prefixes?: Set<string>\n parent?: Scope\n}\n\ninterface ValueScopeOptions extends ScopeOptions {\n scope: ScopeStore\n es5?: boolean\n lines?: boolean\n}\n\nexport type ScopeStore = Record<string, ValueReference[] | undefined>\n\ntype ScopeValues = {\n [Prefix in string]?: Map<unknown, ValueScopeName>\n}\n\nexport type ScopeValueSets = {\n [Prefix in string]?: Set<ValueScopeName>\n}\n\nexport enum UsedValueState {\n Started,\n Completed,\n}\n\nexport type UsedScopeValues = {\n [Prefix in string]?: Map<ValueScopeName, UsedValueState | undefined>\n}\n\nexport const varKinds = {\n const: new Name(\"const\"),\n let: new Name(\"let\"),\n var: new Name(\"var\"),\n}\n\nexport class Scope {\n protected readonly _names: {[Prefix in string]?: NameGroup} = {}\n protected readonly _prefixes?: Set<string>\n protected readonly _parent?: Scope\n\n constructor({prefixes, parent}: ScopeOptions = {}) {\n this._prefixes = prefixes\n this._parent = parent\n }\n\n toName(nameOrPrefix: Name | string): Name {\n return nameOrPrefix instanceof Name ? nameOrPrefix : this.name(nameOrPrefix)\n }\n\n name(prefix: string): Name {\n return new Name(this._newName(prefix))\n }\n\n protected _newName(prefix: string): string {\n const ng = this._names[prefix] || this._nameGroup(prefix)\n return `${prefix}${ng.index++}`\n }\n\n private _nameGroup(prefix: string): NameGroup {\n if (this._parent?._prefixes?.has(prefix) || (this._prefixes && !this._prefixes.has(prefix))) {\n throw new Error(`CodeGen: prefix \"${prefix}\" is not allowed in this scope`)\n }\n return (this._names[prefix] = {prefix, index: 0})\n }\n}\n\ninterface ScopePath {\n property: string\n itemIndex: number\n}\n\nexport class ValueScopeName extends Name {\n readonly prefix: string\n value?: NameValue\n scopePath?: Code\n\n constructor(prefix: string, nameStr: string) {\n super(nameStr)\n this.prefix = prefix\n }\n\n setValue(value: NameValue, {property, itemIndex}: ScopePath): void {\n this.value = value\n this.scopePath = _`.${new Name(property)}[${itemIndex}]`\n }\n}\n\ninterface VSOptions extends ValueScopeOptions {\n _n: Code\n}\n\nconst line = _`\\n`\n\nexport class ValueScope extends Scope {\n protected readonly _values: ScopeValues = {}\n protected readonly _scope: ScopeStore\n readonly opts: VSOptions\n\n constructor(opts: ValueScopeOptions) {\n super(opts)\n this._scope = opts.scope\n this.opts = {...opts, _n: opts.lines ? line : nil}\n }\n\n get(): ScopeStore {\n return this._scope\n }\n\n name(prefix: string): ValueScopeName {\n return new ValueScopeName(prefix, this._newName(prefix))\n }\n\n value(nameOrPrefix: ValueScopeName | string, value: NameValue): ValueScopeName {\n if (value.ref === undefined) throw new Error(\"CodeGen: ref must be passed in value\")\n const name = this.toName(nameOrPrefix) as ValueScopeName\n const {prefix} = name\n const valueKey = value.key ?? value.ref\n let vs = this._values[prefix]\n if (vs) {\n const _name = vs.get(valueKey)\n if (_name) return _name\n } else {\n vs = this._values[prefix] = new Map()\n }\n vs.set(valueKey, name)\n\n const s = this._scope[prefix] || (this._scope[prefix] = [])\n const itemIndex = s.length\n s[itemIndex] = value.ref\n name.setValue(value, {property: prefix, itemIndex})\n return name\n }\n\n getValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {\n const vs = this._values[prefix]\n if (!vs) return\n return vs.get(keyOrRef)\n }\n\n scopeRefs(scopeName: Name, values: ScopeValues | ScopeValueSets = this._values): Code {\n return this._reduceValues(values, (name: ValueScopeName) => {\n if (name.scopePath === undefined) throw new Error(`CodeGen: name \"${name}\" has no value`)\n return _`${scopeName}${name.scopePath}`\n })\n }\n\n scopeCode(\n values: ScopeValues | ScopeValueSets = this._values,\n usedValues?: UsedScopeValues,\n getCode?: (n: ValueScopeName) => Code | undefined\n ): Code {\n return this._reduceValues(\n values,\n (name: ValueScopeName) => {\n if (name.value === undefined) throw new Error(`CodeGen: name \"${name}\" has no value`)\n return name.value.code\n },\n usedValues,\n getCode\n )\n }\n\n private _reduceValues(\n values: ScopeValues | ScopeValueSets,\n valueCode: (n: ValueScopeName) => Code | undefined,\n usedValues: UsedScopeValues = {},\n getCode?: (n: ValueScopeName) => Code | undefined\n ): Code {\n let code: Code = nil\n for (const prefix in values) {\n const vs = values[prefix]\n if (!vs) continue\n const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map())\n vs.forEach((name: ValueScopeName) => {\n if (nameSet.has(name)) return\n nameSet.set(name, UsedValueState.Started)\n let c = valueCode(name)\n if (c) {\n const def = this.opts.es5 ? varKinds.var : varKinds.const\n code = _`${code}${def} ${name} = ${c};${this.opts._n}`\n } else if ((c = getCode?.(name))) {\n code = _`${code}${c}${this.opts._n}`\n } else {\n throw new ValueError(name)\n }\n nameSet.set(name, UsedValueState.Completed)\n })\n }\n return code\n }\n}\n", "import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from \"./scope\"\nimport {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from \"./code\"\nimport {Scope, varKinds} from \"./scope\"\n\nexport {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from \"./code\"\nexport {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from \"./scope\"\n\n// type for expressions that can be safely inserted in code without quotes\nexport type SafeExpr = Code | number | boolean | null\n\n// type that is either Code of function that adds code to CodeGen instance using its methods\nexport type Block = Code | (() => void)\n\nexport const operators = {\n GT: new _Code(\">\"),\n GTE: new _Code(\">=\"),\n LT: new _Code(\"<\"),\n LTE: new _Code(\"<=\"),\n EQ: new _Code(\"===\"),\n NEQ: new _Code(\"!==\"),\n NOT: new _Code(\"!\"),\n OR: new _Code(\"||\"),\n AND: new _Code(\"&&\"),\n ADD: new _Code(\"+\"),\n}\n\nabstract class Node {\n abstract readonly names: UsedNames\n\n optimizeNodes(): this | ChildNode | ChildNode[] | undefined {\n return this\n }\n\n optimizeNames(_names: UsedNames, _constants: Constants): this | undefined {\n return this\n }\n\n // get count(): number {\n // return 1\n // }\n}\n\nclass Def extends Node {\n constructor(\n private readonly varKind: Name,\n private readonly name: Name,\n private rhs?: SafeExpr\n ) {\n super()\n }\n\n render({es5, _n}: CGOptions): string {\n const varKind = es5 ? varKinds.var : this.varKind\n const rhs = this.rhs === undefined ? \"\" : ` = ${this.rhs}`\n return `${varKind} ${this.name}${rhs};` + _n\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!names[this.name.str]) return\n if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return this.rhs instanceof _CodeOrName ? this.rhs.names : {}\n }\n}\n\nclass Assign extends Node {\n constructor(\n readonly lhs: Code,\n public rhs: SafeExpr,\n private readonly sideEffects?: boolean\n ) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.lhs} = ${this.rhs};` + _n\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return\n this.rhs = optimizeExpr(this.rhs, names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = this.lhs instanceof Name ? {} : {...this.lhs.names}\n return addExprNames(names, this.rhs)\n }\n}\n\nclass AssignOp extends Assign {\n constructor(\n lhs: Code,\n private readonly op: Code,\n rhs: SafeExpr,\n sideEffects?: boolean\n ) {\n super(lhs, rhs, sideEffects)\n }\n\n render({_n}: CGOptions): string {\n return `${this.lhs} ${this.op}= ${this.rhs};` + _n\n }\n}\n\nclass Label extends Node {\n readonly names: UsedNames = {}\n constructor(readonly label: Name) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.label}:` + _n\n }\n}\n\nclass Break extends Node {\n readonly names: UsedNames = {}\n constructor(readonly label?: Code) {\n super()\n }\n\n render({_n}: CGOptions): string {\n const label = this.label ? ` ${this.label}` : \"\"\n return `break${label};` + _n\n }\n}\n\nclass Throw extends Node {\n constructor(readonly error: Code) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `throw ${this.error};` + _n\n }\n\n get names(): UsedNames {\n return this.error.names\n }\n}\n\nclass AnyCode extends Node {\n constructor(private code: SafeExpr) {\n super()\n }\n\n render({_n}: CGOptions): string {\n return `${this.code};` + _n\n }\n\n optimizeNodes(): this | undefined {\n return `${this.code}` ? this : undefined\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this {\n this.code = optimizeExpr(this.code, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return this.code instanceof _CodeOrName ? this.code.names : {}\n }\n}\n\nabstract class ParentNode extends Node {\n constructor(readonly nodes: ChildNode[] = []) {\n super()\n }\n\n render(opts: CGOptions): string {\n return this.nodes.reduce((code, n) => code + n.render(opts), \"\")\n }\n\n optimizeNodes(): this | ChildNode | ChildNode[] | undefined {\n const {nodes} = this\n let i = nodes.length\n while (i--) {\n const n = nodes[i].optimizeNodes()\n if (Array.isArray(n)) nodes.splice(i, 1, ...n)\n else if (n) nodes[i] = n\n else nodes.splice(i, 1)\n }\n return nodes.length > 0 ? this : undefined\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n const {nodes} = this\n let i = nodes.length\n while (i--) {\n // iterating backwards improves 1-pass optimization\n const n = nodes[i]\n if (n.optimizeNames(names, constants)) continue\n subtractNames(names, n.names)\n nodes.splice(i, 1)\n }\n return nodes.length > 0 ? this : undefined\n }\n\n get names(): UsedNames {\n return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {})\n }\n\n // get count(): number {\n // return this.nodes.reduce((c, n) => c + n.count, 1)\n // }\n}\n\nabstract class BlockNode extends ParentNode {\n render(opts: CGOptions): string {\n return \"{\" + opts._n + super.render(opts) + \"}\" + opts._n\n }\n}\n\nclass Root extends ParentNode {}\n\nclass Else extends BlockNode {\n static readonly kind = \"else\"\n}\n\nclass If extends BlockNode {\n static readonly kind = \"if\"\n else?: If | Else\n constructor(\n private condition: Code | boolean,\n nodes?: ChildNode[]\n ) {\n super(nodes)\n }\n\n render(opts: CGOptions): string {\n let code = `if(${this.condition})` + super.render(opts)\n if (this.else) code += \"else \" + this.else.render(opts)\n return code\n }\n\n optimizeNodes(): If | ChildNode[] | undefined {\n super.optimizeNodes()\n const cond = this.condition\n if (cond === true) return this.nodes // else is ignored here\n let e = this.else\n if (e) {\n const ns = e.optimizeNodes()\n e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined)\n }\n if (e) {\n if (cond === false) return e instanceof If ? e : e.nodes\n if (this.nodes.length) return this\n return new If(not(cond), e instanceof If ? [e] : e.nodes)\n }\n if (cond === false || !this.nodes.length) return undefined\n return this\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n this.else = this.else?.optimizeNames(names, constants)\n if (!(super.optimizeNames(names, constants) || this.else)) return\n this.condition = optimizeExpr(this.condition, names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = super.names\n addExprNames(names, this.condition)\n if (this.else) addNames(names, this.else.names)\n return names\n }\n\n // get count(): number {\n // return super.count + (this.else?.count || 0)\n // }\n}\n\nabstract class For extends BlockNode {\n static readonly kind = \"for\"\n}\n\nclass ForLoop extends For {\n constructor(private iteration: Code) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `for(${this.iteration})` + super.render(opts)\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!super.optimizeNames(names, constants)) return\n this.iteration = optimizeExpr(this.iteration, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return addNames(super.names, this.iteration.names)\n }\n}\n\nclass ForRange extends For {\n constructor(\n private readonly varKind: Name,\n private readonly name: Name,\n private readonly from: SafeExpr,\n private readonly to: SafeExpr\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n const varKind = opts.es5 ? varKinds.var : this.varKind\n const {name, from, to} = this\n return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts)\n }\n\n get names(): UsedNames {\n const names = addExprNames(super.names, this.from)\n return addExprNames(names, this.to)\n }\n}\n\nclass ForIter extends For {\n constructor(\n private readonly loop: \"of\" | \"in\",\n private readonly varKind: Name,\n private readonly name: Name,\n private iterable: Code\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts)\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this | undefined {\n if (!super.optimizeNames(names, constants)) return\n this.iterable = optimizeExpr(this.iterable, names, constants)\n return this\n }\n\n get names(): UsedNames {\n return addNames(super.names, this.iterable.names)\n }\n}\n\nclass Func extends BlockNode {\n static readonly kind = \"func\"\n constructor(\n public name: Name,\n public args: Code,\n public async?: boolean\n ) {\n super()\n }\n\n render(opts: CGOptions): string {\n const _async = this.async ? \"async \" : \"\"\n return `${_async}function ${this.name}(${this.args})` + super.render(opts)\n }\n}\n\nclass Return extends ParentNode {\n static readonly kind = \"return\"\n\n render(opts: CGOptions): string {\n return \"return \" + super.render(opts)\n }\n}\n\nclass Try extends BlockNode {\n catch?: Catch\n finally?: Finally\n\n render(opts: CGOptions): string {\n let code = \"try\" + super.render(opts)\n if (this.catch) code += this.catch.render(opts)\n if (this.finally) code += this.finally.render(opts)\n return code\n }\n\n optimizeNodes(): this {\n super.optimizeNodes()\n this.catch?.optimizeNodes() as Catch | undefined\n this.finally?.optimizeNodes() as Finally | undefined\n return this\n }\n\n optimizeNames(names: UsedNames, constants: Constants): this {\n super.optimizeNames(names, constants)\n this.catch?.optimizeNames(names, constants)\n this.finally?.optimizeNames(names, constants)\n return this\n }\n\n get names(): UsedNames {\n const names = super.names\n if (this.catch) addNames(names, this.catch.names)\n if (this.finally) addNames(names, this.finally.names)\n return names\n }\n\n // get count(): number {\n // return super.count + (this.catch?.count || 0) + (this.finally?.count || 0)\n // }\n}\n\nclass Catch extends BlockNode {\n static readonly kind = \"catch\"\n constructor(readonly error: Name) {\n super()\n }\n\n render(opts: CGOptions): string {\n return `catch(${this.error})` + super.render(opts)\n }\n}\n\nclass Finally extends BlockNode {\n static readonly kind = \"finally\"\n render(opts: CGOptions): string {\n return \"finally\" + super.render(opts)\n }\n}\n\ntype StartBlockNode = If | For | Func | Return | Try\n\ntype LeafNode = Def | Assign | Label | Break | Throw | AnyCode\n\ntype ChildNode = StartBlockNode | LeafNode\n\ntype EndBlockNodeType =\n | typeof If\n | typeof Else\n | typeof For\n | typeof Func\n | typeof Return\n | typeof Catch\n | typeof Finally\n\ntype Constants = Record<string, SafeExpr | undefined>\n\nexport interface CodeGenOptions {\n es5?: boolean\n lines?: boolean\n ownProperties?: boolean\n}\n\ninterface CGOptions extends CodeGenOptions {\n _n: \"\\n\" | \"\"\n}\n\nexport class CodeGen {\n readonly _scope: Scope\n readonly _extScope: ValueScope\n readonly _values: ScopeValueSets = {}\n private readonly _nodes: ParentNode[]\n private readonly _blockStarts: number[] = []\n private readonly _constants: Constants = {}\n private readonly opts: CGOptions\n\n constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {\n this.opts = {...opts, _n: opts.lines ? \"\\n\" : \"\"}\n this._extScope = extScope\n this._scope = new Scope({parent: extScope})\n this._nodes = [new Root()]\n }\n\n toString(): string {\n return this._root.render(this.opts)\n }\n\n // returns unique name in the internal scope\n name(prefix: string): Name {\n return this._scope.name(prefix)\n }\n\n // reserves unique name in the external scope\n scopeName(prefix: string): ValueScopeName {\n return this._extScope.name(prefix)\n }\n\n // reserves unique name in the external scope and assigns value to it\n scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {\n const name = this._extScope.value(prefixOrName, value)\n const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())\n vs.add(name)\n return name\n }\n\n getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {\n return this._extScope.getValue(prefix, keyOrRef)\n }\n\n // return code that assigns values in the external scope to the names that are used internally\n // (same names that were returned by gen.scopeName or gen.scopeValue)\n scopeRefs(scopeName: Name): Code {\n return this._extScope.scopeRefs(scopeName, this._values)\n }\n\n scopeCode(): Code {\n return this._extScope.scopeCode(this._values)\n }\n\n private _def(\n varKind: Name,\n nameOrPrefix: Name | string,\n rhs?: SafeExpr,\n constant?: boolean\n ): Name {\n const name = this._scope.toName(nameOrPrefix)\n if (rhs !== undefined && constant) this._constants[name.str] = rhs\n this._leafNode(new Def(varKind, name, rhs))\n return name\n }\n\n // `const` declaration (`var` in es5 mode)\n const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.const, nameOrPrefix, rhs, _constant)\n }\n\n // `let` declaration with optional assignment (`var` in es5 mode)\n let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.let, nameOrPrefix, rhs, _constant)\n }\n\n // `var` declaration with optional assignment\n var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {\n return this._def(varKinds.var, nameOrPrefix, rhs, _constant)\n }\n\n // assignment code\n assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {\n return this._leafNode(new Assign(lhs, rhs, sideEffects))\n }\n\n // `+=` code\n add(lhs: Code, rhs: SafeExpr): CodeGen {\n return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))\n }\n\n // appends passed SafeExpr to code or executes Block\n code(c: Block | SafeExpr): CodeGen {\n if (typeof c == \"function\") c()\n else if (c !== nil) this._leafNode(new AnyCode(c))\n return this\n }\n\n // returns code for object literal for the passed argument list of key-value pairs\n object(...keyValues: [Name | string, SafeExpr | string][]): _Code {\n const code: CodeItem[] = [\"{\"]\n for (const [key, value] of keyValues) {\n if (code.length > 1) code.push(\",\")\n code.push(key)\n if (key !== value || this.opts.es5) {\n code.push(\":\")\n addCodeArg(code, value)\n }\n }\n code.push(\"}\")\n return new _Code(code)\n }\n\n // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)\n if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {\n this._blockNode(new If(condition))\n\n if (thenBody && elseBody) {\n this.code(thenBody).else().code(elseBody).endIf()\n } else if (thenBody) {\n this.code(thenBody).endIf()\n } else if (elseBody) {\n throw new Error('CodeGen: \"else\" body without \"then\" body')\n }\n return this\n }\n\n // `else if` clause - invalid without `if` or after `else` clauses\n elseIf(condition: Code | boolean): CodeGen {\n return this._elseNode(new If(condition))\n }\n\n // `else` clause - only valid after `if` or `else if` clauses\n else(): CodeGen {\n return this._elseNode(new Else())\n }\n\n // end `if` statement (needed if gen.if was used only with condition)\n endIf(): CodeGen {\n return this._endBlockNode(If, Else)\n }\n\n private _for(node: For, forBody?: Block): CodeGen {\n this._blockNode(node)\n if (forBody) this.code(forBody).endFor()\n return this\n }\n\n // a generic `for` clause (or statement if `forBody` is passed)\n for(iteration: Code, forBody?: Block): CodeGen {\n return this._for(new ForLoop(iteration), forBody)\n }\n\n // `for` statement for a range of values\n forRange(\n nameOrPrefix: Name | string,\n from: SafeExpr,\n to: SafeExpr,\n forBody: (index: Name) => void,\n varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let\n ): CodeGen {\n const name = this._scope.toName(nameOrPrefix)\n return this._for(new ForRange(varKind, name, from, to), () => forBody(name))\n }\n\n // `for-of` statement (in es5 mode replace with a normal for loop)\n forOf(\n nameOrPrefix: Name | string,\n iterable: Code,\n forBody: (item: Name) => void,\n varKind: Code = varKinds.const\n ): CodeGen {\n const name = this._scope.toName(nameOrPrefix)\n if (this.opts.es5) {\n const arr = iterable instanceof Name ? iterable : this.var(\"_arr\", iterable)\n return this.forRange(\"_i\", 0, _`${arr}.length`, (i) => {\n this.var(name, _`${arr}[${i}]`)\n forBody(name)\n })\n }\n return this._for(new ForIter(\"of\", varKind, name, iterable), () => forBody(name))\n }\n\n // `for-in` statement.\n // With option `ownProperties` replaced with a `for-of` loop for object keys\n forIn(\n nameOrPrefix: Name | string,\n obj: Code,\n forBody: (item: Name) => void,\n varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const\n ): CodeGen {\n if (this.opts.ownProperties) {\n return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)\n }\n const name = this._scope.toName(nameOrPrefix)\n return this._for(new ForIter(\"in\", varKind, name, obj), () => forBody(name))\n }\n\n // end `for` loop\n endFor(): CodeGen {\n return this._endBlockNode(For)\n }\n\n // `label` statement\n label(label: Name): CodeGen {\n return this._leafNode(new Label(label))\n }\n\n // `break` statement\n break(label?: Code): CodeGen {\n return this._leafNode(new Break(label))\n }\n\n // `return` statement\n return(value: Block | SafeExpr): CodeGen {\n const node = new Return()\n this._blockNode(node)\n this.code(value)\n if (node.nodes.length !== 1) throw new Error('CodeGen: \"return\" should have one node')\n return this._endBlockNode(Return)\n }\n\n // `try` statement\n try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {\n if (!catchCode && !finallyCode) throw new Error('CodeGen: \"try\" without \"catch\" and \"finally\"')\n const node = new Try()\n this._blockNode(node)\n this.code(tryBody)\n if (catchCode) {\n const error = this.name(\"e\")\n this._currNode = node.catch = new Catch(error)\n catchCode(error)\n }\n if (finallyCode) {\n this._currNode = node.finally = new Finally()\n this.code(finallyCode)\n }\n return this._endBlockNode(Catch, Finally)\n }\n\n // `throw` statement\n throw(error: Code): CodeGen {\n return this._leafNode(new Throw(error))\n }\n\n // start self-balancing block\n block(body?: Block, nodeCount?: number): CodeGen {\n this._blockStarts.push(this._nodes.length)\n if (body) this.code(body).endBlock(nodeCount)\n return this\n }\n\n // end the current self-balancing block\n endBlock(nodeCount?: number): CodeGen {\n const len = this._blockStarts.pop()\n if (len === undefined) throw new Error(\"CodeGen: not in self-balancing block\")\n const toClose = this._nodes.length - len\n if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {\n throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)\n }\n this._nodes.length = len\n return this\n }\n\n // `function` heading (or definition if funcBody is passed)\n func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {\n this._blockNode(new Func(name, args, async))\n if (funcBody) this.code(funcBody).endFunc()\n return this\n }\n\n // end function definition\n endFunc(): CodeGen {\n return this._endBlockNode(Func)\n }\n\n optimize(n = 1): void {\n while (n-- > 0) {\n this._root.optimizeNodes()\n this._root.optimizeNames(this._root.names, this._constants)\n }\n }\n\n private _leafNode(node: LeafNode): CodeGen {\n this._currNode.nodes.push(node)\n return this\n }\n\n private _blockNode(node: StartBlockNode): void {\n this._currNode.nodes.push(node)\n this._nodes.push(node)\n }\n\n private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {\n const n = this._currNode\n if (n instanceof N1 || (N2 && n instanceof N2)) {\n this._nodes.pop()\n return this\n }\n throw new Error(`CodeGen: not in block \"${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}\"`)\n }\n\n private _elseNode(node: If | Else): CodeGen {\n const n = this._currNode\n if (!(n instanceof If)) {\n throw new Error('CodeGen: \"else\" without \"if\"')\n }\n this._currNode = n.else = node\n return this\n }\n\n private get _root(): Root {\n return this._nodes[0] as Root\n }\n\n private get _currNode(): ParentNode {\n const ns = this._nodes\n return ns[ns.length - 1]\n }\n\n private set _currNode(node: ParentNode) {\n const ns = this._nodes\n ns[ns.length - 1] = node\n }\n\n // get nodeCount(): number {\n // return this._root.count\n // }\n}\n\nfunction addNames(names: UsedNames, from: UsedNames): UsedNames {\n for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0)\n return names\n}\n\nfunction addExprNames(names: UsedNames, from: SafeExpr): UsedNames {\n return from instanceof _CodeOrName ? addNames(names, from.names) : names\n}\n\nfunction optimizeExpr<T extends SafeExpr | Code>(expr: T, names: UsedNames, constants: Constants): T\nfunction optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {\n if (expr instanceof Name) return replaceName(expr)\n if (!canOptimize(expr)) return expr\n return new _Code(\n expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {\n if (c instanceof Name) c = replaceName(c)\n if (c instanceof _Code) items.push(...c._items)\n else items.push(c)\n return items\n }, [])\n )\n\n function replaceName(n: Name): SafeExpr {\n const c = constants[n.str]\n if (c === undefined || names[n.str] !== 1) return n\n delete names[n.str]\n return c\n }\n\n function canOptimize(e: SafeExpr): e is _Code {\n return (\n e instanceof _Code &&\n e._items.some(\n (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined\n )\n )\n }\n}\n\nfunction subtractNames(names: UsedNames, from: UsedNames): void {\n for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0)\n}\n\nexport function not<T extends Code | SafeExpr>(x: T): T\nexport function not(x: Code | SafeExpr): Code | SafeExpr {\n return typeof x == \"boolean\" || typeof x == \"number\" || x === null ? !x : _`!${par(x)}`\n}\n\nconst andCode = mappend(operators.AND)\n\n// boolean AND (&&) expression with the passed arguments\nexport function and(...args: Code[]): Code {\n return args.reduce(andCode)\n}\n\nconst orCode = mappend(operators.OR)\n\n// boolean OR (||) expression with the passed arguments\nexport function or(...args: Code[]): Code {\n return args.reduce(orCode)\n}\n\ntype MAppend = (x: Code, y: Code) => Code\n\nfunction mappend(op: Code): MAppend {\n return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`)\n}\n\nfunction par(x: Code): Code {\n return x instanceof Name ? x : _`(${x})`\n}\n", "import type {AnySchema, EvaluatedProperties, EvaluatedItems} from \"../types\"\nimport type {SchemaCxt, SchemaObjCxt} from \".\"\nimport {_, getProperty, Code, Name, CodeGen} from \"./codegen\"\nimport {_Code} from \"./codegen/code\"\nimport type {Rule, ValidationRules} from \"./rules\"\n\n// TODO refactor to use Set\nexport function toHash<T extends string = string>(arr: T[]): {[K in T]?: true} {\n const hash: {[K in T]?: true} = {}\n for (const item of arr) hash[item] = true\n return hash\n}\n\nexport function alwaysValidSchema(it: SchemaCxt, schema: AnySchema): boolean | void {\n if (typeof schema == \"boolean\") return schema\n if (Object.keys(schema).length === 0) return true\n checkUnknownRules(it, schema)\n return !schemaHasRules(schema, it.self.RULES.all)\n}\n\nexport function checkUnknownRules(it: SchemaCxt, schema: AnySchema = it.schema): void {\n const {opts, self} = it\n if (!opts.strictSchema) return\n if (typeof schema === \"boolean\") return\n const rules = self.RULES.keywords\n for (const key in schema) {\n if (!rules[key]) checkStrictMode(it, `unknown keyword: \"${key}\"`)\n }\n}\n\nexport function schemaHasRules(\n schema: AnySchema,\n rules: {[Key in string]?: boolean | Rule}\n): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (rules[key]) return true\n return false\n}\n\nexport function schemaHasRulesButRef(schema: AnySchema, RULES: ValidationRules): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (key !== \"$ref\" && RULES.all[key]) return true\n return false\n}\n\nexport function schemaRefOrVal(\n {topSchemaRef, schemaPath}: SchemaObjCxt,\n schema: unknown,\n keyword: string,\n $data?: string | false\n): Code | number | boolean {\n if (!$data) {\n if (typeof schema == \"number\" || typeof schema == \"boolean\") return schema\n if (typeof schema == \"string\") return _`${schema}`\n }\n return _`${topSchemaRef}${schemaPath}${getProperty(keyword)}`\n}\n\nexport function unescapeFragment(str: string): string {\n return unescapeJsonPointer(decodeURIComponent(str))\n}\n\nexport function escapeFragment(str: string | number): string {\n return encodeURIComponent(escapeJsonPointer(str))\n}\n\nexport function escapeJsonPointer(str: string | number): string {\n if (typeof str == \"number\") return `${str}`\n return str.replace(/~/g, \"~0\").replace(/\\//g, \"~1\")\n}\n\nexport function unescapeJsonPointer(str: string): string {\n return str.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n}\n\nexport function eachItem<T>(xs: T | T[], f: (x: T) => void): void {\n if (Array.isArray(xs)) {\n for (const x of xs) f(x)\n } else {\n f(xs)\n }\n}\n\ntype SomeEvaluated = EvaluatedProperties | EvaluatedItems\n\ntype MergeEvaluatedFunc<T extends SomeEvaluated> = (\n gen: CodeGen,\n from: Name | T,\n to: Name | Exclude<T, true> | undefined,\n toName?: typeof Name\n) => Name | T\n\ninterface MakeMergeFuncArgs<T extends SomeEvaluated> {\n mergeNames: (gen: CodeGen, from: Name, to: Name) => void\n mergeToName: (gen: CodeGen, from: T, to: Name) => void\n mergeValues: (from: T, to: Exclude<T, true>) => T\n resultToName: (gen: CodeGen, res?: T) => Name\n}\n\nfunction makeMergeEvaluated<T extends SomeEvaluated>({\n mergeNames,\n mergeToName,\n mergeValues,\n resultToName,\n}: MakeMergeFuncArgs<T>): MergeEvaluatedFunc<T> {\n return (gen, from, to, toName) => {\n const res =\n to === undefined\n ? from\n : to instanceof Name\n ? (from instanceof Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)\n : from instanceof Name\n ? (mergeToName(gen, to, from), from)\n : mergeValues(from, to)\n return toName === Name && !(res instanceof Name) ? resultToName(gen, res) : res\n }\n}\n\ninterface MergeEvaluated {\n props: MergeEvaluatedFunc<EvaluatedProperties>\n items: MergeEvaluatedFunc<EvaluatedItems>\n}\n\nexport const mergeEvaluated: MergeEvaluated = {\n props: makeMergeEvaluated({\n mergeNames: (gen, from, to) =>\n gen.if(_`${to} !== true && ${from} !== undefined`, () => {\n gen.if(\n _`${from} === true`,\n () => gen.assign(to, true),\n () => gen.assign(to, _`${to} || {}`).code(_`Object.assign(${to}, ${from})`)\n )\n }),\n mergeToName: (gen, from, to) =>\n gen.if(_`${to} !== true`, () => {\n if (from === true) {\n gen.assign(to, true)\n } else {\n gen.assign(to, _`${to} || {}`)\n setEvaluated(gen, to, from)\n }\n }),\n mergeValues: (from, to) => (from === true ? true : {...from, ...to}),\n resultToName: evaluatedPropsToName,\n }),\n items: makeMergeEvaluated({\n mergeNames: (gen, from, to) =>\n gen.if(_`${to} !== true && ${from} !== undefined`, () =>\n gen.assign(to, _`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)\n ),\n mergeToName: (gen, from, to) =>\n gen.if(_`${to} !== true`, () =>\n gen.assign(to, from === true ? true : _`${to} > ${from} ? ${to} : ${from}`)\n ),\n mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),\n resultToName: (gen, items) => gen.var(\"items\", items),\n }),\n}\n\nexport function evaluatedPropsToName(gen: CodeGen, ps?: EvaluatedProperties): Name {\n if (ps === true) return gen.var(\"props\", true)\n const props = gen.var(\"props\", _`{}`)\n if (ps !== undefined) setEvaluated(gen, props, ps)\n return props\n}\n\nexport function setEvaluated(gen: CodeGen, props: Name, ps: {[K in string]?: true}): void {\n Object.keys(ps).forEach((p) => gen.assign(_`${props}${getProperty(p)}`, true))\n}\n\nconst snippets: {[S in string]?: _Code} = {}\n\nexport function useFunc(gen: CodeGen, f: {code: string}): Name {\n return gen.scopeValue(\"func\", {\n ref: f,\n code: snippets[f.code] || (snippets[f.code] = new _Code(f.code)),\n })\n}\n\nexport enum Type {\n Num,\n Str,\n}\n\nexport function getErrorPath(\n dataProp: Name | string | number,\n dataPropType?: Type,\n jsPropertySyntax?: boolean\n): Code | string {\n // let path\n if (dataProp instanceof Name) {\n const isNumber = dataPropType === Type.Num\n return jsPropertySyntax\n ? isNumber\n ? _`\"[\" + ${dataProp} + \"]\"`\n : _`\"['\" + ${dataProp} + \"']\"`\n : isNumber\n ? _`\"/\" + ${dataProp}`\n : _`\"/\" + ${dataProp}.replace(/~/g, \"~0\").replace(/\\\\//g, \"~1\")` // TODO maybe use global escapePointer\n }\n return jsPropertySyntax ? getProperty(dataProp).toString() : \"/\" + escapeJsonPointer(dataProp)\n}\n\nexport function checkStrictMode(\n it: SchemaCxt,\n msg: string,\n mode: boolean | \"log\" = it.opts.strictSchema\n): void {\n if (!mode) return\n msg = `strict mode: ${msg}`\n if (mode === true) throw new Error(msg)\n it.self.logger.warn(msg)\n}\n", "import {Name} from \"./codegen\"\n\nconst names = {\n // validation function arguments\n data: new Name(\"data\"), // data passed to validation function\n // args passed from referencing schema\n valCxt: new Name(\"valCxt\"), // validation/data context - should not be used directly, it is destructured to the names below\n instancePath: new Name(\"instancePath\"),\n parentData: new Name(\"parentData\"),\n parentDataProperty: new Name(\"parentDataProperty\"),\n rootData: new Name(\"rootData\"), // root data - same as the data passed to the first/top validation function\n dynamicAnchors: new Name(\"dynamicAnchors\"), // used to support recursiveRef and dynamicRef\n // function scoped variables\n vErrors: new Name(\"vErrors\"), // null or array of validation errors\n errors: new Name(\"errors\"), // counter of validation errors\n this: new Name(\"this\"),\n // \"globals\"\n self: new Name(\"self\"),\n scope: new Name(\"scope\"),\n // JTD serialize/parse name for JSON string and position\n json: new Name(\"json\"),\n jsonPos: new Name(\"jsonPos\"),\n jsonLen: new Name(\"jsonLen\"),\n jsonPart: new Name(\"jsonPart\"),\n}\n\nexport default names\n", "import type {KeywordErrorCxt, KeywordErrorDefinition} from \"../types\"\nimport type {SchemaCxt} from \"./index\"\nimport {CodeGen, _, str, strConcat, Code, Name} from \"./codegen\"\nimport {SafeExpr} from \"./codegen/code\"\nimport {getErrorPath, Type} from \"./util\"\nimport N from \"./names\"\n\nexport const keywordError: KeywordErrorDefinition = {\n message: ({keyword}) => str`must pass \"${keyword}\" keyword validation`,\n}\n\nexport const keyword$DataError: KeywordErrorDefinition = {\n message: ({keyword, schemaType}) =>\n schemaType\n ? str`\"${keyword}\" keyword must be ${schemaType} ($data)`\n : str`\"${keyword}\" keyword is invalid ($data)`,\n}\n\nexport interface ErrorPaths {\n instancePath?: Code\n schemaPath?: string\n parentSchema?: boolean\n}\n\nexport function reportError(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition = keywordError,\n errorPaths?: ErrorPaths,\n overrideAllErrors?: boolean\n): void {\n const {it} = cxt\n const {gen, compositeRule, allErrors} = it\n const errObj = errorObjectCode(cxt, error, errorPaths)\n if (overrideAllErrors ?? (compositeRule || allErrors)) {\n addError(gen, errObj)\n } else {\n returnErrors(it, _`[${errObj}]`)\n }\n}\n\nexport function reportExtraError(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition = keywordError,\n errorPaths?: ErrorPaths\n): void {\n const {it} = cxt\n const {gen, compositeRule, allErrors} = it\n const errObj = errorObjectCode(cxt, error, errorPaths)\n addError(gen, errObj)\n if (!(compositeRule || allErrors)) {\n returnErrors(it, N.vErrors)\n }\n}\n\nexport function resetErrorsCount(gen: CodeGen, errsCount: Name): void {\n gen.assign(N.errors, errsCount)\n gen.if(_`${N.vErrors} !== null`, () =>\n gen.if(\n errsCount,\n () => gen.assign(_`${N.vErrors}.length`, errsCount),\n () => gen.assign(N.vErrors, null)\n )\n )\n}\n\nexport function extendErrors({\n gen,\n keyword,\n schemaValue,\n data,\n errsCount,\n it,\n}: KeywordErrorCxt): void {\n /* istanbul ignore if */\n if (errsCount === undefined) throw new Error(\"ajv implementation error\")\n const err = gen.name(\"err\")\n gen.forRange(\"i\", errsCount, N.errors, (i) => {\n gen.const(err, _`${N.vErrors}[${i}]`)\n gen.if(_`${err}.instancePath === undefined`, () =>\n gen.assign(_`${err}.instancePath`, strConcat(N.instancePath, it.errorPath))\n )\n gen.assign(_`${err}.schemaPath`, str`${it.errSchemaPath}/${keyword}`)\n if (it.opts.verbose) {\n gen.assign(_`${err}.schema`, schemaValue)\n gen.assign(_`${err}.data`, data)\n }\n })\n}\n\nfunction addError(gen: CodeGen, errObj: Code): void {\n const err = gen.const(\"err\", errObj)\n gen.if(\n _`${N.vErrors} === null`,\n () => gen.assign(N.vErrors, _`[${err}]`),\n _`${N.vErrors}.push(${err})`\n )\n gen.code(_`${N.errors}++`)\n}\n\nfunction returnErrors(it: SchemaCxt, errs: Code): void {\n const {gen, validateName, schemaEnv} = it\n if (schemaEnv.$async) {\n gen.throw(_`new ${it.ValidationError as Name}(${errs})`)\n } else {\n gen.assign(_`${validateName}.errors`, errs)\n gen.return(false)\n }\n}\n\nconst E = {\n keyword: new Name(\"keyword\"),\n schemaPath: new Name(\"schemaPath\"), // also used in JTD errors\n params: new Name(\"params\"),\n propertyName: new Name(\"propertyName\"),\n message: new Name(\"message\"),\n schema: new Name(\"schema\"),\n parentSchema: new Name(\"parentSchema\"),\n}\n\nfunction errorObjectCode(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition,\n errorPaths?: ErrorPaths\n): Code {\n const {createErrors} = cxt.it\n if (createErrors === false) return _`{}`\n return errorObject(cxt, error, errorPaths)\n}\n\nfunction errorObject(\n cxt: KeywordErrorCxt,\n error: KeywordErrorDefinition,\n errorPaths: ErrorPaths = {}\n): Code {\n const {gen, it} = cxt\n const keyValues: [Name, SafeExpr | string][] = [\n errorInstancePath(it, errorPaths),\n errorSchemaPath(cxt, errorPaths),\n ]\n extraErrorProps(cxt, error, keyValues)\n return gen.object(...keyValues)\n}\n\nfunction errorInstancePath({errorPath}: SchemaCxt, {instancePath}: ErrorPaths): [Name, Code] {\n const instPath = instancePath\n ? str`${errorPath}${getErrorPath(instancePath, Type.Str)}`\n : errorPath\n return [N.instancePath, strConcat(N.instancePath, instPath)]\n}\n\nfunction errorSchemaPath(\n {keyword, it: {errSchemaPath}}: KeywordErrorCxt,\n {schemaPath, parentSchema}: ErrorPaths\n): [Name, string | Code] {\n let schPath = parentSchema ? errSchemaPath : str`${errSchemaPath}/${keyword}`\n if (schemaPath) {\n schPath = str`${schPath}${getErrorPath(schemaPath, Type.Str)}`\n }\n return [E.schemaPath, schPath]\n}\n\nfunction extraErrorProps(\n cxt: KeywordErrorCxt,\n {params, message}: KeywordErrorDefinition,\n keyValues: [Name, SafeExpr | string][]\n): void {\n const {keyword, data, schemaValue, it} = cxt\n const {opts, propertyName, topSchemaRef, schemaPath} = it\n keyValues.push(\n [E.keyword, keyword],\n [E.params, typeof params == \"function\" ? params(cxt) : params || _`{}`]\n )\n if (opts.messages) {\n keyValues.push([E.message, typeof message == \"function\" ? message(cxt) : message])\n }\n if (opts.verbose) {\n keyValues.push(\n [E.schema, schemaValue],\n [E.parentSchema, _`${topSchemaRef}${schemaPath}`],\n [N.data, data]\n )\n }\n if (propertyName) keyValues.push([E.propertyName, propertyName])\n}\n", "import type {KeywordErrorDefinition, KeywordErrorCxt} from \"../../types\"\nimport type {SchemaCxt} from \"..\"\nimport {reportError} from \"../errors\"\nimport {_, Name} from \"../codegen\"\nimport N from \"../names\"\n\nconst boolError: KeywordErrorDefinition = {\n message: \"boolean schema is false\",\n}\n\nexport function topBoolOrEmptySchema(it: SchemaCxt): void {\n const {gen, schema, validateName} = it\n if (schema === false) {\n falseSchemaError(it, false)\n } else if (typeof schema == \"object\" && schema.$async === true) {\n gen.return(N.data)\n } else {\n gen.assign(_`${validateName}.errors`, null)\n gen.return(true)\n }\n}\n\nexport function boolOrEmptySchema(it: SchemaCxt, valid: Name): void {\n const {gen, schema} = it\n if (schema === false) {\n gen.var(valid, false) // TODO var\n falseSchemaError(it)\n } else {\n gen.var(valid, true) // TODO var\n }\n}\n\nfunction falseSchemaError(it: SchemaCxt, overrideAllErrors?: boolean): void {\n const {gen, data} = it\n // TODO maybe some other interface should be used for non-keyword validation errors...\n const cxt: KeywordErrorCxt = {\n gen,\n keyword: \"false schema\",\n data,\n schema: false,\n schemaCode: false,\n schemaValue: false,\n params: {},\n it,\n }\n reportError(cxt, boolError, undefined, overrideAllErrors)\n}\n", "import type {AddedKeywordDefinition} from \"../types\"\n\nconst _jsonTypes = [\"string\", \"number\", \"integer\", \"boolean\", \"null\", \"object\", \"array\"] as const\n\nexport type JSONType = (typeof _jsonTypes)[number]\n\nconst jsonTypes: Set<string> = new Set(_jsonTypes)\n\nexport function isJSONType(x: unknown): x is JSONType {\n return typeof x == \"string\" && jsonTypes.has(x)\n}\n\ntype ValidationTypes = {\n [K in JSONType]: boolean | RuleGroup | undefined\n}\n\nexport interface ValidationRules {\n rules: RuleGroup[]\n post: RuleGroup\n all: {[Key in string]?: boolean | Rule} // rules that have to be validated\n keywords: {[Key in string]?: boolean} // all known keywords (superset of \"all\")\n types: ValidationTypes\n}\n\nexport interface RuleGroup {\n type?: JSONType\n rules: Rule[]\n}\n\n// This interface wraps KeywordDefinition because definition can have multiple keywords\nexport interface Rule {\n keyword: string\n definition: AddedKeywordDefinition\n}\n\nexport function getRules(): ValidationRules {\n const groups: Record<\"number\" | \"string\" | \"array\" | \"object\", RuleGroup> = {\n number: {type: \"number\", rules: []},\n string: {type: \"string\", rules: []},\n array: {type: \"array\", rules: []},\n object: {type: \"object\", rules: []},\n }\n return {\n types: {...groups, integer: true, boolean: true, null: true},\n rules: [{rules: []}, groups.number, groups.string, groups.array, groups.object],\n post: {rules: []},\n all: {},\n keywords: {},\n }\n}\n", "import type {AnySchemaObject} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport type {JSONType, RuleGroup, Rule} from \"../rules\"\n\nexport function schemaHasRulesForType(\n {schema, self}: SchemaObjCxt,\n type: JSONType\n): boolean | undefined {\n const group = self.RULES.types[type]\n return group && group !== true && shouldUseGroup(schema, group)\n}\n\nexport function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean {\n return group.rules.some((rule) => shouldUseRule(schema, rule))\n}\n\nexport function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined {\n return (\n schema[rule.keyword] !== undefined ||\n rule.definition.implements?.some((kwd) => schema[kwd] !== undefined)\n )\n}\n", "import type {\n KeywordErrorDefinition,\n KeywordErrorCxt,\n ErrorObject,\n AnySchemaObject,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {isJSONType, JSONType} from \"../rules\"\nimport {schemaHasRulesForType} from \"./applicability\"\nimport {reportError} from \"../errors\"\nimport {_, nil, and, not, operators, Code, Name} from \"../codegen\"\nimport {toHash, schemaRefOrVal} from \"../util\"\n\nexport enum DataType {\n Correct,\n Wrong,\n}\n\nexport function getSchemaTypes(schema: AnySchemaObject): JSONType[] {\n const types = getJSONTypes(schema.type)\n const hasNull = types.includes(\"null\")\n if (hasNull) {\n if (schema.nullable === false) throw new Error(\"type: null contradicts nullable: false\")\n } else {\n if (!types.length && schema.nullable !== undefined) {\n throw new Error('\"nullable\" cannot be used without \"type\"')\n }\n if (schema.nullable === true) types.push(\"null\")\n }\n return types\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\nexport function getJSONTypes(ts: unknown | unknown[]): JSONType[] {\n const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : []\n if (types.every(isJSONType)) return types\n throw new Error(\"type must be JSONType or JSONType[]: \" + types.join(\",\"))\n}\n\nexport function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean {\n const {gen, data, opts} = it\n const coerceTo = coerceToTypes(types, opts.coerceTypes)\n const checkTypes =\n types.length > 0 &&\n !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0]))\n if (checkTypes) {\n const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong)\n gen.if(wrongType, () => {\n if (coerceTo.length) coerceData(it, types, coerceTo)\n else reportTypeError(it)\n })\n }\n return checkTypes\n}\n\nconst COERCIBLE: Set<JSONType> = new Set([\"string\", \"number\", \"integer\", \"boolean\", \"null\"])\nfunction coerceToTypes(types: JSONType[], coerceTypes?: boolean | \"array\"): JSONType[] {\n return coerceTypes\n ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === \"array\" && t === \"array\"))\n : []\n}\n\nfunction coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void {\n const {gen, data, opts} = it\n const dataType = gen.let(\"dataType\", _`typeof ${data}`)\n const coerced = gen.let(\"coerced\", _`undefined`)\n if (opts.coerceTypes === \"array\") {\n gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () =>\n gen\n .assign(data, _`${data}[0]`)\n .assign(dataType, _`typeof ${data}`)\n .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))\n )\n }\n gen.if(_`${coerced} !== undefined`)\n for (const t of coerceTo) {\n if (COERCIBLE.has(t) || (t === \"array\" && opts.coerceTypes === \"array\")) {\n coerceSpecificType(t)\n }\n }\n gen.else()\n reportTypeError(it)\n gen.endIf()\n\n gen.if(_`${coerced} !== undefined`, () => {\n gen.assign(data, coerced)\n assignParentData(it, coerced)\n })\n\n function coerceSpecificType(t: string): void {\n switch (t) {\n case \"string\":\n gen\n .elseIf(_`${dataType} == \"number\" || ${dataType} == \"boolean\"`)\n .assign(coerced, _`\"\" + ${data}`)\n .elseIf(_`${data} === null`)\n .assign(coerced, _`\"\"`)\n return\n case \"number\":\n gen\n .elseIf(\n _`${dataType} == \"boolean\" || ${data} === null\n || (${dataType} == \"string\" && ${data} && ${data} == +${data})`\n )\n .assign(coerced, _`+${data}`)\n return\n case \"integer\":\n gen\n .elseIf(\n _`${dataType} === \"boolean\" || ${data} === null\n || (${dataType} === \"string\" && ${data} && ${data} == +${data} && !(${data} % 1))`\n )\n .assign(coerced, _`+${data}`)\n return\n case \"boolean\":\n gen\n .elseIf(_`${data} === \"false\" || ${data} === 0 || ${data} === null`)\n .assign(coerced, false)\n .elseIf(_`${data} === \"true\" || ${data} === 1`)\n .assign(coerced, true)\n return\n case \"null\":\n gen.elseIf(_`${data} === \"\" || ${data} === 0 || ${data} === false`)\n gen.assign(coerced, null)\n return\n\n case \"array\":\n gen\n .elseIf(\n _`${dataType} === \"string\" || ${dataType} === \"number\"\n || ${dataType} === \"boolean\" || ${data} === null`\n )\n .assign(coerced, _`[${data}]`)\n }\n }\n}\n\nfunction assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void {\n // TODO use gen.property\n gen.if(_`${parentData} !== undefined`, () =>\n gen.assign(_`${parentData}[${parentDataProperty}]`, expr)\n )\n}\n\nexport function checkDataType(\n dataType: JSONType,\n data: Name,\n strictNums?: boolean | \"log\",\n correct = DataType.Correct\n): Code {\n const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ\n let cond: Code\n switch (dataType) {\n case \"null\":\n return _`${data} ${EQ} null`\n case \"array\":\n cond = _`Array.isArray(${data})`\n break\n case \"object\":\n cond = _`${data} && typeof ${data} == \"object\" && !Array.isArray(${data})`\n break\n case \"integer\":\n cond = numCond(_`!(${data} % 1) && !isNaN(${data})`)\n break\n case \"number\":\n cond = numCond()\n break\n default:\n return _`typeof ${data} ${EQ} ${dataType}`\n }\n return correct === DataType.Correct ? cond : not(cond)\n\n function numCond(_cond: Code = nil): Code {\n return and(_`typeof ${data} == \"number\"`, _cond, strictNums ? _`isFinite(${data})` : nil)\n }\n}\n\nexport function checkDataTypes(\n dataTypes: JSONType[],\n data: Name,\n strictNums?: boolean | \"log\",\n correct?: DataType\n): Code {\n if (dataTypes.length === 1) {\n return checkDataType(dataTypes[0], data, strictNums, correct)\n }\n let cond: Code\n const types = toHash(dataTypes)\n if (types.array && types.object) {\n const notObj = _`typeof ${data} != \"object\"`\n cond = types.null ? notObj : _`!${data} || ${notObj}`\n delete types.null\n delete types.array\n delete types.object\n } else {\n cond = nil\n }\n if (types.number) delete types.integer\n for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct))\n return cond\n}\n\nexport type TypeError = ErrorObject<\"type\", {type: string}>\n\nconst typeError: KeywordErrorDefinition = {\n message: ({schema}) => `must be ${schema}`,\n params: ({schema, schemaValue}) =>\n typeof schema == \"string\" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`,\n}\n\nexport function reportTypeError(it: SchemaObjCxt): void {\n const cxt = getTypeErrorContext(it)\n reportError(cxt, typeError)\n}\n\nfunction getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt {\n const {gen, data, schema} = it\n const schemaCode = schemaRefOrVal(it, schema, \"type\")\n return {\n gen,\n keyword: \"type\",\n data,\n schema: schema.type,\n schemaCode,\n schemaValue: schemaCode,\n parentSchema: schema,\n params: {},\n it,\n }\n}\n", "import type {SchemaObjCxt} from \"..\"\nimport {_, getProperty, stringify} from \"../codegen\"\nimport {checkStrictMode} from \"../util\"\n\nexport function assignDefaults(it: SchemaObjCxt, ty?: string): void {\n const {properties, items} = it.schema\n if (ty === \"object\" && properties) {\n for (const key in properties) {\n assignDefault(it, key, properties[key].default)\n }\n } else if (ty === \"array\" && Array.isArray(items)) {\n items.forEach((sch, i: number) => assignDefault(it, i, sch.default))\n }\n}\n\nfunction assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void {\n const {gen, compositeRule, data, opts} = it\n if (defaultValue === undefined) return\n const childData = _`${data}${getProperty(prop)}`\n if (compositeRule) {\n checkStrictMode(it, `default is ignored for: ${childData}`)\n return\n }\n\n let condition = _`${childData} === undefined`\n if (opts.useDefaults === \"empty\") {\n condition = _`${condition} || ${childData} === null || ${childData} === \"\"`\n }\n // `${childData} === undefined` +\n // (opts.useDefaults === \"empty\" ? ` || ${childData} === null || ${childData} === \"\"` : \"\")\n gen.if(condition, _`${childData} = ${stringify(defaultValue)}`)\n}\n", "import type {AnySchema, SchemaMap} from \"../types\"\nimport type {SchemaCxt} from \"../compile\"\nimport type {KeywordCxt} from \"../compile/validate\"\nimport {CodeGen, _, and, or, not, nil, strConcat, getProperty, Code, Name} from \"../compile/codegen\"\nimport {alwaysValidSchema, Type} from \"../compile/util\"\nimport N from \"../compile/names\"\nimport {useFunc} from \"../compile/util\"\nexport function checkReportMissingProp(cxt: KeywordCxt, prop: string): void {\n const {gen, data, it} = cxt\n gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {\n cxt.setParams({missingProperty: _`${prop}`}, true)\n cxt.error()\n })\n}\n\nexport function checkMissingProp(\n {gen, data, it: {opts}}: KeywordCxt,\n properties: string[],\n missing: Name\n): Code {\n return or(\n ...properties.map((prop) =>\n and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`)\n )\n )\n}\n\nexport function reportMissingProp(cxt: KeywordCxt, missing: Name): void {\n cxt.setParams({missingProperty: missing}, true)\n cxt.error()\n}\n\nexport function hasPropFunc(gen: CodeGen): Name {\n return gen.scopeValue(\"func\", {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n ref: Object.prototype.hasOwnProperty,\n code: _`Object.prototype.hasOwnProperty`,\n })\n}\n\nexport function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code {\n return _`${hasPropFunc(gen)}.call(${data}, ${property})`\n}\n\nexport function propertyInData(\n gen: CodeGen,\n data: Name,\n property: Name | string,\n ownProperties?: boolean\n): Code {\n const cond = _`${data}${getProperty(property)} !== undefined`\n return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond\n}\n\nexport function noPropertyInData(\n gen: CodeGen,\n data: Name,\n property: Name | string,\n ownProperties?: boolean\n): Code {\n const cond = _`${data}${getProperty(property)} === undefined`\n return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond\n}\n\nexport function allSchemaProperties(schemaMap?: SchemaMap): string[] {\n return schemaMap ? Object.keys(schemaMap).filter((p) => p !== \"__proto__\") : []\n}\n\nexport function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] {\n return allSchemaProperties(schemaMap).filter(\n (p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema)\n )\n}\n\nexport function callValidateCode(\n {schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt,\n func: Code,\n context: Code,\n passSchema?: boolean\n): Code {\n const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data\n const valCxt: [Name, Code | number][] = [\n [N.instancePath, strConcat(N.instancePath, errorPath)],\n [N.parentData, it.parentData],\n [N.parentDataProperty, it.parentDataProperty],\n [N.rootData, N.rootData],\n ]\n if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors])\n const args = _`${dataAndSchema}, ${gen.object(...valCxt)}`\n return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})`\n}\n\nconst newRegExp = _`new RegExp`\n\nexport function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name {\n const u = opts.unicodeRegExp ? \"u\" : \"\"\n const {regExp} = opts.code\n const rx = regExp(pattern, u)\n\n return gen.scopeValue(\"pattern\", {\n key: rx.toString(),\n ref: rx,\n code: _`${regExp.code === \"new RegExp\" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`,\n })\n}\n\nexport function validateArray(cxt: KeywordCxt): Name {\n const {gen, data, keyword, it} = cxt\n const valid = gen.name(\"valid\")\n if (it.allErrors) {\n const validArr = gen.let(\"valid\", true)\n validateItems(() => gen.assign(validArr, false))\n return validArr\n }\n gen.var(valid, true)\n validateItems(() => gen.break())\n return valid\n\n function validateItems(notValid: () => void): void {\n const len = gen.const(\"len\", _`${data}.length`)\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema(\n {\n keyword,\n dataProp: i,\n dataPropType: Type.Num,\n },\n valid\n )\n gen.if(not(valid), notValid)\n })\n }\n}\n\nexport function validateUnion(cxt: KeywordCxt): void {\n const {gen, schema, keyword, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch))\n if (alwaysValid && !it.opts.unevaluated) return\n\n const valid = gen.let(\"valid\", false)\n const schValid = gen.name(\"_valid\")\n\n gen.block(() =>\n schema.forEach((_sch: AnySchema, i: number) => {\n const schCxt = cxt.subschema(\n {\n keyword,\n schemaProp: i,\n compositeRule: true,\n },\n schValid\n )\n gen.assign(valid, _`${valid} || ${schValid}`)\n const merged = cxt.mergeValidEvaluated(schCxt, schValid)\n // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)\n // or if all properties and items were evaluated (it.props === true && it.items === true)\n if (!merged) gen.if(not(valid))\n })\n )\n\n cxt.result(\n valid,\n () => cxt.reset(),\n () => cxt.error(true)\n )\n}\n", "import type {KeywordCxt} from \".\"\nimport type {\n AnySchema,\n SchemaValidateFunction,\n AnyValidateFunction,\n AddedKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {_, nil, not, stringify, Code, Name, CodeGen} from \"../codegen\"\nimport N from \"../names\"\nimport type {JSONType} from \"../rules\"\nimport {callValidateCode} from \"../../vocabularies/code\"\nimport {extendErrors} from \"../errors\"\n\ntype KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction\n\nexport function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void {\n const {gen, keyword, schema, parentSchema, it} = cxt\n const macroSchema = def.macro.call(it.self, schema, parentSchema, it)\n const schemaRef = useKeyword(gen, keyword, macroSchema)\n if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true)\n\n const valid = gen.name(\"valid\")\n cxt.subschema(\n {\n schema: macroSchema,\n schemaPath: nil,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n topSchemaRef: schemaRef,\n compositeRule: true,\n },\n valid\n )\n cxt.pass(valid, () => cxt.error(true))\n}\n\nexport function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void {\n const {gen, keyword, schema, parentSchema, $data, it} = cxt\n checkAsyncKeyword(it, def)\n const validate =\n !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate\n const validateRef = useKeyword(gen, keyword, validate)\n const valid = gen.let(\"valid\")\n cxt.block$data(valid, validateKeyword)\n cxt.ok(def.valid ?? valid)\n\n function validateKeyword(): void {\n if (def.errors === false) {\n assignValid()\n if (def.modifying) modifyData(cxt)\n reportErrs(() => cxt.error())\n } else {\n const ruleErrs = def.async ? validateAsync() : validateSync()\n if (def.modifying) modifyData(cxt)\n reportErrs(() => addErrs(cxt, ruleErrs))\n }\n }\n\n function validateAsync(): Name {\n const ruleErrs = gen.let(\"ruleErrs\", null)\n gen.try(\n () => assignValid(_`await `),\n (e) =>\n gen.assign(valid, false).if(\n _`${e} instanceof ${it.ValidationError as Name}`,\n () => gen.assign(ruleErrs, _`${e}.errors`),\n () => gen.throw(e)\n )\n )\n return ruleErrs\n }\n\n function validateSync(): Code {\n const validateErrs = _`${validateRef}.errors`\n gen.assign(validateErrs, null)\n assignValid(nil)\n return validateErrs\n }\n\n function assignValid(_await: Code = def.async ? _`await ` : nil): void {\n const passCxt = it.opts.passContext ? N.this : N.self\n const passSchema = !((\"compile\" in def && !$data) || def.schema === false)\n gen.assign(\n valid,\n _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`,\n def.modifying\n )\n }\n\n function reportErrs(errors: () => void): void {\n gen.if(not(def.valid ?? valid), errors)\n }\n}\n\nfunction modifyData(cxt: KeywordCxt): void {\n const {gen, data, it} = cxt\n gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`))\n}\n\nfunction addErrs(cxt: KeywordCxt, errs: Code): void {\n const {gen} = cxt\n gen.if(\n _`Array.isArray(${errs})`,\n () => {\n gen\n .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`)\n .assign(N.errors, _`${N.vErrors}.length`)\n extendErrors(cxt)\n },\n () => cxt.error()\n )\n}\n\nfunction checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void {\n if (def.async && !schemaEnv.$async) throw new Error(\"async keyword in sync schema\")\n}\n\nfunction useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name {\n if (result === undefined) throw new Error(`keyword \"${keyword}\" failed to compile`)\n return gen.scopeValue(\n \"keyword\",\n typeof result == \"function\" ? {ref: result} : {ref: result, code: stringify(result)}\n )\n}\n\nexport function validSchemaType(\n schema: unknown,\n schemaType: JSONType[],\n allowUndefined = false\n): boolean {\n // TODO add tests\n return (\n !schemaType.length ||\n schemaType.some((st) =>\n st === \"array\"\n ? Array.isArray(schema)\n : st === \"object\"\n ? schema && typeof schema == \"object\" && !Array.isArray(schema)\n : typeof schema == st || (allowUndefined && typeof schema == \"undefined\")\n )\n )\n}\n\nexport function validateKeywordUsage(\n {schema, opts, self, errSchemaPath}: SchemaObjCxt,\n def: AddedKeywordDefinition,\n keyword: string\n): void {\n /* istanbul ignore if */\n if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {\n throw new Error(\"ajv implementation error\")\n }\n\n const deps = def.dependencies\n if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {\n throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(\",\")}`)\n }\n\n if (def.validateSchema) {\n const valid = def.validateSchema(schema[keyword])\n if (!valid) {\n const msg =\n `keyword \"${keyword}\" value is invalid at path \"${errSchemaPath}\": ` +\n self.errorsText(def.validateSchema.errors)\n if (opts.validateSchema === \"log\") self.logger.error(msg)\n else throw new Error(msg)\n }\n }\n}\n", "import type {AnySchema} from \"../../types\"\nimport type {SchemaObjCxt} from \"..\"\nimport {_, str, getProperty, Code, Name} from \"../codegen\"\nimport {escapeFragment, getErrorPath, Type} from \"../util\"\nimport type {JSONType} from \"../rules\"\n\nexport interface SubschemaContext {\n // TODO use Optional? align with SchemCxt property types\n schema: AnySchema\n schemaPath: Code\n errSchemaPath: string\n topSchemaRef?: Code\n errorPath?: Code\n dataLevel?: number\n dataTypes?: JSONType[]\n data?: Name\n parentData?: Name\n parentDataProperty?: Code | number\n dataNames?: Name[]\n dataPathArr?: (Code | number)[]\n propertyName?: Name\n jtdDiscriminator?: string\n jtdMetadata?: boolean\n compositeRule?: true\n createErrors?: boolean\n allErrors?: boolean\n}\n\nexport type SubschemaArgs = Partial<{\n keyword: string\n schemaProp: string | number\n schema: AnySchema\n schemaPath: Code\n errSchemaPath: string\n topSchemaRef: Code\n data: Name | Code\n dataProp: Code | string | number\n dataTypes: JSONType[]\n definedProperties: Set<string>\n propertyName: Name\n dataPropType: Type\n jtdDiscriminator: string\n jtdMetadata: boolean\n compositeRule: true\n createErrors: boolean\n allErrors: boolean\n}>\n\nexport function getSubschema(\n it: SchemaObjCxt,\n {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs\n): SubschemaContext {\n if (keyword !== undefined && schema !== undefined) {\n throw new Error('both \"keyword\" and \"schema\" passed, only one allowed')\n }\n\n if (keyword !== undefined) {\n const sch = it.schema[keyword]\n return schemaProp === undefined\n ? {\n schema: sch,\n schemaPath: _`${it.schemaPath}${getProperty(keyword)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}`,\n }\n : {\n schema: sch[schemaProp],\n schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`,\n errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`,\n }\n }\n\n if (schema !== undefined) {\n if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {\n throw new Error('\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\"')\n }\n return {\n schema,\n schemaPath,\n topSchemaRef,\n errSchemaPath,\n }\n }\n\n throw new Error('either \"keyword\" or \"schema\" must be passed')\n}\n\nexport function extendSubschemaData(\n subschema: SubschemaContext,\n it: SchemaObjCxt,\n {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs\n): void {\n if (data !== undefined && dataProp !== undefined) {\n throw new Error('both \"data\" and \"dataProp\" passed, only one allowed')\n }\n\n const {gen} = it\n\n if (dataProp !== undefined) {\n const {errorPath, dataPathArr, opts} = it\n const nextData = gen.let(\"data\", _`${it.data}${getProperty(dataProp)}`, true)\n dataContextProps(nextData)\n subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}`\n subschema.parentDataProperty = _`${dataProp}`\n subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]\n }\n\n if (data !== undefined) {\n const nextData = data instanceof Name ? data : gen.let(\"data\", data, true) // replaceable if used once?\n dataContextProps(nextData)\n if (propertyName !== undefined) subschema.propertyName = propertyName\n // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr\n }\n\n if (dataTypes) subschema.dataTypes = dataTypes\n\n function dataContextProps(_nextData: Name): void {\n subschema.data = _nextData\n subschema.dataLevel = it.dataLevel + 1\n subschema.dataTypes = []\n it.definedProperties = new Set<string>()\n subschema.parentData = it.data\n subschema.dataNames = [...it.dataNames, _nextData]\n }\n}\n\nexport function extendSubschemaMode(\n subschema: SubschemaContext,\n {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs\n): void {\n if (compositeRule !== undefined) subschema.compositeRule = compositeRule\n if (createErrors !== undefined) subschema.createErrors = createErrors\n if (allErrors !== undefined) subschema.allErrors = allErrors\n subschema.jtdDiscriminator = jtdDiscriminator // not inherited\n subschema.jtdMetadata = jtdMetadata // not inherited\n}\n", "'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n", "'use strict';\n\nvar traverse = module.exports = function (schema, opts, cb) {\n // Legacy support for v0.3.1 and earlier.\n if (typeof opts == 'function') {\n cb = opts;\n opts = {};\n }\n\n cb = opts.cb || cb;\n var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};\n var post = cb.post || function() {};\n\n _traverse(opts, pre, post, schema, '', schema);\n};\n\n\ntraverse.keywords = {\n additionalItems: true,\n items: true,\n contains: true,\n additionalProperties: true,\n propertyNames: true,\n not: true,\n if: true,\n then: true,\n else: true\n};\n\ntraverse.arrayKeywords = {\n items: true,\n allOf: true,\n anyOf: true,\n oneOf: true\n};\n\ntraverse.propsKeywords = {\n $defs: true,\n definitions: true,\n properties: true,\n patternProperties: true,\n dependencies: true\n};\n\ntraverse.skipKeywords = {\n default: true,\n enum: true,\n const: true,\n required: true,\n maximum: true,\n minimum: true,\n exclusiveMaximum: true,\n exclusiveMinimum: true,\n multipleOf: true,\n maxLength: true,\n minLength: true,\n pattern: true,\n format: true,\n maxItems: true,\n minItems: true,\n uniqueItems: true,\n maxProperties: true,\n minProperties: true\n};\n\n\nfunction _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {\n if (schema && typeof schema == 'object' && !Array.isArray(schema)) {\n pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n for (var key in schema) {\n var sch = schema[key];\n if (Array.isArray(sch)) {\n if (key in traverse.arrayKeywords) {\n for (var i=0; i<sch.length; i++)\n _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);\n }\n } else if (key in traverse.propsKeywords) {\n if (sch && typeof sch == 'object') {\n for (var prop in sch)\n _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);\n }\n } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {\n _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);\n }\n }\n post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);\n }\n}\n\n\nfunction escapeJsonPtr(str) {\n return str.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n", "import type {AnySchema, AnySchemaObject, UriResolver} from \"../types\"\nimport type Ajv from \"../ajv\"\nimport type {URIComponent} from \"fast-uri\"\nimport {eachItem} from \"./util\"\nimport * as equal from \"fast-deep-equal\"\nimport * as traverse from \"json-schema-traverse\"\n\n// the hash of local references inside the schema (created by getSchemaRefs), used for inline resolution\nexport type LocalRefs = {[Ref in string]?: AnySchemaObject}\n\n// TODO refactor to use keyword definitions\nconst SIMPLE_INLINED = new Set([\n \"type\",\n \"format\",\n \"pattern\",\n \"maxLength\",\n \"minLength\",\n \"maxProperties\",\n \"minProperties\",\n \"maxItems\",\n \"minItems\",\n \"maximum\",\n \"minimum\",\n \"uniqueItems\",\n \"multipleOf\",\n \"required\",\n \"enum\",\n \"const\",\n])\n\nexport function inlineRef(schema: AnySchema, limit: boolean | number = true): boolean {\n if (typeof schema == \"boolean\") return true\n if (limit === true) return !hasRef(schema)\n if (!limit) return false\n return countKeys(schema) <= limit\n}\n\nconst REF_KEYWORDS = new Set([\n \"$ref\",\n \"$recursiveRef\",\n \"$recursiveAnchor\",\n \"$dynamicRef\",\n \"$dynamicAnchor\",\n])\n\nfunction hasRef(schema: AnySchemaObject): boolean {\n for (const key in schema) {\n if (REF_KEYWORDS.has(key)) return true\n const sch = schema[key]\n if (Array.isArray(sch) && sch.some(hasRef)) return true\n if (typeof sch == \"object\" && hasRef(sch)) return true\n }\n return false\n}\n\nfunction countKeys(schema: AnySchemaObject): number {\n let count = 0\n for (const key in schema) {\n if (key === \"$ref\") return Infinity\n count++\n if (SIMPLE_INLINED.has(key)) continue\n if (typeof schema[key] == \"object\") {\n eachItem(schema[key], (sch) => (count += countKeys(sch)))\n }\n if (count === Infinity) return Infinity\n }\n return count\n}\n\nexport function getFullPath(resolver: UriResolver, id = \"\", normalize?: boolean): string {\n if (normalize !== false) id = normalizeId(id)\n const p = resolver.parse(id)\n return _getFullPath(resolver, p)\n}\n\nexport function _getFullPath(resolver: UriResolver, p: URIComponent): string {\n const serialized = resolver.serialize(p)\n return serialized.split(\"#\")[0] + \"#\"\n}\n\nconst TRAILING_SLASH_HASH = /#\\/?$/\nexport function normalizeId(id: string | undefined): string {\n return id ? id.replace(TRAILING_SLASH_HASH, \"\") : \"\"\n}\n\nexport function resolveUrl(resolver: UriResolver, baseId: string, id: string): string {\n id = normalizeId(id)\n return resolver.resolve(baseId, id)\n}\n\nconst ANCHOR = /^[a-z_][-a-z0-9._]*$/i\n\nexport function getSchemaRefs(this: Ajv, schema: AnySchema, baseId: string): LocalRefs {\n if (typeof schema == \"boolean\") return {}\n const {schemaId, uriResolver} = this.opts\n const schId = normalizeId(schema[schemaId] || baseId)\n const baseIds: {[JsonPtr in string]?: string} = {\"\": schId}\n const pathPrefix = getFullPath(uriResolver, schId, false)\n const localRefs: LocalRefs = {}\n const schemaRefs: Set<string> = new Set()\n\n traverse(schema, {allKeys: true}, (sch, jsonPtr, _, parentJsonPtr) => {\n if (parentJsonPtr === undefined) return\n const fullPath = pathPrefix + jsonPtr\n let innerBaseId = baseIds[parentJsonPtr]\n if (typeof sch[schemaId] == \"string\") innerBaseId = addRef.call(this, sch[schemaId])\n addAnchor.call(this, sch.$anchor)\n addAnchor.call(this, sch.$dynamicAnchor)\n baseIds[jsonPtr] = innerBaseId\n\n function addRef(this: Ajv, ref: string): string {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const _resolve = this.opts.uriResolver.resolve\n ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref)\n if (schemaRefs.has(ref)) throw ambiguos(ref)\n schemaRefs.add(ref)\n let schOrRef = this.refs[ref]\n if (typeof schOrRef == \"string\") schOrRef = this.refs[schOrRef]\n if (typeof schOrRef == \"object\") {\n checkAmbiguosRef(sch, schOrRef.schema, ref)\n } else if (ref !== normalizeId(fullPath)) {\n if (ref[0] === \"#\") {\n checkAmbiguosRef(sch, localRefs[ref], ref)\n localRefs[ref] = sch\n } else {\n this.refs[ref] = fullPath\n }\n }\n return ref\n }\n\n function addAnchor(this: Ajv, anchor: unknown): void {\n if (typeof anchor == \"string\") {\n if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor \"${anchor}\"`)\n addRef.call(this, `#${anchor}`)\n }\n }\n })\n\n return localRefs\n\n function checkAmbiguosRef(sch1: AnySchema, sch2: AnySchema | undefined, ref: string): void {\n if (sch2 !== undefined && !equal(sch1, sch2)) throw ambiguos(ref)\n }\n\n function ambiguos(ref: string): Error {\n return new Error(`reference \"${ref}\" resolves to more than one schema`)\n }\n}\n", "import type {\n AddedKeywordDefinition,\n AnySchema,\n AnySchemaObject,\n KeywordErrorCxt,\n KeywordCxtParams,\n} from \"../../types\"\nimport type {SchemaCxt, SchemaObjCxt} from \"..\"\nimport type {InstanceOptions} from \"../../core\"\nimport {boolOrEmptySchema, topBoolOrEmptySchema} from \"./boolSchema\"\nimport {coerceAndCheckDataType, getSchemaTypes} from \"./dataType\"\nimport {shouldUseGroup, shouldUseRule} from \"./applicability\"\nimport {checkDataType, checkDataTypes, reportTypeError, DataType} from \"./dataType\"\nimport {assignDefaults} from \"./defaults\"\nimport {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from \"./keyword\"\nimport {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from \"./subschema\"\nimport {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from \"../codegen\"\nimport N from \"../names\"\nimport {resolveUrl} from \"../resolve\"\nimport {\n schemaRefOrVal,\n schemaHasRulesButRef,\n checkUnknownRules,\n checkStrictMode,\n unescapeJsonPointer,\n mergeEvaluated,\n} from \"../util\"\nimport type {JSONType, Rule, RuleGroup} from \"../rules\"\nimport {\n ErrorPaths,\n reportError,\n reportExtraError,\n resetErrorsCount,\n keyword$DataError,\n} from \"../errors\"\n\n// schema compilation - generates validation function, subschemaCode (below) is used for subschemas\nexport function validateFunctionCode(it: SchemaCxt): void {\n if (isSchemaObj(it)) {\n checkKeywords(it)\n if (schemaCxtHasRules(it)) {\n topSchemaObjCode(it)\n return\n }\n }\n validateFunction(it, () => topBoolOrEmptySchema(it))\n}\n\nfunction validateFunction(\n {gen, validateName, schema, schemaEnv, opts}: SchemaCxt,\n body: Block\n): void {\n if (opts.code.es5) {\n gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => {\n gen.code(_`\"use strict\"; ${funcSourceUrl(schema, opts)}`)\n destructureValCxtES5(gen, opts)\n gen.code(body)\n })\n } else {\n gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () =>\n gen.code(funcSourceUrl(schema, opts)).code(body)\n )\n }\n}\n\nfunction destructureValCxt(opts: InstanceOptions): Code {\n return _`{${N.instancePath}=\"\", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${\n N.data\n }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}`\n}\n\nfunction destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void {\n gen.if(\n N.valCxt,\n () => {\n gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`)\n gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`)\n gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`)\n gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`)\n if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`)\n },\n () => {\n gen.var(N.instancePath, _`\"\"`)\n gen.var(N.parentData, _`undefined`)\n gen.var(N.parentDataProperty, _`undefined`)\n gen.var(N.rootData, N.data)\n if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`)\n }\n )\n}\n\nfunction topSchemaObjCode(it: SchemaObjCxt): void {\n const {schema, opts, gen} = it\n validateFunction(it, () => {\n if (opts.$comment && schema.$comment) commentKeyword(it)\n checkNoDefault(it)\n gen.let(N.vErrors, null)\n gen.let(N.errors, 0)\n if (opts.unevaluated) resetEvaluated(it)\n typeAndKeywords(it)\n returnResults(it)\n })\n return\n}\n\nfunction resetEvaluated(it: SchemaObjCxt): void {\n // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated\n const {gen, validateName} = it\n it.evaluated = gen.const(\"evaluated\", _`${validateName}.evaluated`)\n gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`))\n gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`))\n}\n\nfunction funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code {\n const schId = typeof schema == \"object\" && schema[opts.schemaId]\n return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil\n}\n\n// schema compilation - this function is used recursively to generate code for sub-schemas\nfunction subschemaCode(it: SchemaCxt, valid: Name): void {\n if (isSchemaObj(it)) {\n checkKeywords(it)\n if (schemaCxtHasRules(it)) {\n subSchemaObjCode(it, valid)\n return\n }\n }\n boolOrEmptySchema(it, valid)\n}\n\nfunction schemaCxtHasRules({schema, self}: SchemaCxt): boolean {\n if (typeof schema == \"boolean\") return !schema\n for (const key in schema) if (self.RULES.all[key]) return true\n return false\n}\n\nfunction isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {\n return typeof it.schema != \"boolean\"\n}\n\nfunction subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {\n const {schema, gen, opts} = it\n if (opts.$comment && schema.$comment) commentKeyword(it)\n updateContext(it)\n checkAsyncSchema(it)\n const errsCount = gen.const(\"_errs\", N.errors)\n typeAndKeywords(it, errsCount)\n // TODO var\n gen.var(valid, _`${errsCount} === ${N.errors}`)\n}\n\nfunction checkKeywords(it: SchemaObjCxt): void {\n checkUnknownRules(it)\n checkRefsAndKeywords(it)\n}\n\nfunction typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void {\n if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount)\n const types = getSchemaTypes(it.schema)\n const checkedTypes = coerceAndCheckDataType(it, types)\n schemaKeywords(it, types, !checkedTypes, errsCount)\n}\n\nfunction checkRefsAndKeywords(it: SchemaObjCxt): void {\n const {schema, errSchemaPath, opts, self} = it\n if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) {\n self.logger.warn(`$ref: keywords ignored in schema at path \"${errSchemaPath}\"`)\n }\n}\n\nfunction checkNoDefault(it: SchemaObjCxt): void {\n const {schema, opts} = it\n if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {\n checkStrictMode(it, \"default is ignored in the schema root\")\n }\n}\n\nfunction updateContext(it: SchemaObjCxt): void {\n const schId = it.schema[it.opts.schemaId]\n if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId)\n}\n\nfunction checkAsyncSchema(it: SchemaObjCxt): void {\n if (it.schema.$async && !it.schemaEnv.$async) throw new Error(\"async schema in sync schema\")\n}\n\nfunction commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void {\n const msg = schema.$comment\n if (opts.$comment === true) {\n gen.code(_`${N.self}.logger.log(${msg})`)\n } else if (typeof opts.$comment == \"function\") {\n const schemaPath = str`${errSchemaPath}/$comment`\n const rootName = gen.scopeValue(\"root\", {ref: schemaEnv.root})\n gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)\n }\n}\n\nfunction returnResults(it: SchemaCxt): void {\n const {gen, schemaEnv, validateName, ValidationError, opts} = it\n if (schemaEnv.$async) {\n // TODO assign unevaluated\n gen.if(\n _`${N.errors} === 0`,\n () => gen.return(N.data),\n () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`)\n )\n } else {\n gen.assign(_`${validateName}.errors`, N.vErrors)\n if (opts.unevaluated) assignEvaluated(it)\n gen.return(_`${N.errors} === 0`)\n }\n}\n\nfunction assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void {\n if (props instanceof Name) gen.assign(_`${evaluated}.props`, props)\n if (items instanceof Name) gen.assign(_`${evaluated}.items`, items)\n}\n\nfunction schemaKeywords(\n it: SchemaObjCxt,\n types: JSONType[],\n typeErrors: boolean,\n errsCount?: Name\n): void {\n const {gen, schema, data, allErrors, opts, self} = it\n const {RULES} = self\n if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {\n gen.block(() => keywordCode(it, \"$ref\", (RULES.all.$ref as Rule).definition)) // TODO typecast\n return\n }\n if (!opts.jtd) checkStrictTypes(it, types)\n gen.block(() => {\n for (const group of RULES.rules) groupKeywords(group)\n groupKeywords(RULES.post)\n })\n\n function groupKeywords(group: RuleGroup): void {\n if (!shouldUseGroup(schema, group)) return\n if (group.type) {\n gen.if(checkDataType(group.type, data, opts.strictNumbers))\n iterateKeywords(it, group)\n if (types.length === 1 && types[0] === group.type && typeErrors) {\n gen.else()\n reportTypeError(it)\n }\n gen.endIf()\n } else {\n iterateKeywords(it, group)\n }\n // TODO make it \"ok\" call?\n if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)\n }\n}\n\nfunction iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {\n const {\n gen,\n schema,\n opts: {useDefaults},\n } = it\n if (useDefaults) assignDefaults(it, group.type)\n gen.block(() => {\n for (const rule of group.rules) {\n if (shouldUseRule(schema, rule)) {\n keywordCode(it, rule.keyword, rule.definition, group.type)\n }\n }\n })\n}\n\nfunction checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void {\n if (it.schemaEnv.meta || !it.opts.strictTypes) return\n checkContextTypes(it, types)\n if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types)\n checkKeywordTypes(it, it.dataTypes)\n}\n\nfunction checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void {\n if (!types.length) return\n if (!it.dataTypes.length) {\n it.dataTypes = types\n return\n }\n types.forEach((t) => {\n if (!includesType(it.dataTypes, t)) {\n strictTypesError(it, `type \"${t}\" not allowed by context \"${it.dataTypes.join(\",\")}\"`)\n }\n })\n narrowSchemaTypes(it, types)\n}\n\nfunction checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void {\n if (ts.length > 1 && !(ts.length === 2 && ts.includes(\"null\"))) {\n strictTypesError(it, \"use allowUnionTypes to allow union type keyword\")\n }\n}\n\nfunction checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void {\n const rules = it.self.RULES.all\n for (const keyword in rules) {\n const rule = rules[keyword]\n if (typeof rule == \"object\" && shouldUseRule(it.schema, rule)) {\n const {type} = rule.definition\n if (type.length && !type.some((t) => hasApplicableType(ts, t))) {\n strictTypesError(it, `missing type \"${type.join(\",\")}\" for keyword \"${keyword}\"`)\n }\n }\n }\n}\n\nfunction hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean {\n return schTs.includes(kwdT) || (kwdT === \"number\" && schTs.includes(\"integer\"))\n}\n\nfunction includesType(ts: JSONType[], t: JSONType): boolean {\n return ts.includes(t) || (t === \"integer\" && ts.includes(\"number\"))\n}\n\nfunction narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void {\n const ts: JSONType[] = []\n for (const t of it.dataTypes) {\n if (includesType(withTypes, t)) ts.push(t)\n else if (withTypes.includes(\"integer\") && t === \"number\") ts.push(\"integer\")\n }\n it.dataTypes = ts\n}\n\nfunction strictTypesError(it: SchemaObjCxt, msg: string): void {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath\n msg += ` at \"${schemaPath}\" (strictTypes)`\n checkStrictMode(it, msg, it.opts.strictTypes)\n}\n\nexport class KeywordCxt implements KeywordErrorCxt {\n readonly gen: CodeGen\n readonly allErrors?: boolean\n readonly keyword: string\n readonly data: Name // Name referencing the current level of the data instance\n readonly $data?: string | false\n schema: any // keyword value in the schema\n readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value\n readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)\n readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema\n readonly parentSchema: AnySchemaObject\n readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,\n // requires option trackErrors in keyword definition\n params: KeywordCxtParams // object to pass parameters to error messages from keyword code\n readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)\n readonly def: AddedKeywordDefinition\n\n constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {\n validateKeywordUsage(it, def, keyword)\n this.gen = it.gen\n this.allErrors = it.allErrors\n this.keyword = keyword\n this.data = it.data\n this.schema = it.schema[keyword]\n this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data\n this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)\n this.schemaType = def.schemaType\n this.parentSchema = it.schema\n this.params = {}\n this.it = it\n this.def = def\n\n if (this.$data) {\n this.schemaCode = it.gen.const(\"vSchema\", getData(this.$data, it))\n } else {\n this.schemaCode = this.schemaValue\n if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {\n throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)\n }\n }\n\n if (\"code\" in def ? def.trackErrors : def.errors !== false) {\n this.errsCount = it.gen.const(\"_errs\", N.errors)\n }\n }\n\n result(condition: Code, successAction?: () => void, failAction?: () => void): void {\n this.failResult(not(condition), successAction, failAction)\n }\n\n failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {\n this.gen.if(condition)\n if (failAction) failAction()\n else this.error()\n if (successAction) {\n this.gen.else()\n successAction()\n if (this.allErrors) this.gen.endIf()\n } else {\n if (this.allErrors) this.gen.endIf()\n else this.gen.else()\n }\n }\n\n pass(condition: Code, failAction?: () => void): void {\n this.failResult(not(condition), undefined, failAction)\n }\n\n fail(condition?: Code): void {\n if (condition === undefined) {\n this.error()\n if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize\n return\n }\n this.gen.if(condition)\n this.error()\n if (this.allErrors) this.gen.endIf()\n else this.gen.else()\n }\n\n fail$data(condition: Code): void {\n if (!this.$data) return this.fail(condition)\n const {schemaCode} = this\n this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)\n }\n\n error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {\n if (errorParams) {\n this.setParams(errorParams)\n this._error(append, errorPaths)\n this.setParams({})\n return\n }\n this._error(append, errorPaths)\n }\n\n private _error(append?: boolean, errorPaths?: ErrorPaths): void {\n ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)\n }\n\n $dataError(): void {\n reportError(this, this.def.$dataError || keyword$DataError)\n }\n\n reset(): void {\n if (this.errsCount === undefined) throw new Error('add \"trackErrors\" to keyword definition')\n resetErrorsCount(this.gen, this.errsCount)\n }\n\n ok(cond: Code | boolean): void {\n if (!this.allErrors) this.gen.if(cond)\n }\n\n setParams(obj: KeywordCxtParams, assign?: true): void {\n if (assign) Object.assign(this.params, obj)\n else this.params = obj\n }\n\n block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {\n this.gen.block(() => {\n this.check$data(valid, $dataValid)\n codeBlock()\n })\n }\n\n check$data(valid: Name = nil, $dataValid: Code = nil): void {\n if (!this.$data) return\n const {gen, schemaCode, schemaType, def} = this\n gen.if(or(_`${schemaCode} === undefined`, $dataValid))\n if (valid !== nil) gen.assign(valid, true)\n if (schemaType.length || def.validateSchema) {\n gen.elseIf(this.invalid$data())\n this.$dataError()\n if (valid !== nil) gen.assign(valid, false)\n }\n gen.else()\n }\n\n invalid$data(): Code {\n const {gen, schemaCode, schemaType, def, it} = this\n return or(wrong$DataType(), invalid$DataSchema())\n\n function wrong$DataType(): Code {\n if (schemaType.length) {\n /* istanbul ignore if */\n if (!(schemaCode instanceof Name)) throw new Error(\"ajv implementation error\")\n const st = Array.isArray(schemaType) ? schemaType : [schemaType]\n return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`\n }\n return nil\n }\n\n function invalid$DataSchema(): Code {\n if (def.validateSchema) {\n const validateSchemaRef = gen.scopeValue(\"validate$data\", {ref: def.validateSchema}) // TODO value.code for standalone\n return _`!${validateSchemaRef}(${schemaCode})`\n }\n return nil\n }\n }\n\n subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {\n const subschema = getSubschema(this.it, appl)\n extendSubschemaData(subschema, this.it, appl)\n extendSubschemaMode(subschema, appl)\n const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}\n subschemaCode(nextContext, valid)\n return nextContext\n }\n\n mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {\n const {it, gen} = this\n if (!it.opts.unevaluated) return\n if (it.props !== true && schemaCxt.props !== undefined) {\n it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)\n }\n if (it.items !== true && schemaCxt.items !== undefined) {\n it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)\n }\n }\n\n mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {\n const {it, gen} = this\n if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {\n gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))\n return true\n }\n }\n}\n\nfunction keywordCode(\n it: SchemaObjCxt,\n keyword: string,\n def: AddedKeywordDefinition,\n ruleType?: JSONType\n): void {\n const cxt = new KeywordCxt(it, def, keyword)\n if (\"code\" in def) {\n def.code(cxt, ruleType)\n } else if (cxt.$data && def.validate) {\n funcKeywordCode(cxt, def)\n } else if (\"macro\" in def) {\n macroKeywordCode(cxt, def)\n } else if (def.compile || def.validate) {\n funcKeywordCode(cxt, def)\n }\n}\n\nconst JSON_POINTER = /^\\/(?:[^~]|~0|~1)*$/\nconst RELATIVE_JSON_POINTER = /^([0-9]+)(#|\\/(?:[^~]|~0|~1)*)?$/\nexport function getData(\n $data: string,\n {dataLevel, dataNames, dataPathArr}: SchemaCxt\n): Code | number {\n let jsonPointer\n let data: Code\n if ($data === \"\") return N.rootData\n if ($data[0] === \"/\") {\n if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)\n jsonPointer = $data\n data = N.rootData\n } else {\n const matches = RELATIVE_JSON_POINTER.exec($data)\n if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)\n const up: number = +matches[1]\n jsonPointer = matches[2]\n if (jsonPointer === \"#\") {\n if (up >= dataLevel) throw new Error(errorMsg(\"property/index\", up))\n return dataPathArr[dataLevel - up]\n }\n if (up > dataLevel) throw new Error(errorMsg(\"data\", up))\n data = dataNames[dataLevel - up]\n if (!jsonPointer) return data\n }\n\n let expr = data\n const segments = jsonPointer.split(\"/\")\n for (const segment of segments) {\n if (segment) {\n data = _`${data}${getProperty(unescapeJsonPointer(segment))}`\n expr = _`${expr} && ${data}`\n }\n }\n return expr\n\n function errorMsg(pointerType: string, up: number): string {\n return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`\n }\n}\n", "import type {ErrorObject} from \"../types\"\n\nexport default class ValidationError extends Error {\n readonly errors: Partial<ErrorObject>[]\n readonly ajv: true\n readonly validation: true\n\n constructor(errors: Partial<ErrorObject>[]) {\n super(\"validation failed\")\n this.errors = errors\n this.ajv = this.validation = true\n }\n}\n", "import {resolveUrl, normalizeId, getFullPath} from \"./resolve\"\nimport type {UriResolver} from \"../types\"\n\nexport default class MissingRefError extends Error {\n readonly missingRef: string\n readonly missingSchema: string\n\n constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) {\n super(msg || `can't resolve reference ${ref} from id ${baseId}`)\n this.missingRef = resolveUrl(resolver, baseId, ref)\n this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef))\n }\n}\n", "import type {\n AnySchema,\n AnySchemaObject,\n AnyValidateFunction,\n AsyncValidateFunction,\n EvaluatedProperties,\n EvaluatedItems,\n} from \"../types\"\nimport type Ajv from \"../core\"\nimport type {InstanceOptions} from \"../core\"\nimport {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from \"./codegen\"\nimport ValidationError from \"../runtime/validation_error\"\nimport N from \"./names\"\nimport {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from \"./resolve\"\nimport {schemaHasRulesButRef, unescapeFragment} from \"./util\"\nimport {validateFunctionCode} from \"./validate\"\nimport {URIComponent} from \"fast-uri\"\nimport {JSONType} from \"./rules\"\n\nexport type SchemaRefs = {\n [Ref in string]?: SchemaEnv | AnySchema\n}\n\nexport interface SchemaCxt {\n readonly gen: CodeGen\n readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error\n readonly data: Name // Name with reference to the current part of data instance\n readonly parentData: Name // should be used in keywords modifying data\n readonly parentDataProperty: Code | number // should be used in keywords modifying data\n readonly dataNames: Name[]\n readonly dataPathArr: (Code | number)[]\n readonly dataLevel: number // the level of the currently validated data,\n // it can be used to access both the property names and the data on all levels from the top.\n dataTypes: JSONType[] // data types applied to the current part of data instance\n definedProperties: Set<string> // set of properties to keep track of for required checks\n readonly topSchemaRef: Code\n readonly validateName: Name\n evaluated?: Name\n readonly ValidationError?: Name\n readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt\n readonly schemaEnv: SchemaEnv\n readonly rootId: string\n baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\\$ref)\n readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema\n readonly errSchemaPath: string // this is actual string, should not be changed to Code\n readonly errorPath: Code\n readonly propertyName?: Name\n readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,\n // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).\n // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.\n // You only need to use it if you have many steps in your keywords and potentially can define multiple errors.\n props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function\n items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function\n jtdDiscriminator?: string\n jtdMetadata?: boolean\n readonly createErrors?: boolean\n readonly opts: InstanceOptions // Ajv instance option.\n readonly self: Ajv // current Ajv instance\n}\n\nexport interface SchemaObjCxt extends SchemaCxt {\n readonly schema: AnySchemaObject\n}\ninterface SchemaEnvArgs {\n readonly schema: AnySchema\n readonly schemaId?: \"$id\" | \"id\"\n readonly root?: SchemaEnv\n readonly baseId?: string\n readonly schemaPath?: string\n readonly localRefs?: LocalRefs\n readonly meta?: boolean\n}\n\nexport class SchemaEnv implements SchemaEnvArgs {\n readonly schema: AnySchema\n readonly schemaId?: \"$id\" | \"id\"\n readonly root: SchemaEnv\n baseId: string // TODO possibly, it should be readonly\n schemaPath?: string\n localRefs?: LocalRefs\n readonly meta?: boolean\n readonly $async?: boolean // true if the current schema is asynchronous.\n readonly refs: SchemaRefs = {}\n readonly dynamicAnchors: {[Ref in string]?: true} = {}\n validate?: AnyValidateFunction\n validateName?: ValueScopeName\n serialize?: (data: unknown) => string\n serializeName?: ValueScopeName\n parse?: (data: string) => unknown\n parseName?: ValueScopeName\n\n constructor(env: SchemaEnvArgs) {\n let schema: AnySchemaObject | undefined\n if (typeof env.schema == \"object\") schema = env.schema\n this.schema = env.schema\n this.schemaId = env.schemaId\n this.root = env.root || this\n this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || \"$id\"])\n this.schemaPath = env.schemaPath\n this.localRefs = env.localRefs\n this.meta = env.meta\n this.$async = schema?.$async\n this.refs = {}\n }\n}\n\n// let codeSize = 0\n// let nodeCount = 0\n\n// Compiles schema in SchemaEnv\nexport function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv {\n // TODO refactor - remove compilations\n const _sch = getCompilingSchema.call(this, sch)\n if (_sch) return _sch\n const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails\n const {es5, lines} = this.opts.code\n const {ownProperties} = this.opts\n const gen = new CodeGen(this.scope, {es5, lines, ownProperties})\n let _ValidationError\n if (sch.$async) {\n _ValidationError = gen.scopeValue(\"Error\", {\n ref: ValidationError,\n code: _`require(\"ajv/dist/runtime/validation_error\").default`,\n })\n }\n\n const validateName = gen.scopeName(\"validate\")\n sch.validateName = validateName\n\n const schemaCxt: SchemaCxt = {\n gen,\n allErrors: this.opts.allErrors,\n data: N.data,\n parentData: N.parentData,\n parentDataProperty: N.parentDataProperty,\n dataNames: [N.data],\n dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed?\n dataLevel: 0,\n dataTypes: [],\n definedProperties: new Set<string>(),\n topSchemaRef: gen.scopeValue(\n \"schema\",\n this.opts.code.source === true\n ? {ref: sch.schema, code: stringify(sch.schema)}\n : {ref: sch.schema}\n ),\n validateName,\n ValidationError: _ValidationError,\n schema: sch.schema,\n schemaEnv: sch,\n rootId,\n baseId: sch.baseId || rootId,\n schemaPath: nil,\n errSchemaPath: sch.schemaPath || (this.opts.jtd ? \"\" : \"#\"),\n errorPath: _`\"\"`,\n opts: this.opts,\n self: this,\n }\n\n let sourceCode: string | undefined\n try {\n this._compilations.add(sch)\n validateFunctionCode(schemaCxt)\n gen.optimize(this.opts.code.optimize)\n // gen.optimize(1)\n const validateCode = gen.toString()\n sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}`\n // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))\n if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch)\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode)\n const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode)\n const validate: AnyValidateFunction = makeValidate(this, this.scope.get())\n this.scope.value(validateName, {ref: validate})\n\n validate.errors = null\n validate.schema = sch.schema\n validate.schemaEnv = sch\n if (sch.$async) (validate as AsyncValidateFunction).$async = true\n if (this.opts.code.source === true) {\n validate.source = {validateName, validateCode, scopeValues: gen._values}\n }\n if (this.opts.unevaluated) {\n const {props, items} = schemaCxt\n validate.evaluated = {\n props: props instanceof Name ? undefined : props,\n items: items instanceof Name ? undefined : items,\n dynamicProps: props instanceof Name,\n dynamicItems: items instanceof Name,\n }\n if (validate.source) validate.source.evaluated = stringify(validate.evaluated)\n }\n sch.validate = validate\n return sch\n } catch (e) {\n delete sch.validate\n delete sch.validateName\n if (sourceCode) this.logger.error(\"Error compiling schema, function code:\", sourceCode)\n // console.log(\"\\n\\n\\n *** \\n\", sourceCode, this.opts)\n throw e\n } finally {\n this._compilations.delete(sch)\n }\n}\n\nexport function resolveRef(\n this: Ajv,\n root: SchemaEnv,\n baseId: string,\n ref: string\n): AnySchema | SchemaEnv | undefined {\n ref = resolveUrl(this.opts.uriResolver, baseId, ref)\n const schOrFunc = root.refs[ref]\n if (schOrFunc) return schOrFunc\n\n let _sch = resolve.call(this, root, ref)\n if (_sch === undefined) {\n const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv\n const {schemaId} = this.opts\n if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId})\n }\n\n if (_sch === undefined) return\n return (root.refs[ref] = inlineOrCompile.call(this, _sch))\n}\n\nfunction inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv {\n if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema\n return sch.validate ? sch : compileSchema.call(this, sch)\n}\n\n// Index of schema compilation in the currently compiled list\nexport function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void {\n for (const sch of this._compilations) {\n if (sameSchemaEnv(sch, schEnv)) return sch\n }\n}\n\nfunction sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean {\n return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId\n}\n\n// resolve and compile the references ($ref)\n// TODO returns AnySchemaObject (if the schema can be inlined) or validation function\nfunction resolve(\n this: Ajv,\n root: SchemaEnv, // information about the root schema for the current schema\n ref: string // reference to resolve\n): SchemaEnv | undefined {\n let sch\n while (typeof (sch = this.refs[ref]) == \"string\") ref = sch\n return sch || this.schemas[ref] || resolveSchema.call(this, root, ref)\n}\n\n// Resolve schema, its root and baseId\nexport function resolveSchema(\n this: Ajv,\n root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it\n ref: string // reference to resolve\n): SchemaEnv | undefined {\n const p = this.opts.uriResolver.parse(ref)\n const refPath = _getFullPath(this.opts.uriResolver, p)\n let baseId = getFullPath(this.opts.uriResolver, root.baseId, undefined)\n // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests\n if (Object.keys(root.schema).length > 0 && refPath === baseId) {\n return getJsonPointer.call(this, p, root)\n }\n\n const id = normalizeId(refPath)\n const schOrRef = this.refs[id] || this.schemas[id]\n if (typeof schOrRef == \"string\") {\n const sch = resolveSchema.call(this, root, schOrRef)\n if (typeof sch?.schema !== \"object\") return\n return getJsonPointer.call(this, p, sch)\n }\n\n if (typeof schOrRef?.schema !== \"object\") return\n if (!schOrRef.validate) compileSchema.call(this, schOrRef)\n if (id === normalizeId(ref)) {\n const {schema} = schOrRef\n const {schemaId} = this.opts\n const schId = schema[schemaId]\n if (schId) baseId = resolveUrl(this.opts.uriResolver, baseId, schId)\n return new SchemaEnv({schema, schemaId, root, baseId})\n }\n return getJsonPointer.call(this, p, schOrRef)\n}\n\nconst PREVENT_SCOPE_CHANGE = new Set([\n \"properties\",\n \"patternProperties\",\n \"enum\",\n \"dependencies\",\n \"definitions\",\n])\n\nfunction getJsonPointer(\n this: Ajv,\n parsedRef: URIComponent,\n {baseId, schema, root}: SchemaEnv\n): SchemaEnv | undefined {\n if (parsedRef.fragment?.[0] !== \"/\") return\n for (const part of parsedRef.fragment.slice(1).split(\"/\")) {\n if (typeof schema === \"boolean\") return\n const partSchema = schema[unescapeFragment(part)]\n if (partSchema === undefined) return\n schema = partSchema\n // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?\n const schId = typeof schema === \"object\" && schema[this.opts.schemaId]\n if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {\n baseId = resolveUrl(this.opts.uriResolver, baseId, schId)\n }\n }\n let env: SchemaEnv | undefined\n if (typeof schema != \"boolean\" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {\n const $ref = resolveUrl(this.opts.uriResolver, baseId, schema.$ref)\n env = resolveSchema.call(this, root, $ref)\n }\n // even though resolution failed we need to return SchemaEnv to throw exception\n // so that compileAsync loads missing schema.\n const {schemaId} = this.opts\n env = env || new SchemaEnv({schema, schemaId, root, baseId})\n if (env.schema !== env.root.schema) return env\n return undefined\n}\n", "{\n \"$id\": \"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\n \"description\": \"Meta-schema for $data reference (JSON AnySchema extension proposal)\",\n \"type\": \"object\",\n \"required\": [\"$data\"],\n \"properties\": {\n \"$data\": {\n \"type\": \"string\",\n \"anyOf\": [{\"format\": \"relative-json-pointer\"}, {\"format\": \"json-pointer\"}]\n }\n },\n \"additionalProperties\": false\n}\n", "'use strict'\n\nconst HEX = {\n 0: 0,\n 1: 1,\n 2: 2,\n 3: 3,\n 4: 4,\n 5: 5,\n 6: 6,\n 7: 7,\n 8: 8,\n 9: 9,\n a: 10,\n A: 10,\n b: 11,\n B: 11,\n c: 12,\n C: 12,\n d: 13,\n D: 13,\n e: 14,\n E: 14,\n f: 15,\n F: 15\n}\n\nmodule.exports = {\n HEX\n}\n", "'use strict'\n\nconst { HEX } = require('./scopedChars')\n\nconst IPV4_REG = /^(?:(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)$/u\n\nfunction normalizeIPv4 (host) {\n if (findToken(host, '.') < 3) { return { host, isIPV4: false } }\n const matches = host.match(IPV4_REG) || []\n const [address] = matches\n if (address) {\n return { host: stripLeadingZeros(address, '.'), isIPV4: true }\n } else {\n return { host, isIPV4: false }\n }\n}\n\n/**\n * @param {string[]} input\n * @param {boolean} [keepZero=false]\n * @returns {string|undefined}\n */\nfunction stringArrayToHexStripped (input, keepZero = false) {\n let acc = ''\n let strip = true\n for (const c of input) {\n if (HEX[c] === undefined) return undefined\n if (c !== '0' && strip === true) strip = false\n if (!strip) acc += c\n }\n if (keepZero && acc.length === 0) acc = '0'\n return acc\n}\n\nfunction getIPV6 (input) {\n let tokenCount = 0\n const output = { error: false, address: '', zone: '' }\n const address = []\n const buffer = []\n let isZone = false\n let endipv6Encountered = false\n let endIpv6 = false\n\n function consume () {\n if (buffer.length) {\n if (isZone === false) {\n const hex = stringArrayToHexStripped(buffer)\n if (hex !== undefined) {\n address.push(hex)\n } else {\n output.error = true\n return false\n }\n }\n buffer.length = 0\n }\n return true\n }\n\n for (let i = 0; i < input.length; i++) {\n const cursor = input[i]\n if (cursor === '[' || cursor === ']') { continue }\n if (cursor === ':') {\n if (endipv6Encountered === true) {\n endIpv6 = true\n }\n if (!consume()) { break }\n tokenCount++\n address.push(':')\n if (tokenCount > 7) {\n // not valid\n output.error = true\n break\n }\n if (i - 1 >= 0 && input[i - 1] === ':') {\n endipv6Encountered = true\n }\n continue\n } else if (cursor === '%') {\n if (!consume()) { break }\n // switch to zone detection\n isZone = true\n } else {\n buffer.push(cursor)\n continue\n }\n }\n if (buffer.length) {\n if (isZone) {\n output.zone = buffer.join('')\n } else if (endIpv6) {\n address.push(buffer.join(''))\n } else {\n address.push(stringArrayToHexStripped(buffer))\n }\n }\n output.address = address.join('')\n return output\n}\n\nfunction normalizeIPv6 (host) {\n if (findToken(host, ':') < 2) { return { host, isIPV6: false } }\n const ipv6 = getIPV6(host)\n\n if (!ipv6.error) {\n let newHost = ipv6.address\n let escapedHost = ipv6.address\n if (ipv6.zone) {\n newHost += '%' + ipv6.zone\n escapedHost += '%25' + ipv6.zone\n }\n return { host: newHost, escapedHost, isIPV6: true }\n } else {\n return { host, isIPV6: false }\n }\n}\n\nfunction stripLeadingZeros (str, token) {\n let out = ''\n let skip = true\n const l = str.length\n for (let i = 0; i < l; i++) {\n const c = str[i]\n if (c === '0' && skip) {\n if ((i + 1 <= l && str[i + 1] === token) || i + 1 === l) {\n out += c\n skip = false\n }\n } else {\n if (c === token) {\n skip = true\n } else {\n skip = false\n }\n out += c\n }\n }\n return out\n}\n\nfunction findToken (str, token) {\n let ind = 0\n for (let i = 0; i < str.length; i++) {\n if (str[i] === token) ind++\n }\n return ind\n}\n\nconst RDS1 = /^\\.\\.?\\//u\nconst RDS2 = /^\\/\\.(?:\\/|$)/u\nconst RDS3 = /^\\/\\.\\.(?:\\/|$)/u\nconst RDS5 = /^\\/?(?:.|\\n)*?(?=\\/|$)/u\n\nfunction removeDotSegments (input) {\n const output = []\n\n while (input.length) {\n if (input.match(RDS1)) {\n input = input.replace(RDS1, '')\n } else if (input.match(RDS2)) {\n input = input.replace(RDS2, '/')\n } else if (input.match(RDS3)) {\n input = input.replace(RDS3, '/')\n output.pop()\n } else if (input === '.' || input === '..') {\n input = ''\n } else {\n const im = input.match(RDS5)\n if (im) {\n const s = im[0]\n input = input.slice(s.length)\n output.push(s)\n } else {\n throw new Error('Unexpected dot segment condition')\n }\n }\n }\n return output.join('')\n}\n\nfunction normalizeComponentEncoding (components, esc) {\n const func = esc !== true ? escape : unescape\n if (components.scheme !== undefined) {\n components.scheme = func(components.scheme)\n }\n if (components.userinfo !== undefined) {\n components.userinfo = func(components.userinfo)\n }\n if (components.host !== undefined) {\n components.host = func(components.host)\n }\n if (components.path !== undefined) {\n components.path = func(components.path)\n }\n if (components.query !== undefined) {\n components.query = func(components.query)\n }\n if (components.fragment !== undefined) {\n components.fragment = func(components.fragment)\n }\n return components\n}\n\nfunction recomposeAuthority (components) {\n const uriTokens = []\n\n if (components.userinfo !== undefined) {\n uriTokens.push(components.userinfo)\n uriTokens.push('@')\n }\n\n if (components.host !== undefined) {\n let host = unescape(components.host)\n const ipV4res = normalizeIPv4(host)\n\n if (ipV4res.isIPV4) {\n host = ipV4res.host\n } else {\n const ipV6res = normalizeIPv6(ipV4res.host)\n if (ipV6res.isIPV6 === true) {\n host = `[${ipV6res.escapedHost}]`\n } else {\n host = components.host\n }\n }\n uriTokens.push(host)\n }\n\n if (typeof components.port === 'number' || typeof components.port === 'string') {\n uriTokens.push(':')\n uriTokens.push(String(components.port))\n }\n\n return uriTokens.length ? uriTokens.join('') : undefined\n};\n\nmodule.exports = {\n recomposeAuthority,\n normalizeComponentEncoding,\n removeDotSegments,\n normalizeIPv4,\n normalizeIPv6,\n stringArrayToHexStripped\n}\n", "'use strict'\n\nconst UUID_REG = /^[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12}$/iu\nconst URN_REG = /([\\da-z][\\d\\-a-z]{0,31}):((?:[\\w!$'()*+,\\-.:;=@]|%[\\da-f]{2})+)/iu\n\nfunction isSecure (wsComponents) {\n return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === 'wss'\n}\n\nfunction httpParse (components) {\n if (!components.host) {\n components.error = components.error || 'HTTP URIs must have a host.'\n }\n\n return components\n}\n\nfunction httpSerialize (components) {\n const secure = String(components.scheme).toLowerCase() === 'https'\n\n // normalize the default port\n if (components.port === (secure ? 443 : 80) || components.port === '') {\n components.port = undefined\n }\n\n // normalize the empty path\n if (!components.path) {\n components.path = '/'\n }\n\n // NOTE: We do not parse query strings for HTTP URIs\n // as WWW Form Url Encoded query strings are part of the HTML4+ spec,\n // and not the HTTP spec.\n\n return components\n}\n\nfunction wsParse (wsComponents) {\n// indicate if the secure flag is set\n wsComponents.secure = isSecure(wsComponents)\n\n // construct resouce name\n wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '')\n wsComponents.path = undefined\n wsComponents.query = undefined\n\n return wsComponents\n}\n\nfunction wsSerialize (wsComponents) {\n// normalize the default port\n if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === '') {\n wsComponents.port = undefined\n }\n\n // ensure scheme matches secure flag\n if (typeof wsComponents.secure === 'boolean') {\n wsComponents.scheme = (wsComponents.secure ? 'wss' : 'ws')\n wsComponents.secure = undefined\n }\n\n // reconstruct path from resource name\n if (wsComponents.resourceName) {\n const [path, query] = wsComponents.resourceName.split('?')\n wsComponents.path = (path && path !== '/' ? path : undefined)\n wsComponents.query = query\n wsComponents.resourceName = undefined\n }\n\n // forbid fragment component\n wsComponents.fragment = undefined\n\n return wsComponents\n}\n\nfunction urnParse (urnComponents, options) {\n if (!urnComponents.path) {\n urnComponents.error = 'URN can not be parsed'\n return urnComponents\n }\n const matches = urnComponents.path.match(URN_REG)\n if (matches) {\n const scheme = options.scheme || urnComponents.scheme || 'urn'\n urnComponents.nid = matches[1].toLowerCase()\n urnComponents.nss = matches[2]\n const urnScheme = `${scheme}:${options.nid || urnComponents.nid}`\n const schemeHandler = SCHEMES[urnScheme]\n urnComponents.path = undefined\n\n if (schemeHandler) {\n urnComponents = schemeHandler.parse(urnComponents, options)\n }\n } else {\n urnComponents.error = urnComponents.error || 'URN can not be parsed.'\n }\n\n return urnComponents\n}\n\nfunction urnSerialize (urnComponents, options) {\n const scheme = options.scheme || urnComponents.scheme || 'urn'\n const nid = urnComponents.nid.toLowerCase()\n const urnScheme = `${scheme}:${options.nid || nid}`\n const schemeHandler = SCHEMES[urnScheme]\n\n if (schemeHandler) {\n urnComponents = schemeHandler.serialize(urnComponents, options)\n }\n\n const uriComponents = urnComponents\n const nss = urnComponents.nss\n uriComponents.path = `${nid || options.nid}:${nss}`\n\n options.skipEscape = true\n return uriComponents\n}\n\nfunction urnuuidParse (urnComponents, options) {\n const uuidComponents = urnComponents\n uuidComponents.uuid = uuidComponents.nss\n uuidComponents.nss = undefined\n\n if (!options.tolerant && (!uuidComponents.uuid || !UUID_REG.test(uuidComponents.uuid))) {\n uuidComponents.error = uuidComponents.error || 'UUID is not valid.'\n }\n\n return uuidComponents\n}\n\nfunction urnuuidSerialize (uuidComponents) {\n const urnComponents = uuidComponents\n // normalize UUID\n urnComponents.nss = (uuidComponents.uuid || '').toLowerCase()\n return urnComponents\n}\n\nconst http = {\n scheme: 'http',\n domainHost: true,\n parse: httpParse,\n serialize: httpSerialize\n}\n\nconst https = {\n scheme: 'https',\n domainHost: http.domainHost,\n parse: httpParse,\n serialize: httpSerialize\n}\n\nconst ws = {\n scheme: 'ws',\n domainHost: true,\n parse: wsParse,\n serialize: wsSerialize\n}\n\nconst wss = {\n scheme: 'wss',\n domainHost: ws.domainHost,\n parse: ws.parse,\n serialize: ws.serialize\n}\n\nconst urn = {\n scheme: 'urn',\n parse: urnParse,\n serialize: urnSerialize,\n skipNormalize: true\n}\n\nconst urnuuid = {\n scheme: 'urn:uuid',\n parse: urnuuidParse,\n serialize: urnuuidSerialize,\n skipNormalize: true\n}\n\nconst SCHEMES = {\n http,\n https,\n ws,\n wss,\n urn,\n 'urn:uuid': urnuuid\n}\n\nmodule.exports = SCHEMES\n", "'use strict'\n\nconst { normalizeIPv6, normalizeIPv4, removeDotSegments, recomposeAuthority, normalizeComponentEncoding } = require('./lib/utils')\nconst SCHEMES = require('./lib/schemes')\n\nfunction normalize (uri, options) {\n if (typeof uri === 'string') {\n uri = serialize(parse(uri, options), options)\n } else if (typeof uri === 'object') {\n uri = parse(serialize(uri, options), options)\n }\n return uri\n}\n\nfunction resolve (baseURI, relativeURI, options) {\n const schemelessOptions = Object.assign({ scheme: 'null' }, options)\n const resolved = resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true)\n return serialize(resolved, { ...schemelessOptions, skipEscape: true })\n}\n\nfunction resolveComponents (base, relative, options, skipNormalization) {\n const target = {}\n if (!skipNormalization) {\n base = parse(serialize(base, options), options) // normalize base components\n relative = parse(serialize(relative, options), options) // normalize relative components\n }\n options = options || {}\n\n if (!options.tolerant && relative.scheme) {\n target.scheme = relative.scheme\n // target.authority = relative.authority;\n target.userinfo = relative.userinfo\n target.host = relative.host\n target.port = relative.port\n target.path = removeDotSegments(relative.path || '')\n target.query = relative.query\n } else {\n if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {\n // target.authority = relative.authority;\n target.userinfo = relative.userinfo\n target.host = relative.host\n target.port = relative.port\n target.path = removeDotSegments(relative.path || '')\n target.query = relative.query\n } else {\n if (!relative.path) {\n target.path = base.path\n if (relative.query !== undefined) {\n target.query = relative.query\n } else {\n target.query = base.query\n }\n } else {\n if (relative.path.charAt(0) === '/') {\n target.path = removeDotSegments(relative.path)\n } else {\n if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {\n target.path = '/' + relative.path\n } else if (!base.path) {\n target.path = relative.path\n } else {\n target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path\n }\n target.path = removeDotSegments(target.path)\n }\n target.query = relative.query\n }\n // target.authority = base.authority;\n target.userinfo = base.userinfo\n target.host = base.host\n target.port = base.port\n }\n target.scheme = base.scheme\n }\n\n target.fragment = relative.fragment\n\n return target\n}\n\nfunction equal (uriA, uriB, options) {\n if (typeof uriA === 'string') {\n uriA = unescape(uriA)\n uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { ...options, skipEscape: true })\n } else if (typeof uriA === 'object') {\n uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true })\n }\n\n if (typeof uriB === 'string') {\n uriB = unescape(uriB)\n uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { ...options, skipEscape: true })\n } else if (typeof uriB === 'object') {\n uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true })\n }\n\n return uriA.toLowerCase() === uriB.toLowerCase()\n}\n\nfunction serialize (cmpts, opts) {\n const components = {\n host: cmpts.host,\n scheme: cmpts.scheme,\n userinfo: cmpts.userinfo,\n port: cmpts.port,\n path: cmpts.path,\n query: cmpts.query,\n nid: cmpts.nid,\n nss: cmpts.nss,\n uuid: cmpts.uuid,\n fragment: cmpts.fragment,\n reference: cmpts.reference,\n resourceName: cmpts.resourceName,\n secure: cmpts.secure,\n error: ''\n }\n const options = Object.assign({}, opts)\n const uriTokens = []\n\n // find scheme handler\n const schemeHandler = SCHEMES[(options.scheme || components.scheme || '').toLowerCase()]\n\n // perform scheme specific serialization\n if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options)\n\n if (components.path !== undefined) {\n if (!options.skipEscape) {\n components.path = escape(components.path)\n\n if (components.scheme !== undefined) {\n components.path = components.path.split('%3A').join(':')\n }\n } else {\n components.path = unescape(components.path)\n }\n }\n\n if (options.reference !== 'suffix' && components.scheme) {\n uriTokens.push(components.scheme, ':')\n }\n\n const authority = recomposeAuthority(components)\n if (authority !== undefined) {\n if (options.reference !== 'suffix') {\n uriTokens.push('//')\n }\n\n uriTokens.push(authority)\n\n if (components.path && components.path.charAt(0) !== '/') {\n uriTokens.push('/')\n }\n }\n if (components.path !== undefined) {\n let s = components.path\n\n if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {\n s = removeDotSegments(s)\n }\n\n if (authority === undefined) {\n s = s.replace(/^\\/\\//u, '/%2F') // don't allow the path to start with \"//\"\n }\n\n uriTokens.push(s)\n }\n\n if (components.query !== undefined) {\n uriTokens.push('?', components.query)\n }\n\n if (components.fragment !== undefined) {\n uriTokens.push('#', components.fragment)\n }\n return uriTokens.join('')\n}\n\nconst hexLookUp = Array.from({ length: 127 }, (_v, k) => /[^!\"$&'()*+,\\-.;=_`a-z{}~]/u.test(String.fromCharCode(k)))\n\nfunction nonSimpleDomain (value) {\n let code = 0\n for (let i = 0, len = value.length; i < len; ++i) {\n code = value.charCodeAt(i)\n if (code > 126 || hexLookUp[code]) {\n return true\n }\n }\n return false\n}\n\nconst URI_PARSE = /^(?:([^#/:?]+):)?(?:\\/\\/((?:([^#/?@]*)@)?(\\[[^#/?\\]]+\\]|[^#/:?]*)(?::(\\d*))?))?([^#?]*)(?:\\?([^#]*))?(?:#((?:.|[\\n\\r])*))?/u\n\nfunction parse (uri, opts) {\n const options = Object.assign({}, opts)\n const parsed = {\n scheme: undefined,\n userinfo: undefined,\n host: '',\n port: undefined,\n path: '',\n query: undefined,\n fragment: undefined\n }\n const gotEncoding = uri.indexOf('%') !== -1\n let isIP = false\n if (options.reference === 'suffix') uri = (options.scheme ? options.scheme + ':' : '') + '//' + uri\n\n const matches = uri.match(URI_PARSE)\n\n if (matches) {\n // store each component\n parsed.scheme = matches[1]\n parsed.userinfo = matches[3]\n parsed.host = matches[4]\n parsed.port = parseInt(matches[5], 10)\n parsed.path = matches[6] || ''\n parsed.query = matches[7]\n parsed.fragment = matches[8]\n\n // fix port number\n if (isNaN(parsed.port)) {\n parsed.port = matches[5]\n }\n if (parsed.host) {\n const ipv4result = normalizeIPv4(parsed.host)\n if (ipv4result.isIPV4 === false) {\n const ipv6result = normalizeIPv6(ipv4result.host)\n parsed.host = ipv6result.host.toLowerCase()\n isIP = ipv6result.isIPV6\n } else {\n parsed.host = ipv4result.host\n isIP = true\n }\n }\n if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {\n parsed.reference = 'same-document'\n } else if (parsed.scheme === undefined) {\n parsed.reference = 'relative'\n } else if (parsed.fragment === undefined) {\n parsed.reference = 'absolute'\n } else {\n parsed.reference = 'uri'\n }\n\n // check for reference errors\n if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {\n parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.'\n }\n\n // find scheme handler\n const schemeHandler = SCHEMES[(options.scheme || parsed.scheme || '').toLowerCase()]\n\n // check if scheme can't handle IRIs\n if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {\n // if host component is a domain name\n if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) {\n // convert Unicode IDN -> ASCII IDN\n try {\n parsed.host = URL.domainToASCII(parsed.host.toLowerCase())\n } catch (e) {\n parsed.error = parsed.error || \"Host's domain name can not be converted to ASCII: \" + e\n }\n }\n // convert IRI -> URI\n }\n\n if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {\n if (gotEncoding && parsed.scheme !== undefined) {\n parsed.scheme = unescape(parsed.scheme)\n }\n if (gotEncoding && parsed.host !== undefined) {\n parsed.host = unescape(parsed.host)\n }\n if (parsed.path) {\n parsed.path = escape(unescape(parsed.path))\n }\n if (parsed.fragment) {\n parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment))\n }\n }\n\n // perform scheme specific parsing\n if (schemeHandler && schemeHandler.parse) {\n schemeHandler.parse(parsed, options)\n }\n } else {\n parsed.error = parsed.error || 'URI can not be parsed.'\n }\n return parsed\n}\n\nconst fastUri = {\n SCHEMES,\n normalize,\n resolve,\n resolveComponents,\n equal,\n serialize,\n parse\n}\n\nmodule.exports = fastUri\nmodule.exports.default = fastUri\nmodule.exports.fastUri = fastUri\n", "import * as uri from \"fast-uri\"\n\ntype URI = typeof uri & {code: string}\n;(uri as URI).code = 'require(\"ajv/dist/runtime/uri\").default'\n\nexport default uri as URI\n", "export {\n Format,\n FormatDefinition,\n AsyncFormatDefinition,\n KeywordDefinition,\n KeywordErrorDefinition,\n CodeKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n Vocabulary,\n Schema,\n SchemaObject,\n AnySchemaObject,\n AsyncSchema,\n AnySchema,\n ValidateFunction,\n AsyncValidateFunction,\n AnyValidateFunction,\n ErrorObject,\n ErrorNoParams,\n} from \"./types\"\n\nexport {SchemaCxt, SchemaObjCxt} from \"./compile\"\nexport interface Plugin<Opts> {\n (ajv: Ajv, options?: Opts): Ajv\n [prop: string]: any\n}\n\nexport {KeywordCxt} from \"./compile/validate\"\nexport {DefinedError} from \"./vocabularies/errors\"\nexport {JSONType} from \"./compile/rules\"\nexport {JSONSchemaType} from \"./types/json-schema\"\nexport {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from \"./types/jtd-schema\"\nexport {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from \"./compile/codegen\"\n\nimport type {\n Schema,\n AnySchema,\n AnySchemaObject,\n SchemaObject,\n AsyncSchema,\n Vocabulary,\n KeywordDefinition,\n AddedKeywordDefinition,\n AnyValidateFunction,\n ValidateFunction,\n AsyncValidateFunction,\n ErrorObject,\n Format,\n AddedFormat,\n RegExpEngine,\n UriResolver,\n} from \"./types\"\nimport type {JSONSchemaType} from \"./types/json-schema\"\nimport type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from \"./types/jtd-schema\"\nimport ValidationError from \"./runtime/validation_error\"\nimport MissingRefError from \"./compile/ref_error\"\nimport {getRules, ValidationRules, Rule, RuleGroup, JSONType} from \"./compile/rules\"\nimport {SchemaEnv, compileSchema, resolveSchema} from \"./compile\"\nimport {Code, ValueScope} from \"./compile/codegen\"\nimport {normalizeId, getSchemaRefs} from \"./compile/resolve\"\nimport {getJSONTypes} from \"./compile/validate/dataType\"\nimport {eachItem} from \"./compile/util\"\nimport * as $dataRefSchema from \"./refs/data.json\"\n\nimport DefaultUriResolver from \"./runtime/uri\"\n\nconst defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags)\ndefaultRegExp.code = \"new RegExp\"\n\nconst META_IGNORE_OPTIONS: (keyof Options)[] = [\"removeAdditional\", \"useDefaults\", \"coerceTypes\"]\nconst EXT_SCOPE_NAMES = new Set([\n \"validate\",\n \"serialize\",\n \"parse\",\n \"wrapper\",\n \"root\",\n \"schema\",\n \"keyword\",\n \"pattern\",\n \"formats\",\n \"validate$data\",\n \"func\",\n \"obj\",\n \"Error\",\n])\n\nexport type Options = CurrentOptions & DeprecatedOptions\n\nexport interface CurrentOptions {\n // strict mode options (NEW)\n strict?: boolean | \"log\"\n strictSchema?: boolean | \"log\"\n strictNumbers?: boolean | \"log\"\n strictTypes?: boolean | \"log\"\n strictTuples?: boolean | \"log\"\n strictRequired?: boolean | \"log\"\n allowMatchingProperties?: boolean // disables a strict mode restriction\n allowUnionTypes?: boolean\n validateFormats?: boolean\n // validation and reporting options:\n $data?: boolean\n allErrors?: boolean\n verbose?: boolean\n discriminator?: boolean\n unicodeRegExp?: boolean\n timestamp?: \"string\" | \"date\" // JTD only\n parseDate?: boolean // JTD only\n allowDate?: boolean // JTD only\n $comment?:\n | true\n | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown)\n formats?: {[Name in string]?: Format}\n keywords?: Vocabulary\n schemas?: AnySchema[] | {[Key in string]?: AnySchema}\n logger?: Logger | false\n loadSchema?: (uri: string) => Promise<AnySchemaObject>\n // options to modify validated data:\n removeAdditional?: boolean | \"all\" | \"failing\"\n useDefaults?: boolean | \"empty\"\n coerceTypes?: boolean | \"array\"\n // advanced options:\n next?: boolean // NEW\n unevaluated?: boolean // NEW\n dynamicRef?: boolean // NEW\n schemaId?: \"id\" | \"$id\"\n jtd?: boolean // NEW\n meta?: SchemaObject | boolean\n defaultMeta?: string | AnySchemaObject\n validateSchema?: boolean | \"log\"\n addUsedSchema?: boolean\n inlineRefs?: boolean | number\n passContext?: boolean\n loopRequired?: number\n loopEnum?: number // NEW\n ownProperties?: boolean\n multipleOfPrecision?: number\n int32range?: boolean // JTD only\n messages?: boolean\n code?: CodeOptions // NEW\n uriResolver?: UriResolver\n}\n\nexport interface CodeOptions {\n es5?: boolean\n esm?: boolean\n lines?: boolean\n optimize?: boolean | number\n formats?: Code // code to require (or construct) map of available formats - for standalone code\n source?: boolean\n process?: (code: string, schema?: SchemaEnv) => string\n regExp?: RegExpEngine\n}\n\ninterface InstanceCodeOptions extends CodeOptions {\n regExp: RegExpEngine\n optimize: number\n}\n\ninterface DeprecatedOptions {\n /** @deprecated */\n ignoreKeywordsWithRef?: boolean\n /** @deprecated */\n jsPropertySyntax?: boolean // added instead of jsonPointers\n /** @deprecated */\n unicode?: boolean\n}\n\ninterface RemovedOptions {\n format?: boolean\n errorDataPath?: \"object\" | \"property\"\n nullable?: boolean // \"nullable\" keyword is supported by default\n jsonPointers?: boolean\n extendRefs?: true | \"ignore\" | \"fail\"\n missingRefs?: true | \"ignore\" | \"fail\"\n processCode?: (code: string, schema?: SchemaEnv) => string\n sourceCode?: boolean\n strictDefaults?: boolean\n strictKeywords?: boolean\n uniqueItems?: boolean\n unknownFormats?: true | string[] | \"ignore\"\n cache?: any\n serialize?: (schema: AnySchema) => unknown\n ajvErrors?: boolean\n}\n\ntype OptionsInfo<T extends RemovedOptions | DeprecatedOptions> = {\n [K in keyof T]-?: string | undefined\n}\n\nconst removedOptions: OptionsInfo<RemovedOptions> = {\n errorDataPath: \"\",\n format: \"`validateFormats: false` can be used instead.\",\n nullable: '\"nullable\" keyword is supported by default.',\n jsonPointers: \"Deprecated jsPropertySyntax can be used instead.\",\n extendRefs: \"Deprecated ignoreKeywordsWithRef can be used instead.\",\n missingRefs: \"Pass empty schema with $id that should be ignored to ajv.addSchema.\",\n processCode: \"Use option `code: {process: (code, schemaEnv: object) => string}`\",\n sourceCode: \"Use option `code: {source: true}`\",\n strictDefaults: \"It is default now, see option `strict`.\",\n strictKeywords: \"It is default now, see option `strict`.\",\n uniqueItems: '\"uniqueItems\" keyword is always validated.',\n unknownFormats: \"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).\",\n cache: \"Map is used as cache, schema object as key.\",\n serialize: \"Map is used as cache, schema object as key.\",\n ajvErrors: \"It is default now.\",\n}\n\nconst deprecatedOptions: OptionsInfo<DeprecatedOptions> = {\n ignoreKeywordsWithRef: \"\",\n jsPropertySyntax: \"\",\n unicode: '\"minLength\"/\"maxLength\" account for unicode characters by default.',\n}\n\ntype RequiredInstanceOptions = {\n [K in\n | \"strictSchema\"\n | \"strictNumbers\"\n | \"strictTypes\"\n | \"strictTuples\"\n | \"strictRequired\"\n | \"inlineRefs\"\n | \"loopRequired\"\n | \"loopEnum\"\n | \"meta\"\n | \"messages\"\n | \"schemaId\"\n | \"addUsedSchema\"\n | \"validateSchema\"\n | \"validateFormats\"\n | \"int32range\"\n | \"unicodeRegExp\"\n | \"uriResolver\"]: NonNullable<Options[K]>\n} & {code: InstanceCodeOptions}\n\nexport type InstanceOptions = Options & RequiredInstanceOptions\n\nconst MAX_EXPRESSION = 200\n\n// eslint-disable-next-line complexity\nfunction requiredOptions(o: Options): RequiredInstanceOptions {\n const s = o.strict\n const _optz = o.code?.optimize\n const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0\n const regExp = o.code?.regExp ?? defaultRegExp\n const uriResolver = o.uriResolver ?? DefaultUriResolver\n return {\n strictSchema: o.strictSchema ?? s ?? true,\n strictNumbers: o.strictNumbers ?? s ?? true,\n strictTypes: o.strictTypes ?? s ?? \"log\",\n strictTuples: o.strictTuples ?? s ?? \"log\",\n strictRequired: o.strictRequired ?? s ?? false,\n code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp},\n loopRequired: o.loopRequired ?? MAX_EXPRESSION,\n loopEnum: o.loopEnum ?? MAX_EXPRESSION,\n meta: o.meta ?? true,\n messages: o.messages ?? true,\n inlineRefs: o.inlineRefs ?? true,\n schemaId: o.schemaId ?? \"$id\",\n addUsedSchema: o.addUsedSchema ?? true,\n validateSchema: o.validateSchema ?? true,\n validateFormats: o.validateFormats ?? true,\n unicodeRegExp: o.unicodeRegExp ?? true,\n int32range: o.int32range ?? true,\n uriResolver: uriResolver,\n }\n}\n\nexport interface Logger {\n log(...args: unknown[]): unknown\n warn(...args: unknown[]): unknown\n error(...args: unknown[]): unknown\n}\n\nexport default class Ajv {\n opts: InstanceOptions\n errors?: ErrorObject[] | null // errors from the last validation\n logger: Logger\n // shared external scope values for compiled functions\n readonly scope: ValueScope\n readonly schemas: {[Key in string]?: SchemaEnv} = {}\n readonly refs: {[Ref in string]?: SchemaEnv | string} = {}\n readonly formats: {[Name in string]?: AddedFormat} = {}\n readonly RULES: ValidationRules\n readonly _compilations: Set<SchemaEnv> = new Set()\n private readonly _loading: {[Ref in string]?: Promise<AnySchemaObject>} = {}\n private readonly _cache: Map<AnySchema, SchemaEnv> = new Map()\n private readonly _metaOpts: InstanceOptions\n\n static ValidationError = ValidationError\n static MissingRefError = MissingRefError\n\n constructor(opts: Options = {}) {\n opts = this.opts = {...opts, ...requiredOptions(opts)}\n const {es5, lines} = this.opts.code\n\n this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines})\n this.logger = getLogger(opts.logger)\n const formatOpt = opts.validateFormats\n opts.validateFormats = false\n\n this.RULES = getRules()\n checkOptions.call(this, removedOptions, opts, \"NOT SUPPORTED\")\n checkOptions.call(this, deprecatedOptions, opts, \"DEPRECATED\", \"warn\")\n this._metaOpts = getMetaSchemaOptions.call(this)\n\n if (opts.formats) addInitialFormats.call(this)\n this._addVocabularies()\n this._addDefaultMetaSchema()\n if (opts.keywords) addInitialKeywords.call(this, opts.keywords)\n if (typeof opts.meta == \"object\") this.addMetaSchema(opts.meta)\n addInitialSchemas.call(this)\n opts.validateFormats = formatOpt\n }\n\n _addVocabularies(): void {\n this.addKeyword(\"$async\")\n }\n\n _addDefaultMetaSchema(): void {\n const {$data, meta, schemaId} = this.opts\n let _dataRefSchema: SchemaObject = $dataRefSchema\n if (schemaId === \"id\") {\n _dataRefSchema = {...$dataRefSchema}\n _dataRefSchema.id = _dataRefSchema.$id\n delete _dataRefSchema.$id\n }\n if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false)\n }\n\n defaultMeta(): string | AnySchemaObject | undefined {\n const {meta, schemaId} = this.opts\n return (this.opts.defaultMeta = typeof meta == \"object\" ? meta[schemaId] || meta : undefined)\n }\n\n // Validate data using schema\n // AnySchema will be compiled and cached using schema itself as a key for Map\n validate(schema: Schema | string, data: unknown): boolean\n validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown>\n validate<T>(schema: Schema | JSONSchemaType<T> | string, data: unknown): data is T\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n validate<T>(schema: JTDSchemaType<T>, data: unknown): data is T\n // This overload is only intended for typescript inference, the first\n // argument prevents manual type annotation from matching this overload\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n validate<N extends never, T extends SomeJTDSchemaType>(\n schema: T,\n data: unknown\n ): data is JTDDataType<T>\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n validate<T>(schema: AsyncSchema, data: unknown | T): Promise<T>\n validate<T>(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise<T>\n validate<T>(\n schemaKeyRef: AnySchema | string, // key, ref or schema object\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n data: unknown | T // to be validated\n ): boolean | Promise<T> {\n let v: AnyValidateFunction | undefined\n if (typeof schemaKeyRef == \"string\") {\n v = this.getSchema<T>(schemaKeyRef)\n if (!v) throw new Error(`no schema with key or ref \"${schemaKeyRef}\"`)\n } else {\n v = this.compile<T>(schemaKeyRef)\n }\n\n const valid = v(data)\n if (!(\"$async\" in v)) this.errors = v.errors\n return valid\n }\n\n // Create validation function for passed schema\n // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords.\n compile<T = unknown>(schema: Schema | JSONSchemaType<T>, _meta?: boolean): ValidateFunction<T>\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compile<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): ValidateFunction<T>\n // This overload is only intended for typescript inference, the first\n // argument prevents manual type annotation from matching this overload\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n compile<N extends never, T extends SomeJTDSchemaType>(\n schema: T,\n _meta?: boolean\n ): ValidateFunction<JTDDataType<T>>\n compile<T = unknown>(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction<T>\n compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T>\n compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T> {\n const sch = this._addSchema(schema, _meta)\n return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T>\n }\n\n // Creates validating function for passed schema with asynchronous loading of missing schemas.\n // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.\n // TODO allow passing schema URI\n // meta - optional true to compile meta-schema\n compileAsync<T = unknown>(\n schema: SchemaObject | JSONSchemaType<T>,\n _meta?: boolean\n ): Promise<ValidateFunction<T>>\n // Separated for type inference to work\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compileAsync<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>>\n compileAsync<T = unknown>(schema: AsyncSchema, meta?: boolean): Promise<AsyncValidateFunction<T>>\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n compileAsync<T = unknown>(\n schema: AnySchemaObject,\n meta?: boolean\n ): Promise<AnyValidateFunction<T>>\n compileAsync<T = unknown>(\n schema: AnySchemaObject,\n meta?: boolean\n ): Promise<AnyValidateFunction<T>> {\n if (typeof this.opts.loadSchema != \"function\") {\n throw new Error(\"options.loadSchema should be a function\")\n }\n const {loadSchema} = this.opts\n return runCompileAsync.call(this, schema, meta)\n\n async function runCompileAsync(\n this: Ajv,\n _schema: AnySchemaObject,\n _meta?: boolean\n ): Promise<AnyValidateFunction> {\n await loadMetaSchema.call(this, _schema.$schema)\n const sch = this._addSchema(_schema, _meta)\n return sch.validate || _compileAsync.call(this, sch)\n }\n\n async function loadMetaSchema(this: Ajv, $ref?: string): Promise<void> {\n if ($ref && !this.getSchema($ref)) {\n await runCompileAsync.call(this, {$ref}, true)\n }\n }\n\n async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise<AnyValidateFunction> {\n try {\n return this._compileSchemaEnv(sch)\n } catch (e) {\n if (!(e instanceof MissingRefError)) throw e\n checkLoaded.call(this, e)\n await loadMissingSchema.call(this, e.missingSchema)\n return _compileAsync.call(this, sch)\n }\n }\n\n function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void {\n if (this.refs[ref]) {\n throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)\n }\n }\n\n async function loadMissingSchema(this: Ajv, ref: string): Promise<void> {\n const _schema = await _loadSchema.call(this, ref)\n if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema)\n if (!this.refs[ref]) this.addSchema(_schema, ref, meta)\n }\n\n async function _loadSchema(this: Ajv, ref: string): Promise<AnySchemaObject> {\n const p = this._loading[ref]\n if (p) return p\n try {\n return await (this._loading[ref] = loadSchema(ref))\n } finally {\n delete this._loading[ref]\n }\n }\n }\n\n // Adds schema to the instance\n addSchema(\n schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored\n key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.\n _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.\n _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.\n ): Ajv {\n if (Array.isArray(schema)) {\n for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema)\n return this\n }\n let id: string | undefined\n if (typeof schema === \"object\") {\n const {schemaId} = this.opts\n id = schema[schemaId]\n if (id !== undefined && typeof id != \"string\") {\n throw new Error(`schema ${schemaId} must be string`)\n }\n }\n key = normalizeId(key || id)\n this._checkUnique(key)\n this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true)\n return this\n }\n\n // Add schema that will be used to validate other schemas\n // options in META_IGNORE_OPTIONS are alway set to false\n addMetaSchema(\n schema: AnySchemaObject,\n key?: string, // schema key\n _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema\n ): Ajv {\n this.addSchema(schema, key, true, _validateSchema)\n return this\n }\n\n // Validate schema against its meta-schema\n validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise<unknown> {\n if (typeof schema == \"boolean\") return true\n let $schema: string | AnySchemaObject | undefined\n $schema = schema.$schema\n if ($schema !== undefined && typeof $schema != \"string\") {\n throw new Error(\"$schema must be a string\")\n }\n $schema = $schema || this.opts.defaultMeta || this.defaultMeta()\n if (!$schema) {\n this.logger.warn(\"meta-schema not available\")\n this.errors = null\n return true\n }\n const valid = this.validate($schema, schema)\n if (!valid && throwOrLogError) {\n const message = \"schema is invalid: \" + this.errorsText()\n if (this.opts.validateSchema === \"log\") this.logger.error(message)\n else throw new Error(message)\n }\n return valid\n }\n\n // Get compiled schema by `key` or `ref`.\n // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)\n getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined {\n let sch\n while (typeof (sch = getSchEnv.call(this, keyRef)) == \"string\") keyRef = sch\n if (sch === undefined) {\n const {schemaId} = this.opts\n const root = new SchemaEnv({schema: {}, schemaId})\n sch = resolveSchema.call(this, root, keyRef)\n if (!sch) return\n this.refs[keyRef] = sch\n }\n return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T> | undefined\n }\n\n // Remove cached schema(s).\n // If no parameter is passed all schemas but meta-schemas are removed.\n // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.\n // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.\n removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv {\n if (schemaKeyRef instanceof RegExp) {\n this._removeAllSchemas(this.schemas, schemaKeyRef)\n this._removeAllSchemas(this.refs, schemaKeyRef)\n return this\n }\n switch (typeof schemaKeyRef) {\n case \"undefined\":\n this._removeAllSchemas(this.schemas)\n this._removeAllSchemas(this.refs)\n this._cache.clear()\n return this\n case \"string\": {\n const sch = getSchEnv.call(this, schemaKeyRef)\n if (typeof sch == \"object\") this._cache.delete(sch.schema)\n delete this.schemas[schemaKeyRef]\n delete this.refs[schemaKeyRef]\n return this\n }\n case \"object\": {\n const cacheKey = schemaKeyRef\n this._cache.delete(cacheKey)\n let id = schemaKeyRef[this.opts.schemaId]\n if (id) {\n id = normalizeId(id)\n delete this.schemas[id]\n delete this.refs[id]\n }\n return this\n }\n default:\n throw new Error(\"ajv.removeSchema: invalid parameter\")\n }\n }\n\n // add \"vocabulary\" - a collection of keywords\n addVocabulary(definitions: Vocabulary): Ajv {\n for (const def of definitions) this.addKeyword(def)\n return this\n }\n\n addKeyword(\n kwdOrDef: string | KeywordDefinition,\n def?: KeywordDefinition // deprecated\n ): Ajv {\n let keyword: string | string[]\n if (typeof kwdOrDef == \"string\") {\n keyword = kwdOrDef\n if (typeof def == \"object\") {\n this.logger.warn(\"these parameters are deprecated, see docs for addKeyword\")\n def.keyword = keyword\n }\n } else if (typeof kwdOrDef == \"object\" && def === undefined) {\n def = kwdOrDef\n keyword = def.keyword\n if (Array.isArray(keyword) && !keyword.length) {\n throw new Error(\"addKeywords: keyword must be string or non-empty array\")\n }\n } else {\n throw new Error(\"invalid addKeywords parameters\")\n }\n\n checkKeyword.call(this, keyword, def)\n if (!def) {\n eachItem(keyword, (kwd) => addRule.call(this, kwd))\n return this\n }\n keywordMetaschema.call(this, def)\n const definition: AddedKeywordDefinition = {\n ...def,\n type: getJSONTypes(def.type),\n schemaType: getJSONTypes(def.schemaType),\n }\n eachItem(\n keyword,\n definition.type.length === 0\n ? (k) => addRule.call(this, k, definition)\n : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))\n )\n return this\n }\n\n getKeyword(keyword: string): AddedKeywordDefinition | boolean {\n const rule = this.RULES.all[keyword]\n return typeof rule == \"object\" ? rule.definition : !!rule\n }\n\n // Remove keyword\n removeKeyword(keyword: string): Ajv {\n // TODO return type should be Ajv\n const {RULES} = this\n delete RULES.keywords[keyword]\n delete RULES.all[keyword]\n for (const group of RULES.rules) {\n const i = group.rules.findIndex((rule) => rule.keyword === keyword)\n if (i >= 0) group.rules.splice(i, 1)\n }\n return this\n }\n\n // Add format\n addFormat(name: string, format: Format): Ajv {\n if (typeof format == \"string\") format = new RegExp(format)\n this.formats[name] = format\n return this\n }\n\n errorsText(\n errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors\n {separator = \", \", dataVar = \"data\"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar`\n ): string {\n if (!errors || errors.length === 0) return \"No errors\"\n return errors\n .map((e) => `${dataVar}${e.instancePath} ${e.message}`)\n .reduce((text, msg) => text + separator + msg)\n }\n\n $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject {\n const rules = this.RULES.all\n metaSchema = JSON.parse(JSON.stringify(metaSchema))\n for (const jsonPointer of keywordsJsonPointers) {\n const segments = jsonPointer.split(\"/\").slice(1) // first segment is an empty string\n let keywords = metaSchema\n for (const seg of segments) keywords = keywords[seg] as AnySchemaObject\n\n for (const key in rules) {\n const rule = rules[key]\n if (typeof rule != \"object\") continue\n const {$data} = rule.definition\n const schema = keywords[key] as AnySchemaObject | undefined\n if ($data && schema) keywords[key] = schemaOrData(schema)\n }\n }\n\n return metaSchema\n }\n\n private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void {\n for (const keyRef in schemas) {\n const sch = schemas[keyRef]\n if (!regex || regex.test(keyRef)) {\n if (typeof sch == \"string\") {\n delete schemas[keyRef]\n } else if (sch && !sch.meta) {\n this._cache.delete(sch.schema)\n delete schemas[keyRef]\n }\n }\n }\n }\n\n _addSchema(\n schema: AnySchema,\n meta?: boolean,\n baseId?: string,\n validateSchema = this.opts.validateSchema,\n addSchema = this.opts.addUsedSchema\n ): SchemaEnv {\n let id: string | undefined\n const {schemaId} = this.opts\n if (typeof schema == \"object\") {\n id = schema[schemaId]\n } else {\n if (this.opts.jtd) throw new Error(\"schema must be object\")\n else if (typeof schema != \"boolean\") throw new Error(\"schema must be object or boolean\")\n }\n let sch = this._cache.get(schema)\n if (sch !== undefined) return sch\n\n baseId = normalizeId(id || baseId)\n const localRefs = getSchemaRefs.call(this, schema, baseId)\n sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs})\n this._cache.set(sch.schema, sch)\n if (addSchema && !baseId.startsWith(\"#\")) {\n // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)\n if (baseId) this._checkUnique(baseId)\n this.refs[baseId] = sch\n }\n if (validateSchema) this.validateSchema(schema, true)\n return sch\n }\n\n private _checkUnique(id: string): void {\n if (this.schemas[id] || this.refs[id]) {\n throw new Error(`schema with key or id \"${id}\" already exists`)\n }\n }\n\n private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction {\n if (sch.meta) this._compileMetaSchema(sch)\n else compileSchema.call(this, sch)\n\n /* istanbul ignore if */\n if (!sch.validate) throw new Error(\"ajv implementation error\")\n return sch.validate\n }\n\n private _compileMetaSchema(sch: SchemaEnv): void {\n const currentOpts = this.opts\n this.opts = this._metaOpts\n try {\n compileSchema.call(this, sch)\n } finally {\n this.opts = currentOpts\n }\n }\n}\n\nexport interface ErrorsTextOptions {\n separator?: string\n dataVar?: string\n}\n\nfunction checkOptions(\n this: Ajv,\n checkOpts: OptionsInfo<RemovedOptions | DeprecatedOptions>,\n options: Options & RemovedOptions,\n msg: string,\n log: \"warn\" | \"error\" = \"error\"\n): void {\n for (const key in checkOpts) {\n const opt = key as keyof typeof checkOpts\n if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)\n }\n}\n\nfunction getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined {\n keyRef = normalizeId(keyRef) // TODO tests fail without this line\n return this.schemas[keyRef] || this.refs[keyRef]\n}\n\nfunction addInitialSchemas(this: Ajv): void {\n const optsSchemas = this.opts.schemas\n if (!optsSchemas) return\n if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas)\n else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key)\n}\n\nfunction addInitialFormats(this: Ajv): void {\n for (const name in this.opts.formats) {\n const format = this.opts.formats[name]\n if (format) this.addFormat(name, format)\n }\n}\n\nfunction addInitialKeywords(\n this: Ajv,\n defs: Vocabulary | {[K in string]?: KeywordDefinition}\n): void {\n if (Array.isArray(defs)) {\n this.addVocabulary(defs)\n return\n }\n this.logger.warn(\"keywords option as map is deprecated, pass array\")\n for (const keyword in defs) {\n const def = defs[keyword] as KeywordDefinition\n if (!def.keyword) def.keyword = keyword\n this.addKeyword(def)\n }\n}\n\nfunction getMetaSchemaOptions(this: Ajv): InstanceOptions {\n const metaOpts = {...this.opts}\n for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]\n return metaOpts\n}\n\nconst noLogs = {log() {}, warn() {}, error() {}}\n\nfunction getLogger(logger?: Partial<Logger> | false): Logger {\n if (logger === false) return noLogs\n if (logger === undefined) return console\n if (logger.log && logger.warn && logger.error) return logger as Logger\n throw new Error(\"logger must implement log, warn and error methods\")\n}\n\nconst KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i\n\nfunction checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {\n const {RULES} = this\n eachItem(keyword, (kwd) => {\n if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)\n if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)\n })\n if (!def) return\n if (def.$data && !(\"code\" in def || \"validate\" in def)) {\n throw new Error('$data keyword must have \"code\" or \"validate\" function')\n }\n}\n\nfunction addRule(\n this: Ajv,\n keyword: string,\n definition?: AddedKeywordDefinition,\n dataType?: JSONType\n): void {\n const post = definition?.post\n if (dataType && post) throw new Error('keyword with \"post\" flag cannot have \"type\"')\n const {RULES} = this\n let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)\n if (!ruleGroup) {\n ruleGroup = {type: dataType, rules: []}\n RULES.rules.push(ruleGroup)\n }\n RULES.keywords[keyword] = true\n if (!definition) return\n\n const rule: Rule = {\n keyword,\n definition: {\n ...definition,\n type: getJSONTypes(definition.type),\n schemaType: getJSONTypes(definition.schemaType),\n },\n }\n if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)\n else ruleGroup.rules.push(rule)\n RULES.all[keyword] = rule\n definition.implements?.forEach((kwd) => this.addKeyword(kwd))\n}\n\nfunction addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {\n const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)\n if (i >= 0) {\n ruleGroup.rules.splice(i, 0, rule)\n } else {\n ruleGroup.rules.push(rule)\n this.logger.warn(`rule ${before} is not defined`)\n }\n}\n\nfunction keywordMetaschema(this: Ajv, def: KeywordDefinition): void {\n let {metaSchema} = def\n if (metaSchema === undefined) return\n if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)\n def.validateSchema = this.compile(metaSchema, true)\n}\n\nconst $dataRef = {\n $ref: \"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#\",\n}\n\nfunction schemaOrData(schema: AnySchema): AnySchemaObject {\n return {anyOf: [schema, $dataRef]}\n}\n", "import type {CodeKeywordDefinition, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport MissingRefError from \"../../compile/ref_error\"\nimport {callValidateCode} from \"../code\"\nimport {_, nil, stringify, Code, Name} from \"../../compile/codegen\"\nimport N from \"../../compile/names\"\nimport {SchemaEnv, resolveRef} from \"../../compile\"\nimport {mergeEvaluated} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"$ref\",\n schemaType: \"string\",\n code(cxt: KeywordCxt): void {\n const {gen, schema: $ref, it} = cxt\n const {baseId, schemaEnv: env, validateName, opts, self} = it\n const {root} = env\n if (($ref === \"#\" || $ref === \"#/\") && baseId === root.baseId) return callRootRef()\n const schOrEnv = resolveRef.call(self, root, baseId, $ref)\n if (schOrEnv === undefined) throw new MissingRefError(it.opts.uriResolver, baseId, $ref)\n if (schOrEnv instanceof SchemaEnv) return callValidate(schOrEnv)\n return inlineRefSchema(schOrEnv)\n\n function callRootRef(): void {\n if (env === root) return callRef(cxt, validateName, env, env.$async)\n const rootName = gen.scopeValue(\"root\", {ref: root})\n return callRef(cxt, _`${rootName}.validate`, root, root.$async)\n }\n\n function callValidate(sch: SchemaEnv): void {\n const v = getValidate(cxt, sch)\n callRef(cxt, v, sch, sch.$async)\n }\n\n function inlineRefSchema(sch: AnySchema): void {\n const schName = gen.scopeValue(\n \"schema\",\n opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch}\n )\n const valid = gen.name(\"valid\")\n const schCxt = cxt.subschema(\n {\n schema: sch,\n dataTypes: [],\n schemaPath: nil,\n topSchemaRef: schName,\n errSchemaPath: $ref,\n },\n valid\n )\n cxt.mergeEvaluated(schCxt)\n cxt.ok(valid)\n }\n },\n}\n\nexport function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code {\n const {gen} = cxt\n return sch.validate\n ? gen.scopeValue(\"validate\", {ref: sch.validate})\n : _`${gen.scopeValue(\"wrapper\", {ref: sch})}.validate`\n}\n\nexport function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void {\n const {gen, it} = cxt\n const {allErrors, schemaEnv: env, opts} = it\n const passCxt = opts.passContext ? N.this : nil\n if ($async) callAsyncRef()\n else callSyncRef()\n\n function callAsyncRef(): void {\n if (!env.$async) throw new Error(\"async schema referenced by sync schema\")\n const valid = gen.let(\"valid\")\n gen.try(\n () => {\n gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`)\n addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result\n if (!allErrors) gen.assign(valid, true)\n },\n (e) => {\n gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e))\n addErrorsFrom(e)\n if (!allErrors) gen.assign(valid, false)\n }\n )\n cxt.ok(valid)\n }\n\n function callSyncRef(): void {\n cxt.result(\n callValidateCode(cxt, v, passCxt),\n () => addEvaluatedFrom(v),\n () => addErrorsFrom(v)\n )\n }\n\n function addErrorsFrom(source: Code): void {\n const errs = _`${source}.errors`\n gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged\n gen.assign(N.errors, _`${N.vErrors}.length`)\n }\n\n function addEvaluatedFrom(source: Code): void {\n if (!it.opts.unevaluated) return\n const schEvaluated = sch?.validate?.evaluated\n // TODO refactor\n if (it.props !== true) {\n if (schEvaluated && !schEvaluated.dynamicProps) {\n if (schEvaluated.props !== undefined) {\n it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props)\n }\n } else {\n const props = gen.var(\"props\", _`${source}.evaluated.props`)\n it.props = mergeEvaluated.props(gen, props, it.props, Name)\n }\n }\n if (it.items !== true) {\n if (schEvaluated && !schEvaluated.dynamicItems) {\n if (schEvaluated.items !== undefined) {\n it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items)\n }\n } else {\n const items = gen.var(\"items\", _`${source}.evaluated.items`)\n it.items = mergeEvaluated.items(gen, items, it.items, Name)\n }\n }\n }\n}\n\nexport default def\n", "import type {Vocabulary} from \"ajv/dist/core\"\nimport refKeyword from \"ajv/dist/vocabularies/core/ref\"\n\nconst core: Vocabulary = [\n \"$schema\",\n \"id\",\n \"$defs\",\n {keyword: \"$comment\"},\n \"definitions\",\n refKeyword,\n]\n\nexport default core\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordCxt,\n KeywordErrorDefinition,\n} from \"ajv/dist/core\"\nimport type {KeywordErrorCxt} from \"ajv/dist/types\"\nimport {_, str, Code} from \"ajv/dist/core\"\nimport {operators} from \"ajv/dist/compile/codegen\"\n\nconst ops = operators\n\nexport type LimitKwd = \"maximum\" | \"minimum\"\n\nexport type ExclusiveLimitKwd = \"exclusiveMaximum\" | \"exclusiveMinimum\"\n\ntype Comparison = \"<=\" | \">=\" | \"<\" | \">\"\n\ninterface KwdOp {\n okStr: Comparison\n ok: Code\n fail: Code\n}\n\ninterface KwdDef {\n exclusive: ExclusiveLimitKwd\n ops: [KwdOp, KwdOp]\n}\n\nconst KWDs: {[K in LimitKwd]: KwdDef} = {\n maximum: {\n exclusive: \"exclusiveMaximum\",\n ops: [\n {okStr: \"<=\", ok: ops.LTE, fail: ops.GT},\n {okStr: \"<\", ok: ops.LT, fail: ops.GTE},\n ],\n },\n minimum: {\n exclusive: \"exclusiveMinimum\",\n ops: [\n {okStr: \">=\", ok: ops.GTE, fail: ops.LT},\n {okStr: \">\", ok: ops.GT, fail: ops.LTE},\n ],\n },\n}\n\nexport type LimitNumberError = ErrorObject<\n LimitKwd,\n {limit: number; comparison: Comparison},\n number | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: (cxt) => str`must be ${kwdOp(cxt).okStr} ${cxt.schemaCode}`,\n params: (cxt) => _`{comparison: ${kwdOp(cxt).okStr}, limit: ${cxt.schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: Object.keys(KWDs),\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {data, schemaCode} = cxt\n cxt.fail$data(_`${data} ${kwdOp(cxt).fail} ${schemaCode} || isNaN(${data})`)\n },\n}\n\nfunction kwdOp(cxt: KeywordErrorCxt): KwdOp {\n const keyword = cxt.keyword as LimitKwd\n const opsIdx = cxt.parentSchema?.[KWDs[keyword].exclusive] ? 1 : 0\n return KWDs[keyword].ops[opsIdx]\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n // ErrorObject,\n KeywordCxt,\n // KeywordErrorDefinition,\n} from \"ajv/dist/core\"\nimport {LimitKwd, ExclusiveLimitKwd} from \"./limitNumber\"\n\nconst KWDs: {[K in ExclusiveLimitKwd]: LimitKwd} = {\n exclusiveMaximum: \"maximum\",\n exclusiveMinimum: \"minimum\",\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: Object.keys(KWDs),\n type: \"number\",\n schemaType: \"boolean\",\n code({keyword, parentSchema}: KeywordCxt) {\n const limitKwd = KWDs[keyword as ExclusiveLimitKwd]\n if (parentSchema[limitKwd] === undefined) {\n throw new Error(`${keyword} can only be used with ${limitKwd}`)\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\n\nexport type MultipleOfError = ErrorObject<\n \"multipleOf\",\n {multipleOf: number},\n number | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must be multiple of ${schemaCode}`,\n params: ({schemaCode}) => _`{multipleOf: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"multipleOf\",\n type: \"number\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, schemaCode, it} = cxt\n // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)\n const prec = it.opts.multipleOfPrecision\n const res = gen.let(\"res\")\n const invalid = prec\n ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`\n : _`${res} !== parseInt(${res})`\n cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`)\n },\n}\n\nexport default def\n", "// https://mathiasbynens.be/notes/javascript-encoding\n// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode\nexport default function ucs2length(str: string): number {\n const len = str.length\n let length = 0\n let pos = 0\n let value: number\n while (pos < len) {\n length++\n value = str.charCodeAt(pos++)\n if (value >= 0xd800 && value <= 0xdbff && pos < len) {\n // high surrogate, and there is a next character\n value = str.charCodeAt(pos)\n if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate\n }\n }\n return length\n}\n\nucs2length.code = 'require(\"ajv/dist/runtime/ucs2length\").default'\n", "import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport ucs2length from \"../../runtime/ucs2length\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxLength\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} characters`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxLength\", \"minLength\"],\n type: \"string\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode, it} = cxt\n const op = keyword === \"maxLength\" ? operators.GT : operators.LT\n const len =\n it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})`\n cxt.fail$data(_`${len} ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {usePattern} from \"../code\"\nimport {_, str} from \"../../compile/codegen\"\n\nexport type PatternError = ErrorObject<\"pattern\", {pattern: string}, string | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must match pattern \"${schemaCode}\"`,\n params: ({schemaCode}) => _`{pattern: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"pattern\",\n type: \"string\",\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {data, $data, schema, schemaCode, it} = cxt\n // TODO regexp should be wrapped in try/catchs\n const u = it.opts.unicodeRegExp ? \"u\" : \"\"\n const regExp = $data ? _`(new RegExp(${schemaCode}, ${u}))` : usePattern(cxt, schema)\n cxt.fail$data(_`!${regExp}.test(${data})`)\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxProperties\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} properties`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxProperties\", \"minProperties\"],\n type: \"object\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n const op = keyword === \"maxProperties\" ? operators.GT : operators.LT\n cxt.fail$data(_`Object.keys(${data}).length ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {\n checkReportMissingProp,\n checkMissingProp,\n reportMissingProp,\n propertyInData,\n noPropertyInData,\n} from \"../code\"\nimport {_, str, nil, not, Name, Code} from \"../../compile/codegen\"\nimport {checkStrictMode} from \"../../compile/util\"\n\nexport type RequiredError = ErrorObject<\n \"required\",\n {missingProperty: string},\n string[] | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {missingProperty}}) => str`must have required property '${missingProperty}'`,\n params: ({params: {missingProperty}}) => _`{missingProperty: ${missingProperty}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"required\",\n type: \"object\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, schemaCode, data, $data, it} = cxt\n const {opts} = it\n if (!$data && schema.length === 0) return\n const useLoop = schema.length >= opts.loopRequired\n if (it.allErrors) allErrorsMode()\n else exitOnErrorMode()\n\n if (opts.strictRequired) {\n const props = cxt.parentSchema.properties\n const {definedProperties} = cxt.it\n for (const requiredKey of schema) {\n if (props?.[requiredKey] === undefined && !definedProperties.has(requiredKey)) {\n const schemaPath = it.schemaEnv.baseId + it.errSchemaPath\n const msg = `required property \"${requiredKey}\" is not defined at \"${schemaPath}\" (strictRequired)`\n checkStrictMode(it, msg, it.opts.strictRequired)\n }\n }\n }\n\n function allErrorsMode(): void {\n if (useLoop || $data) {\n cxt.block$data(nil, loopAllRequired)\n } else {\n for (const prop of schema) {\n checkReportMissingProp(cxt, prop)\n }\n }\n }\n\n function exitOnErrorMode(): void {\n const missing = gen.let(\"missing\")\n if (useLoop || $data) {\n const valid = gen.let(\"valid\", true)\n cxt.block$data(valid, () => loopUntilMissing(missing, valid))\n cxt.ok(valid)\n } else {\n gen.if(checkMissingProp(cxt, schema, missing))\n reportMissingProp(cxt, missing)\n gen.else()\n }\n }\n\n function loopAllRequired(): void {\n gen.forOf(\"prop\", schemaCode as Code, (prop) => {\n cxt.setParams({missingProperty: prop})\n gen.if(noPropertyInData(gen, data, prop, opts.ownProperties), () => cxt.error())\n })\n }\n\n function loopUntilMissing(missing: Name, valid: Name): void {\n cxt.setParams({missingProperty: missing})\n gen.forOf(\n missing,\n schemaCode as Code,\n () => {\n gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties))\n gen.if(not(valid), () => {\n cxt.error()\n gen.break()\n })\n },\n nil\n )\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, operators} from \"../../compile/codegen\"\n\nconst error: KeywordErrorDefinition = {\n message({keyword, schemaCode}) {\n const comp = keyword === \"maxItems\" ? \"more\" : \"fewer\"\n return str`must NOT have ${comp} than ${schemaCode} items`\n },\n params: ({schemaCode}) => _`{limit: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"maxItems\", \"minItems\"],\n type: \"array\",\n schemaType: \"number\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {keyword, data, schemaCode} = cxt\n const op = keyword === \"maxItems\" ? operators.GT : operators.LT\n cxt.fail$data(_`${data}.length ${op} ${schemaCode}`)\n },\n}\n\nexport default def\n", "// https://github.com/ajv-validator/ajv/issues/889\nimport * as equal from \"fast-deep-equal\"\n\ntype Equal = typeof equal & {code: string}\n;(equal as Equal).code = 'require(\"ajv/dist/runtime/equal\").default'\n\nexport default equal as Equal\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {checkDataTypes, getSchemaTypes, DataType} from \"../../compile/validate/dataType\"\nimport {_, str, Name} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type UniqueItemsError = ErrorObject<\n \"uniqueItems\",\n {i: number; j: number},\n boolean | {$data: string}\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {i, j}}) =>\n str`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,\n params: ({params: {i, j}}) => _`{i: ${i}, j: ${j}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"uniqueItems\",\n type: \"array\",\n schemaType: \"boolean\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt\n if (!$data && !schema) return\n const valid = gen.let(\"valid\")\n const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : []\n cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`)\n cxt.ok(valid)\n\n function validateUniqueItems(): void {\n const i = gen.let(\"i\", _`${data}.length`)\n const j = gen.let(\"j\")\n cxt.setParams({i, j})\n gen.assign(valid, true)\n gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j))\n }\n\n function canOptimize(): boolean {\n return itemTypes.length > 0 && !itemTypes.some((t) => t === \"object\" || t === \"array\")\n }\n\n function loopN(i: Name, j: Name): void {\n const item = gen.name(\"item\")\n const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong)\n const indices = gen.const(\"indices\", _`{}`)\n gen.for(_`;${i}--;`, () => {\n gen.let(item, _`${data}[${i}]`)\n gen.if(wrongType, _`continue`)\n if (itemTypes.length > 1) gen.if(_`typeof ${item} == \"string\"`, _`${item} += \"_\"`)\n gen\n .if(_`typeof ${indices}[${item}] == \"number\"`, () => {\n gen.assign(j, _`${indices}[${item}]`)\n cxt.error()\n gen.assign(valid, false).break()\n })\n .code(_`${indices}[${item}] = ${i}`)\n })\n }\n\n function loopN2(i: Name, j: Name): void {\n const eql = useFunc(gen, equal)\n const outer = gen.name(\"outer\")\n gen.label(outer).for(_`;${i}--;`, () =>\n gen.for(_`${j} = ${i}; ${j}--;`, () =>\n gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => {\n cxt.error()\n gen.assign(valid, false).break(outer)\n })\n )\n )\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type ConstError = ErrorObject<\"const\", {allowedValue: any}>\n\nconst error: KeywordErrorDefinition = {\n message: \"must be equal to constant\",\n params: ({schemaCode}) => _`{allowedValue: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"const\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schemaCode, schema} = cxt\n if ($data || (schema && typeof schema == \"object\")) {\n cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`)\n } else {\n cxt.fail(_`${schema} !== ${data}`)\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, or, Name, Code} from \"../../compile/codegen\"\nimport {useFunc} from \"../../compile/util\"\nimport equal from \"../../runtime/equal\"\n\nexport type EnumError = ErrorObject<\"enum\", {allowedValues: any[]}, any[] | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: \"must be equal to one of the allowed values\",\n params: ({schemaCode}) => _`{allowedValues: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"enum\",\n schemaType: \"array\",\n $data: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n if (!$data && schema.length === 0) throw new Error(\"enum must have non-empty array\")\n const useLoop = schema.length >= it.opts.loopEnum\n let eql: Name | undefined\n const getEql = (): Name => (eql ??= useFunc(gen, equal))\n\n let valid: Code\n if (useLoop || $data) {\n valid = gen.let(\"valid\")\n cxt.block$data(valid, loopEnum)\n } else {\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const vSchema = gen.const(\"vSchema\", schemaCode)\n valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i)))\n }\n cxt.pass(valid)\n\n function loopEnum(): void {\n gen.assign(valid, false)\n gen.forOf(\"v\", schemaCode as Code, (v) =>\n gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())\n )\n }\n\n function equalCode(vSchema: Name, i: number): Code {\n const sch = schema[i]\n return typeof sch === \"object\" && sch !== null\n ? _`${getEql()}(${data}, ${vSchema}[${i}])`\n : _`${data} === ${sch}`\n }\n },\n}\n\nexport default def\n", "import type {ErrorObject, Vocabulary} from \"ajv/dist/core\"\nimport limitNumber, {LimitNumberError} from \"./limitNumber\"\nimport limitNumberExclusive from \"./limitNumberExclusive\"\nimport multipleOf, {MultipleOfError} from \"ajv/dist/vocabularies/validation/multipleOf\"\nimport limitLength from \"ajv/dist/vocabularies/validation/limitLength\"\nimport pattern, {PatternError} from \"ajv/dist/vocabularies/validation/pattern\"\nimport limitProperties from \"ajv/dist/vocabularies/validation/limitProperties\"\nimport required, {RequiredError} from \"ajv/dist/vocabularies/validation/required\"\nimport limitItems from \"ajv/dist/vocabularies/validation/limitItems\"\nimport uniqueItems, {UniqueItemsError} from \"ajv/dist/vocabularies/validation/uniqueItems\"\nimport constKeyword, {ConstError} from \"ajv/dist/vocabularies/validation/const\"\nimport enumKeyword, {EnumError} from \"ajv/dist/vocabularies/validation/enum\"\n\nconst validation: Vocabulary = [\n // number\n limitNumber,\n limitNumberExclusive,\n multipleOf,\n // string\n limitLength,\n pattern,\n // object\n limitProperties,\n required,\n // array\n limitItems,\n uniqueItems,\n // any\n {keyword: \"type\", schemaType: [\"string\", \"array\"]},\n {keyword: \"nullable\", schemaType: \"boolean\"},\n constKeyword,\n enumKeyword,\n]\n\nexport default validation\n\ntype LimitError = ErrorObject<\n \"maxItems\" | \"minItems\" | \"minProperties\" | \"maxProperties\" | \"minLength\" | \"maxLength\",\n {limit: number},\n number | {$data: string}\n>\n\nexport type ValidationKeywordError =\n | LimitError\n | LimitNumberError\n | MultipleOfError\n | PatternError\n | RequiredError\n | UniqueItemsError\n | ConstError\n | EnumError\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode, Type} from \"../../compile/util\"\n\nexport type AdditionalItemsError = ErrorObject<\"additionalItems\", {limit: number}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {len}}) => str`must NOT have more than ${len} items`,\n params: ({params: {len}}) => _`{limit: ${len}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"additionalItems\" as const,\n type: \"array\",\n schemaType: [\"boolean\", \"object\"],\n before: \"uniqueItems\",\n error,\n code(cxt: KeywordCxt) {\n const {parentSchema, it} = cxt\n const {items} = parentSchema\n if (!Array.isArray(items)) {\n checkStrictMode(it, '\"additionalItems\" is ignored when \"items\" is not an array of schemas')\n return\n }\n validateAdditionalItems(cxt, items)\n },\n}\n\nexport function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void {\n const {gen, schema, data, keyword, it} = cxt\n it.items = true\n const len = gen.const(\"len\", _`${data}.length`)\n if (schema === false) {\n cxt.setParams({len: items.length})\n cxt.pass(_`${len} <= ${items.length}`)\n } else if (typeof schema == \"object\" && !alwaysValidSchema(it, schema)) {\n const valid = gen.var(\"valid\", _`${len} <= ${items.length}`) // TODO var\n gen.if(not(valid), () => validateItems(valid))\n cxt.ok(valid)\n }\n\n function validateItems(valid: Name): void {\n gen.forRange(\"i\", items.length, len, (i) => {\n cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid)\n if (!it.allErrors) gen.if(not(valid), () => gen.break())\n })\n }\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, AnySchema, AnySchemaObject} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_} from \"../../compile/codegen\"\nimport {alwaysValidSchema, mergeEvaluated, checkStrictMode} from \"../../compile/util\"\nimport {validateArray} from \"../code\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"array\", \"boolean\"],\n before: \"uniqueItems\",\n code(cxt: KeywordCxt) {\n const {schema, it} = cxt\n if (Array.isArray(schema)) return validateTuple(cxt, \"additionalItems\", schema)\n it.items = true\n if (alwaysValidSchema(it, schema)) return\n cxt.ok(validateArray(cxt))\n },\n}\n\nexport function validateTuple(\n cxt: KeywordCxt,\n extraItems: string,\n schArr: AnySchema[] = cxt.schema\n): void {\n const {gen, parentSchema, data, keyword, it} = cxt\n checkStrictTuple(parentSchema)\n if (it.opts.unevaluated && schArr.length && it.items !== true) {\n it.items = mergeEvaluated.items(gen, schArr.length, it.items)\n }\n const valid = gen.name(\"valid\")\n const len = gen.const(\"len\", _`${data}.length`)\n schArr.forEach((sch: AnySchema, i: number) => {\n if (alwaysValidSchema(it, sch)) return\n gen.if(_`${len} > ${i}`, () =>\n cxt.subschema(\n {\n keyword,\n schemaProp: i,\n dataProp: i,\n },\n valid\n )\n )\n cxt.ok(valid)\n })\n\n function checkStrictTuple(sch: AnySchemaObject): void {\n const {opts, errSchemaPath} = it\n const l = schArr.length\n const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false)\n if (opts.strictTuples && !fullTuple) {\n const msg = `\"${keyword}\" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path \"${errSchemaPath}\"`\n checkStrictMode(it, msg, opts.strictTuples)\n }\n }\n}\n\nexport default def\n", "import type {CodeKeywordDefinition} from \"../../types\"\nimport {validateTuple} from \"./items\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"prefixItems\",\n type: \"array\",\n schemaType: [\"array\"],\n before: \"uniqueItems\",\n code: (cxt) => validateTuple(cxt, \"items\"),\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {validateArray} from \"../code\"\nimport {validateAdditionalItems} from \"./additionalItems\"\n\nexport type ItemsError = ErrorObject<\"items\", {limit: number}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {len}}) => str`must NOT have more than ${len} items`,\n params: ({params: {len}}) => _`{limit: ${len}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"items\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n error,\n code(cxt: KeywordCxt) {\n const {schema, parentSchema, it} = cxt\n const {prefixItems} = parentSchema\n it.items = true\n if (alwaysValidSchema(it, schema)) return\n if (prefixItems) validateAdditionalItems(cxt, prefixItems)\n else cxt.ok(validateArray(cxt))\n },\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode, Type} from \"../../compile/util\"\n\nexport type ContainsError = ErrorObject<\n \"contains\",\n {minContains: number; maxContains?: number},\n AnySchema\n>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {min, max}}) =>\n max === undefined\n ? str`must contain at least ${min} valid item(s)`\n : str`must contain at least ${min} and no more than ${max} valid item(s)`,\n params: ({params: {min, max}}) =>\n max === undefined ? _`{minContains: ${min}}` : _`{minContains: ${min}, maxContains: ${max}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"contains\",\n type: \"array\",\n schemaType: [\"object\", \"boolean\"],\n before: \"uniqueItems\",\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, data, it} = cxt\n let min: number\n let max: number | undefined\n const {minContains, maxContains} = parentSchema\n if (it.opts.next) {\n min = minContains === undefined ? 1 : minContains\n max = maxContains\n } else {\n min = 1\n }\n const len = gen.const(\"len\", _`${data}.length`)\n cxt.setParams({min, max})\n if (max === undefined && min === 0) {\n checkStrictMode(it, `\"minContains\" == 0 without \"maxContains\": \"contains\" keyword ignored`)\n return\n }\n if (max !== undefined && min > max) {\n checkStrictMode(it, `\"minContains\" > \"maxContains\" is always invalid`)\n cxt.fail()\n return\n }\n if (alwaysValidSchema(it, schema)) {\n let cond = _`${len} >= ${min}`\n if (max !== undefined) cond = _`${cond} && ${len} <= ${max}`\n cxt.pass(cond)\n return\n }\n\n it.items = true\n const valid = gen.name(\"valid\")\n if (max === undefined && min === 1) {\n validateItems(valid, () => gen.if(valid, () => gen.break()))\n } else if (min === 0) {\n gen.let(valid, true)\n if (max !== undefined) gen.if(_`${data}.length > 0`, validateItemsWithCount)\n } else {\n gen.let(valid, false)\n validateItemsWithCount()\n }\n cxt.result(valid, () => cxt.reset())\n\n function validateItemsWithCount(): void {\n const schValid = gen.name(\"_valid\")\n const count = gen.let(\"count\", 0)\n validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)))\n }\n\n function validateItems(_valid: Name, block: () => void): void {\n gen.forRange(\"i\", 0, len, (i) => {\n cxt.subschema(\n {\n keyword: \"contains\",\n dataProp: i,\n dataPropType: Type.Num,\n compositeRule: true,\n },\n _valid\n )\n block()\n })\n }\n\n function checkLimits(count: Name): void {\n gen.code(_`${count}++`)\n if (max === undefined) {\n gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break())\n } else {\n gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break())\n if (min === 1) gen.assign(valid, true)\n else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true))\n }\n }\n },\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n SchemaMap,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {checkReportMissingProp, checkMissingProp, reportMissingProp, propertyInData} from \"../code\"\n\nexport type PropertyDependencies = {[K in string]?: string[]}\n\nexport interface DependenciesErrorParams {\n property: string\n missingProperty: string\n depsCount: number\n deps: string // TODO change to string[]\n}\n\ntype SchemaDependencies = SchemaMap\n\nexport type DependenciesError = ErrorObject<\n \"dependencies\",\n DependenciesErrorParams,\n {[K in string]?: string[] | AnySchema}\n>\n\nexport const error: KeywordErrorDefinition = {\n message: ({params: {property, depsCount, deps}}) => {\n const property_ies = depsCount === 1 ? \"property\" : \"properties\"\n return str`must have ${property_ies} ${deps} when property ${property} is present`\n },\n params: ({params: {property, depsCount, deps, missingProperty}}) =>\n _`{property: ${property},\n missingProperty: ${missingProperty},\n depsCount: ${depsCount},\n deps: ${deps}}`, // TODO change to reference\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"dependencies\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code(cxt: KeywordCxt) {\n const [propDeps, schDeps] = splitDependencies(cxt)\n validatePropertyDeps(cxt, propDeps)\n validateSchemaDeps(cxt, schDeps)\n },\n}\n\nfunction splitDependencies({schema}: KeywordCxt): [PropertyDependencies, SchemaDependencies] {\n const propertyDeps: PropertyDependencies = {}\n const schemaDeps: SchemaDependencies = {}\n for (const key in schema) {\n if (key === \"__proto__\") continue\n const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps\n deps[key] = schema[key]\n }\n return [propertyDeps, schemaDeps]\n}\n\nexport function validatePropertyDeps(\n cxt: KeywordCxt,\n propertyDeps: {[K in string]?: string[]} = cxt.schema\n): void {\n const {gen, data, it} = cxt\n if (Object.keys(propertyDeps).length === 0) return\n const missing = gen.let(\"missing\")\n for (const prop in propertyDeps) {\n const deps = propertyDeps[prop] as string[]\n if (deps.length === 0) continue\n const hasProperty = propertyInData(gen, data, prop, it.opts.ownProperties)\n cxt.setParams({\n property: prop,\n depsCount: deps.length,\n deps: deps.join(\", \"),\n })\n if (it.allErrors) {\n gen.if(hasProperty, () => {\n for (const depProp of deps) {\n checkReportMissingProp(cxt, depProp)\n }\n })\n } else {\n gen.if(_`${hasProperty} && (${checkMissingProp(cxt, deps, missing)})`)\n reportMissingProp(cxt, missing)\n gen.else()\n }\n }\n}\n\nexport function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void {\n const {gen, data, keyword, it} = cxt\n const valid = gen.name(\"valid\")\n for (const prop in schemaDeps) {\n if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue\n gen.if(\n propertyInData(gen, data, prop, it.opts.ownProperties),\n () => {\n const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid)\n cxt.mergeValidEvaluated(schCxt, valid)\n },\n () => gen.var(valid, true) // TODO var\n )\n cxt.ok(valid)\n }\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, not} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nexport type PropertyNamesError = ErrorObject<\"propertyNames\", {propertyName: string}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: \"property name must be valid\",\n params: ({params}) => _`{propertyName: ${params.propertyName}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"propertyNames\",\n type: \"object\",\n schemaType: [\"object\", \"boolean\"],\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, data, it} = cxt\n if (alwaysValidSchema(it, schema)) return\n const valid = gen.name(\"valid\")\n\n gen.forIn(\"key\", data, (key) => {\n cxt.setParams({propertyName: key})\n cxt.subschema(\n {\n keyword: \"propertyNames\",\n data: key,\n dataTypes: [\"string\"],\n propertyName: key,\n compositeRule: true,\n },\n valid\n )\n gen.if(not(valid), () => {\n cxt.error(true)\n if (!it.allErrors) gen.break()\n })\n })\n\n cxt.ok(valid)\n },\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n AddedKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport {allSchemaProperties, usePattern, isOwnProperty} from \"../code\"\nimport {_, nil, or, not, Code, Name} from \"../../compile/codegen\"\nimport N from \"../../compile/names\"\nimport type {SubschemaArgs} from \"../../compile/validate/subschema\"\nimport {alwaysValidSchema, schemaRefOrVal, Type} from \"../../compile/util\"\n\nexport type AdditionalPropertiesError = ErrorObject<\n \"additionalProperties\",\n {additionalProperty: string},\n AnySchema\n>\n\nconst error: KeywordErrorDefinition = {\n message: \"must NOT have additional properties\",\n params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,\n}\n\nconst def: CodeKeywordDefinition & AddedKeywordDefinition = {\n keyword: \"additionalProperties\",\n type: [\"object\"],\n schemaType: [\"boolean\", \"object\"],\n allowUndefined: true,\n trackErrors: true,\n error,\n code(cxt) {\n const {gen, schema, parentSchema, data, errsCount, it} = cxt\n /* istanbul ignore if */\n if (!errsCount) throw new Error(\"ajv implementation error\")\n const {allErrors, opts} = it\n it.props = true\n if (opts.removeAdditional !== \"all\" && alwaysValidSchema(it, schema)) return\n const props = allSchemaProperties(parentSchema.properties)\n const patProps = allSchemaProperties(parentSchema.patternProperties)\n checkAdditionalProperties()\n cxt.ok(_`${errsCount} === ${N.errors}`)\n\n function checkAdditionalProperties(): void {\n gen.forIn(\"key\", data, (key: Name) => {\n if (!props.length && !patProps.length) additionalPropertyCode(key)\n else gen.if(isAdditional(key), () => additionalPropertyCode(key))\n })\n }\n\n function isAdditional(key: Name): Code {\n let definedProp: Code\n if (props.length > 8) {\n // TODO maybe an option instead of hard-coded 8?\n const propsSchema = schemaRefOrVal(it, parentSchema.properties, \"properties\")\n definedProp = isOwnProperty(gen, propsSchema as Code, key)\n } else if (props.length) {\n definedProp = or(...props.map((p) => _`${key} === ${p}`))\n } else {\n definedProp = nil\n }\n if (patProps.length) {\n definedProp = or(definedProp, ...patProps.map((p) => _`${usePattern(cxt, p)}.test(${key})`))\n }\n return not(definedProp)\n }\n\n function deleteAdditional(key: Name): void {\n gen.code(_`delete ${data}[${key}]`)\n }\n\n function additionalPropertyCode(key: Name): void {\n if (opts.removeAdditional === \"all\" || (opts.removeAdditional && schema === false)) {\n deleteAdditional(key)\n return\n }\n\n if (schema === false) {\n cxt.setParams({additionalProperty: key})\n cxt.error()\n if (!allErrors) gen.break()\n return\n }\n\n if (typeof schema == \"object\" && !alwaysValidSchema(it, schema)) {\n const valid = gen.name(\"valid\")\n if (opts.removeAdditional === \"failing\") {\n applyAdditionalSchema(key, valid, false)\n gen.if(not(valid), () => {\n cxt.reset()\n deleteAdditional(key)\n })\n } else {\n applyAdditionalSchema(key, valid)\n if (!allErrors) gen.if(not(valid), () => gen.break())\n }\n }\n }\n\n function applyAdditionalSchema(key: Name, valid: Name, errors?: false): void {\n const subschema: SubschemaArgs = {\n keyword: \"additionalProperties\",\n dataProp: key,\n dataPropType: Type.Str,\n }\n if (errors === false) {\n Object.assign(subschema, {\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n })\n }\n cxt.subschema(subschema, valid)\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition} from \"../../types\"\nimport {KeywordCxt} from \"../../compile/validate\"\nimport {propertyInData, allSchemaProperties} from \"../code\"\nimport {alwaysValidSchema, toHash, mergeEvaluated} from \"../../compile/util\"\nimport apDef from \"./additionalProperties\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"properties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, data, it} = cxt\n if (it.opts.removeAdditional === \"all\" && parentSchema.additionalProperties === undefined) {\n apDef.code(new KeywordCxt(it, apDef, \"additionalProperties\"))\n }\n const allProps = allSchemaProperties(schema)\n for (const prop of allProps) {\n it.definedProperties.add(prop)\n }\n if (it.opts.unevaluated && allProps.length && it.props !== true) {\n it.props = mergeEvaluated.props(gen, toHash(allProps), it.props)\n }\n const properties = allProps.filter((p) => !alwaysValidSchema(it, schema[p]))\n if (properties.length === 0) return\n const valid = gen.name(\"valid\")\n\n for (const prop of properties) {\n if (hasDefault(prop)) {\n applyPropertySchema(prop)\n } else {\n gen.if(propertyInData(gen, data, prop, it.opts.ownProperties))\n applyPropertySchema(prop)\n if (!it.allErrors) gen.else().var(valid, true)\n gen.endIf()\n }\n cxt.it.definedProperties.add(prop)\n cxt.ok(valid)\n }\n\n function hasDefault(prop: string): boolean | undefined {\n return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined\n }\n\n function applyPropertySchema(prop: string): void {\n cxt.subschema(\n {\n keyword: \"properties\",\n schemaProp: prop,\n dataProp: prop,\n },\n valid\n )\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {allSchemaProperties, usePattern} from \"../code\"\nimport {_, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode} from \"../../compile/util\"\nimport {evaluatedPropsToName, Type} from \"../../compile/util\"\nimport {AnySchema} from \"../../types\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"patternProperties\",\n type: \"object\",\n schemaType: \"object\",\n code(cxt: KeywordCxt) {\n const {gen, schema, data, parentSchema, it} = cxt\n const {opts} = it\n const patterns = allSchemaProperties(schema)\n const alwaysValidPatterns = patterns.filter((p) =>\n alwaysValidSchema(it, schema[p] as AnySchema)\n )\n\n if (\n patterns.length === 0 ||\n (alwaysValidPatterns.length === patterns.length &&\n (!it.opts.unevaluated || it.props === true))\n ) {\n return\n }\n\n const checkProperties =\n opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties\n const valid = gen.name(\"valid\")\n if (it.props !== true && !(it.props instanceof Name)) {\n it.props = evaluatedPropsToName(gen, it.props)\n }\n const {props} = it\n validatePatternProperties()\n\n function validatePatternProperties(): void {\n for (const pat of patterns) {\n if (checkProperties) checkMatchingProperties(pat)\n if (it.allErrors) {\n validateProperties(pat)\n } else {\n gen.var(valid, true) // TODO var\n validateProperties(pat)\n gen.if(valid)\n }\n }\n }\n\n function checkMatchingProperties(pat: string): void {\n for (const prop in checkProperties) {\n if (new RegExp(pat).test(prop)) {\n checkStrictMode(\n it,\n `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`\n )\n }\n }\n }\n\n function validateProperties(pat: string): void {\n gen.forIn(\"key\", data, (key) => {\n gen.if(_`${usePattern(cxt, pat)}.test(${key})`, () => {\n const alwaysValid = alwaysValidPatterns.includes(pat)\n if (!alwaysValid) {\n cxt.subschema(\n {\n keyword: \"patternProperties\",\n schemaProp: pat,\n dataProp: key,\n dataPropType: Type.Str,\n },\n valid\n )\n }\n\n if (it.opts.unevaluated && props !== true) {\n gen.assign(_`${props}[${key}]`, true)\n } else if (!alwaysValid && !it.allErrors) {\n // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)\n // or if all properties were evaluated (props === true)\n gen.if(not(valid), () => gen.break())\n }\n })\n })\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nexport type NotKeywordError = ErrorNoParams<\"not\", AnySchema>\n\nconst def: CodeKeywordDefinition = {\n keyword: \"not\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n code(cxt: KeywordCxt) {\n const {gen, schema, it} = cxt\n if (alwaysValidSchema(it, schema)) {\n cxt.fail()\n return\n }\n\n const valid = gen.name(\"valid\")\n cxt.subschema(\n {\n keyword: \"not\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n },\n valid\n )\n\n cxt.failResult(\n valid,\n () => cxt.reset(),\n () => cxt.error()\n )\n },\n error: {message: \"must NOT be valid\"},\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, ErrorNoParams, AnySchema} from \"../../types\"\nimport {validateUnion} from \"../code\"\n\nexport type AnyOfError = ErrorNoParams<\"anyOf\", AnySchema[]>\n\nconst def: CodeKeywordDefinition = {\n keyword: \"anyOf\",\n schemaType: \"array\",\n trackErrors: true,\n code: validateUnion,\n error: {message: \"must match a schema in anyOf\"},\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema} from \"../../compile/util\"\nimport {SchemaCxt} from \"../../compile\"\n\nexport type OneOfError = ErrorObject<\n \"oneOf\",\n {passingSchemas: [number, number] | null},\n AnySchema[]\n>\n\nconst error: KeywordErrorDefinition = {\n message: \"must match exactly one schema in oneOf\",\n params: ({params}) => _`{passingSchemas: ${params.passing}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"oneOf\",\n schemaType: \"array\",\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, schema, parentSchema, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n if (it.opts.discriminator && parentSchema.discriminator) return\n const schArr: AnySchema[] = schema\n const valid = gen.let(\"valid\", false)\n const passing = gen.let(\"passing\", null)\n const schValid = gen.name(\"_valid\")\n cxt.setParams({passing})\n // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas\n\n gen.block(validateOneOf)\n\n cxt.result(\n valid,\n () => cxt.reset(),\n () => cxt.error(true)\n )\n\n function validateOneOf(): void {\n schArr.forEach((sch: AnySchema, i: number) => {\n let schCxt: SchemaCxt | undefined\n if (alwaysValidSchema(it, sch)) {\n gen.var(schValid, true)\n } else {\n schCxt = cxt.subschema(\n {\n keyword: \"oneOf\",\n schemaProp: i,\n compositeRule: true,\n },\n schValid\n )\n }\n\n if (i > 0) {\n gen\n .if(_`${schValid} && ${valid}`)\n .assign(valid, false)\n .assign(passing, _`[${passing}, ${i}]`)\n .else()\n }\n\n gen.if(schValid, () => {\n gen.assign(valid, true)\n gen.assign(passing, i)\n if (schCxt) cxt.mergeEvaluated(schCxt, Name)\n })\n })\n }\n },\n}\n\nexport default def\n", "import type {CodeKeywordDefinition, AnySchema} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {alwaysValidSchema} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: \"allOf\",\n schemaType: \"array\",\n code(cxt: KeywordCxt) {\n const {gen, schema, it} = cxt\n /* istanbul ignore if */\n if (!Array.isArray(schema)) throw new Error(\"ajv implementation error\")\n const valid = gen.name(\"valid\")\n schema.forEach((sch: AnySchema, i: number) => {\n if (alwaysValidSchema(it, sch)) return\n const schCxt = cxt.subschema({keyword: \"allOf\", schemaProp: i}, valid)\n cxt.ok(valid)\n cxt.mergeEvaluated(schCxt)\n })\n },\n}\n\nexport default def\n", "import type {\n CodeKeywordDefinition,\n ErrorObject,\n KeywordErrorDefinition,\n AnySchema,\n} from \"../../types\"\nimport type {SchemaObjCxt} from \"../../compile\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, not, Name} from \"../../compile/codegen\"\nimport {alwaysValidSchema, checkStrictMode} from \"../../compile/util\"\n\nexport type IfKeywordError = ErrorObject<\"if\", {failingKeyword: string}, AnySchema>\n\nconst error: KeywordErrorDefinition = {\n message: ({params}) => str`must match \"${params.ifClause}\" schema`,\n params: ({params}) => _`{failingKeyword: ${params.ifClause}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"if\",\n schemaType: [\"object\", \"boolean\"],\n trackErrors: true,\n error,\n code(cxt: KeywordCxt) {\n const {gen, parentSchema, it} = cxt\n if (parentSchema.then === undefined && parentSchema.else === undefined) {\n checkStrictMode(it, '\"if\" without \"then\" and \"else\" is ignored')\n }\n const hasThen = hasSchema(it, \"then\")\n const hasElse = hasSchema(it, \"else\")\n if (!hasThen && !hasElse) return\n\n const valid = gen.let(\"valid\", true)\n const schValid = gen.name(\"_valid\")\n validateIf()\n cxt.reset()\n\n if (hasThen && hasElse) {\n const ifClause = gen.let(\"ifClause\")\n cxt.setParams({ifClause})\n gen.if(schValid, validateClause(\"then\", ifClause), validateClause(\"else\", ifClause))\n } else if (hasThen) {\n gen.if(schValid, validateClause(\"then\"))\n } else {\n gen.if(not(schValid), validateClause(\"else\"))\n }\n\n cxt.pass(valid, () => cxt.error(true))\n\n function validateIf(): void {\n const schCxt = cxt.subschema(\n {\n keyword: \"if\",\n compositeRule: true,\n createErrors: false,\n allErrors: false,\n },\n schValid\n )\n cxt.mergeEvaluated(schCxt)\n }\n\n function validateClause(keyword: string, ifClause?: Name): () => void {\n return () => {\n const schCxt = cxt.subschema({keyword}, schValid)\n gen.assign(valid, schValid)\n cxt.mergeValidEvaluated(schCxt, valid)\n if (ifClause) gen.assign(ifClause, _`${keyword}`)\n else cxt.setParams({ifClause: keyword})\n }\n }\n },\n}\n\nfunction hasSchema(it: SchemaObjCxt, keyword: string): boolean {\n const schema = it.schema[keyword]\n return schema !== undefined && !alwaysValidSchema(it, schema)\n}\n\nexport default def\n", "import type {CodeKeywordDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {checkStrictMode} from \"../../compile/util\"\n\nconst def: CodeKeywordDefinition = {\n keyword: [\"then\", \"else\"],\n schemaType: [\"object\", \"boolean\"],\n code({keyword, parentSchema, it}: KeywordCxt) {\n if (parentSchema.if === undefined) checkStrictMode(it, `\"${keyword}\" without \"if\" is ignored`)\n },\n}\n\nexport default def\n", "import type {ErrorNoParams, Vocabulary} from \"../../types\"\nimport additionalItems, {AdditionalItemsError} from \"./additionalItems\"\nimport prefixItems from \"./prefixItems\"\nimport items from \"./items\"\nimport items2020, {ItemsError} from \"./items2020\"\nimport contains, {ContainsError} from \"./contains\"\nimport dependencies, {DependenciesError} from \"./dependencies\"\nimport propertyNames, {PropertyNamesError} from \"./propertyNames\"\nimport additionalProperties, {AdditionalPropertiesError} from \"./additionalProperties\"\nimport properties from \"./properties\"\nimport patternProperties from \"./patternProperties\"\nimport notKeyword, {NotKeywordError} from \"./not\"\nimport anyOf, {AnyOfError} from \"./anyOf\"\nimport oneOf, {OneOfError} from \"./oneOf\"\nimport allOf from \"./allOf\"\nimport ifKeyword, {IfKeywordError} from \"./if\"\nimport thenElse from \"./thenElse\"\n\nexport default function getApplicator(draft2020 = false): Vocabulary {\n const applicator = [\n // any\n notKeyword,\n anyOf,\n oneOf,\n allOf,\n ifKeyword,\n thenElse,\n // object\n propertyNames,\n additionalProperties,\n dependencies,\n properties,\n patternProperties,\n ]\n // array\n if (draft2020) applicator.push(prefixItems, items2020)\n else applicator.push(additionalItems, items)\n applicator.push(contains)\n return applicator\n}\n\nexport type ApplicatorKeywordError =\n | ErrorNoParams<\"false schema\">\n | AdditionalItemsError\n | ItemsError\n | ContainsError\n | AdditionalPropertiesError\n | DependenciesError\n | IfKeywordError\n | AnyOfError\n | OneOfError\n | NotKeywordError\n | PropertyNamesError\n", "import type {\n AddedFormat,\n FormatValidator,\n AsyncFormatValidator,\n CodeKeywordDefinition,\n KeywordErrorDefinition,\n ErrorObject,\n} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, str, nil, or, Code, getProperty, regexpCode} from \"../../compile/codegen\"\n\ntype FormatValidate =\n | FormatValidator<string>\n | FormatValidator<number>\n | AsyncFormatValidator<string>\n | AsyncFormatValidator<number>\n | RegExp\n | string\n | true\n\nexport type FormatError = ErrorObject<\"format\", {format: string}, string | {$data: string}>\n\nconst error: KeywordErrorDefinition = {\n message: ({schemaCode}) => str`must match format \"${schemaCode}\"`,\n params: ({schemaCode}) => _`{format: ${schemaCode}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"format\",\n type: [\"number\", \"string\"],\n schemaType: \"string\",\n $data: true,\n error,\n code(cxt: KeywordCxt, ruleType?: string) {\n const {gen, data, $data, schema, schemaCode, it} = cxt\n const {opts, errSchemaPath, schemaEnv, self} = it\n if (!opts.validateFormats) return\n\n if ($data) validate$DataFormat()\n else validateFormat()\n\n function validate$DataFormat(): void {\n const fmts = gen.scopeValue(\"formats\", {\n ref: self.formats,\n code: opts.code.formats,\n })\n const fDef = gen.const(\"fDef\", _`${fmts}[${schemaCode}]`)\n const fType = gen.let(\"fType\")\n const format = gen.let(\"format\")\n // TODO simplify\n gen.if(\n _`typeof ${fDef} == \"object\" && !(${fDef} instanceof RegExp)`,\n () => gen.assign(fType, _`${fDef}.type || \"string\"`).assign(format, _`${fDef}.validate`),\n () => gen.assign(fType, _`\"string\"`).assign(format, fDef)\n )\n cxt.fail$data(or(unknownFmt(), invalidFmt()))\n\n function unknownFmt(): Code {\n if (opts.strictSchema === false) return nil\n return _`${schemaCode} && !${format}`\n }\n\n function invalidFmt(): Code {\n const callFormat = schemaEnv.$async\n ? _`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`\n : _`${format}(${data})`\n const validData = _`(typeof ${format} == \"function\" ? ${callFormat} : ${format}.test(${data}))`\n return _`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`\n }\n }\n\n function validateFormat(): void {\n const formatDef: AddedFormat | undefined = self.formats[schema]\n if (!formatDef) {\n unknownFormat()\n return\n }\n if (formatDef === true) return\n const [fmtType, format, fmtRef] = getFormat(formatDef)\n if (fmtType === ruleType) cxt.pass(validCondition())\n\n function unknownFormat(): void {\n if (opts.strictSchema === false) {\n self.logger.warn(unknownMsg())\n return\n }\n throw new Error(unknownMsg())\n\n function unknownMsg(): string {\n return `unknown format \"${schema as string}\" ignored in schema at path \"${errSchemaPath}\"`\n }\n }\n\n function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] {\n const code =\n fmtDef instanceof RegExp\n ? regexpCode(fmtDef)\n : opts.code.formats\n ? _`${opts.code.formats}${getProperty(schema)}`\n : undefined\n const fmt = gen.scopeValue(\"formats\", {key: schema, ref: fmtDef, code})\n if (typeof fmtDef == \"object\" && !(fmtDef instanceof RegExp)) {\n return [fmtDef.type || \"string\", fmtDef.validate, _`${fmt}.validate`]\n }\n\n return [\"string\", fmtDef, fmt]\n }\n\n function validCondition(): Code {\n if (typeof formatDef == \"object\" && !(formatDef instanceof RegExp) && formatDef.async) {\n if (!schemaEnv.$async) throw new Error(\"async format in sync schema\")\n return _`await ${fmtRef}(${data})`\n }\n return typeof format == \"function\" ? _`${fmtRef}(${data})` : _`${fmtRef}.test(${data})`\n }\n }\n },\n}\n\nexport default def\n", "import type {Vocabulary} from \"../../types\"\nimport formatKeyword from \"./format\"\n\nconst format: Vocabulary = [formatKeyword]\n\nexport default format\n", "import type {Vocabulary} from \"ajv/dist/core\"\nimport coreVocabulary from \"./core\"\nimport validationDraft4 from \"./validation\"\nimport getApplicatorVocabulary from \"ajv/dist/vocabularies/applicator\"\nimport formatVocabulary from \"ajv/dist/vocabularies/format\"\n\nconst metadataVocabulary: Vocabulary = [\"title\", \"description\", \"default\"]\n\nconst draft4Vocabularies: Vocabulary[] = [\n coreVocabulary,\n validationDraft4,\n getApplicatorVocabulary(),\n formatVocabulary,\n metadataVocabulary,\n]\n\nexport default draft4Vocabularies\n", "import type {ErrorObject} from \"../../types\"\n\nexport enum DiscrError {\n Tag = \"tag\",\n Mapping = \"mapping\",\n}\n\nexport type DiscrErrorObj<E extends DiscrError> = ErrorObject<\n \"discriminator\",\n {error: E; tag: string; tagValue: unknown},\n string\n>\n", "import type {CodeKeywordDefinition, AnySchemaObject, KeywordErrorDefinition} from \"../../types\"\nimport type {KeywordCxt} from \"../../compile/validate\"\nimport {_, getProperty, Name} from \"../../compile/codegen\"\nimport {DiscrError, DiscrErrorObj} from \"../discriminator/types\"\nimport {resolveRef, SchemaEnv} from \"../../compile\"\nimport MissingRefError from \"../../compile/ref_error\"\nimport {schemaHasRulesButRef} from \"../../compile/util\"\n\nexport type DiscriminatorError = DiscrErrorObj<DiscrError.Tag> | DiscrErrorObj<DiscrError.Mapping>\n\nconst error: KeywordErrorDefinition = {\n message: ({params: {discrError, tagName}}) =>\n discrError === DiscrError.Tag\n ? `tag \"${tagName}\" must be string`\n : `value of tag \"${tagName}\" must be in oneOf`,\n params: ({params: {discrError, tag, tagName}}) =>\n _`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,\n}\n\nconst def: CodeKeywordDefinition = {\n keyword: \"discriminator\",\n type: \"object\",\n schemaType: \"object\",\n error,\n code(cxt: KeywordCxt) {\n const {gen, data, schema, parentSchema, it} = cxt\n const {oneOf} = parentSchema\n if (!it.opts.discriminator) {\n throw new Error(\"discriminator: requires discriminator option\")\n }\n const tagName = schema.propertyName\n if (typeof tagName != \"string\") throw new Error(\"discriminator: requires propertyName\")\n if (schema.mapping) throw new Error(\"discriminator: mapping is not supported\")\n if (!oneOf) throw new Error(\"discriminator: requires oneOf keyword\")\n const valid = gen.let(\"valid\", false)\n const tag = gen.const(\"tag\", _`${data}${getProperty(tagName)}`)\n gen.if(\n _`typeof ${tag} == \"string\"`,\n () => validateMapping(),\n () => cxt.error(false, {discrError: DiscrError.Tag, tag, tagName})\n )\n cxt.ok(valid)\n\n function validateMapping(): void {\n const mapping = getMapping()\n gen.if(false)\n for (const tagValue in mapping) {\n gen.elseIf(_`${tag} === ${tagValue}`)\n gen.assign(valid, applyTagSchema(mapping[tagValue]))\n }\n gen.else()\n cxt.error(false, {discrError: DiscrError.Mapping, tag, tagName})\n gen.endIf()\n }\n\n function applyTagSchema(schemaProp?: number): Name {\n const _valid = gen.name(\"valid\")\n const schCxt = cxt.subschema({keyword: \"oneOf\", schemaProp}, _valid)\n cxt.mergeEvaluated(schCxt, Name)\n return _valid\n }\n\n function getMapping(): {[T in string]?: number} {\n const oneOfMapping: {[T in string]?: number} = {}\n const topRequired = hasRequired(parentSchema)\n let tagRequired = true\n for (let i = 0; i < oneOf.length; i++) {\n let sch = oneOf[i]\n if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) {\n const ref = sch.$ref\n sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref)\n if (sch instanceof SchemaEnv) sch = sch.schema\n if (sch === undefined) throw new MissingRefError(it.opts.uriResolver, it.baseId, ref)\n }\n const propSch = sch?.properties?.[tagName]\n if (typeof propSch != \"object\") {\n throw new Error(\n `discriminator: oneOf subschemas (or referenced schemas) must have \"properties/${tagName}\"`\n )\n }\n tagRequired = tagRequired && (topRequired || hasRequired(sch))\n addMappings(propSch, i)\n }\n if (!tagRequired) throw new Error(`discriminator: \"${tagName}\" must be required`)\n return oneOfMapping\n\n function hasRequired({required}: AnySchemaObject): boolean {\n return Array.isArray(required) && required.includes(tagName)\n }\n\n function addMappings(sch: AnySchemaObject, i: number): void {\n if (sch.const) {\n addMapping(sch.const, i)\n } else if (sch.enum) {\n for (const tagValue of sch.enum) {\n addMapping(tagValue, i)\n }\n } else {\n throw new Error(`discriminator: \"properties/${tagName}\" must have \"const\" or \"enum\"`)\n }\n }\n\n function addMapping(tagValue: unknown, i: number): void {\n if (typeof tagValue != \"string\" || tagValue in oneOfMapping) {\n throw new Error(`discriminator: \"${tagName}\" values must be unique strings`)\n }\n oneOfMapping[tagValue] = i\n }\n }\n },\n}\n\nexport default def\n", "{\n \"id\": \"http://json-schema.org/draft-04/schema#\",\n \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n \"description\": \"Core schema meta-schema\",\n \"definitions\": {\n \"schemaArray\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\"$ref\": \"#\"}\n },\n \"positiveInteger\": {\n \"type\": \"integer\",\n \"minimum\": 0\n },\n \"positiveIntegerDefault0\": {\n \"allOf\": [{\"$ref\": \"#/definitions/positiveInteger\"}, {\"default\": 0}]\n },\n \"simpleTypes\": {\n \"enum\": [\"array\", \"boolean\", \"integer\", \"null\", \"number\", \"object\", \"string\"]\n },\n \"stringArray\": {\n \"type\": \"array\",\n \"items\": {\"type\": \"string\"},\n \"minItems\": 1,\n \"uniqueItems\": true\n }\n },\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"format\": \"uri\"\n },\n \"$schema\": {\n \"type\": \"string\",\n \"format\": \"uri\"\n },\n \"title\": {\n \"type\": \"string\"\n },\n \"description\": {\n \"type\": \"string\"\n },\n \"default\": {},\n \"multipleOf\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"exclusiveMinimum\": true\n },\n \"maximum\": {\n \"type\": \"number\"\n },\n \"exclusiveMaximum\": {\n \"type\": \"boolean\",\n \"default\": false\n },\n \"minimum\": {\n \"type\": \"number\"\n },\n \"exclusiveMinimum\": {\n \"type\": \"boolean\",\n \"default\": false\n },\n \"maxLength\": {\"$ref\": \"#/definitions/positiveInteger\"},\n \"minLength\": {\"$ref\": \"#/definitions/positiveIntegerDefault0\"},\n \"pattern\": {\n \"type\": \"string\",\n \"format\": \"regex\"\n },\n \"additionalItems\": {\n \"anyOf\": [{\"type\": \"boolean\"}, {\"$ref\": \"#\"}],\n \"default\": {}\n },\n \"items\": {\n \"anyOf\": [{\"$ref\": \"#\"}, {\"$ref\": \"#/definitions/schemaArray\"}],\n \"default\": {}\n },\n \"maxItems\": {\"$ref\": \"#/definitions/positiveInteger\"},\n \"minItems\": {\"$ref\": \"#/definitions/positiveIntegerDefault0\"},\n \"uniqueItems\": {\n \"type\": \"boolean\",\n \"default\": false\n },\n \"maxProperties\": {\"$ref\": \"#/definitions/positiveInteger\"},\n \"minProperties\": {\"$ref\": \"#/definitions/positiveIntegerDefault0\"},\n \"required\": {\"$ref\": \"#/definitions/stringArray\"},\n \"additionalProperties\": {\n \"anyOf\": [{\"type\": \"boolean\"}, {\"$ref\": \"#\"}],\n \"default\": {}\n },\n \"definitions\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"default\": {}\n },\n \"properties\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"default\": {}\n },\n \"patternProperties\": {\n \"type\": \"object\",\n \"additionalProperties\": {\"$ref\": \"#\"},\n \"default\": {}\n },\n \"dependencies\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"anyOf\": [{\"$ref\": \"#\"}, {\"$ref\": \"#/definitions/stringArray\"}]\n }\n },\n \"enum\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"uniqueItems\": true\n },\n \"type\": {\n \"anyOf\": [\n {\"$ref\": \"#/definitions/simpleTypes\"},\n {\n \"type\": \"array\",\n \"items\": {\"$ref\": \"#/definitions/simpleTypes\"},\n \"minItems\": 1,\n \"uniqueItems\": true\n }\n ]\n },\n \"allOf\": {\"$ref\": \"#/definitions/schemaArray\"},\n \"anyOf\": {\"$ref\": \"#/definitions/schemaArray\"},\n \"oneOf\": {\"$ref\": \"#/definitions/schemaArray\"},\n \"not\": {\"$ref\": \"#\"}\n },\n \"dependencies\": {\n \"exclusiveMaximum\": [\"maximum\"],\n \"exclusiveMinimum\": [\"minimum\"]\n },\n \"default\": {}\n}\n", "import type {AnySchemaObject, Options} from \"ajv/dist/core\"\nimport AjvCore from \"ajv/dist/core\"\nimport draft4Vocabularies from \"./vocabulary/draft4\"\nimport discriminator from \"ajv/dist/vocabularies/discriminator\"\nimport * as draft4MetaSchema from \"./refs/json-schema-draft-04.json\"\n\nconst META_SUPPORT_DATA = [\"/properties\"]\n\nconst META_SCHEMA_ID = \"http://json-schema.org/draft-04/schema\"\n\nclass Ajv extends AjvCore {\n constructor(opts: Options = {}) {\n super({\n ...opts,\n schemaId: \"id\",\n })\n }\n\n _addVocabularies(): void {\n super._addVocabularies()\n draft4Vocabularies.forEach((v) => this.addVocabulary(v))\n if (this.opts.discriminator) this.addKeyword(discriminator)\n }\n\n _addDefaultMetaSchema(): void {\n super._addDefaultMetaSchema()\n if (!this.opts.meta) return\n const metaSchema = this.opts.$data\n ? this.$dataMetaSchema(draft4MetaSchema, META_SUPPORT_DATA)\n : draft4MetaSchema\n this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)\n this.refs[\"http://json-schema.org/schema\"] = META_SCHEMA_ID\n }\n\n defaultMeta(): string | AnySchemaObject | undefined {\n return (this.opts.defaultMeta =\n super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))\n }\n}\n\nmodule.exports = exports = Ajv\nObject.defineProperty(exports, \"__esModule\", {value: true})\n\nexport default Ajv\n\nexport {\n Format,\n FormatDefinition,\n AsyncFormatDefinition,\n KeywordDefinition,\n KeywordErrorDefinition,\n CodeKeywordDefinition,\n MacroKeywordDefinition,\n FuncKeywordDefinition,\n Vocabulary,\n Schema,\n SchemaObject,\n AnySchemaObject,\n AsyncSchema,\n AnySchema,\n ValidateFunction,\n AsyncValidateFunction,\n SchemaValidateFunction,\n ErrorObject,\n ErrorNoParams,\n} from \"ajv/dist/types\"\n\nexport {\n Plugin,\n Options,\n CodeOptions,\n InstanceOptions,\n Logger,\n ErrorsTextOptions,\n} from \"ajv/dist/core\"\nexport {SchemaCxt, SchemaObjCxt} from \"ajv/dist/core\"\nexport {KeywordCxt} from \"ajv/dist/core\"\nexport {DefinedError} from \"ajv/dist/core\"\nexport {JSONType} from \"ajv/dist/core\"\nexport {JSONSchemaType} from \"ajv/dist/core\"\nexport {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from \"ajv/dist/core\"\n", "import Ajv from \"ajv-draft-04\";\nimport { Graffiti } from \"@graffiti-garden/api\";\nimport type {\n GraffitiSession,\n GraffitiObject,\n JSONSchema4,\n GraffitiStream,\n} from \"@graffiti-garden/api\";\nimport type { GraffitiObjectBase } from \"@graffiti-garden/api\";\nimport { Repeater } from \"@repeaterjs/repeater\";\nimport { applyPatch } from \"fast-json-patch\";\nimport {\n applyGraffitiPatch,\n attemptAjvCompile,\n isActorAllowedGraffitiObject,\n locationToUri,\n maskGraffitiObject,\n unpackLocationOrUri,\n} from \"@graffiti-garden/implementation-local/utilities\";\nexport type * from \"@graffiti-garden/api\";\n\nexport type GraffitiSynchronizeCallback = (\n oldObject: GraffitiObjectBase,\n newObject?: GraffitiObjectBase,\n) => void;\n\n/**\n * Wraps the [Graffiti API](https://api.graffiti.garden/classes/Graffiti.html)\n * so that changes made or received in one part of an application\n * are automatically routed to other parts of the application.\n * This is an important tool for building responsive\n * and consistent user interfaces, and is built upon to make\n * the [Graffiti Vue Plugin](https://vue.graffiti.garden/variables/GraffitiPlugin.html)\n * and possibly other front-end libraries in the future.\n *\n * Specifically, it provides the following *synchronize*\n * methods for each of the following API methods:\n *\n * | API Method | Synchronize Method |\n * |------------|--------------------|\n * | {@link get} | {@link synchronizeGet} |\n * | {@link discover} | {@link synchronizeDiscover} |\n * | {@link recoverOrphans} | {@link synchronizeRecoverOrphans} |\n *\n * Whenever a change is made via {@link put}, {@link patch}, and {@link delete} or\n * received from {@link get}, {@link discover}, and {@link recoverOrphans},\n * those changes are forwarded to the appropriate synchronize method.\n * Each synchronize method returns an iterator that streams these changes\n * continually until the user calls `return` on the iterator or `break`s out of the loop,\n * allowing for live updates without additional polling.\n *\n * Example 1: Suppose a user publishes a post using {@link put}. If the feed\n * displaying that user's posts is using {@link synchronizeDiscover} to listen for changes,\n * then the user's new post will instantly appear in their feed, giving the UI a\n * responsive feel.\n *\n * Example 2: Suppose one of a user's friends changes their name. As soon as the\n * user's application receives one notice of that change (using {@link get}\n * or {@link discover}), then {@link synchronizeDiscover} listeners can be used to update\n * all instance's of that friend's name in the user's application instantly,\n * providing a consistent user experience.\n *\n * @groupDescription Synchronize Methods\n * This group contains methods that listen for changes made via\n * {@link put}, {@link patch}, and {@link delete} or fetched from\n * {@link get}, {@link discover}, and {@link recoverOrphans} and then\n * streams appropriate changes to provide a responsive and consistent user experience.\n */\nexport class GraffitiSynchronize extends Graffiti {\n protected readonly ajv: Ajv;\n protected readonly graffiti: Graffiti;\n protected readonly callbacks = new Set<GraffitiSynchronizeCallback>();\n\n channelStats: Graffiti[\"channelStats\"];\n locationToUri: Graffiti[\"locationToUri\"];\n uriToLocation: Graffiti[\"uriToLocation\"];\n login: Graffiti[\"login\"];\n logout: Graffiti[\"logout\"];\n sessionEvents: Graffiti[\"sessionEvents\"];\n\n /**\n * Wraps a Graffiti API instance to provide the synchronize methods.\n * The GraffitiSyncrhonize class rather than the Graffiti class\n * must be used for all functions for the synchronize methods to work.\n */\n constructor(\n /**\n * The [Graffiti API](https://api.graffiti.garden/classes/Graffiti.html)\n * instance to wrap.\n */\n graffiti: Graffiti,\n /**\n * An optional instance of Ajv to use for validating\n * objects before dispatching them to listeners.\n * If not provided, a new instance of Ajv will be created.\n */\n ajv?: Ajv,\n ) {\n super();\n this.ajv = ajv ?? new Ajv({ strict: false });\n this.graffiti = graffiti;\n this.channelStats = graffiti.channelStats.bind(graffiti);\n this.locationToUri = graffiti.locationToUri.bind(graffiti);\n this.uriToLocation = graffiti.uriToLocation.bind(graffiti);\n this.login = graffiti.login.bind(graffiti);\n this.logout = graffiti.logout.bind(graffiti);\n this.sessionEvents = graffiti.sessionEvents;\n }\n\n protected synchronize<Schema extends JSONSchema4>(\n matchObject: (object: GraffitiObjectBase) => boolean,\n channels: string[],\n schema: Schema,\n session?: GraffitiSession | null,\n ) {\n const validate = attemptAjvCompile(this.ajv, schema);\n\n const repeater: GraffitiStream<GraffitiObject<Schema>> = new Repeater(\n async (push, stop) => {\n const callback: GraffitiSynchronizeCallback = (\n oldObjectRaw,\n newObjectRaw,\n ) => {\n for (const objectRaw of [newObjectRaw, oldObjectRaw]) {\n if (\n objectRaw &&\n matchObject(objectRaw) &&\n isActorAllowedGraffitiObject(objectRaw, session)\n ) {\n const object = { ...objectRaw };\n maskGraffitiObject(object, channels, session);\n if (validate(object)) {\n push({ value: object });\n break;\n }\n }\n }\n };\n\n this.callbacks.add(callback);\n await stop;\n this.callbacks.delete(callback);\n },\n );\n\n return repeater;\n }\n\n /**\n * This method has the same signature as {@link discover} but listens for\n * changes made via {@link put}, {@link patch}, and {@link delete} or\n * fetched from {@link get}, {@link discover}, and {@link recoverOrphans}\n * and then streams appropriate changes to provide a responsive and\n * consistent user experience.\n *\n * Unlike {@link discover}, this method continuously listens for changes\n * and will not terminate unless the user calls the `return` method on the iterator\n * or `break`s out of the loop.\n *\n * @group Synchronize Methods\n */\n synchronizeDiscover<Schema extends JSONSchema4>(\n ...args: Parameters<typeof Graffiti.prototype.discover<Schema>>\n ): GraffitiStream<GraffitiObject<Schema>> {\n const [channels, schema, session] = args;\n function matchObject(object: GraffitiObjectBase) {\n return object.channels.some((channel) => channels.includes(channel));\n }\n return this.synchronize(matchObject, channels, schema, session);\n }\n\n /**\n * This method has the same signature as {@link get} but\n * listens for changes made via {@link put}, {@link patch}, and {@link delete} or\n * fetched from {@link get}, {@link discover}, and {@link recoverOrphans} and then\n * streams appropriate changes to provide a responsive and consistent user experience.\n *\n * Unlike {@link get}, which returns a single result, this method continuously\n * listens for changes which are output as an asynchronous {@link GraffitiStream}.\n *\n * @group Synchronize Methods\n */\n synchronizeGet<Schema extends JSONSchema4>(\n ...args: Parameters<typeof Graffiti.prototype.get<Schema>>\n ): GraffitiStream<GraffitiObject<Schema>> {\n const [locationOrUri, schema, session] = args;\n function matchObject(object: GraffitiObjectBase) {\n const objectUri = locationToUri(object);\n const { uri } = unpackLocationOrUri(locationOrUri);\n return objectUri === uri;\n }\n return this.synchronize(matchObject, [], schema, session);\n }\n\n /**\n * This method has the same signature as {@link recoverOrphans} but\n * listens for changes made via\n * {@link put}, {@link patch}, and {@link delete} or fetched from\n * {@link get}, {@link discover}, and {@link recoverOrphans} and then\n * streams appropriate changes to provide a responsive and consistent user experience.\n *\n * Unlike {@link recoverOrphans}, this method continuously listens for changes\n * and will not terminate unless the user calls the `return` method on the iterator\n * or `break`s out of the loop.\n *\n * @group Synchronize Methods\n */\n synchronizeRecoverOrphans<Schema extends JSONSchema4>(\n ...args: Parameters<typeof Graffiti.prototype.recoverOrphans<Schema>>\n ): GraffitiStream<GraffitiObject<Schema>> {\n const [schema, session] = args;\n function matchObject(object: GraffitiObjectBase) {\n return object.actor === session.actor && object.channels.length === 0;\n }\n return this.synchronize(matchObject, [], schema, session);\n }\n\n protected async synchronizeDispatch(\n oldObject: GraffitiObjectBase,\n newObject?: GraffitiObjectBase,\n waitForListeners = false,\n ) {\n for (const callback of this.callbacks) {\n callback(oldObject, newObject);\n }\n if (waitForListeners) {\n // Wait for the listeners to receive\n // their objects, before returning the operation\n // that triggered them.\n //\n // This is important for mutators (put, patch, delete)\n // to ensure the application state has been updated\n // everywhere before returning, giving consistent\n // feedback to the user that the operation has completed.\n //\n // The opposite is true for accessors (get, discover, recoverOrphans),\n // where it is a weird user experience to call `get`\n // in one place and have the application update\n // somewhere else first. It is also less efficient.\n //\n // The hack is simply to await one \"macro task cycle\".\n // We need to wait for this cycle rather than using\n // `await push` in the callback, because it turns out\n // that `await push` won't resolve until the following\n // .next() call of the iterator, so if only\n // one .next() is called, this dispatch will hang.\n await new Promise((resolve) => setTimeout(resolve, 0));\n }\n }\n\n get: Graffiti[\"get\"] = async (...args) => {\n const object = await this.graffiti.get(...args);\n this.synchronizeDispatch(object);\n return object;\n };\n\n put: Graffiti[\"put\"] = async (...args) => {\n const oldObject = await this.graffiti.put(...args);\n const partialObject = args[0];\n const newObject: GraffitiObjectBase = {\n ...oldObject,\n value: partialObject.value,\n channels: partialObject.channels,\n allowed: partialObject.allowed,\n tombstone: false,\n };\n await this.synchronizeDispatch(oldObject, newObject, true);\n return oldObject;\n };\n\n patch: Graffiti[\"patch\"] = async (...args) => {\n const oldObject = await this.graffiti.patch(...args);\n const newObject: GraffitiObjectBase = { ...oldObject };\n newObject.tombstone = false;\n for (const prop of [\"value\", \"channels\", \"allowed\"] as const) {\n applyGraffitiPatch(applyPatch, prop, args[0], newObject);\n }\n await this.synchronizeDispatch(oldObject, newObject, true);\n return oldObject;\n };\n\n delete: Graffiti[\"delete\"] = async (...args) => {\n const oldObject = await this.graffiti.delete(...args);\n await this.synchronizeDispatch(oldObject, undefined, true);\n return oldObject;\n };\n\n protected objectStream<Schema extends JSONSchema4>(\n iterator: ReturnType<typeof Graffiti.prototype.discover<Schema>>,\n ) {\n const dispatch = this.synchronizeDispatch.bind(this);\n const wrapper = async function* () {\n let result = await iterator.next();\n while (!result.done) {\n if (!result.value.error) {\n dispatch(result.value.value);\n }\n yield result.value;\n result = await iterator.next();\n }\n return result.value;\n };\n return wrapper();\n }\n\n discover: Graffiti[\"discover\"] = (...args) => {\n const iterator = this.graffiti.discover(...args);\n return this.objectStream(iterator);\n };\n\n recoverOrphans: Graffiti[\"recoverOrphans\"] = (...args) => {\n const iterator = this.graffiti.recoverOrphans(...args);\n return this.objectStream(iterator);\n };\n}\n", "import type {\n GraffitiLocation,\n GraffitiObject,\n GraffitiObjectBase,\n GraffitiPatch,\n GraffitiSession,\n GraffitiPutObject,\n GraffitiStream,\n ChannelStats,\n} from \"./2-types\";\nimport type { JSONSchema4 } from \"json-schema\";\n\n/**\n * This API describes a small but powerful set of methods that\n * can be used to create many different kinds of social media applications,\n * all of which can interoperate.\n * These methods should satisfy all of an application's needs for\n * the communication, storage, and access management of social data.\n * The rest of the application can be built with standard client-side\n * user interface tools to present and interact with the data \u2014\n * no server code necessary.\n * The Typescript source for this API is available at\n * [graffiti-garden/api](https://github.com/graffiti-garden/api).\n *\n * There are several different implementations of this Graffiti API available,\n * including a [federated implementation](https://github.com/graffiti-garden/implementation-federated),\n * that lets users choose where their data is stored,\n * and a [local implementation](https://github.com/graffiti-garden/implementation-local)\n * that can be used for testing and development. In our design of Graffiti, this API is our\n * primary focus as it is the layer that shapes the experience\n * of developing applications. While different implementations can provide tradeoffs between\n * other important properties (e.g. privacy, security, scalability), those properties\n * are useless if the system as a whole doesn't expose useful functionality to developers.\n *\n * On the other side of the stack, there is [Vue plugin](https://github.com/graffiti-garden/wrapper-vue/)\n * that wraps around this API to provide reactivity. Other high-level libraries\n * will be available in the future.\n *\n * ## Overview\n *\n * Graffiti provides applications with methods to create and store data\n * on behalf of their users using standard CRUD operations:\n * {@link put}, {@link get}, {@link patch}, and {@link delete}.\n * This data can represent both social artifacts (e.g. posts, profiles) and\n * activities (e.g. likes, follows) and is stored as JSON.\n *\n * The social aspect of Graffiti comes from the {@link discover} method\n * which allows applications to find objects that other users made.\n * It is a lot like a traditional query operation, but it only\n * returns objects that have been placed in particular\n * {@link GraffitiObjectBase.channels | `channels`}\n * specified by the discovering application.\n *\n * Graffiti builds on well known concepts and standards wherever possible.\n * JSON Objects can be typed with [JSON Schema](https://json-schema.org/) and patches\n * can be applied with [JSON Patch](https://jsonpatch.com).\n * For interoperability between Graffiti applications, we recommend that\n * objects use established properties from the\n * [Activity Vocabulary](https://www.w3.org/TR/activitystreams-vocabulary/) when available,\n * however it is always possible to create additional properties, contributing\n * to the broader [folksonomy](https://en.wikipedia.org/wiki/Folksonomy).\n *\n * {@link GraffitiObjectBase.channels | `channels`} are one of the major concepts\n * unique to Graffiti along with *interaction relativity*, defined below.\n * Channels create boundaries between public spaces and work to prevent\n * [context collapse](https://en.wikipedia.org/wiki/Context_collapse)\n * even in a highly interoperable environment.\n * Interaction relativity means that all interactions between users are\n * actually atomic single-user operations that can be interpreted in different ways,\n * which also supports interoperability and pluralism.\n *\n * ### Channels\n *\n * {@link GraffitiObjectBase.channels | `channels`}\n * are a way for the creators of social data to express the intended audience of their\n * data. When a user creates data using the {@link put} method, they\n * can place their data in one or more channels.\n * Content consumers using the {@link discover} method will only see data\n * contained in one of the channels they specify.\n *\n * While many channels may be public, they partition\n * the public into different \"contexts\", mitigating the\n * phenomenon of [context collapse](https://en.wikipedia.org/wiki/Context_collapse) or the \"flattening of multiple audiences.\"\n * Any [URI](https://en.wikipedia.org/wiki/Uniform_Resource_Identifier) can be used as a channel, and so channels can represent people,\n * comment threads, topics, places (real or virtual), pieces of media, and more.\n *\n * For example, consider a comment on a post. If we place that comment in the channel\n * represented by the post's URI, then only people viewing the post will know to\n * look in that channel, giving it visibility akin to a comment on a blog post\n * or comment on Instagram ([since 2019](https://www.buzzfeednews.com/article/katienotopoulos/instagrams-following-activity-tab-is-going-away)).\n * If we also place the comment in the channel represented by the commenter's URI (their\n * {@link GraffitiObjectBase.actor | `actor` URI}), then people viewing the commenter's profile\n * will also see the comment, giving it more visibility, like a reply on Twitter.\n * If we *only* place the comment in the channel represented by the commenter's URI, then\n * it becomes like a quote tweet ([prior to 2020](https://x.com/Support/status/1300555325750292480)),\n * where the comment is only visible to the commenter's followers but not the audience\n * of the original post.\n *\n * The channel model differs from other models of communication such as the\n * [actor model](https://www.w3.org/TR/activitypub/#Overview) used by ActivityPub,\n * the protocol underlying Mastodon, or the [firehose model](https://bsky.social/about/blog/5-5-2023-federation-architecture)\n * used by the AT Protocol, the protocol underlying BlueSky.\n * The actor model is a fusion of direct messaging (like Email) and broadcasting\n * (like RSS) and works well for follow-based communication but struggles\n * to pass information via other rendez-vous.\n * In the actor model, even something as simple as comments can be\n * [very tricky and require server \"side effects\"](https://seb.jambor.dev/posts/understanding-activitypub-part-3-the-state-of-mastodon/).\n * The firehose model dumps all user data into one public database,\n * which doesn't allow for the carving out of different contexts that we did in our comment\n * example above. In the firehose model a comment will always be visible to *both* the original post's audience and\n * the commenter's followers.\n *\n * In some sense, channels provide a sort of \"social access control\" by forming\n * expectations about the audiences of different online spaces.\n * As a real world analogy, oftentimes support groups, such as alcoholics\n * anonymous, are open to the public but people in those spaces feel comfortable sharing intimate details\n * because they have expectations about the other people attending.\n * If someone malicious went to support groups just to spread people's secrets,\n * they would be shamed for violating these norms.\n * Similarly, in Graffiti, while you could spider public channels like a search engine\n * to find content about a person, revealing that you've done such a thing\n * would be shameful.\n *\n * Still, social access control is not perfect and so in situations where privacy is important,\n * objects can also be given\n * an {@link GraffitiObjectBase.allowed | `allowed`} list.\n * For example, to send someone a direct message you should put an object representing\n * that message in the channel that represents them (their {@link GraffitiObjectBase.actor | `actor` URI}),\n * so they can find it, *and* set the `allowed` field to only include the recipient,\n * so only they can read it.\n *\n * ### Interaction relativity\n *\n * Interaction relativity posits that \"interaction between two individuals only\n * exists relative to an observer,\" or equivalently, all interaction is [reified](https://en.wikipedia.org/wiki/Reification_(computer_science)).\n * For example, if one user creates a post and another user wants to \"like\" that post,\n * their like is not modifying the original post, it is simply another data object that points\n * to the post being liked, via its {@link locationToUri | URI}.\n *\n * ```json\n * {\n * activity: 'like',\n * target: 'uri-of-the-post-i-like',\n * actor: 'my-user-id'\n * }\n * ```\n *\n * In Graffiti, all interactions including *moderation* and *collaboration* are relative.\n * This means that applications can freely choose which interactions\n * they want to express to their users and how.\n * For example, one application could have a single fixed moderator,\n * another could allow users to choose which moderators they would like filter their content\n * like [Bluesky's stackable moderation](https://bsky.social/about/blog/03-12-2024-stackable-moderation),\n * and another could implement a fully democratic system like [PolicyKit](https://policykit.org/).\n * Each of these applications is one interpretation of the underlying refieid user interactions and\n * users can freely switch between them.\n *\n * Interaction relativy also allows applications to introduce new sorts of interactions\n * without having to coordinate with all the other existing applications,\n * keeping the ecosystem flexible and interoperable.\n * For example, an application could [add a \"Trust\" button to posts](https://social.cs.washington.edu/pub_details.html?id=trustnet)\n * and use it assess the truthfulness of posts made on applications across Graffiti.\n * New sorts of interactions like these can be smoothly absorbed by the broader ecosystem\n * as a [folksonomy](https://en.wikipedia.org/wiki/Folksonomy).\n *\n * Interactivy relativity is realized in Graffiti through two design decisions:\n * 1. The creators of objects can only modify their own objects. It is important for\n * users to be able to change and delete their own content to respect their\n * [right to be forgotten](https://en.wikipedia.org/wiki/Right_to_be_forgotten),\n * but beyond self-correction and self-censorship all other interaction is reified.\n * Many interactions can be reified via pointers, as in the \"like\" example above, and collaborative\n * edits can be refieid via [CRDTs](https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type).\n * 2. No one owns channels. Unlike IRC/Slack channels or [Matrix rooms](https://matrix.org/docs/matrix-concepts/rooms_and_events/),\n * anyone can post to any channel, so long as they know the URI of that channel.\n * It is up to applications to hide content from channels either according to manual\n * filters or in response to user action.\n * For example, a user may create a post with the flag `disableReplies`.\n * Applications could then filter out any content from the replies channel\n * that the original poster has not specifically approved.\n *\n * @groupDescription CRUD Methods\n * Methods for {@link put | creating}, {@link get | reading}, {@link patch | updating},\n * and {@link delete | deleting} {@link GraffitiObjectBase | Graffiti objects}.\n * @groupDescription Query Methods\n * Methods that retrieve or accumulate information about multiple {@link GraffitiObjectBase | Graffiti objects} at a time.\n * @groupDescription Session Management\n * Methods and properties for logging in and out of a Graffiti implementation.\n * @groupDescription Utilities\n * Methods for for converting Graffiti objects to and from URIs.\n */\nexport abstract class Graffiti {\n /**\n * Converts a {@link GraffitiLocation} object containing a\n * {@link GraffitiObjectBase.name | `name`}, {@link GraffitiObjectBase.actor | `actor`},\n * and {@link GraffitiObjectBase.source | `source`} into a globally unique URI.\n * The form of this URI is implementation dependent.\n *\n * Its exact inverse is {@link uriToLocation}.\n *\n * @group Utilities\n */\n abstract locationToUri(location: GraffitiLocation): string;\n\n /**\n * Parses a globally unique Graffiti URI into a {@link GraffitiLocation}\n * object containing a {@link GraffitiObjectBase.name | `name`},\n * {@link GraffitiObjectBase.actor | `actor`}, and {@link GraffitiObjectBase.source | `source`}.\n *\n * Its exact inverse is {@link locationToUri}.\n *\n * @group Utilities\n */\n abstract uriToLocation(uri: string): GraffitiLocation;\n\n /**\n * An alias of {@link locationToUri}\n *\n * @group Utilities\n */\n objectToUri(object: GraffitiObjectBase) {\n return this.locationToUri(object);\n }\n\n /**\n * Creates a new {@link GraffitiObjectBase | object} or replaces an existing object.\n * An object can only be replaced by the same {@link GraffitiObjectBase.actor | `actor`}\n * that created it.\n *\n * Replacement occurs when the {@link GraffitiLocation} properties of the supplied object\n * ({@link GraffitiObjectBase.name | `name`}, {@link GraffitiObjectBase.actor | `actor`},\n * and {@link GraffitiObjectBase.source | `source`}) exactly match the location of an existing object.\n *\n * @returns The object that was replaced if one exists or an object with\n * with a `null` {@link GraffitiObjectBase.value | `value`} if this method\n * created a new object.\n * The object will have a {@link GraffitiObjectBase.tombstone | `tombstone`}\n * field set to `true` and a {@link GraffitiObjectBase.lastModified | `lastModified`}\n * field updated to the time of replacement/creation.\n *\n * @group CRUD Methods\n */\n abstract put<Schema>(\n /**\n * The object to be put. This object is statically type-checked against the [JSON schema](https://json-schema.org/) that can be optionally provided\n * as the generic type parameter. We highly recommend providing a schema to\n * ensure that the PUT object matches subsequent {@link get} or {@link discover}\n * methods.\n */\n object: GraffitiPutObject<Schema>,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}.\n */\n session: GraffitiSession,\n ): Promise<GraffitiObjectBase>;\n\n /**\n * Retrieves an object from a given location.\n *\n * The retrieved object is type-checked against the provided [JSON schema](https://json-schema.org/)\n * otherwise a {@link GraffitiErrorSchemaMismatch} is thrown.\n *\n * If the object existed but has since been deleted,\n * or the retrieving {@link GraffitiObjectBase.actor | `actor`}\n * was {@link GraffitiObjectBase.allowed | `allowed`} to access\n * the object but now isn't, this method will return the latest\n * version of the object that the {@link GraffitiObjectBase.actor | `actor`}\n * was allowed to access with its {@link GraffitiObjectBase.tombstone | `tombstone`}\n * set to `true`, so long as that version is still cached.\n *\n * Otherwise, if the object never existed, or the\n * retrieving {@link GraffitiObjectBase.actor | `actor`} was never\n * {@link GraffitiObjectBase.allowed | `allowed`} to access it, or if\n * the object was changed long enough ago that its history has been\n * purged from the cache, a {@link GraffitiErrorNotFound} is thrown.\n * The rate at which the cache is purged is implementation dependent.\n * See the `tombstoneReturn` property returned by {@link discover}.\n *\n * @group CRUD Methods\n */\n abstract get<Schema extends JSONSchema4>(\n /**\n * The location of the object to get.\n */\n locationOrUri: GraffitiLocation | string,\n /**\n * The JSON schema to validate the retrieved object against.\n */\n schema: Schema,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}. If no `session` is provided,\n * the retrieved object's {@link GraffitiObjectBase.allowed | `allowed`}\n * property must be `undefined`.\n */\n session?: GraffitiSession | null,\n ): Promise<GraffitiObject<Schema>>;\n\n /**\n * Patches an existing object at a given location.\n * The patching {@link GraffitiObjectBase.actor | `actor`} must be the same as the\n * `actor` that created the object.\n *\n * @returns The object that was deleted if one exists or an object with\n * with a `null` {@link GraffitiObjectBase.value | `value`} otherwise.\n * The object will have a {@link GraffitiObjectBase.tombstone | `tombstone`}\n * field set to `true` and a {@link GraffitiObjectBase.lastModified | `lastModified`}\n * field updated to the time of deletion.\n *\n * @group CRUD Methods\n */\n abstract patch(\n /**\n * A collection of [JSON Patch](https://jsonpatch.com) operations\n * to apply to the object. See {@link GraffitiPatch} for more information.\n */\n patch: GraffitiPatch,\n /**\n * The location of the object to patch.\n */\n locationOrUri: GraffitiLocation | string,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}.\n */\n session: GraffitiSession,\n ): Promise<GraffitiObjectBase>;\n\n /**\n * Deletes an object from a given location.\n * The deleting {@link GraffitiObjectBase.actor | `actor`} must be the same as the\n * `actor` that created the object.\n *\n * If the object does not exist or has already been deleted,\n * {@link GraffitiErrorNotFound} is thrown.\n *\n * @returns The object that was deleted if one exists or an object with\n * with a `null` {@link GraffitiObjectBase.value | `value`} otherwise.\n * The object will have a {@link GraffitiObjectBase.tombstone | `tombstone`}\n * field set to `true` and a {@link GraffitiObjectBase.lastModified | `lastModified`}\n * field updated to the time of deletion.\n *\n * @group CRUD Methods\n */\n abstract delete(\n /**\n * The location of the object to delete.\n */\n locationOrUri: GraffitiLocation | string,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}.\n */\n session: GraffitiSession,\n ): Promise<GraffitiObjectBase>;\n\n /**\n * Discovers objects created by any user that are contained\n * in at least one of the given {@link GraffitiObjectBase.channels | `channels`}\n * and match the given [JSON Schema](https://json-schema.org).\n *\n * Objects are returned asynchronously as they are discovered but the stream\n * will end once all leads have been exhausted.\n * The method must be polled again for new objects.\n *\n * `discover` will not return objects that the {@link GraffitiObjectBase.actor | `actor`}\n * is not {@link GraffitiObjectBase.allowed | `allowed`} to access.\n * If the actor is not the creator of a discovered object,\n * the allowed list will be masked to only contain the querying actor if the\n * allowed list is not `undefined` (public). Additionally, if the actor is not the\n * creator of a discovered object, any {@link GraffitiObjectBase.channels | `channels`}\n * not specified by the `discover` method will not be revealed. This masking happens\n * before the supplied schema is applied.\n *\n * Since different implementations may fetch data from multiple sources there is\n * no guarentee on the order that objects are returned in. Additionally, the method\n * will return objects that have been deleted but with a\n * {@link GraffitiObjectBase.tombstone | `tombstone`} field set to `true` for\n * cache invalidation purposes.\n * The final `return()` value of the stream includes a `tombstoneRetention`\n * property that represents the minimum amount of time,\n * in milliseconds, that an application will retain and return tombstones for objects that\n * have been deleted.\n *\n * When repolling, the {@link GraffitiObjectBase.lastModified | `lastModified`}\n * field can be queried via the schema to\n * only fetch objects that have been modified since the last poll.\n * Such queries should only be done if the time since the last poll\n * is less than the `tombstoneRetention` value of that poll, otherwise the tombstones\n * for objects that have been deleted may not be returned.\n *\n * ```json\n * {\n * \"properties\": {\n * \"lastModified\": {\n * \"minimum\": LAST_RETRIEVED_TIME\n * }\n * }\n * }\n * ```\n *\n * `discover` needs to be polled for new data because live updates to\n * an application can be visually distracting or lead to toxic engagement.\n * If and when an application wants real-time updates, such as in a chat\n * application, application authors must be intentional about their polling.\n *\n * Implementers should be aware that some users may applications may try to poll\n * {@link discover} repetitively. You can deal with this by rate limiting or\n * preemptively fetching data via a bidirectional channel, like a WebSocket.\n * Additionally, implementers should probably index the `lastModified` field\n * to speed up responses to schemas like the one above.\n *\n * @returns A stream of objects that match the given {@link GraffitiObjectBase.channels | `channels`}\n * and [JSON Schema](https://json-schema.org).\n *\n * @group Query Methods\n */\n abstract discover<Schema extends JSONSchema4>(\n /**\n * The {@link GraffitiObjectBase.channels | `channels`} that objects must be associated with.\n */\n channels: string[],\n /**\n * A [JSON Schema](https://json-schema.org) that objects must satisfy.\n */\n schema: Schema,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}. If no `session` is provided,\n * only objects that have no {@link GraffitiObjectBase.allowed | `allowed`}\n * property will be returned.\n */\n session?: GraffitiSession | null,\n ): GraffitiStream<\n GraffitiObject<Schema>,\n {\n tombstoneRetention: number;\n }\n >;\n\n /**\n * Discovers objects **not** contained in any\n * {@link GraffitiObjectBase.channels | `channels`}\n * that were created by the querying {@link GraffitiObjectBase.actor | `actor`}\n * and match the given [JSON Schema](https://json-schema.org).\n * Unlike {@link discover}, this method will not return objects created by other users.\n *\n * This method is not useful for most applications, but necessary for\n * getting a global view of all a user's Graffiti data or debugging\n * channel usage.\n *\n * It's return value is the same as {@link discover}.\n *\n * @group Query Methods\n */\n abstract recoverOrphans<Schema extends JSONSchema4>(\n /**\n * A [JSON Schema](https://json-schema.org) that orphaned objects must satisfy.\n */\n schema: Schema,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}.\n */\n session: GraffitiSession,\n ): GraffitiStream<\n GraffitiObject<Schema>,\n {\n tombstoneRetention: number;\n }\n >;\n\n /**\n * Returns statistics about all the {@link GraffitiObjectBase.channels | `channels`}\n * that an {@link GraffitiObjectBase.actor | `actor`} has posted to.\n * This is not very useful for most applications, but\n * necessary for certain applications where a user wants a\n * global view of all their Graffiti data or to debug\n * channel usage.\n *\n * @group Query Methods\n *\n * @returns A stream of statistics for each {@link GraffitiObjectBase.channels | `channel`}\n * that the {@link GraffitiObjectBase.actor | `actor`} has posted to.\n */\n abstract channelStats(\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}.\n */\n session: GraffitiSession,\n ): GraffitiStream<ChannelStats>;\n\n /**\n * Begins the login process. Depending on the implementation, this may\n * involve redirecting the user to a login page or opening a popup,\n * so it should always be called in response to a user action.\n *\n * The {@link GraffitiSession | session} object is returned\n * asynchronously via {@link Graffiti.sessionEvents | sessionEvents}\n * as a {@link GraffitiLoginEvent} with event type `login`.\n *\n * @group Session Management\n */\n abstract login(\n /**\n * Suggestions for the permissions that the\n * login process should grant. The login process may not\n * provide the exact proposed permissions.\n */\n proposal?: {\n /**\n * A suggested actor to login as. For example, if a user tries to\n * edit a post but are not logged in, the interface can infer that\n * they might want to log in as the actor who created the post\n * they are attempting to edit.\n *\n * Even if provided, the implementation should allow the user\n * to log in as a different actor if they choose.\n */\n actor?: string;\n /**\n * A yet to be defined permissions scope. An application may use\n * this to indicate the minimum necessary scope needed to\n * operate. For example, it may need to be able read private\n * messages from a certain set of channels, or write messages that\n * follow a particular schema.\n *\n * The login process should make it clear what scope an application\n * is requesting and allow the user to enhance or reduce that\n * scope as necessary.\n */\n scope?: {};\n },\n ): Promise<void>;\n\n /**\n * Begins the logout process. Depending on the implementation, this may\n * involve redirecting the user to a logout page or opening a popup,\n * so it should always be called in response to a user action.\n *\n * A confirmation will be returned asynchronously via\n * {@link Graffiti.sessionEvents | sessionEvents}\n * as a {@link GraffitiLogoutEvent} as event type `logout`.\n *\n * @group Session Management\n */\n abstract logout(\n /**\n * The {@link GraffitiSession | session} object to logout.\n */\n session: GraffitiSession,\n ): Promise<void>;\n\n /**\n * An event target that can be used to listen for the following\n * events and they're corresponding event types:\n * - `login` - {@link GraffitiLoginEvent}\n * - `logout` - {@link GraffitiLogoutEvent}\n * - `initialized` - {@link GraffitiSessionInitializedEvent}\n *\n * @group Session Management\n */\n abstract readonly sessionEvents: EventTarget;\n}\n", "export class GraffitiErrorUnauthorized extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorUnauthorized\";\n Object.setPrototypeOf(this, GraffitiErrorUnauthorized.prototype);\n }\n}\n\nexport class GraffitiErrorForbidden extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorForbidden\";\n Object.setPrototypeOf(this, GraffitiErrorForbidden.prototype);\n }\n}\n\nexport class GraffitiErrorNotFound extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorNotFound\";\n Object.setPrototypeOf(this, GraffitiErrorNotFound.prototype);\n }\n}\n\nexport class GraffitiErrorInvalidSchema extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorInvalidSchema\";\n Object.setPrototypeOf(this, GraffitiErrorInvalidSchema.prototype);\n }\n}\n\nexport class GraffitiErrorSchemaMismatch extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorSchemaMismatch\";\n Object.setPrototypeOf(this, GraffitiErrorSchemaMismatch.prototype);\n }\n}\n\nexport class GraffitiErrorPatchTestFailed extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorPatchTestFailed\";\n Object.setPrototypeOf(this, GraffitiErrorPatchTestFailed.prototype);\n }\n}\n\nexport class GraffitiErrorPatchError extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorPatchError\";\n Object.setPrototypeOf(this, GraffitiErrorPatchError.prototype);\n }\n}\n\nexport class GraffitiErrorInvalidUri extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorInvalidUri\";\n Object.setPrototypeOf(this, GraffitiErrorInvalidUri.prototype);\n }\n}\n", "/// <reference types=\"./repeater.d.ts\" />\n/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nfunction __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nfunction __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nfunction __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nfunction __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nfunction __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nfunction __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\n\n/** An error subclass which is thrown when there are too many pending push or next operations on a single repeater. */\r\nvar RepeaterOverflowError = /** @class */ (function (_super) {\r\n __extends(RepeaterOverflowError, _super);\r\n function RepeaterOverflowError(message) {\r\n var _this = _super.call(this, message) || this;\r\n Object.defineProperty(_this, \"name\", {\r\n value: \"RepeaterOverflowError\",\r\n enumerable: false,\r\n });\r\n if (typeof Object.setPrototypeOf === \"function\") {\r\n Object.setPrototypeOf(_this, _this.constructor.prototype);\r\n }\r\n else {\r\n _this.__proto__ = _this.constructor.prototype;\r\n }\r\n if (typeof Error.captureStackTrace === \"function\") {\r\n Error.captureStackTrace(_this, _this.constructor);\r\n }\r\n return _this;\r\n }\r\n return RepeaterOverflowError;\r\n}(Error));\r\n/** A buffer which allows you to push a set amount of values to the repeater without pushes waiting or throwing errors. */\r\nvar FixedBuffer = /** @class */ (function () {\r\n function FixedBuffer(capacity) {\r\n if (capacity < 0) {\r\n throw new RangeError(\"Capacity may not be less than 0\");\r\n }\r\n this._c = capacity;\r\n this._q = [];\r\n }\r\n Object.defineProperty(FixedBuffer.prototype, \"empty\", {\r\n get: function () {\r\n return this._q.length === 0;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n Object.defineProperty(FixedBuffer.prototype, \"full\", {\r\n get: function () {\r\n return this._q.length >= this._c;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n FixedBuffer.prototype.add = function (value) {\r\n if (this.full) {\r\n throw new Error(\"Buffer full\");\r\n }\r\n else {\r\n this._q.push(value);\r\n }\r\n };\r\n FixedBuffer.prototype.remove = function () {\r\n if (this.empty) {\r\n throw new Error(\"Buffer empty\");\r\n }\r\n return this._q.shift();\r\n };\r\n return FixedBuffer;\r\n}());\r\n// TODO: Use a circular buffer here.\r\n/** Sliding buffers allow you to push a set amount of values to the repeater without pushes waiting or throwing errors. If the number of values exceeds the capacity set in the constructor, the buffer will discard the earliest values added. */\r\nvar SlidingBuffer = /** @class */ (function () {\r\n function SlidingBuffer(capacity) {\r\n if (capacity < 1) {\r\n throw new RangeError(\"Capacity may not be less than 1\");\r\n }\r\n this._c = capacity;\r\n this._q = [];\r\n }\r\n Object.defineProperty(SlidingBuffer.prototype, \"empty\", {\r\n get: function () {\r\n return this._q.length === 0;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n Object.defineProperty(SlidingBuffer.prototype, \"full\", {\r\n get: function () {\r\n return false;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n SlidingBuffer.prototype.add = function (value) {\r\n while (this._q.length >= this._c) {\r\n this._q.shift();\r\n }\r\n this._q.push(value);\r\n };\r\n SlidingBuffer.prototype.remove = function () {\r\n if (this.empty) {\r\n throw new Error(\"Buffer empty\");\r\n }\r\n return this._q.shift();\r\n };\r\n return SlidingBuffer;\r\n}());\r\n/** Dropping buffers allow you to push a set amount of values to the repeater without the push function waiting or throwing errors. If the number of values exceeds the capacity set in the constructor, the buffer will discard the latest values added. */\r\nvar DroppingBuffer = /** @class */ (function () {\r\n function DroppingBuffer(capacity) {\r\n if (capacity < 1) {\r\n throw new RangeError(\"Capacity may not be less than 1\");\r\n }\r\n this._c = capacity;\r\n this._q = [];\r\n }\r\n Object.defineProperty(DroppingBuffer.prototype, \"empty\", {\r\n get: function () {\r\n return this._q.length === 0;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n Object.defineProperty(DroppingBuffer.prototype, \"full\", {\r\n get: function () {\r\n return false;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n DroppingBuffer.prototype.add = function (value) {\r\n if (this._q.length < this._c) {\r\n this._q.push(value);\r\n }\r\n };\r\n DroppingBuffer.prototype.remove = function () {\r\n if (this.empty) {\r\n throw new Error(\"Buffer empty\");\r\n }\r\n return this._q.shift();\r\n };\r\n return DroppingBuffer;\r\n}());\r\n/** Makes sure promise-likes don\u2019t cause unhandled rejections. */\r\nfunction swallow(value) {\r\n if (value != null && typeof value.then === \"function\") {\r\n value.then(NOOP, NOOP);\r\n }\r\n}\r\n/*** REPEATER STATES ***/\r\n/** The following is an enumeration of all possible repeater states. These states are ordered, and a repeater may only advance to higher states. */\r\n/** The initial state of the repeater. */\r\nvar Initial = 0;\r\n/** Repeaters advance to this state the first time the next method is called on the repeater. */\r\nvar Started = 1;\r\n/** Repeaters advance to this state when the stop function is called. */\r\nvar Stopped = 2;\r\n/** Repeaters advance to this state when there are no values left to be pulled from the repeater. */\r\nvar Done = 3;\r\n/** Repeaters advance to this state if an error is thrown into the repeater. */\r\nvar Rejected = 4;\r\n/** The maximum number of push or next operations which may exist on a single repeater. */\r\nvar MAX_QUEUE_LENGTH = 1024;\r\nvar NOOP = function () { };\r\n/** A helper function used to mimic the behavior of async generators where the final iteration is consumed. */\r\nfunction consumeExecution(r) {\r\n var err = r.err;\r\n var execution = Promise.resolve(r.execution).then(function (value) {\r\n if (err != null) {\r\n throw err;\r\n }\r\n return value;\r\n });\r\n r.err = undefined;\r\n r.execution = execution.then(function () { return undefined; }, function () { return undefined; });\r\n return r.pending === undefined ? execution : r.pending.then(function () { return execution; });\r\n}\r\n/** A helper function for building iterations from values. Promises are unwrapped, so that iterations never have their value property set to a promise. */\r\nfunction createIteration(r, value) {\r\n var done = r.state >= Done;\r\n return Promise.resolve(value).then(function (value) {\r\n if (!done && r.state >= Rejected) {\r\n return consumeExecution(r).then(function (value) { return ({\r\n value: value,\r\n done: true,\r\n }); });\r\n }\r\n return { value: value, done: done };\r\n });\r\n}\r\n/**\r\n * This function is bound and passed to the executor as the stop argument.\r\n *\r\n * Advances state to Stopped.\r\n */\r\nfunction stop(r, err) {\r\n var e_1, _a;\r\n if (r.state >= Stopped) {\r\n return;\r\n }\r\n r.state = Stopped;\r\n r.onnext();\r\n r.onstop();\r\n if (r.err == null) {\r\n r.err = err;\r\n }\r\n if (r.pushes.length === 0 &&\r\n (typeof r.buffer === \"undefined\" || r.buffer.empty)) {\r\n finish(r);\r\n }\r\n else {\r\n try {\r\n for (var _b = __values(r.pushes), _d = _b.next(); !_d.done; _d = _b.next()) {\r\n var push_1 = _d.value;\r\n push_1.resolve();\r\n }\r\n }\r\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\r\n finally {\r\n try {\r\n if (_d && !_d.done && (_a = _b.return)) _a.call(_b);\r\n }\r\n finally { if (e_1) throw e_1.error; }\r\n }\r\n }\r\n}\r\n/**\r\n * The difference between stopping a repeater vs finishing a repeater is that stopping a repeater allows next to continue to drain values from the push queue and buffer, while finishing a repeater will clear all pending values and end iteration immediately. Once, a repeater is finished, all iterations will have the done property set to true.\r\n *\r\n * Advances state to Done.\r\n */\r\nfunction finish(r) {\r\n var e_2, _a;\r\n if (r.state >= Done) {\r\n return;\r\n }\r\n if (r.state < Stopped) {\r\n stop(r);\r\n }\r\n r.state = Done;\r\n r.buffer = undefined;\r\n try {\r\n for (var _b = __values(r.nexts), _d = _b.next(); !_d.done; _d = _b.next()) {\r\n var next = _d.value;\r\n var execution = r.pending === undefined\r\n ? consumeExecution(r)\r\n : r.pending.then(function () { return consumeExecution(r); });\r\n next.resolve(createIteration(r, execution));\r\n }\r\n }\r\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\r\n finally {\r\n try {\r\n if (_d && !_d.done && (_a = _b.return)) _a.call(_b);\r\n }\r\n finally { if (e_2) throw e_2.error; }\r\n }\r\n r.pushes = [];\r\n r.nexts = [];\r\n}\r\n/**\r\n * Called when a promise passed to push rejects, or when a push call is unhandled.\r\n *\r\n * Advances state to Rejected.\r\n */\r\nfunction reject(r) {\r\n if (r.state >= Rejected) {\r\n return;\r\n }\r\n if (r.state < Done) {\r\n finish(r);\r\n }\r\n r.state = Rejected;\r\n}\r\n/** This function is bound and passed to the executor as the push argument. */\r\nfunction push(r, value) {\r\n swallow(value);\r\n if (r.pushes.length >= MAX_QUEUE_LENGTH) {\r\n throw new RepeaterOverflowError(\"No more than \" + MAX_QUEUE_LENGTH + \" pending calls to push are allowed on a single repeater.\");\r\n }\r\n else if (r.state >= Stopped) {\r\n return Promise.resolve(undefined);\r\n }\r\n var valueP = r.pending === undefined\r\n ? Promise.resolve(value)\r\n : r.pending.then(function () { return value; });\r\n valueP = valueP.catch(function (err) {\r\n if (r.state < Stopped) {\r\n r.err = err;\r\n }\r\n reject(r);\r\n return undefined; // void :(\r\n });\r\n var nextP;\r\n if (r.nexts.length) {\r\n var next_1 = r.nexts.shift();\r\n next_1.resolve(createIteration(r, valueP));\r\n if (r.nexts.length) {\r\n nextP = Promise.resolve(r.nexts[0].value);\r\n }\r\n else if (typeof r.buffer !== \"undefined\" && !r.buffer.full) {\r\n nextP = Promise.resolve(undefined);\r\n }\r\n else {\r\n nextP = new Promise(function (resolve) { return (r.onnext = resolve); });\r\n }\r\n }\r\n else if (typeof r.buffer !== \"undefined\" && !r.buffer.full) {\r\n r.buffer.add(valueP);\r\n nextP = Promise.resolve(undefined);\r\n }\r\n else {\r\n nextP = new Promise(function (resolve) { return r.pushes.push({ resolve: resolve, value: valueP }); });\r\n }\r\n // If an error is thrown into the repeater via the next or throw methods, we give the repeater a chance to handle this by rejecting the promise returned from push. If the push call is not immediately handled we throw the next iteration of the repeater.\r\n // To check that the promise returned from push is floating, we modify the then and catch methods of the returned promise so that they flip the floating flag. The push function actually does not return a promise, because modern engines do not call the then and catch methods on native promises. By making next a plain old javascript object, we ensure that the then and catch methods will be called.\r\n var floating = true;\r\n var next = {};\r\n var unhandled = nextP.catch(function (err) {\r\n if (floating) {\r\n throw err;\r\n }\r\n return undefined; // void :(\r\n });\r\n next.then = function (onfulfilled, onrejected) {\r\n floating = false;\r\n return Promise.prototype.then.call(nextP, onfulfilled, onrejected);\r\n };\r\n next.catch = function (onrejected) {\r\n floating = false;\r\n return Promise.prototype.catch.call(nextP, onrejected);\r\n };\r\n next.finally = nextP.finally.bind(nextP);\r\n r.pending = valueP\r\n .then(function () { return unhandled; })\r\n .catch(function (err) {\r\n r.err = err;\r\n reject(r);\r\n });\r\n return next;\r\n}\r\n/**\r\n * Creates the stop callable promise which is passed to the executor\r\n */\r\nfunction createStop(r) {\r\n var stop1 = stop.bind(null, r);\r\n var stopP = new Promise(function (resolve) { return (r.onstop = resolve); });\r\n stop1.then = stopP.then.bind(stopP);\r\n stop1.catch = stopP.catch.bind(stopP);\r\n stop1.finally = stopP.finally.bind(stopP);\r\n return stop1;\r\n}\r\n/**\r\n * Calls the executor passed into the constructor. This function is called the first time the next method is called on the repeater.\r\n *\r\n * Advances state to Started.\r\n */\r\nfunction execute(r) {\r\n if (r.state >= Started) {\r\n return;\r\n }\r\n r.state = Started;\r\n var push1 = push.bind(null, r);\r\n var stop1 = createStop(r);\r\n r.execution = new Promise(function (resolve) { return resolve(r.executor(push1, stop1)); });\r\n // TODO: We should consider stopping all repeaters when the executor settles.\r\n r.execution.catch(function () { return stop(r); });\r\n}\r\nvar records = new WeakMap();\r\n// NOTE: While repeaters implement and are assignable to the AsyncGenerator interface, and you can use the types interchangeably, we don\u2019t use typescript\u2019s implements syntax here because this would make supporting earlier versions of typescript trickier. This is because TypeScript version 3.6 changed the iterator types by adding the TReturn and TNext type parameters.\r\nvar Repeater = /** @class */ (function () {\r\n function Repeater(executor, buffer) {\r\n records.set(this, {\r\n executor: executor,\r\n buffer: buffer,\r\n err: undefined,\r\n state: Initial,\r\n pushes: [],\r\n nexts: [],\r\n pending: undefined,\r\n execution: undefined,\r\n onnext: NOOP,\r\n onstop: NOOP,\r\n });\r\n }\r\n Repeater.prototype.next = function (value) {\r\n swallow(value);\r\n var r = records.get(this);\r\n if (r === undefined) {\r\n throw new Error(\"WeakMap error\");\r\n }\r\n if (r.nexts.length >= MAX_QUEUE_LENGTH) {\r\n throw new RepeaterOverflowError(\"No more than \" + MAX_QUEUE_LENGTH + \" pending calls to next are allowed on a single repeater.\");\r\n }\r\n if (r.state <= Initial) {\r\n execute(r);\r\n }\r\n r.onnext(value);\r\n if (typeof r.buffer !== \"undefined\" && !r.buffer.empty) {\r\n var result = createIteration(r, r.buffer.remove());\r\n if (r.pushes.length) {\r\n var push_2 = r.pushes.shift();\r\n r.buffer.add(push_2.value);\r\n r.onnext = push_2.resolve;\r\n }\r\n return result;\r\n }\r\n else if (r.pushes.length) {\r\n var push_3 = r.pushes.shift();\r\n r.onnext = push_3.resolve;\r\n return createIteration(r, push_3.value);\r\n }\r\n else if (r.state >= Stopped) {\r\n finish(r);\r\n return createIteration(r, consumeExecution(r));\r\n }\r\n return new Promise(function (resolve) { return r.nexts.push({ resolve: resolve, value: value }); });\r\n };\r\n Repeater.prototype.return = function (value) {\r\n swallow(value);\r\n var r = records.get(this);\r\n if (r === undefined) {\r\n throw new Error(\"WeakMap error\");\r\n }\r\n finish(r);\r\n // We override the execution because return should always return the value passed in.\r\n r.execution = Promise.resolve(r.execution).then(function () { return value; });\r\n return createIteration(r, consumeExecution(r));\r\n };\r\n Repeater.prototype.throw = function (err) {\r\n var r = records.get(this);\r\n if (r === undefined) {\r\n throw new Error(\"WeakMap error\");\r\n }\r\n if (r.state <= Initial ||\r\n r.state >= Stopped ||\r\n (typeof r.buffer !== \"undefined\" && !r.buffer.empty)) {\r\n finish(r);\r\n // If r.err is already set, that mean the repeater has already produced an error, so we throw that error rather than the error passed in, because doing so might be more informative for the caller.\r\n if (r.err == null) {\r\n r.err = err;\r\n }\r\n return createIteration(r, consumeExecution(r));\r\n }\r\n return this.next(Promise.reject(err));\r\n };\r\n Repeater.prototype[Symbol.asyncIterator] = function () {\r\n return this;\r\n };\r\n // TODO: Remove these static methods from the class.\r\n Repeater.race = race;\r\n Repeater.merge = merge;\r\n Repeater.zip = zip;\r\n Repeater.latest = latest;\r\n return Repeater;\r\n}());\r\n/*** COMBINATOR FUNCTIONS ***/\r\n// TODO: move these combinators to their own file.\r\nfunction getIterators(values, options) {\r\n var e_3, _a;\r\n var iters = [];\r\n var _loop_1 = function (value) {\r\n if (value != null && typeof value[Symbol.asyncIterator] === \"function\") {\r\n iters.push(value[Symbol.asyncIterator]());\r\n }\r\n else if (value != null && typeof value[Symbol.iterator] === \"function\") {\r\n iters.push(value[Symbol.iterator]());\r\n }\r\n else {\r\n iters.push((function valueToAsyncIterator() {\r\n return __asyncGenerator(this, arguments, function valueToAsyncIterator_1() {\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!options.yieldValues) return [3 /*break*/, 3];\r\n return [4 /*yield*/, __await(value)];\r\n case 1: return [4 /*yield*/, _a.sent()];\r\n case 2:\r\n _a.sent();\r\n _a.label = 3;\r\n case 3:\r\n if (!options.returnValues) return [3 /*break*/, 5];\r\n return [4 /*yield*/, __await(value)];\r\n case 4: return [2 /*return*/, _a.sent()];\r\n case 5: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n })());\r\n }\r\n };\r\n try {\r\n for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {\r\n var value = values_1_1.value;\r\n _loop_1(value);\r\n }\r\n }\r\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\r\n finally {\r\n try {\r\n if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);\r\n }\r\n finally { if (e_3) throw e_3.error; }\r\n }\r\n return iters;\r\n}\r\n// NOTE: whenever you see any variables called `advance` or `advances`, know that it is a hack to get around the fact that `Promise.race` leaks memory. These variables are intended to be set to the resolve function of a promise which is constructed and awaited as an alternative to Promise.race. For more information, see this comment in the Node.js issue tracker: https://github.com/nodejs/node/issues/17469#issuecomment-685216777.\r\nfunction race(contenders) {\r\n var _this = this;\r\n var iters = getIterators(contenders, { returnValues: true });\r\n return new Repeater(function (push, stop) { return __awaiter(_this, void 0, void 0, function () {\r\n var advance, stopped, finalIteration, iteration, i_1, _loop_2;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!iters.length) {\r\n stop();\r\n return [2 /*return*/];\r\n }\r\n stopped = false;\r\n stop.then(function () {\r\n advance();\r\n stopped = true;\r\n });\r\n _a.label = 1;\r\n case 1:\r\n _a.trys.push([1, , 5, 7]);\r\n iteration = void 0;\r\n i_1 = 0;\r\n _loop_2 = function () {\r\n var j, iters_1, iters_1_1, iter;\r\n var e_4, _a;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0:\r\n j = i_1;\r\n try {\r\n for (iters_1 = (e_4 = void 0, __values(iters)), iters_1_1 = iters_1.next(); !iters_1_1.done; iters_1_1 = iters_1.next()) {\r\n iter = iters_1_1.value;\r\n Promise.resolve(iter.next()).then(function (iteration) {\r\n if (iteration.done) {\r\n stop();\r\n if (finalIteration === undefined) {\r\n finalIteration = iteration;\r\n }\r\n }\r\n else if (i_1 === j) {\r\n // This iterator has won, advance i and resolve the promise.\r\n i_1++;\r\n advance(iteration);\r\n }\r\n }, function (err) { return stop(err); });\r\n }\r\n }\r\n catch (e_4_1) { e_4 = { error: e_4_1 }; }\r\n finally {\r\n try {\r\n if (iters_1_1 && !iters_1_1.done && (_a = iters_1.return)) _a.call(iters_1);\r\n }\r\n finally { if (e_4) throw e_4.error; }\r\n }\r\n return [4 /*yield*/, new Promise(function (resolve) { return (advance = resolve); })];\r\n case 1:\r\n iteration = _b.sent();\r\n if (!(iteration !== undefined)) return [3 /*break*/, 3];\r\n return [4 /*yield*/, push(iteration.value)];\r\n case 2:\r\n _b.sent();\r\n _b.label = 3;\r\n case 3: return [2 /*return*/];\r\n }\r\n });\r\n };\r\n _a.label = 2;\r\n case 2:\r\n if (!!stopped) return [3 /*break*/, 4];\r\n return [5 /*yield**/, _loop_2()];\r\n case 3:\r\n _a.sent();\r\n return [3 /*break*/, 2];\r\n case 4: return [2 /*return*/, finalIteration && finalIteration.value];\r\n case 5:\r\n stop();\r\n return [4 /*yield*/, Promise.race(iters.map(function (iter) { return iter.return && iter.return(); }))];\r\n case 6:\r\n _a.sent();\r\n return [7 /*endfinally*/];\r\n case 7: return [2 /*return*/];\r\n }\r\n });\r\n }); });\r\n}\r\nfunction merge(contenders) {\r\n var _this = this;\r\n var iters = getIterators(contenders, { yieldValues: true });\r\n return new Repeater(function (push, stop) { return __awaiter(_this, void 0, void 0, function () {\r\n var advances, stopped, finalIteration;\r\n var _this = this;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!iters.length) {\r\n stop();\r\n return [2 /*return*/];\r\n }\r\n advances = [];\r\n stopped = false;\r\n stop.then(function () {\r\n var e_5, _a;\r\n stopped = true;\r\n try {\r\n for (var advances_1 = __values(advances), advances_1_1 = advances_1.next(); !advances_1_1.done; advances_1_1 = advances_1.next()) {\r\n var advance = advances_1_1.value;\r\n advance();\r\n }\r\n }\r\n catch (e_5_1) { e_5 = { error: e_5_1 }; }\r\n finally {\r\n try {\r\n if (advances_1_1 && !advances_1_1.done && (_a = advances_1.return)) _a.call(advances_1);\r\n }\r\n finally { if (e_5) throw e_5.error; }\r\n }\r\n });\r\n _a.label = 1;\r\n case 1:\r\n _a.trys.push([1, , 3, 4]);\r\n return [4 /*yield*/, Promise.all(iters.map(function (iter, i) { return __awaiter(_this, void 0, void 0, function () {\r\n var iteration, _a;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0:\r\n _b.trys.push([0, , 6, 9]);\r\n _b.label = 1;\r\n case 1:\r\n if (!!stopped) return [3 /*break*/, 5];\r\n Promise.resolve(iter.next()).then(function (iteration) { return advances[i](iteration); }, function (err) { return stop(err); });\r\n return [4 /*yield*/, new Promise(function (resolve) {\r\n advances[i] = resolve;\r\n })];\r\n case 2:\r\n iteration = _b.sent();\r\n if (!(iteration !== undefined)) return [3 /*break*/, 4];\r\n if (iteration.done) {\r\n finalIteration = iteration;\r\n return [2 /*return*/];\r\n }\r\n return [4 /*yield*/, push(iteration.value)];\r\n case 3:\r\n _b.sent();\r\n _b.label = 4;\r\n case 4: return [3 /*break*/, 1];\r\n case 5: return [3 /*break*/, 9];\r\n case 6:\r\n _a = iter.return;\r\n if (!_a) return [3 /*break*/, 8];\r\n return [4 /*yield*/, iter.return()];\r\n case 7:\r\n _a = (_b.sent());\r\n _b.label = 8;\r\n case 8:\r\n return [7 /*endfinally*/];\r\n case 9: return [2 /*return*/];\r\n }\r\n });\r\n }); }))];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/, finalIteration && finalIteration.value];\r\n case 3:\r\n stop();\r\n return [7 /*endfinally*/];\r\n case 4: return [2 /*return*/];\r\n }\r\n });\r\n }); });\r\n}\r\nfunction zip(contenders) {\r\n var _this = this;\r\n var iters = getIterators(contenders, { returnValues: true });\r\n return new Repeater(function (push, stop) { return __awaiter(_this, void 0, void 0, function () {\r\n var advance, stopped, iterations, values;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!iters.length) {\r\n stop();\r\n return [2 /*return*/, []];\r\n }\r\n stopped = false;\r\n stop.then(function () {\r\n advance();\r\n stopped = true;\r\n });\r\n _a.label = 1;\r\n case 1:\r\n _a.trys.push([1, , 6, 8]);\r\n _a.label = 2;\r\n case 2:\r\n if (!!stopped) return [3 /*break*/, 5];\r\n Promise.all(iters.map(function (iter) { return iter.next(); })).then(function (iterations) { return advance(iterations); }, function (err) { return stop(err); });\r\n return [4 /*yield*/, new Promise(function (resolve) { return (advance = resolve); })];\r\n case 3:\r\n iterations = _a.sent();\r\n if (iterations === undefined) {\r\n return [2 /*return*/];\r\n }\r\n values = iterations.map(function (iteration) { return iteration.value; });\r\n if (iterations.some(function (iteration) { return iteration.done; })) {\r\n return [2 /*return*/, values];\r\n }\r\n return [4 /*yield*/, push(values)];\r\n case 4:\r\n _a.sent();\r\n return [3 /*break*/, 2];\r\n case 5: return [3 /*break*/, 8];\r\n case 6:\r\n stop();\r\n return [4 /*yield*/, Promise.all(iters.map(function (iter) { return iter.return && iter.return(); }))];\r\n case 7:\r\n _a.sent();\r\n return [7 /*endfinally*/];\r\n case 8: return [2 /*return*/];\r\n }\r\n });\r\n }); });\r\n}\r\nfunction latest(contenders) {\r\n var _this = this;\r\n var iters = getIterators(contenders, {\r\n yieldValues: true,\r\n returnValues: true,\r\n });\r\n return new Repeater(function (push, stop) { return __awaiter(_this, void 0, void 0, function () {\r\n var advance, advances, stopped, iterations_1, values_2;\r\n var _this = this;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!iters.length) {\r\n stop();\r\n return [2 /*return*/, []];\r\n }\r\n advances = [];\r\n stopped = false;\r\n stop.then(function () {\r\n var e_6, _a;\r\n advance();\r\n try {\r\n for (var advances_2 = __values(advances), advances_2_1 = advances_2.next(); !advances_2_1.done; advances_2_1 = advances_2.next()) {\r\n var advance1 = advances_2_1.value;\r\n advance1();\r\n }\r\n }\r\n catch (e_6_1) { e_6 = { error: e_6_1 }; }\r\n finally {\r\n try {\r\n if (advances_2_1 && !advances_2_1.done && (_a = advances_2.return)) _a.call(advances_2);\r\n }\r\n finally { if (e_6) throw e_6.error; }\r\n }\r\n stopped = true;\r\n });\r\n _a.label = 1;\r\n case 1:\r\n _a.trys.push([1, , 5, 7]);\r\n Promise.all(iters.map(function (iter) { return iter.next(); })).then(function (iterations) { return advance(iterations); }, function (err) { return stop(err); });\r\n return [4 /*yield*/, new Promise(function (resolve) { return (advance = resolve); })];\r\n case 2:\r\n iterations_1 = _a.sent();\r\n if (iterations_1 === undefined) {\r\n return [2 /*return*/];\r\n }\r\n values_2 = iterations_1.map(function (iteration) { return iteration.value; });\r\n if (iterations_1.every(function (iteration) { return iteration.done; })) {\r\n return [2 /*return*/, values_2];\r\n }\r\n // We continuously yield and mutate the same values array so we shallow copy it each time it is pushed.\r\n return [4 /*yield*/, push(values_2.slice())];\r\n case 3:\r\n // We continuously yield and mutate the same values array so we shallow copy it each time it is pushed.\r\n _a.sent();\r\n return [4 /*yield*/, Promise.all(iters.map(function (iter, i) { return __awaiter(_this, void 0, void 0, function () {\r\n var iteration;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (iterations_1[i].done) {\r\n return [2 /*return*/, iterations_1[i].value];\r\n }\r\n _a.label = 1;\r\n case 1:\r\n if (!!stopped) return [3 /*break*/, 4];\r\n Promise.resolve(iter.next()).then(function (iteration) { return advances[i](iteration); }, function (err) { return stop(err); });\r\n return [4 /*yield*/, new Promise(function (resolve) { return (advances[i] = resolve); })];\r\n case 2:\r\n iteration = _a.sent();\r\n if (iteration === undefined) {\r\n return [2 /*return*/, iterations_1[i].value];\r\n }\r\n else if (iteration.done) {\r\n return [2 /*return*/, iteration.value];\r\n }\r\n values_2[i] = iteration.value;\r\n return [4 /*yield*/, push(values_2.slice())];\r\n case 3:\r\n _a.sent();\r\n return [3 /*break*/, 1];\r\n case 4: return [2 /*return*/];\r\n }\r\n });\r\n }); }))];\r\n case 4: return [2 /*return*/, _a.sent()];\r\n case 5:\r\n stop();\r\n return [4 /*yield*/, Promise.all(iters.map(function (iter) { return iter.return && iter.return(); }))];\r\n case 6:\r\n _a.sent();\r\n return [7 /*endfinally*/];\r\n case 7: return [2 /*return*/];\r\n }\r\n });\r\n }); });\r\n}\n\nexport { DroppingBuffer, FixedBuffer, MAX_QUEUE_LENGTH, Repeater, RepeaterOverflowError, SlidingBuffer };\n//# sourceMappingURL=repeater.js.map\n", "import { PatchError, _deepClone, isInteger, unescapePathComponent, hasUndefined } from './helpers.mjs';\nexport var JsonPatchError = PatchError;\nexport var deepClone = _deepClone;\n/* We use a Javascript hash to store each\n function. Each hash entry (property) uses\n the operation identifiers specified in rfc6902.\n In this way, we can map each patch operation\n to its dedicated function in efficient way.\n */\n/* The operations applicable to an object */\nvar objOps = {\n add: function (obj, key, document) {\n obj[key] = this.value;\n return { newDocument: document };\n },\n remove: function (obj, key, document) {\n var removed = obj[key];\n delete obj[key];\n return { newDocument: document, removed: removed };\n },\n replace: function (obj, key, document) {\n var removed = obj[key];\n obj[key] = this.value;\n return { newDocument: document, removed: removed };\n },\n move: function (obj, key, document) {\n /* in case move target overwrites an existing value,\n return the removed value, this can be taxing performance-wise,\n and is potentially unneeded */\n var removed = getValueByPointer(document, this.path);\n if (removed) {\n removed = _deepClone(removed);\n }\n var originalValue = applyOperation(document, { op: \"remove\", path: this.from }).removed;\n applyOperation(document, { op: \"add\", path: this.path, value: originalValue });\n return { newDocument: document, removed: removed };\n },\n copy: function (obj, key, document) {\n var valueToCopy = getValueByPointer(document, this.from);\n // enforce copy by value so further operations don't affect source (see issue #177)\n applyOperation(document, { op: \"add\", path: this.path, value: _deepClone(valueToCopy) });\n return { newDocument: document };\n },\n test: function (obj, key, document) {\n return { newDocument: document, test: _areEquals(obj[key], this.value) };\n },\n _get: function (obj, key, document) {\n this.value = obj[key];\n return { newDocument: document };\n }\n};\n/* The operations applicable to an array. Many are the same as for the object */\nvar arrOps = {\n add: function (arr, i, document) {\n if (isInteger(i)) {\n arr.splice(i, 0, this.value);\n }\n else { // array props\n arr[i] = this.value;\n }\n // this may be needed when using '-' in an array\n return { newDocument: document, index: i };\n },\n remove: function (arr, i, document) {\n var removedList = arr.splice(i, 1);\n return { newDocument: document, removed: removedList[0] };\n },\n replace: function (arr, i, document) {\n var removed = arr[i];\n arr[i] = this.value;\n return { newDocument: document, removed: removed };\n },\n move: objOps.move,\n copy: objOps.copy,\n test: objOps.test,\n _get: objOps._get\n};\n/**\n * Retrieves a value from a JSON document by a JSON pointer.\n * Returns the value.\n *\n * @param document The document to get the value from\n * @param pointer an escaped JSON pointer\n * @return The retrieved value\n */\nexport function getValueByPointer(document, pointer) {\n if (pointer == '') {\n return document;\n }\n var getOriginalDestination = { op: \"_get\", path: pointer };\n applyOperation(document, getOriginalDestination);\n return getOriginalDestination.value;\n}\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the {newDocument, result} of the operation.\n * It modifies the `document` and `operation` objects - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return `{newDocument, result}` after the operation\n */\nexport function applyOperation(document, operation, validateOperation, mutateDocument, banPrototypeModifications, index) {\n if (validateOperation === void 0) { validateOperation = false; }\n if (mutateDocument === void 0) { mutateDocument = true; }\n if (banPrototypeModifications === void 0) { banPrototypeModifications = true; }\n if (index === void 0) { index = 0; }\n if (validateOperation) {\n if (typeof validateOperation == 'function') {\n validateOperation(operation, 0, document, operation.path);\n }\n else {\n validator(operation, 0);\n }\n }\n /* ROOT OPERATIONS */\n if (operation.path === \"\") {\n var returnValue = { newDocument: document };\n if (operation.op === 'add') {\n returnValue.newDocument = operation.value;\n return returnValue;\n }\n else if (operation.op === 'replace') {\n returnValue.newDocument = operation.value;\n returnValue.removed = document; //document we removed\n return returnValue;\n }\n else if (operation.op === 'move' || operation.op === 'copy') { // it's a move or copy to root\n returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field\n if (operation.op === 'move') { // report removed item\n returnValue.removed = document;\n }\n return returnValue;\n }\n else if (operation.op === 'test') {\n returnValue.test = _areEquals(document, operation.value);\n if (returnValue.test === false) {\n throw new JsonPatchError(\"Test operation failed\", 'TEST_OPERATION_FAILED', index, operation, document);\n }\n returnValue.newDocument = document;\n return returnValue;\n }\n else if (operation.op === 'remove') { // a remove on root\n returnValue.removed = document;\n returnValue.newDocument = null;\n return returnValue;\n }\n else if (operation.op === '_get') {\n operation.value = document;\n return returnValue;\n }\n else { /* bad operation */\n if (validateOperation) {\n throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document);\n }\n else {\n return returnValue;\n }\n }\n } /* END ROOT OPERATIONS */\n else {\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n var path = operation.path || \"\";\n var keys = path.split('/');\n var obj = document;\n var t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift\n var len = keys.length;\n var existingPathFragment = undefined;\n var key = void 0;\n var validateFunction = void 0;\n if (typeof validateOperation == 'function') {\n validateFunction = validateOperation;\n }\n else {\n validateFunction = validator;\n }\n while (true) {\n key = keys[t];\n if (key && key.indexOf('~') != -1) {\n key = unescapePathComponent(key);\n }\n if (banPrototypeModifications &&\n (key == '__proto__' ||\n (key == 'prototype' && t > 0 && keys[t - 1] == 'constructor'))) {\n throw new TypeError('JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README');\n }\n if (validateOperation) {\n if (existingPathFragment === undefined) {\n if (obj[key] === undefined) {\n existingPathFragment = keys.slice(0, t).join('/');\n }\n else if (t == len - 1) {\n existingPathFragment = operation.path;\n }\n if (existingPathFragment !== undefined) {\n validateFunction(operation, 0, document, existingPathFragment);\n }\n }\n }\n t++;\n if (Array.isArray(obj)) {\n if (key === '-') {\n key = obj.length;\n }\n else {\n if (validateOperation && !isInteger(key)) {\n throw new JsonPatchError(\"Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index\", \"OPERATION_PATH_ILLEGAL_ARRAY_INDEX\", index, operation, document);\n } // only parse key when it's an integer for `arr.prop` to work\n else if (isInteger(key)) {\n key = ~~key;\n }\n }\n if (t >= len) {\n if (validateOperation && operation.op === \"add\" && key > obj.length) {\n throw new JsonPatchError(\"The specified index MUST NOT be greater than the number of elements in the array\", \"OPERATION_VALUE_OUT_OF_BOUNDS\", index, operation, document);\n }\n var returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\"Test operation failed\", 'TEST_OPERATION_FAILED', index, operation, document);\n }\n return returnValue;\n }\n }\n else {\n if (t >= len) {\n var returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\"Test operation failed\", 'TEST_OPERATION_FAILED', index, operation, document);\n }\n return returnValue;\n }\n }\n obj = obj[key];\n // If we have more keys in the path, but the next value isn't a non-null object,\n // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again.\n if (validateOperation && t < len && (!obj || typeof obj !== \"object\")) {\n throw new JsonPatchError('Cannot perform operation at the desired path', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document);\n }\n }\n }\n}\n/**\n * Apply a full JSON Patch array on a JSON document.\n * Returns the {newDocument, result} of the patch.\n * It modifies the `document` object and `patch` - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.\n *\n * @param document The document to patch\n * @param patch The patch to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return An array of `{newDocument, result}` after the patch\n */\nexport function applyPatch(document, patch, validateOperation, mutateDocument, banPrototypeModifications) {\n if (mutateDocument === void 0) { mutateDocument = true; }\n if (banPrototypeModifications === void 0) { banPrototypeModifications = true; }\n if (validateOperation) {\n if (!Array.isArray(patch)) {\n throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');\n }\n }\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n var results = new Array(patch.length);\n for (var i = 0, length_1 = patch.length; i < length_1; i++) {\n // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true`\n results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i);\n document = results[i].newDocument; // in case root was replaced\n }\n results.newDocument = document;\n return results;\n}\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the updated document.\n * Suitable as a reducer.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @return The updated document\n */\nexport function applyReducer(document, operation, index) {\n var operationResult = applyOperation(document, operation);\n if (operationResult.test === false) { // failed test\n throw new JsonPatchError(\"Test operation failed\", 'TEST_OPERATION_FAILED', index, operation, document);\n }\n return operationResult.newDocument;\n}\n/**\n * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.\n * @param {object} operation - operation object (patch)\n * @param {number} index - index of operation in the sequence\n * @param {object} [document] - object where the operation is supposed to be applied\n * @param {string} [existingPathFragment] - comes along with `document`\n */\nexport function validator(operation, index, document, existingPathFragment) {\n if (typeof operation !== 'object' || operation === null || Array.isArray(operation)) {\n throw new JsonPatchError('Operation is not an object', 'OPERATION_NOT_AN_OBJECT', index, operation, document);\n }\n else if (!objOps[operation.op]) {\n throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document);\n }\n else if (typeof operation.path !== 'string') {\n throw new JsonPatchError('Operation `path` property is not a string', 'OPERATION_PATH_INVALID', index, operation, document);\n }\n else if (operation.path.indexOf('/') !== 0 && operation.path.length > 0) {\n // paths that aren't empty string should start with \"/\"\n throw new JsonPatchError('Operation `path` property must start with \"/\"', 'OPERATION_PATH_INVALID', index, operation, document);\n }\n else if ((operation.op === 'move' || operation.op === 'copy') && typeof operation.from !== 'string') {\n throw new JsonPatchError('Operation `from` property is not present (applicable in `move` and `copy` operations)', 'OPERATION_FROM_REQUIRED', index, operation, document);\n }\n else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && operation.value === undefined) {\n throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_REQUIRED', index, operation, document);\n }\n else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && hasUndefined(operation.value)) {\n throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED', index, operation, document);\n }\n else if (document) {\n if (operation.op == \"add\") {\n var pathLen = operation.path.split(\"/\").length;\n var existingPathLen = existingPathFragment.split(\"/\").length;\n if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {\n throw new JsonPatchError('Cannot perform an `add` operation at the desired path', 'OPERATION_PATH_CANNOT_ADD', index, operation, document);\n }\n }\n else if (operation.op === 'replace' || operation.op === 'remove' || operation.op === '_get') {\n if (operation.path !== existingPathFragment) {\n throw new JsonPatchError('Cannot perform the operation at a path that does not exist', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document);\n }\n }\n else if (operation.op === 'move' || operation.op === 'copy') {\n var existingValue = { op: \"_get\", path: operation.from, value: undefined };\n var error = validate([existingValue], document);\n if (error && error.name === 'OPERATION_PATH_UNRESOLVABLE') {\n throw new JsonPatchError('Cannot perform the operation from a path that does not exist', 'OPERATION_FROM_UNRESOLVABLE', index, operation, document);\n }\n }\n }\n}\n/**\n * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.\n * If error is encountered, returns a JsonPatchError object\n * @param sequence\n * @param document\n * @returns {JsonPatchError|undefined}\n */\nexport function validate(sequence, document, externalValidator) {\n try {\n if (!Array.isArray(sequence)) {\n throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');\n }\n if (document) {\n //clone document and sequence so that we can safely try applying operations\n applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true);\n }\n else {\n externalValidator = externalValidator || validator;\n for (var i = 0; i < sequence.length; i++) {\n externalValidator(sequence[i], i, document, undefined);\n }\n }\n }\n catch (e) {\n if (e instanceof JsonPatchError) {\n return e;\n }\n else {\n throw e;\n }\n }\n}\n// based on https://github.com/epoberezkin/fast-deep-equal\n// MIT License\n// Copyright (c) 2017 Evgeny Poberezkin\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\nexport function _areEquals(a, b) {\n if (a === b)\n return true;\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key;\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length)\n return false;\n for (i = length; i-- !== 0;)\n if (!_areEquals(a[i], b[i]))\n return false;\n return true;\n }\n if (arrA != arrB)\n return false;\n var keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length)\n return false;\n for (i = length; i-- !== 0;)\n if (!b.hasOwnProperty(keys[i]))\n return false;\n for (i = length; i-- !== 0;) {\n key = keys[i];\n if (!_areEquals(a[key], b[key]))\n return false;\n }\n return true;\n }\n return a !== a && b !== b;\n}\n;\n", "/*!\n * https://github.com/Starcounter-Jack/JSON-Patch\n * (c) 2017-2022 Joachim Wester\n * MIT licensed\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\nexport function hasOwnProperty(obj, key) {\n return _hasOwnProperty.call(obj, key);\n}\nexport function _objectKeys(obj) {\n if (Array.isArray(obj)) {\n var keys_1 = new Array(obj.length);\n for (var k = 0; k < keys_1.length; k++) {\n keys_1[k] = \"\" + k;\n }\n return keys_1;\n }\n if (Object.keys) {\n return Object.keys(obj);\n }\n var keys = [];\n for (var i in obj) {\n if (hasOwnProperty(obj, i)) {\n keys.push(i);\n }\n }\n return keys;\n}\n;\n/**\n* Deeply clone the object.\n* https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy)\n* @param {any} obj value to clone\n* @return {any} cloned obj\n*/\nexport function _deepClone(obj) {\n switch (typeof obj) {\n case \"object\":\n return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5\n case \"undefined\":\n return null; //this is how JSON.stringify behaves for array items\n default:\n return obj; //no need to clone primitives\n }\n}\n//3x faster than cached /^\\d+$/.test(str)\nexport function isInteger(str) {\n var i = 0;\n var len = str.length;\n var charCode;\n while (i < len) {\n charCode = str.charCodeAt(i);\n if (charCode >= 48 && charCode <= 57) {\n i++;\n continue;\n }\n return false;\n }\n return true;\n}\n/**\n* Escapes a json pointer path\n* @param path The raw pointer\n* @return the Escaped path\n*/\nexport function escapePathComponent(path) {\n if (path.indexOf('/') === -1 && path.indexOf('~') === -1)\n return path;\n return path.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n/**\n * Unescapes a json pointer path\n * @param path The escaped pointer\n * @return The unescaped path\n */\nexport function unescapePathComponent(path) {\n return path.replace(/~1/g, '/').replace(/~0/g, '~');\n}\nexport function _getPathRecursive(root, obj) {\n var found;\n for (var key in root) {\n if (hasOwnProperty(root, key)) {\n if (root[key] === obj) {\n return escapePathComponent(key) + '/';\n }\n else if (typeof root[key] === 'object') {\n found = _getPathRecursive(root[key], obj);\n if (found != '') {\n return escapePathComponent(key) + '/' + found;\n }\n }\n }\n }\n return '';\n}\nexport function getPath(root, obj) {\n if (root === obj) {\n return '/';\n }\n var path = _getPathRecursive(root, obj);\n if (path === '') {\n throw new Error(\"Object not found in root\");\n }\n return \"/\" + path;\n}\n/**\n* Recursively checks whether an object has any undefined values inside.\n*/\nexport function hasUndefined(obj) {\n if (obj === undefined) {\n return true;\n }\n if (obj) {\n if (Array.isArray(obj)) {\n for (var i_1 = 0, len = obj.length; i_1 < len; i_1++) {\n if (hasUndefined(obj[i_1])) {\n return true;\n }\n }\n }\n else if (typeof obj === \"object\") {\n var objKeys = _objectKeys(obj);\n var objKeysLength = objKeys.length;\n for (var i = 0; i < objKeysLength; i++) {\n if (hasUndefined(obj[objKeys[i]])) {\n return true;\n }\n }\n }\n }\n return false;\n}\nfunction patchErrorMessageFormatter(message, args) {\n var messageParts = [message];\n for (var key in args) {\n var value = typeof args[key] === 'object' ? JSON.stringify(args[key], null, 2) : args[key]; // pretty print\n if (typeof value !== 'undefined') {\n messageParts.push(key + \": \" + value);\n }\n }\n return messageParts.join('\\n');\n}\nvar PatchError = /** @class */ (function (_super) {\n __extends(PatchError, _super);\n function PatchError(message, name, index, operation, tree) {\n var _newTarget = this.constructor;\n var _this = _super.call(this, patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree })) || this;\n _this.name = name;\n _this.index = index;\n _this.operation = operation;\n _this.tree = tree;\n Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359\n _this.message = patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree });\n return _this;\n }\n return PatchError;\n}(Error));\nexport { PatchError };\n", "/*!\n * https://github.com/Starcounter-Jack/JSON-Patch\n * (c) 2017-2021 Joachim Wester\n * MIT license\n */\nimport { _deepClone, _objectKeys, escapePathComponent, hasOwnProperty } from './helpers.mjs';\nimport { applyPatch } from './core.mjs';\nvar beforeDict = new WeakMap();\nvar Mirror = /** @class */ (function () {\n function Mirror(obj) {\n this.observers = new Map();\n this.obj = obj;\n }\n return Mirror;\n}());\nvar ObserverInfo = /** @class */ (function () {\n function ObserverInfo(callback, observer) {\n this.callback = callback;\n this.observer = observer;\n }\n return ObserverInfo;\n}());\nfunction getMirror(obj) {\n return beforeDict.get(obj);\n}\nfunction getObserverFromMirror(mirror, callback) {\n return mirror.observers.get(callback);\n}\nfunction removeObserverFromMirror(mirror, observer) {\n mirror.observers.delete(observer.callback);\n}\n/**\n * Detach an observer from an object\n */\nexport function unobserve(root, observer) {\n observer.unobserve();\n}\n/**\n * Observes changes made to an object, which can then be retrieved using generate\n */\nexport function observe(obj, callback) {\n var patches = [];\n var observer;\n var mirror = getMirror(obj);\n if (!mirror) {\n mirror = new Mirror(obj);\n beforeDict.set(obj, mirror);\n }\n else {\n var observerInfo = getObserverFromMirror(mirror, callback);\n observer = observerInfo && observerInfo.observer;\n }\n if (observer) {\n return observer;\n }\n observer = {};\n mirror.value = _deepClone(obj);\n if (callback) {\n observer.callback = callback;\n observer.next = null;\n var dirtyCheck = function () {\n generate(observer);\n };\n var fastCheck = function () {\n clearTimeout(observer.next);\n observer.next = setTimeout(dirtyCheck);\n };\n if (typeof window !== 'undefined') { //not Node\n window.addEventListener('mouseup', fastCheck);\n window.addEventListener('keyup', fastCheck);\n window.addEventListener('mousedown', fastCheck);\n window.addEventListener('keydown', fastCheck);\n window.addEventListener('change', fastCheck);\n }\n }\n observer.patches = patches;\n observer.object = obj;\n observer.unobserve = function () {\n generate(observer);\n clearTimeout(observer.next);\n removeObserverFromMirror(mirror, observer);\n if (typeof window !== 'undefined') {\n window.removeEventListener('mouseup', fastCheck);\n window.removeEventListener('keyup', fastCheck);\n window.removeEventListener('mousedown', fastCheck);\n window.removeEventListener('keydown', fastCheck);\n window.removeEventListener('change', fastCheck);\n }\n };\n mirror.observers.set(callback, new ObserverInfo(callback, observer));\n return observer;\n}\n/**\n * Generate an array of patches from an observer\n */\nexport function generate(observer, invertible) {\n if (invertible === void 0) { invertible = false; }\n var mirror = beforeDict.get(observer.object);\n _generate(mirror.value, observer.object, observer.patches, \"\", invertible);\n if (observer.patches.length) {\n applyPatch(mirror.value, observer.patches);\n }\n var temp = observer.patches;\n if (temp.length > 0) {\n observer.patches = [];\n if (observer.callback) {\n observer.callback(temp);\n }\n }\n return temp;\n}\n// Dirty check if obj is different from mirror, generate patches and update mirror\nfunction _generate(mirror, obj, patches, path, invertible) {\n if (obj === mirror) {\n return;\n }\n if (typeof obj.toJSON === \"function\") {\n obj = obj.toJSON();\n }\n var newKeys = _objectKeys(obj);\n var oldKeys = _objectKeys(mirror);\n var changed = false;\n var deleted = false;\n //if ever \"move\" operation is implemented here, make sure this test runs OK: \"should not generate the same patch twice (move)\"\n for (var t = oldKeys.length - 1; t >= 0; t--) {\n var key = oldKeys[t];\n var oldVal = mirror[key];\n if (hasOwnProperty(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) {\n var newVal = obj[key];\n if (typeof oldVal == \"object\" && oldVal != null && typeof newVal == \"object\" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) {\n _generate(oldVal, newVal, patches, path + \"/\" + escapePathComponent(key), invertible);\n }\n else {\n if (oldVal !== newVal) {\n changed = true;\n if (invertible) {\n patches.push({ op: \"test\", path: path + \"/\" + escapePathComponent(key), value: _deepClone(oldVal) });\n }\n patches.push({ op: \"replace\", path: path + \"/\" + escapePathComponent(key), value: _deepClone(newVal) });\n }\n }\n }\n else if (Array.isArray(mirror) === Array.isArray(obj)) {\n if (invertible) {\n patches.push({ op: \"test\", path: path + \"/\" + escapePathComponent(key), value: _deepClone(oldVal) });\n }\n patches.push({ op: \"remove\", path: path + \"/\" + escapePathComponent(key) });\n deleted = true; // property has been deleted\n }\n else {\n if (invertible) {\n patches.push({ op: \"test\", path: path, value: mirror });\n }\n patches.push({ op: \"replace\", path: path, value: obj });\n changed = true;\n }\n }\n if (!deleted && newKeys.length == oldKeys.length) {\n return;\n }\n for (var t = 0; t < newKeys.length; t++) {\n var key = newKeys[t];\n if (!hasOwnProperty(mirror, key) && obj[key] !== undefined) {\n patches.push({ op: \"add\", path: path + \"/\" + escapePathComponent(key), value: _deepClone(obj[key]) });\n }\n }\n}\n/**\n * Create an array of patches from the differences in two objects\n */\nexport function compare(tree1, tree2, invertible) {\n if (invertible === void 0) { invertible = false; }\n var patches = [];\n _generate(tree1, tree2, patches, '', invertible);\n return patches;\n}\n", "export * from './module/core.mjs';\nexport * from './module/duplex.mjs';\nexport {\n PatchError as JsonPatchError,\n _deepClone as deepClone,\n escapePathComponent,\n unescapePathComponent\n} from './module/helpers.mjs';\n\n\n/**\n * Default export for backwards compat\n */\n\nimport * as core from './module/core.mjs';\nimport * as duplex from './module/duplex.mjs';\nimport {\n PatchError as JsonPatchError,\n _deepClone as deepClone,\n escapePathComponent,\n unescapePathComponent\n} from './module/helpers.mjs';\n\nexport default Object.assign({}, core, duplex, {\n JsonPatchError,\n deepClone,\n escapePathComponent,\n unescapePathComponent\n});", "import type {\n GraffitiLocation,\n GraffitiObject,\n GraffitiObjectBase,\n GraffitiPatch,\n GraffitiSession,\n GraffitiPutObject,\n GraffitiStream,\n ChannelStats,\n} from \"./2-types\";\nimport type { JSONSchema4 } from \"json-schema\";\n\n/**\n * This API describes a small but powerful set of methods that\n * can be used to create many different kinds of social media applications,\n * all of which can interoperate.\n * These methods should satisfy all of an application's needs for\n * the communication, storage, and access management of social data.\n * The rest of the application can be built with standard client-side\n * user interface tools to present and interact with the data \u2014\n * no server code necessary.\n * The Typescript source for this API is available at\n * [graffiti-garden/api](https://github.com/graffiti-garden/api).\n *\n * There are several different implementations of this Graffiti API available,\n * including a [federated implementation](https://github.com/graffiti-garden/implementation-federated),\n * that lets users choose where their data is stored,\n * and a [local implementation](https://github.com/graffiti-garden/implementation-local)\n * that can be used for testing and development. In our design of Graffiti, this API is our\n * primary focus as it is the layer that shapes the experience\n * of developing applications. While different implementations can provide tradeoffs between\n * other important properties (e.g. privacy, security, scalability), those properties\n * are useless if the system as a whole doesn't expose useful functionality to developers.\n *\n * On the other side of the stack, there is [Vue plugin](https://github.com/graffiti-garden/wrapper-vue/)\n * that wraps around this API to provide reactivity. Other high-level libraries\n * will be available in the future.\n *\n * ## Overview\n *\n * Graffiti provides applications with methods to create and store data\n * on behalf of their users using standard CRUD operations:\n * {@link put}, {@link get}, {@link patch}, and {@link delete}.\n * This data can represent both social artifacts (e.g. posts, profiles) and\n * activities (e.g. likes, follows) and is stored as JSON.\n *\n * The social aspect of Graffiti comes from the {@link discover} method\n * which allows applications to find objects that other users made.\n * It is a lot like a traditional query operation, but it only\n * returns objects that have been placed in particular\n * {@link GraffitiObjectBase.channels | `channels`}\n * specified by the discovering application.\n *\n * Graffiti builds on well known concepts and standards wherever possible.\n * JSON Objects can be typed with [JSON Schema](https://json-schema.org/) and patches\n * can be applied with [JSON Patch](https://jsonpatch.com).\n * For interoperability between Graffiti applications, we recommend that\n * objects use established properties from the\n * [Activity Vocabulary](https://www.w3.org/TR/activitystreams-vocabulary/) when available,\n * however it is always possible to create additional properties, contributing\n * to the broader [folksonomy](https://en.wikipedia.org/wiki/Folksonomy).\n *\n * {@link GraffitiObjectBase.channels | `channels`} are one of the major concepts\n * unique to Graffiti along with *interaction relativity*.\n * Channels create boundaries between public spaces and work to prevent\n * [context collapse](https://en.wikipedia.org/wiki/Context_collapse)\n * even in a highly interoperable environment.\n * Interaction relativity means that all interactions between users are\n * actually atomic single-user operations that can be interpreted in different ways,\n * which also supports interoperability and pluralism.\n *\n * ### Channels\n *\n * {@link GraffitiObjectBase.channels | `channels`}\n * are a way for the creators of social data to express the intended audience of their\n * data. When a user creates data using the {@link put} method, they\n * can place their data in one or more channels.\n * Content consumers using the {@link discover} method will only see data\n * contained in one of the channels they specify.\n *\n * While many channels may be public, they partition\n * the public into different \"contexts\", mitigating the\n * phenomenon of [context collapse](https://en.wikipedia.org/wiki/Context_collapse) or the \"flattening of multiple audiences.\"\n * Any [URI](https://en.wikipedia.org/wiki/Uniform_Resource_Identifier) can be used as a channel, and so channels can represent people,\n * comment threads, topics, places (real or virtual), pieces of media, and more.\n *\n * For example, consider a comment on a post. If we place that comment in the channel\n * represented by the post's URI, then only people viewing the post will know to\n * look in that channel, giving it visibility akin to a comment on a blog post\n * or comment on Instagram ([since 2019](https://www.buzzfeednews.com/article/katienotopoulos/instagrams-following-activity-tab-is-going-away)).\n * If we also place the comment in the channel represented by the commenter's URI (their\n * {@link GraffitiObjectBase.actor | `actor` URI}), then people viewing the commenter's profile\n * will also see the comment, giving it more visibility, like a reply on Twitter.\n * If we *only* place the comment in the channel represented by the commenter's URI, then\n * it becomes like a quote tweet ([prior to 2020](https://x.com/Support/status/1300555325750292480)),\n * where the comment is only visible to the commenter's followers but not the audience\n * of the original post.\n *\n * The channel model differs from other models of communication such as the\n * [actor model](https://www.w3.org/TR/activitypub/#Overview) used by ActivityPub,\n * the protocol underlying Mastodon, or the [firehose model](https://bsky.social/about/blog/5-5-2023-federation-architecture)\n * used by the AT Protocol, the protocol underlying BlueSky.\n * The actor model is a fusion of direct messaging (like Email) and broadcasting\n * (like RSS) and works well for follow-based communication but struggles\n * to pass information via other rendez-vous.\n * In the actor model, even something as simple as comments can be\n * [very tricky and require server \"side effects\"](https://seb.jambor.dev/posts/understanding-activitypub-part-3-the-state-of-mastodon/).\n * The firehose model dumps all user data into one public database,\n * which doesn't allow for the carving out of different contexts that we did in our comment\n * example above. In the firehose model a comment will always be visible to *both* the original post's audience and\n * the commenter's followers.\n *\n * In some sense, channels provide a sort of \"social access control\" by forming\n * expectations about the audiences of different online spaces.\n * As a real world analogy, oftentimes support groups, such as alcoholics\n * anonymous, are open to the public but people in those spaces feel comfortable sharing intimate details\n * because they have expectations about the other people attending.\n * If someone malicious went to support groups just to spread people's secrets,\n * they would be shamed for violating these norms.\n * Similarly, in Graffiti, while you could spider public channels like a search engine\n * to find content about a person, revealing that you've done such a thing\n * would be shameful.\n *\n * Still, social access control is not perfect and so in situations where privacy is important,\n * objects can also be given\n * an {@link GraffitiObjectBase.allowed | `allowed`} list.\n * For example, to send someone a direct message you should put an object representing\n * that message in the channel that represents them (their {@link GraffitiObjectBase.actor | `actor` URI}),\n * so they can find it, *and* set the `allowed` field to only include the recipient,\n * so only they can read it.\n *\n * ### Interaction relativity\n *\n * Interaction relativity posits that \"interaction between two individuals only\n * exists relative to an observer,\" or equivalently, all interaction is [reified](https://en.wikipedia.org/wiki/Reification_(computer_science)).\n * For example, if one user creates a post and another user wants to \"like\" that post,\n * their like is not modifying the original post, it is simply another data object that points\n * to the post being liked, via its {@link locationToUri | URI}.\n *\n * ```json\n * {\n * activity: 'like',\n * target: 'uri-of-the-post-i-like',\n * actor: 'my-user-id'\n * }\n * ```\n *\n * In Graffiti, all interactions including *moderation* and *collaboration* are relative.\n * This means that applications can freely choose which interactions\n * they want to express to their users and how.\n * For example, one application could have a single fixed moderator,\n * another could allow users to choose which moderators they would like filter their content\n * like [Bluesky's stackable moderation](https://bsky.social/about/blog/03-12-2024-stackable-moderation),\n * and another could implement a fully democratic system like [PolicyKit](https://policykit.org/).\n * Each of these applications is one interpretation of the underlying refieid user interactions and\n * users can freely switch between them.\n *\n * Interaction relativy also allows applications to introduce new sorts of interactions\n * without having to coordinate with all the other existing applications,\n * keeping the ecosystem flexible and interoperable.\n * For example, an application could [add a \"Trust\" button to posts](https://social.cs.washington.edu/pub_details.html?id=trustnet)\n * and use it assess the truthfulness of posts made on applications across Graffiti.\n * New sorts of interactions like these can be smoothly absorbed by the broader ecosystem\n * as a [folksonomy](https://en.wikipedia.org/wiki/Folksonomy).\n *\n * Interactivy relativity is realized in Graffiti through two design decisions:\n * 1. The creators of objects can only modify their own objects. It is important for\n * users to be able to change and delete their own content to respect their\n * [right to be forgotten](https://en.wikipedia.org/wiki/Right_to_be_forgotten),\n * but beyond self-correction and self-censorship all other interaction is reified.\n * Many interactions can be reified via pointers, as in the \"like\" example above, and collaborative\n * edits can be refieid via [CRDTs](https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type).\n * 2. No one owns channels. Unlike IRC/Slack channels or [Matrix rooms](https://matrix.org/docs/matrix-concepts/rooms_and_events/),\n * anyone can post to any channel, so long as they know the URI of that channel.\n * It is up to applications to hide content from channels either according to manual\n * filters or in response to user action.\n * For example, a user may create a post with the flag `disableReplies`.\n * Applications could then filter out any content from the replies channel\n * that the original poster has not specifically approved.\n *\n * ## Implementing the API\n *\n * To implement the API, first install it:\n *\n * ```bash\n * npm install @graffiti-garden/api\n * ```\n *\n * Then create a class that extends the `Graffiti` class and implement the abstract methods.\n *\n * ```typescript\n * import { Graffiti } from \"@graffiti-garden/api\";\n *\n * class MyGraffitiImplementation extends Graffiti {\n * // Implement the abstract methods here\n * }\n * ```\n * ### Testing\n *\n * We have written a number of unit tests written with [vitest](https://vitest.dev/)\n * that can be used to verify implementations of the API.\n * To use them, create a test file in that ends in `*.spec.ts` and format it as follows:\n *\n * ```typescript\n * import { graffitiCRUDTests } from \"@graffiti-garden/api/tests\";\n *\n * const useGraffiti = () => new MyGraffitiImplementation();\n * // Fill in with implementation-specific information\n * // to provide to valid actor sessions for the tests\n * // to use as identities.\n * const useSession1 = () => ({ actor: \"someone\" });\n * const useSession2 = () => ({ actor: \"someoneelse\" });\n *\n * // Run the tests\n * graffitiCRUDTests(useGraffiti, useSession1, useSession2);\n * ```\n *\n * Then run the tests in the root of your directory with:\n *\n * ```bash\n * npx vitest\n * ```\n *\n * ## Building the Documentation\n *\n * To build the [TypeDoc](https://typedoc.org/) documentation, run the following commands:\n *\n * ```bash\n * npm run install\n * npm run docs\n * ```\n *\n * Then run a local server to view the documentation:\n *\n * ```bash\n * cd docs\n * npx http-server\n * ```\n *\n * ## TODO\n *\n * - Implement scope.\n *\n * @groupDescription CRUD Methods\n * Methods for {@link put | creating}, {@link get | reading}, {@link patch | updating},\n * and {@link delete | deleting} {@link GraffitiObjectBase | Graffiti objects}.\n * @groupDescription Query Methods\n * Methods that retrieve or accumulate information about multiple {@link GraffitiObjectBase | Graffiti objects} at a time.\n * @groupDescription Session Management\n * Methods and properties for logging in and out of a Graffiti implementation.\n * @groupDescription Utilities\n * Methods for for converting Graffiti objects to and from URIs.\n */\nexport abstract class Graffiti {\n /**\n * Converts a {@link GraffitiLocation} object containing a\n * {@link GraffitiObjectBase.name | `name`}, {@link GraffitiObjectBase.actor | `actor`},\n * and {@link GraffitiObjectBase.source | `source`} into a globally unique URI.\n * The form of this URI is implementation dependent.\n *\n * Its exact inverse is {@link uriToLocation}.\n *\n * @group Utilities\n */\n abstract locationToUri(location: GraffitiLocation): string;\n\n /**\n * Parses a globally unique Graffiti URI into a {@link GraffitiLocation}\n * object containing a {@link GraffitiObjectBase.name | `name`},\n * {@link GraffitiObjectBase.actor | `actor`}, and {@link GraffitiObjectBase.source | `source`}.\n *\n * Its exact inverse is {@link locationToUri}.\n *\n * @group Utilities\n */\n abstract uriToLocation(uri: string): GraffitiLocation;\n\n /**\n * An alias of {@link locationToUri}\n *\n * @group Utilities\n */\n objectToUri(object: GraffitiObjectBase) {\n return this.locationToUri(object);\n }\n\n /**\n * Creates a new {@link GraffitiObjectBase | object} or replaces an existing object.\n * An object can only be replaced by the same {@link GraffitiObjectBase.actor | `actor`}\n * that created it.\n *\n * Replacement occurs when the {@link GraffitiLocation} properties of the supplied object\n * ({@link GraffitiObjectBase.name | `name`}, {@link GraffitiObjectBase.actor | `actor`},\n * and {@link GraffitiObjectBase.source | `source`}) exactly match the location of an existing object.\n *\n * @returns The object that was replaced if one exists or an object with\n * with a `null` {@link GraffitiObjectBase.value | `value`} if this method\n * created a new object.\n * The object will have a {@link GraffitiObjectBase.tombstone | `tombstone`}\n * field set to `true` and a {@link GraffitiObjectBase.lastModified | `lastModified`}\n * field updated to the time of replacement/creation.\n *\n * @group CRUD Methods\n */\n abstract put<Schema>(\n /**\n * The object to be put. This object is statically type-checked against the [JSON schema](https://json-schema.org/) that can be optionally provided\n * as the generic type parameter. We highly recommend providing a schema to\n * ensure that the PUT object matches subsequent {@link get} or {@link discover}\n * methods.\n */\n object: GraffitiPutObject<Schema>,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}.\n */\n session: GraffitiSession,\n ): Promise<GraffitiObjectBase>;\n\n /**\n * Retrieves an object from a given location.\n *\n * The retrieved object is type-checked against the provided [JSON schema](https://json-schema.org/)\n * otherwise a {@link GraffitiErrorSchemaMismatch} is thrown.\n *\n * If the object existed but has since been deleted,\n * or the retrieving {@link GraffitiObjectBase.actor | `actor`}\n * was {@link GraffitiObjectBase.allowed | `allowed`} to access\n * the object but now isn't, this method will return the latest\n * version of the object that the {@link GraffitiObjectBase.actor | `actor`}\n * was allowed to access with its {@link GraffitiObjectBase.tombstone | `tombstone`}\n * set to `true`, so long as that version is still cached.\n *\n * Otherwise, if the object never existed, or the\n * retrieving {@link GraffitiObjectBase.actor | `actor`} was never\n * {@link GraffitiObjectBase.allowed | `allowed`} to access it, or if\n * the object was changed long enough ago that its history has been\n * purged from the cache, a {@link GraffitiErrorNotFound} is thrown.\n * The rate at which the cache is purged is implementation dependent.\n * See the `tombstoneReturn` property returned by {@link discover}.\n *\n * @group CRUD Methods\n */\n abstract get<Schema extends JSONSchema4>(\n /**\n * The location of the object to get.\n */\n locationOrUri: GraffitiLocation | string,\n /**\n * The JSON schema to validate the retrieved object against.\n */\n schema: Schema,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}. If no `session` is provided,\n * the retrieved object's {@link GraffitiObjectBase.allowed | `allowed`}\n * property must be `undefined`.\n */\n session?: GraffitiSession | null,\n ): Promise<GraffitiObject<Schema>>;\n\n /**\n * Patches an existing object at a given location.\n * The patching {@link GraffitiObjectBase.actor | `actor`} must be the same as the\n * `actor` that created the object.\n *\n * @returns The object that was deleted if one exists or an object with\n * with a `null` {@link GraffitiObjectBase.value | `value`} otherwise.\n * The object will have a {@link GraffitiObjectBase.tombstone | `tombstone`}\n * field set to `true` and a {@link GraffitiObjectBase.lastModified | `lastModified`}\n * field updated to the time of deletion.\n *\n * @group CRUD Methods\n */\n abstract patch(\n /**\n * A collection of [JSON Patch](https://jsonpatch.com) operations\n * to apply to the object. See {@link GraffitiPatch} for more information.\n */\n patch: GraffitiPatch,\n /**\n * The location of the object to patch.\n */\n locationOrUri: GraffitiLocation | string,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}.\n */\n session: GraffitiSession,\n ): Promise<GraffitiObjectBase>;\n\n /**\n * Deletes an object from a given location.\n * The deleting {@link GraffitiObjectBase.actor | `actor`} must be the same as the\n * `actor` that created the object.\n *\n * If the object does not exist or has already been deleted,\n * {@link GraffitiErrorNotFound} is thrown.\n *\n * @returns The object that was deleted if one exists or an object with\n * with a `null` {@link GraffitiObjectBase.value | `value`} otherwise.\n * The object will have a {@link GraffitiObjectBase.tombstone | `tombstone`}\n * field set to `true` and a {@link GraffitiObjectBase.lastModified | `lastModified`}\n * field updated to the time of deletion.\n *\n * @group CRUD Methods\n */\n abstract delete(\n /**\n * The location of the object to delete.\n */\n locationOrUri: GraffitiLocation | string,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}.\n */\n session: GraffitiSession,\n ): Promise<GraffitiObjectBase>;\n\n /**\n * Discovers objects created by any user that are contained\n * in at least one of the given {@link GraffitiObjectBase.channels | `channels`}\n * and match the given [JSON Schema](https://json-schema.org).\n *\n * Objects are returned asynchronously as they are discovered but the stream\n * will end once all leads have been exhausted.\n * The method must be polled again for new objects.\n *\n * `discover` will not return objects that the {@link GraffitiObjectBase.actor | `actor`}\n * is not {@link GraffitiObjectBase.allowed | `allowed`} to access.\n * If the actor is not the creator of a discovered object,\n * the allowed list will be masked to only contain the querying actor if the\n * allowed list is not `undefined` (public). Additionally, if the actor is not the\n * creator of a discovered object, any {@link GraffitiObjectBase.channels | `channels`}\n * not specified by the `discover` method will not be revealed. This masking happens\n * before the supplied schema is applied.\n *\n * {@link discover} can be used in conjunction with {@link synchronizeDiscover}\n * to provide a responsive and consistent user experience.\n *\n * Since different implementations may fetch data from multiple sources there is\n * no guarentee on the order that objects are returned in. Additionally, the method\n * will return objects that have been deleted but with a\n * {@link GraffitiObjectBase.tombstone | `tombstone`} field set to `true` for\n * cache invalidation purposes.\n * The final `return()` value of the stream includes a `tombstoneRetention`\n * property that represents the minimum amount of time,\n * in milliseconds, that an application will retain and return tombstones for objects that\n * have been deleted.\n *\n * When repolling, the {@link GraffitiObjectBase.lastModified | `lastModified`}\n * field can be queried via the schema to\n * only fetch objects that have been modified since the last poll.\n * Such queries should only be done if the time since the last poll\n * is less than the `tombstoneRetention` value of that poll, otherwise the tombstones\n * for objects that have been deleted may not be returned.\n *\n * ```json\n * {\n * \"properties\": {\n * \"lastModified\": {\n * \"minimum\": LAST_RETRIEVED_TIME\n * }\n * }\n * }\n * ```\n *\n * `discover` needs to be polled for new data because live updates to\n * an application can be visually distracting or lead to toxic engagement.\n * If and when an application wants real-time updates, such as in a chat\n * application, application authors must be intentional about their polling.\n *\n * Implementers should be aware that some users may applications may try to poll\n * {@link discover} repetitively. You can deal with this by rate limiting or\n * preemptively fetching data via a bidirectional channel, like a WebSocket.\n * Additionally, implementers should probably index the `lastModified` field\n * to speed up responses to schemas like the one above.\n *\n * @returns A stream of objects that match the given {@link GraffitiObjectBase.channels | `channels`}\n * and [JSON Schema](https://json-schema.org).\n *\n * @group Query Methods\n */\n abstract discover<Schema extends JSONSchema4>(\n /**\n * The {@link GraffitiObjectBase.channels | `channels`} that objects must be associated with.\n */\n channels: string[],\n /**\n * A [JSON Schema](https://json-schema.org) that objects must satisfy.\n */\n schema: Schema,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}. If no `session` is provided,\n * only objects that have no {@link GraffitiObjectBase.allowed | `allowed`}\n * property will be returned.\n */\n session?: GraffitiSession | null,\n ): GraffitiStream<\n GraffitiObject<Schema>,\n {\n tombstoneRetention: number;\n }\n >;\n\n /**\n * Discovers objects **not** contained in any\n * {@link GraffitiObjectBase.channels | `channels`}\n * that were created by the querying {@link GraffitiObjectBase.actor | `actor`}\n * and match the given [JSON Schema](https://json-schema.org).\n * Unlike {@link discover}, this method will not return objects created by other users.\n *\n * This method is not useful for most applications, but necessary for\n * getting a global view of all a user's Graffiti data or debugging\n * channel usage.\n *\n * It's return value is the same as {@link discover}.\n *\n * @group Query Methods\n */\n abstract recoverOrphans<Schema extends JSONSchema4>(\n /**\n * A [JSON Schema](https://json-schema.org) that orphaned objects must satisfy.\n */\n schema: Schema,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}.\n */\n session: GraffitiSession,\n ): GraffitiStream<\n GraffitiObject<Schema>,\n {\n tombstoneRetention: number;\n }\n >;\n\n /**\n * Returns statistics about all the {@link GraffitiObjectBase.channels | `channels`}\n * that an {@link GraffitiObjectBase.actor | `actor`} has posted to.\n * This is not very useful for most applications, but\n * necessary for certain applications where a user wants a\n * global view of all their Graffiti data or to debug\n * channel usage.\n *\n * @group Query Methods\n *\n * @returns A stream of statistics for each {@link GraffitiObjectBase.channels | `channel`}\n * that the {@link GraffitiObjectBase.actor | `actor`} has posted to.\n */\n abstract channelStats(\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}.\n */\n session: GraffitiSession,\n ): GraffitiStream<ChannelStats>;\n\n /**\n * Begins the login process. Depending on the implementation, this may\n * involve redirecting the user to a login page or opening a popup,\n * so it should always be called in response to a user action.\n *\n * The {@link GraffitiSession | session} object is returned\n * asynchronously via {@link Graffiti.sessionEvents | sessionEvents}\n * as a {@link GraffitiLoginEvent} with event type `login`.\n *\n * @group Session Management\n */\n abstract login(\n /**\n * Suggestions for the permissions that the\n * login process should grant. The login process may not\n * provide the exact proposed permissions.\n */\n proposal?: {\n /**\n * A suggested actor to login as. For example, if a user tries to\n * edit a post but are not logged in, the interface can infer that\n * they might want to log in as the actor who created the post\n * they are attempting to edit.\n *\n * Even if provided, the implementation should allow the user\n * to log in as a different actor if they choose.\n */\n actor?: string;\n /**\n * A yet to be defined permissions scope. An application may use\n * this to indicate the minimum necessary scope needed to\n * operate. For example, it may need to be able read private\n * messages from a certain set of channels, or write messages that\n * follow a particular schema.\n *\n * The login process should make it clear what scope an application\n * is requesting and allow the user to enhance or reduce that\n * scope as necessary.\n */\n scope?: {};\n },\n ): Promise<void>;\n\n /**\n * Begins the logout process. Depending on the implementation, this may\n * involve redirecting the user to a logout page or opening a popup,\n * so it should always be called in response to a user action.\n *\n * A confirmation will be returned asynchronously via\n * {@link Graffiti.sessionEvents | sessionEvents}\n * as a {@link GraffitiLogoutEvent} as event type `logout`.\n *\n * @group Session Management\n */\n abstract logout(\n /**\n * The {@link GraffitiSession | session} object to logout.\n */\n session: GraffitiSession,\n ): Promise<void>;\n\n /**\n * An event target that can be used to listen for the following\n * events and they're corresponding event types:\n * - `login` - {@link GraffitiLoginEvent}\n * - `logout` - {@link GraffitiLogoutEvent}\n * - `initialized` - {@link GraffitiSessionInitializedEvent}\n *\n * @group Session Management\n */\n abstract readonly sessionEvents: EventTarget;\n\n /**\n * This method has the same signature as {@link discover} but listens for\n * changes made via {@link put}, {@link patch}, and {@link delete} or\n * fetched from {@link get}, {@link discover}, and {@link recoverOrphans}\n * and then streams appropriate changes to provide a responsive and\n * consistent user experience.\n *\n * Unlike {@link discover}, this method continuously listens for changes\n * and will not terminate unless the user calls the `return` method on the iterator\n * or `break`s out of the loop.\n *\n * Example 1: Suppose a user publishes a post using {@link put}. If the feed\n * displaying that user's posts is using {@link synchronizeDiscover} to listen for changes,\n * then the user's new post will instantly appear in their feed, giving the UI a\n * responsive feel.\n *\n * Example 2: Suppose one of a user's friends changes their name. As soon as the\n * user's application receives one notice of that change (using {@link get}\n * or {@link discover}), then {@link synchronizeDiscover} listeners can be used to update\n * all instance's of that friend's name in the user's application instantly,\n * providing a consistent user experience.\n *\n * @group Synchronize Methods\n */\n abstract synchronizeDiscover<Schema extends JSONSchema4>(\n /**\n * The {@link GraffitiObjectBase.channels | `channels`} that the objects must be associated with.\n */\n channels: string[],\n /**\n * A [JSON Schema](https://json-schema.org) that objects must satisfy.\n */\n schema: Schema,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}. If no `session` is provided,\n * only objects that have no {@link GraffitiObjectBase.allowed | `allowed`}\n * property will be returned.\n */\n session?: GraffitiSession | null,\n ): GraffitiStream<GraffitiObject<Schema>>;\n\n /**\n * This method has the same signature as {@link get} but, like {@link synchronizeDiscover},\n * it listens for changes made via {@link put}, {@link patch}, and {@link delete} or\n * fetched from {@link get}, {@link discover}, and {@link recoverOrphans} and then\n * streams appropriate changes to provide a responsive and consistent user experience.\n *\n * Unlike {@link get}, which returns a single result, this method continuously\n * listens for changes which are output as an asynchronous {@link GraffitiStream}.\n *\n * @group Synchronize Methods\n */\n abstract synchronizeGet<Schema extends JSONSchema4>(\n /**\n * The location of the object to get.\n */\n locationOrUri: GraffitiLocation | string,\n /**\n * The JSON schema to validate the retrieved object against.\n */\n schema: Schema,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}. If no `session` is provided,\n * the retrieved object's {@link GraffitiObjectBase.allowed | `allowed`}\n * property must be `undefined`.\n */\n session?: GraffitiSession | null,\n ): GraffitiStream<GraffitiObject<Schema>>;\n\n /**\n * This method has the same signature as {@link recoverOrphans} but,\n * like {@link synchronizeDiscover}, it listens for changes made via\n * {@link put}, {@link patch}, and {@link delete} or fetched from\n * {@link get}, {@link discover}, and {@link recoverOrphans} and then\n * streams appropriate changes to provide a responsive and consistent user experience.\n *\n * Unlike {@link recoverOrphans}, this method continuously listens for changes\n * and will not terminate unless the user calls the `return` method on the iterator\n * or `break`s out of the loop.\n *\n * @group Synchronize Methods\n */\n abstract synchronizeRecoverOrphans<Schema extends JSONSchema4>(\n /**\n * A [JSON Schema](https://json-schema.org) that orphaned objects must satisfy.\n */\n schema: Schema,\n /**\n * An implementation-specific object with information to authenticate the\n * {@link GraffitiObjectBase.actor | `actor`}.\n */\n session: GraffitiSession,\n ): GraffitiStream<GraffitiObject<Schema>>;\n}\n\n/**\n * This is a factory function that produces an instance of\n * the {@link Graffiti} class. Since the Graffiti class is\n * abstract, factory functions provide an easy way to\n * swap out different implementations.\n */\nexport type GraffitiFactory = () => Graffiti;\n", "export class GraffitiErrorUnauthorized extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorUnauthorized\";\n Object.setPrototypeOf(this, GraffitiErrorUnauthorized.prototype);\n }\n}\n\nexport class GraffitiErrorForbidden extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorForbidden\";\n Object.setPrototypeOf(this, GraffitiErrorForbidden.prototype);\n }\n}\n\nexport class GraffitiErrorNotFound extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorNotFound\";\n Object.setPrototypeOf(this, GraffitiErrorNotFound.prototype);\n }\n}\n\nexport class GraffitiErrorInvalidSchema extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorInvalidSchema\";\n Object.setPrototypeOf(this, GraffitiErrorInvalidSchema.prototype);\n }\n}\n\nexport class GraffitiErrorSchemaMismatch extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorSchemaMismatch\";\n Object.setPrototypeOf(this, GraffitiErrorSchemaMismatch.prototype);\n }\n}\n\nexport class GraffitiErrorPatchTestFailed extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorPatchTestFailed\";\n Object.setPrototypeOf(this, GraffitiErrorPatchTestFailed.prototype);\n }\n}\n\nexport class GraffitiErrorPatchError extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorPatchError\";\n Object.setPrototypeOf(this, GraffitiErrorPatchError.prototype);\n }\n}\n\nexport class GraffitiErrorInvalidUri extends Error {\n constructor(message?: string) {\n super(message);\n this.name = \"GraffitiErrorInvalidUri\";\n Object.setPrototypeOf(this, GraffitiErrorInvalidUri.prototype);\n }\n}\n", "import {\n GraffitiErrorInvalidSchema,\n GraffitiErrorInvalidUri,\n GraffitiErrorPatchError,\n GraffitiErrorPatchTestFailed,\n} from \"@graffiti-garden/api\";\nimport type {\n Graffiti,\n GraffitiObjectBase,\n GraffitiLocation,\n GraffitiPatch,\n JSONSchema4,\n GraffitiSession,\n} from \"@graffiti-garden/api\";\nimport type { Ajv } from \"ajv\";\nimport type { applyPatch } from \"fast-json-patch\";\n\nexport const locationToUri: Graffiti[\"locationToUri\"] = (location) => {\n return `${location.source}/${encodeURIComponent(location.actor)}/${encodeURIComponent(location.name)}`;\n};\n\nexport const uriToLocation: Graffiti[\"uriToLocation\"] = (uri) => {\n const parts = uri.split(\"/\");\n const nameEncoded = parts.pop();\n const webIdEncoded = parts.pop();\n if (!nameEncoded || !webIdEncoded || !parts.length) {\n throw new GraffitiErrorInvalidUri();\n }\n return {\n name: decodeURIComponent(nameEncoded),\n actor: decodeURIComponent(webIdEncoded),\n source: parts.join(\"/\"),\n };\n};\n\nexport function randomBase64(numBytes: number = 16) {\n const bytes = new Uint8Array(numBytes);\n crypto.getRandomValues(bytes);\n // Convert it to base64\n const base64 = btoa(String.fromCodePoint(...bytes));\n // Make sure it is url safe\n return base64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/\\=+$/, \"\");\n}\n\nexport function unpackLocationOrUri(locationOrUri: GraffitiLocation | string) {\n if (typeof locationOrUri === \"string\") {\n return {\n location: uriToLocation(locationOrUri),\n uri: locationOrUri,\n };\n } else {\n return {\n location: {\n name: locationOrUri.name,\n actor: locationOrUri.actor,\n source: locationOrUri.source,\n },\n uri: locationToUri(locationOrUri),\n };\n }\n}\n\nexport function isObjectNewer(\n left: GraffitiObjectBase,\n right: GraffitiObjectBase,\n) {\n return (\n left.lastModified > right.lastModified ||\n (left.lastModified === right.lastModified &&\n !left.tombstone &&\n right.tombstone)\n );\n}\n\nexport function applyGraffitiPatch<Prop extends keyof GraffitiPatch>(\n apply: typeof applyPatch,\n prop: Prop,\n patch: GraffitiPatch,\n object: GraffitiObjectBase,\n): void {\n const ops = patch[prop];\n if (!ops || !ops.length) return;\n try {\n object[prop] = apply(object[prop], ops, true, false).newDocument;\n } catch (e) {\n if (\n typeof e === \"object\" &&\n e &&\n \"name\" in e &&\n typeof e.name === \"string\" &&\n \"message\" in e &&\n typeof e.message === \"string\"\n ) {\n if (e.name === \"TEST_OPERATION_FAILED\") {\n throw new GraffitiErrorPatchTestFailed(e.message);\n } else {\n throw new GraffitiErrorPatchError(e.name + \": \" + e.message);\n }\n } else {\n throw e;\n }\n }\n}\n\nexport function attemptAjvCompile<Schema extends JSONSchema4>(\n ajv: Ajv,\n schema: Schema,\n) {\n try {\n return ajv.compile(schema);\n } catch (error) {\n throw new GraffitiErrorInvalidSchema(\n error instanceof Error ? error.message : undefined,\n );\n }\n}\n\nexport function maskGraffitiObject(\n object: GraffitiObjectBase,\n channels: string[],\n session?: GraffitiSession | null,\n): void {\n if (object.actor !== session?.actor) {\n object.allowed = object.allowed && session ? [session.actor] : undefined;\n object.channels = object.channels.filter((channel) =>\n channels.includes(channel),\n );\n }\n}\nexport function isActorAllowedGraffitiObject(\n object: GraffitiObjectBase,\n session?: GraffitiSession | null,\n) {\n return (\n object.allowed === undefined ||\n object.allowed === null ||\n (!!session?.actor &&\n (object.actor === session.actor ||\n object.allowed.includes(session.actor)))\n );\n}\n"],
|
|
5
|
+
"mappings": "g0BACA,IAAsBA,GAAtB,KAAiC,GAAjCC,EAAA,YAAAD,GAOaC,E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AS,EAEzD,aAAM,KAAK,oBAAoBD,EAAWC,EAAW,EAAI,EAClDD,CACT,EAEA,OAA6B,SAAUP,IAAS,CAC9C,IAAMO,EAAY,MAAM,KAAK,SAAS,OAAO,GAAGP,CAAI,EACpD,aAAM,KAAK,oBAAoBO,EAAW,OAAW,EAAI,EAClDA,CACT,EAEU,aACRQ,EACA,CACA,IAAMC,EAAW,KAAK,oBAAoB,KAAK,IAAI,EAYnD,OAXgB,iBAAmB,CACjC,IAAIC,EAAS,MAAMF,EAAS,KAAK,EACjC,KAAO,CAACE,EAAO,MACRA,EAAO,MAAM,OAChBD,EAASC,EAAO,MAAM,KAAK,EAE7B,MAAMA,EAAO,MACbA,EAAS,MAAMF,EAAS,KAAK,EAE/B,OAAOE,EAAO,KAChB,EACe,CACjB,CAEA,SAAiC,IAAIjB,IAAS,CAC5C,IAAMe,EAAW,KAAK,SAAS,SAAS,GAAGf,CAAI,EAC/C,OAAO,KAAK,aAAae,CAAQ,CACnC,EAEA,eAA6C,IAAIf,IAAS,CACxD,IAAMe,EAAW,KAAK,SAAS,eAAe,GAAGf,CAAI,EACrD,OAAO,KAAK,aAAae,CAAQ,CACnC,CACF",
|
|
6
|
+
"names": ["_CodeOrName", "exports", "Name", "s", "_Code", "code", "item", "_a", "c", "names", "_", "strs", "args", "i", "addCodeArg", "plus", "str", "expr", "safeStringify", "optimize", "arg", "interpolate", "res", "mergeExprItems", "a", "b", "strConcat", "c1", "c2", "x", "stringify", "getProperty", "key", "getEsmExportName", "regexpCode", "rx", "code_1", "ValueError", "name", "UsedValueState", "exports", "Scope", "prefixes", "parent", "nameOrPrefix", "prefix", "ng", "_b", "_a", "ValueScopeName", "nameStr", "value", "property", "itemIndex", "line", "ValueScope", "opts", "valueKey", "vs", "_name", "s", "keyOrRef", "scopeName", "values", "usedValues", "getCode", "valueCode", "code", "nameSet", "c", "def", "code_1", "scope_1", "code_2", "exports", "scope_2", "Node", "_names", "_constants", "Def", "varKind", "name", "rhs", "es5", "_n", "names", "constants", "optimizeExpr", "Assign", "lhs", "sideEffects", "addExprNames", "AssignOp", "op", "Label", "label", "Break", "Throw", "error", "AnyCode", "code", "ParentNode", "nodes", "opts", "i", "n", "subtractNames", "addNames", "BlockNode", "Root", "Else", "If", "_If", "condition", "cond", "e", "ns", "not", "_a", "For", "ForLoop", "iteration", "ForRange", "from", "to", "ForIter", "loop", "iterable", "Func", "args", "async", "Return", "Try", "_b", "Catch", "Finally", "CodeGen", "extScope", "prefix", "prefixOrName", "value", "keyOrRef", "scopeName", "nameOrPrefix", "constant", "_constant", "c", "keyValues", "key", "thenBody", "elseBody", "node", "forBody", "arr", "obj", "tryBody", "catchCode", "finallyCode", "body", "nodeCount", "len", "toClose", "funcBody", "N1", "N2", "expr", "replaceName", "canOptimize", "items", "x", "par", "andCode", "mappend", "and", "orCode", "or", "y", "codegen_1", "code_1", "toHash", "arr", "hash", "item", "exports", "alwaysValidSchema", "it", "schema", "checkUnknownRules", "schemaHasRules", "opts", "self", "rules", "key", "checkStrictMode", "schemaHasRulesButRef", "RULES", "schemaRefOrVal", "topSchemaRef", "schemaPath", "keyword", "$data", "unescapeFragment", "str", "unescapeJsonPointer", "escapeFragment", "escapeJsonPointer", "eachItem", "xs", "f", "x", "makeMergeEvaluated", "mergeNames", "mergeToName", "mergeValues", "resultToName", "gen", "from", "to", "toName", "res", "setEvaluated", "evaluatedPropsToName", "items", "ps", "props", "p", "snippets", "useFunc", "Type", "getErrorPath", "dataProp", "dataPropType", "jsPropertySyntax", "isNumber", "msg", "mode", "codegen_1", "names", "exports", "codegen_1", "util_1", "names_1", "exports", "keyword", "schemaType", "reportError", "cxt", "error", "errorPaths", "overrideAllErrors", "it", "gen", "compositeRule", "allErrors", "errObj", "errorObjectCode", "addError", "returnErrors", "reportExtraError", "resetErrorsCount", "errsCount", "extendErrors", "schemaValue", "data", "err", "i", "errs", "validateName", "schemaEnv", "E", "createErrors", "errorObject", "keyValues", "errorInstancePath", "errorSchemaPath", "extraErrorProps", "errorPath", "instancePath", "instPath", "errSchemaPath", "schemaPath", "parentSchema", "schPath", "params", "message", "opts", "propertyName", "topSchemaRef", "errors_1", "codegen_1", "names_1", "boolError", "topBoolOrEmptySchema", "it", "gen", "schema", "validateName", "falseSchemaError", "exports", "boolOrEmptySchema", "valid", "overrideAllErrors", "data", "cxt", "_jsonTypes", "jsonTypes", "isJSONType", "x", "exports", "getRules", "groups", "schemaHasRulesForType", "schema", "self", "type", "group", "shouldUseGroup", "exports", "rule", "shouldUseRule", "_a", "kwd", "rules_1", "applicability_1", "errors_1", "codegen_1", "util_1", "DataType", "exports", "getSchemaTypes", "schema", "types", "getJSONTypes", "ts", "coerceAndCheckDataType", "it", "gen", "data", "opts", "coerceTo", "coerceToTypes", "checkTypes", "wrongType", "checkDataTypes", "coerceData", "reportTypeError", "COERCIBLE", "coerceTypes", "t", "dataType", "coerced", "coerceSpecificType", "assignParentData", "parentData", "parentDataProperty", "expr", "checkDataType", "strictNums", "correct", "EQ", "cond", "numCond", "_cond", "dataTypes", "notObj", "typeError", "schemaValue", "cxt", "getTypeErrorContext", "schemaCode", "codegen_1", "util_1", "assignDefaults", "it", "ty", "properties", "items", "key", "assignDefault", "sch", "i", "exports", "prop", "defaultValue", "gen", "compositeRule", "data", "opts", "childData", "condition", "codegen_1", "util_1", "names_1", "util_2", "checkReportMissingProp", "cxt", "prop", "gen", "data", "it", "noPropertyInData", "exports", "checkMissingProp", "opts", "properties", "missing", "reportMissingProp", "hasPropFunc", "isOwnProperty", "property", "propertyInData", "ownProperties", "cond", "allSchemaProperties", "schemaMap", "p", "schemaProperties", "callValidateCode", "schemaCode", "topSchemaRef", "schemaPath", "errorPath", "func", "context", "passSchema", "dataAndSchema", "valCxt", "args", "newRegExp", "usePattern", "pattern", "u", "regExp", "rx", "validateArray", "keyword", "valid", "validArr", "validateItems", "notValid", "len", "i", "validateUnion", "schema", "sch", "schValid", "_sch", "schCxt", "codegen_1", "names_1", "code_1", "errors_1", "macroKeywordCode", "cxt", "def", "gen", "keyword", "schema", "parentSchema", "it", "macroSchema", "schemaRef", "useKeyword", "valid", "exports", "funcKeywordCode", "$data", "checkAsyncKeyword", "validate", "validateRef", "validateKeyword", "_a", "assignValid", "modifyData", "reportErrs", "ruleErrs", "validateAsync", "validateSync", "addErrs", "e", "validateErrs", "_await", "passCxt", "passSchema", "errors", "data", "errs", "schemaEnv", "result", "validSchemaType", "schemaType", "allowUndefined", "st", "validateKeywordUsage", "opts", "self", "errSchemaPath", "deps", "kwd", "msg", "codegen_1", "util_1", "getSubschema", "it", "keyword", "schemaProp", "schema", "schemaPath", "errSchemaPath", "topSchemaRef", "sch", "exports", "extendSubschemaData", "subschema", "dataProp", "dpType", "data", "dataTypes", "propertyName", "gen", "errorPath", "dataPathArr", "opts", "nextData", "dataContextProps", "_nextData", "extendSubschemaMode", "jtdDiscriminator", "jtdMetadata", "compositeRule", "createErrors", "allErrors", "require_fast_deep_equal", "__commonJSMin", "exports", "module", "equal", "a", "b", "length", "i", "keys", "key", "require_json_schema_traverse", "__commonJSMin", "exports", "module", "traverse", "schema", "opts", "cb", "pre", "post", "_traverse", "jsonPtr", "rootSchema", "parentJsonPtr", "parentKeyword", "parentSchema", "keyIndex", "key", "sch", "i", "prop", "escapeJsonPtr", "str", "util_1", "equal", "traverse", "SIMPLE_INLINED", "inlineRef", "schema", "limit", "hasRef", "countKeys", "exports", "REF_KEYWORDS", "key", "sch", "count", "getFullPath", "resolver", "id", "normalize", "normalizeId", "p", "_getFullPath", "TRAILING_SLASH_HASH", "resolveUrl", "baseId", "ANCHOR", "getSchemaRefs", "schemaId", "uriResolver", "schId", "baseIds", "pathPrefix", "localRefs", "schemaRefs", "jsonPtr", "_", "parentJsonPtr", "fullPath", "innerBaseId", "addRef", "addAnchor", "ref", "_resolve", "ambiguos", "schOrRef", "checkAmbiguosRef", "anchor", "sch1", "sch2", "boolSchema_1", "dataType_1", "applicability_1", "dataType_2", "defaults_1", "keyword_1", "subschema_1", "codegen_1", "names_1", "resolve_1", "util_1", "errors_1", "validateFunctionCode", "it", "isSchemaObj", "checkKeywords", "schemaCxtHasRules", "topSchemaObjCode", "validateFunction", "exports", "gen", "validateName", "schema", "schemaEnv", "opts", "body", "funcSourceUrl", "destructureValCxtES5", "destructureValCxt", "commentKeyword", "checkNoDefault", "resetEvaluated", "typeAndKeywords", "returnResults", "schId", "subschemaCode", "valid", "subSchemaObjCode", "self", "key", "updateContext", "checkAsyncSchema", "errsCount", "checkRefsAndKeywords", "schemaKeywords", "types", "checkedTypes", "errSchemaPath", "msg", "schemaPath", "rootName", "ValidationError", "assignEvaluated", "evaluated", "props", "items", "typeErrors", "data", "allErrors", "RULES", "keywordCode", "checkStrictTypes", "group", "groupKeywords", "iterateKeywords", "useDefaults", "rule", "checkContextTypes", "checkMultipleTypes", "checkKeywordTypes", "t", "includesType", "strictTypesError", "narrowSchemaTypes", "ts", "rules", "keyword", "type", "hasApplicableType", "schTs", "kwdT", "withTypes", "KeywordCxt", "def", "getData", "condition", "successAction", "failAction", "schemaCode", "append", "errorParams", "errorPaths", "cond", "obj", "assign", "codeBlock", "$dataValid", "schemaType", "wrong$DataType", "invalid$DataSchema", "st", "validateSchemaRef", "appl", "subschema", "nextContext", "schemaCxt", "toName", "ruleType", "cxt", "JSON_POINTER", "RELATIVE_JSON_POINTER", "$data", "dataLevel", "dataNames", "dataPathArr", "jsonPointer", "matches", "up", "errorMsg", "expr", "segments", "segment", "pointerType", "ValidationError", "errors", "exports", "resolve_1", "MissingRefError", "resolver", "baseId", "ref", "msg", "exports", "codegen_1", "validation_error_1", "names_1", "resolve_1", "util_1", "validate_1", "SchemaEnv", "env", "schema", "_a", "exports", "compileSchema", "sch", "_sch", "getCompilingSchema", "rootId", "es5", "lines", "ownProperties", "gen", "_ValidationError", "validateName", "schemaCxt", "sourceCode", "validateCode", "validate", "props", "items", "e", "resolveRef", "root", "baseId", "ref", "schOrFunc", "resolve", "schemaId", "inlineOrCompile", "schEnv", "sameSchemaEnv", "s1", "s2", "resolveSchema", "p", "refPath", "getJsonPointer", "id", "schOrRef", "schId", "PREVENT_SCOPE_CHANGE", "parsedRef", "part", "partSchema", "$ref", "require_data", "__commonJSMin", "exports", "module", "require_scopedChars", "__commonJSMin", "exports", "module", "HEX", "require_utils", "__commonJSMin", "exports", "module", "HEX", "IPV4_REG", "normalizeIPv4", "host", "findToken", "matches", "address", "stripLeadingZeros", "stringArrayToHexStripped", "input", "keepZero", "acc", "strip", "c", "getIPV6", "tokenCount", "output", "buffer", "isZone", "endipv6Encountered", "endIpv6", "consume", "hex", "i", "cursor", "normalizeIPv6", "ipv6", "newHost", "escapedHost", "str", "token", "out", "skip", "l", "ind", "RDS1", "RDS2", "RDS3", "RDS5", "removeDotSegments", "im", "s", "normalizeComponentEncoding", "components", "esc", "func", "recomposeAuthority", "uriTokens", "ipV4res", "ipV6res", "require_schemes", "__commonJSMin", "exports", "module", "UUID_REG", "URN_REG", "isSecure", "wsComponents", "httpParse", "components", "httpSerialize", "secure", "wsParse", "wsSerialize", "path", "query", "urnParse", "urnComponents", "options", "matches", "scheme", "urnScheme", "schemeHandler", "SCHEMES", "urnSerialize", "nid", "uriComponents", "nss", "urnuuidParse", "uuidComponents", "urnuuidSerialize", "http", "https", "ws", "wss", "urn", "urnuuid", "require_fast_uri", "__commonJSMin", "exports", "module", "normalizeIPv6", "normalizeIPv4", "removeDotSegments", "recomposeAuthority", "normalizeComponentEncoding", "SCHEMES", "normalize", "uri", "options", "serialize", "parse", "resolve", "baseURI", "relativeURI", "schemelessOptions", "resolved", "resolveComponents", "base", "relative", "skipNormalization", "target", "equal", "uriA", "uriB", "cmpts", "opts", "components", "uriTokens", "schemeHandler", "authority", "s", "hexLookUp", "_v", "k", "nonSimpleDomain", "value", "code", "i", "len", "URI_PARSE", "parsed", "gotEncoding", "isIP", "matches", "ipv4result", "ipv6result", "e", "fastUri", "uri", "exports", "validate_1", "exports", "codegen_1", "validation_error_1", "ref_error_1", "rules_1", "compile_1", "codegen_2", "resolve_1", "dataType_1", "util_1", "$dataRefSchema", "uri_1", "defaultRegExp", "str", "flags", "META_IGNORE_OPTIONS", "EXT_SCOPE_NAMES", "removedOptions", "deprecatedOptions", "MAX_EXPRESSION", "requiredOptions", "o", "s", "_optz", "_a", "optimize", "regExp", "_c", "_b", "uriResolver", "_d", "_f", "_e", "_h", "_g", "_k", "_j", "_m", "_l", "_p", "_o", "_q", "_r", "_s", "_t", "_u", "_v", "_w", "_x", "_y", "_z", "_0", "Ajv", "opts", "es5", "lines", "getLogger", "formatOpt", "checkOptions", "getMetaSchemaOptions", "addInitialFormats", "addInitialKeywords", "addInitialSchemas", "$data", "meta", "schemaId", "_dataRefSchema", "schemaKeyRef", "data", "v", "valid", "schema", "_meta", "sch", "loadSchema", "runCompileAsync", "_schema", "loadMetaSchema", "_compileAsync", "$ref", "e", "checkLoaded", "loadMissingSchema", "ref", "missingRef", "_loadSchema", "p", "key", "_validateSchema", "id", "throwOrLogError", "$schema", "message", "keyRef", "getSchEnv", "root", "cacheKey", "definitions", "def", "kwdOrDef", "keyword", "checkKeyword", "kwd", "addRule", "keywordMetaschema", "definition", "k", "t", "rule", "RULES", "group", "i", "name", "format", "errors", "separator", "dataVar", "text", "msg", "metaSchema", "keywordsJsonPointers", "rules", "jsonPointer", "segments", "keywords", "seg", "schemaOrData", "schemas", "regex", "baseId", "validateSchema", "addSchema", "localRefs", "currentOpts", "checkOpts", "options", "log", "opt", "optsSchemas", "defs", "metaOpts", "noLogs", "logger", "KEYWORD_NAME", "dataType", "post", "ruleGroup", "addBeforeRule", "before", "_rule", "$dataRef", "ref_error_1", "code_1", "codegen_1", "names_1", "compile_1", "util_1", "def", "cxt", "gen", "$ref", "it", "baseId", "env", "validateName", "opts", "self", "root", "callRootRef", "schOrEnv", "callValidate", "inlineRefSchema", "callRef", "rootName", "sch", "v", "getValidate", "schName", "valid", "schCxt", "exports", "$async", "allErrors", "passCxt", "callAsyncRef", "callSyncRef", "addEvaluatedFrom", "e", "addErrorsFrom", "source", "errs", "schEvaluated", "_a", "props", "items", "ref_1", "core", "exports", "core_1", "codegen_1", "ops", "KWDs", "error", "cxt", "kwdOp", "def", "data", "schemaCode", "keyword", "opsIdx", "_a", "exports", "KWDs", "def", "keyword", "parentSchema", "limitKwd", "exports", "codegen_1", "error", "schemaCode", "def", "cxt", "gen", "data", "it", "prec", "res", "invalid", "exports", "ucs2length", "str", "len", "length", "pos", "value", "exports", "codegen_1", "util_1", "ucs2length_1", "error", "keyword", "schemaCode", "comp", "def", "cxt", "data", "it", "op", "len", "exports", "code_1", "codegen_1", "error", "schemaCode", "def", "cxt", "data", "$data", "schema", "it", "u", "regExp", "exports", "codegen_1", "error", "keyword", "schemaCode", "comp", "def", "cxt", "data", "op", "exports", "code_1", "codegen_1", "util_1", "error", "missingProperty", "def", "cxt", "gen", "schema", "schemaCode", "data", "$data", "it", "opts", "useLoop", "allErrorsMode", "exitOnErrorMode", "props", "definedProperties", "requiredKey", "schemaPath", "msg", "loopAllRequired", "prop", "missing", "valid", "loopUntilMissing", "exports", "codegen_1", "error", "keyword", "schemaCode", "comp", "def", "cxt", "data", "op", "exports", "equal", "exports", "dataType_1", "codegen_1", "util_1", "equal_1", "error", "i", "j", "def", "cxt", "gen", "data", "$data", "schema", "parentSchema", "schemaCode", "it", "valid", "itemTypes", "validateUniqueItems", "canOptimize", "loopN", "loopN2", "t", "item", "wrongType", "indices", "eql", "outer", "exports", "codegen_1", "util_1", "equal_1", "error", "schemaCode", "def", "cxt", "gen", "data", "$data", "schema", "exports", "codegen_1", "util_1", "equal_1", "error", "schemaCode", "def", "cxt", "gen", "data", "$data", "schema", "it", "useLoop", "eql", "getEql", "valid", "loopEnum", "vSchema", "_x", "i", "equalCode", "v", "sch", "exports", "limitNumber_1", "limitNumberExclusive_1", "multipleOf_1", "limitLength_1", "pattern_1", "limitProperties_1", "required_1", "limitItems_1", "uniqueItems_1", "const_1", "enum_1", "validation", "exports", "codegen_1", "util_1", "error", "len", "def", "cxt", "parentSchema", "it", "items", "validateAdditionalItems", "gen", "schema", "data", "keyword", "valid", "validateItems", "i", "exports", "codegen_1", "util_1", "code_1", "def", "cxt", "schema", "it", "validateTuple", "extraItems", "schArr", "gen", "parentSchema", "data", "keyword", "checkStrictTuple", "valid", "len", "sch", "i", "opts", "errSchemaPath", "l", "fullTuple", "msg", "exports", "items_1", "def", "cxt", "exports", "codegen_1", "util_1", "code_1", "additionalItems_1", "error", "len", "def", "cxt", "schema", "parentSchema", "it", "prefixItems", "exports", "codegen_1", "util_1", "error", "min", "max", "def", "cxt", "gen", "schema", "parentSchema", "data", "it", "minContains", "maxContains", "len", "cond", "valid", "validateItems", "validateItemsWithCount", "schValid", "count", "checkLimits", "_valid", "block", "i", "exports", "codegen_1", "util_1", "code_1", "exports", "property", "depsCount", "deps", "property_ies", "missingProperty", "def", "cxt", "propDeps", "schDeps", "splitDependencies", "validatePropertyDeps", "validateSchemaDeps", "schema", "propertyDeps", "schemaDeps", "key", "gen", "data", "it", "missing", "prop", "hasProperty", "depProp", "keyword", "valid", "schCxt", "codegen_1", "util_1", "error", "params", "def", "cxt", "gen", "schema", "data", "it", "valid", "key", "exports", "code_1", "codegen_1", "names_1", "util_1", "error", "params", "def", "cxt", "gen", "schema", "parentSchema", "data", "errsCount", "it", "allErrors", "opts", "props", "patProps", "checkAdditionalProperties", "key", "additionalPropertyCode", "isAdditional", "definedProp", "propsSchema", "p", "deleteAdditional", "valid", "applyAdditionalSchema", "errors", "subschema", "exports", "validate_1", "code_1", "util_1", "additionalProperties_1", "def", "cxt", "gen", "schema", "parentSchema", "data", "it", "allProps", "prop", "properties", "p", "valid", "hasDefault", "applyPropertySchema", "exports", "code_1", "codegen_1", "util_1", "util_2", "def", "cxt", "gen", "schema", "data", "parentSchema", "it", "opts", "patterns", "alwaysValidPatterns", "p", "checkProperties", "valid", "props", "validatePatternProperties", "pat", "checkMatchingProperties", "validateProperties", "prop", "key", "alwaysValid", "exports", "util_1", "def", "cxt", "gen", "schema", "it", "valid", "exports", "code_1", "def", "exports", "codegen_1", "util_1", "error", "params", "def", "cxt", "gen", "schema", "parentSchema", "it", "schArr", "valid", "passing", "schValid", "validateOneOf", "sch", "i", "schCxt", "exports", "util_1", "def", "cxt", "gen", "schema", "it", "valid", "sch", "schCxt", "exports", "codegen_1", "util_1", "error", "params", "def", "cxt", "gen", "parentSchema", "it", "hasThen", "hasSchema", "hasElse", "valid", "schValid", "validateIf", "ifClause", "validateClause", "schCxt", "keyword", "schema", "exports", "util_1", "def", "keyword", "parentSchema", "it", "exports", "additionalItems_1", "prefixItems_1", "items_1", "items2020_1", "contains_1", "dependencies_1", "propertyNames_1", "additionalProperties_1", "properties_1", "patternProperties_1", "not_1", "anyOf_1", "oneOf_1", "allOf_1", "if_1", "thenElse_1", "getApplicator", "draft2020", "applicator", "exports", "codegen_1", "error", "schemaCode", "def", "cxt", "ruleType", "gen", "data", "$data", "schema", "it", "opts", "errSchemaPath", "schemaEnv", "self", "validate$DataFormat", "validateFormat", "fmts", "fDef", "fType", "format", "unknownFmt", "invalidFmt", "callFormat", "validData", "formatDef", "unknownFormat", "fmtType", "fmtRef", "getFormat", "validCondition", "unknownMsg", "fmtDef", "code", "fmt", "exports", "format_1", "format", "exports", "core_1", "validation_1", "applicator_1", "format_1", "metadataVocabulary", "draft4Vocabularies", "exports", "DiscrError", "exports", "codegen_1", "types_1", "compile_1", "ref_error_1", "util_1", "error", "discrError", "tagName", "tag", "def", "cxt", "gen", "data", "schema", "parentSchema", "it", "oneOf", "valid", "validateMapping", "mapping", "getMapping", "tagValue", "applyTagSchema", "schemaProp", "_valid", "schCxt", "oneOfMapping", "topRequired", "hasRequired", "tagRequired", "i", "sch", "ref", "propSch", "_a", "addMappings", "required", "addMapping", "exports", "require_json_schema_draft_04", "__commonJSMin", "exports", "module", "core_1", "draft4_1", "discriminator_1", "draft4MetaSchema", "META_SUPPORT_DATA", "META_SCHEMA_ID", "Ajv", "opts", "v", "metaSchema", "module", "exports", "core_2", "core_3", "import_ajv_draft_04", "Graffiti", "object", "extendStatics", "d", "b", "p", "__extends", "__", "__awaiter", "thisArg", "_arguments", "P", "generator", "adopt", "value", "resolve", "reject", "fulfilled", "step", "e", "rejected", "result", "__generator", "body", "_", "t", "f", "y", "g", "verb", "n", "v", "op", "__values", "o", "s", "m", "i", "__await", "__asyncGenerator", "q", "a", "resume", "settle", "r", "fulfill", "RepeaterOverflowError", "_super", "message", "_this", "FixedBuffer", "capacity", "SlidingBuffer", "DroppingBuffer", "swallow", "NOOP", "Initial", "Started", "Stopped", "Done", "Rejected", "MAX_QUEUE_LENGTH", "consumeExecution", "err", "execution", "createIteration", "done", "stop", "e_1", "_a", "finish", "_b", "_d", "push_1", "e_1_1", "e_2", "next", "e_2_1", "push", "valueP", "nextP", "next_1", "floating", "unhandled", "onfulfilled", "onrejected", "createStop", "stop1", "stopP", "execute", "push1", "records", "Repeater", "executor", "buffer", "push_2", "push_3", "race", "merge", "zip", "latest", "getIterators", "values", "options", "e_3", "iters", "_loop_1", "values_1", "values_1_1", "e_3_1", "contenders", "advance", "stopped", "finalIteration", "iteration", "i_1", "_loop_2", "j", "iters_1", "iters_1_1", "iter", "e_4", "e_4_1", "advances", "e_5", "advances_1", "advances_1_1", "e_5_1", "iterations", "iterations_1", "values_2", "e_6", "advances_2", "advances_2_1", "advance1", "e_6_1", "core_exports", "__export", "JsonPatchError", "_areEquals", "applyOperation", "applyPatch", "applyReducer", "deepClone", "getValueByPointer", "validate", "validator", "__extends", "extendStatics", "d", "b", "p", "__", "_hasOwnProperty", "hasOwnProperty", "obj", "key", "_objectKeys", "keys_1", "k", "keys", "i", "_deepClone", "isInteger", "str", "len", "charCode", "escapePathComponent", "path", "unescapePathComponent", "hasUndefined", "obj", "i_1", "len", "objKeys", "_objectKeys", "objKeysLength", "i", "patchErrorMessageFormatter", "message", "args", "messageParts", "key", "value", "PatchError", "_super", "__extends", "name", "index", "operation", "tree", "_newTarget", "_this", "JsonPatchError", "PatchError", "deepClone", "_deepClone", "objOps", "obj", "key", "document", "removed", "getValueByPointer", "originalValue", "applyOperation", "valueToCopy", "_areEquals", "arrOps", "arr", "i", "isInteger", "removedList", "pointer", "getOriginalDestination", "operation", "validateOperation", "mutateDocument", "banPrototypeModifications", "index", "validator", "returnValue", "path", "keys", "t", "len", "existingPathFragment", "validateFunction", "unescapePathComponent", "applyPatch", "patch", "results", "length_1", "applyReducer", "operationResult", "hasUndefined", "pathLen", "existingPathLen", "existingValue", "error", "validate", "sequence", "externalValidator", "e", "a", "b", "arrA", "arrB", "length", "duplex_exports", "__export", "compare", "generate", "observe", "unobserve", "beforeDict", "Mirror", "obj", "ObserverInfo", "callback", "observer", "getMirror", "getObserverFromMirror", "mirror", "removeObserverFromMirror", "unobserve", "root", "observe", "patches", "observerInfo", "_deepClone", "dirtyCheck", "generate", "fastCheck", "invertible", "_generate", "applyPatch", "temp", "path", "newKeys", "_objectKeys", "oldKeys", "changed", "deleted", "t", "key", "oldVal", "hasOwnProperty", "newVal", "escapePathComponent", "compare", "tree1", "tree2", "fast_json_patch_default", "core_exports", "duplex_exports", "PatchError", "_deepClone", "escapePathComponent", "unescapePathComponent", "GraffitiErrorInvalidSchema", "_GraffitiErrorInvalidSchema", "message", "GraffitiErrorPatchTestFailed", "_GraffitiErrorPatchTestFailed", "message", "GraffitiErrorPatchError", "_GraffitiErrorPatchError", "GraffitiErrorInvalidUri", "_GraffitiErrorInvalidUri", "locationToUri", "location", "uriToLocation", "uri", "parts", "nameEncoded", "webIdEncoded", "GraffitiErrorInvalidUri", "unpackLocationOrUri", "locationOrUri", "uriToLocation", "locationToUri", "applyGraffitiPatch", "apply", "prop", "patch", "object", "ops", "e", "GraffitiErrorPatchTestFailed", "GraffitiErrorPatchError", "attemptAjvCompile", "ajv", "schema", "error", "GraffitiErrorInvalidSchema", "maskGraffitiObject", "channels", "session", "channel", "isActorAllowedGraffitiObject", "GraffitiSynchronize", "r", "graffiti", "ajv", "Ajv", "matchObject", "channels", "schema", "session", "validate", "w", "Repeater", "push", "stop", "callback", "oldObjectRaw", "newObjectRaw", "objectRaw", "g", "object", "y", "args", "channel", "locationOrUri", "objectUri", "p", "uri", "u", "oldObject", "newObject", "waitForListeners", "resolve", "partialObject", "prop", "h", "applyPatch", "iterator", "dispatch", "result"]
|
|
7
|
+
}
|