Repository: stoplightio/spectral (ts)

Issue:
Certain valid patterns are not accepted by schema function 
**Describe the bug**

In some cases, Ajv bails upon a valid pattern.
It's presumably an issue with Ajv, or, with the way we use Ajv.

**To Reproduce**

1. Run the following snippet
```js
const Ajv = require('ajv');
const ajv = new Ajv();
const assert = require('assert');

const schema = {
  type: 'string',
  pattern: '^[A-Za-z0-9\\-\\_]',
};

assert.ok(ajv.validate(schema, 'test-case-1'));
```
2. Exits with non-zero code

**Expected behavior**

Exits with a zero-code


Related to https://github.com/stoplightio/platform-internal/issues/7541

Pull request description:
fix(functions): schema fn should allow redundant escapes
Fixes #1782 

**Checklist**

- [x] Tests added / updated
- [x] Docs added / updated

**Does this PR introduce a breaking change?**

- [ ] Yes
- [x] No


**Additional context**

This is not a bug in Ajv or anything, it's just how the unicode flag works.


Patch:
diff --git a/packages/functions/src/schema/ajv.ts b/packages/functions/src/schema/ajv.ts
index b4c054a0..035eb1ab 100644
--- a/packages/functions/src/schema/ajv.ts
+++ b/packages/functions/src/schema/ajv.ts
@@ -23,7 +23,15 @@ const logger = {
 };
 
 function createAjvInstance(Ajv: typeof AjvCore, allErrors: boolean): AjvCore {
-  const ajv = new Ajv({ allErrors, meta: true, messages: true, strict: false, allowUnionTypes: true, logger });
+  const ajv = new Ajv({
+    allErrors,
+    meta: true,
+    messages: true,
+    strict: false,
+    allowUnionTypes: true,
+    logger,
+    unicodeRegExp: false,
+  });
   addFormats(ajv);
   if (allErrors) {
     ajvErrors(ajv);


Test patch:
diff --git a/packages/functions/src/__tests__/schema.test.ts b/packages/functions/src/__tests__/schema.test.ts
index aa7d7330..32312108 100644
--- a/packages/functions/src/__tests__/schema.test.ts
+++ b/packages/functions/src/__tests__/schema.test.ts
@@ -42,6 +42,34 @@ describe('Core Functions / Schema', () => {
     expect(await runSchema(2, { schema, dialect: 'auto' })).toStrictEqual(result);
   });
 
+  it('allows redundant escapes', async () => {
+    let schema = {
+      $schema: 'http://json-schema.org/draft-07/schema#',
+      type: 'string',
+      pattern: '[\\-_]', // this one is good and would work with unicodeRegExp: true
+    };
+
+    expect(await runSchema(2, { schema })).toEqual([
+      {
+        message: 'Value type must be string',
+        path: [],
+      },
+    ]);
+
+    schema = {
+      $schema: 'http://json-schema.org/draft-06/schema#',
+      type: 'string',
+      pattern: '[\\_-]', // the escape here is redundant
+    };
+
+    expect(await runSchema(2, { schema })).toEqual([
+      {
+        message: 'Value type must be string',
+        path: [],
+      },
+    ]);
+  });
+
   describe('validates falsy values such as', () => {
     it('empty string', async () => {
       const schema: JSONSchema = {