diff --git a/packages/validator/src/schema/did.js b/packages/validator/src/schema/did.js index 69277c58..42ee8bff 100644 --- a/packages/validator/src/schema/did.js +++ b/packages/validator/src/schema/did.js @@ -37,3 +37,9 @@ export const match = options => /** @type {Schema.Schema & API.URI<"did:">>} */ ( Schema.string().refine(new DIDSchema(options.method)) ) + +/** + * Create a DID string from any input (or throw) + * @param {unknown} input + */ +export const from = input => match({}).from(input) diff --git a/packages/validator/test/extra-schema.spec.js b/packages/validator/test/extra-schema.spec.js index 292ed919..c722b05a 100644 --- a/packages/validator/test/extra-schema.spec.js +++ b/packages/validator/test/extra-schema.spec.js @@ -381,3 +381,41 @@ test('URI.from', () => { }) } } + +{ + /** @type {Array<[unknown, null|{ name: string, message: string }]>} */ + const dataset = [ + ['did:key:foo', null], + ['did:web:example.com', null], + ['did:twosegments', null], + [ + 'notdid', + { + name: 'SchemaError', + message: 'Expected a did: but got "notdid" instead', + }, + ], + [ + undefined, + { + name: 'TypeError', + message: 'Expected value of type string instead got undefined', + }, + ], + ] + for (const [did, errorExpectation] of dataset) { + test(`DID.from("${did}")`, () => { + let error + try { + DID.from(did) + } catch (_error) { + error = _error + } + if (errorExpectation) { + assert.containSubset(error, errorExpectation) + } else { + assert.notOk(error, 'expected no error, but got an error') + } + }) + } +}