Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 60 additions & 13 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
},
"homepage": "https://github.com/benfrancis/webthing-node-2#readme",
"dependencies": {
"ajv": "^8.20.0",
"express": "^5.1.0"
},
"devDependencies": {
Expand Down
63 changes: 53 additions & 10 deletions src/action-affordance.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import InteractionAffordance from './interaction-affordance.js';
import ValidationError from './validation-error.js';
import { randomUUID } from 'node:crypto';
import DataSchema from './data-schema.js';

/** @import {DataSchema, PartialActionDescription, ActionDescription, Form,
/** @import {DataSchemaDescription, PartialActionDescription, ActionDescription, Form,
* ActionStatus} from "./types.js"
*/

Expand All @@ -16,12 +17,12 @@ import { randomUUID } from 'node:crypto';
*/
class ActionAffordance extends InteractionAffordance {
/**
* @type {DataSchema|undefined}
* @type {DataSchemaDescription|undefined}
*/
input;

/**
* @type {DataSchema|undefined}
* @type {DataSchemaDescription|undefined}
*/
output;

Expand Down Expand Up @@ -50,6 +51,16 @@ class ActionAffordance extends InteractionAffordance {
*/
#actionRequests = new Map();

/**
* @type {DataSchema}
*/
inputSchema;

/**
* @type {DataSchema}
*/
outputSchema;

/**
* Create a new Action.
*
Expand Down Expand Up @@ -101,12 +112,18 @@ class ActionAffordance extends InteractionAffordance {
if (validationError.validationErrors.length > 0) {
throw validationError;
}

this.inputSchema = new DataSchema(this.input, `actions.${this.name}.input`);
this.outputSchema = new DataSchema(
this.output,
`actions.${this.name}.output`,
);
}

/**
* Parse input member.
*
* @param {DataSchema|undefined} input
* @param {DataSchemaDescription|undefined} input
*/
#parseInputMember(input) {
if (!(input === undefined || typeof input === 'object')) {
Expand All @@ -117,13 +134,12 @@ class ActionAffordance extends InteractionAffordance {
},
]);
}
// TODO: Validate DataSchema
this.input = input;
}

/**
* Parse output member.
* @param {DataSchema|undefined} output
* @param {DataSchemaDescription|undefined} output
*/
#parseOutputMember(output) {
if (!(output === undefined || typeof output === 'object')) {
Expand All @@ -134,7 +150,6 @@ class ActionAffordance extends InteractionAffordance {
},
]);
}
// TODO: Validate DataSchema
this.output = output;
}

Expand Down Expand Up @@ -224,24 +239,51 @@ class ActionAffordance extends InteractionAffordance {
* schema.
* @returns {Promise<any>} A Promise which resolves with the output of the
* action (if any), conforming to the output data schema.
* @throws {Error} Throws InternalError if handler is missing.
*
*/
async invoke(input) {
// TODO: Validate input against data schema
if (!this.invokeHandler) {
console.error(`No invoke handler set for action ${this.name}`);
throw new Error('InternalError');
}
return this.invokeHandler(input);
this.#validateInput(input);
const output = await this.invokeHandler(input);
this.#validateOutput(output);
return output;
}

/**
* @param {any} input
* @throws {Error} Throws BadRequest on invalid input.
*/
#validateInput(input) {
if (!this.inputSchema.validate(input)) {
console.error(`Tried to invoke action ${this.name} with invalid input`);
throw new Error('BadRequest');
}
}

/**
* @param {any} output
* @throws {Error} Throws InternalError on invalid output.
*/
#validateOutput(output) {
if (!this.outputSchema.validate(output)) {
console.error(`Action ${this.name} returned invalid output`);
throw new Error('InternalError');
}
}

/**
* Invoke an asynchronous action.
*
* @param {any} input The action input.
* @returns {ActionStatus & {href: string}} The initial status of the action request.
* @throws {Error} Throws InternalError if handler is missing.
*/
invokeAsync(input) {
this.#validateInput(input);
if (!this.invokeHandler) {
console.error(`No invoke handler set for action ${this.name}`);
throw new Error('InternalError');
Expand Down Expand Up @@ -269,6 +311,7 @@ class ActionAffordance extends InteractionAffordance {
input,
request.controller.signal,
);
this.#validateOutput(output);
if (this.#actionRequests.get(actionID) !== request) {
return;
}
Expand Down Expand Up @@ -325,7 +368,7 @@ class ActionAffordance extends InteractionAffordance {
* @throws {Error} Throws NotFoundError if the request does not exist,
* or ConflictError if it has already completed or failed.
*/
cancelAction(actionID) {
cancel(actionID) {
const request = this.#actionRequests.get(actionID);
if (!request) {
throw new Error('NotFoundError');
Expand Down
51 changes: 51 additions & 0 deletions src/data-schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Ajv } from 'ajv';
import ValidationError from './validation-error.js';

/**
* Data Schema
*
* Represents a DataSchema from the WoT Thing Description 1.1 specification.
* https://www.w3.org/TR/wot-thing-description/#dataschema
*/
class DataSchema {
/**
* @type {import('ajv').ValidateFunction|undefined}
*/
#validator;

/**
* @param {object|undefined} schema A raw data schema from a
* Thing Description.
* @param {string|undefined} [field] The Thing Description field the schema
* came from, following the dot-separated format from validationErrors in WoT Discovery.
*/
constructor(schema, field = undefined) {
if (schema === undefined) {
return;
}

try {
const ajv = new Ajv({ allErrors: true, strict: false });
this.#validator = ajv.compile(schema);
} catch (error) {
throw new ValidationError([
{
field,
description: `Invalid data schema${error instanceof Error ? `: ${error.message}` : ''}`,
},
]);
}
}

/**
* Check whether a value conforms to this data schema.
*
* @param {any} value
* @returns {boolean}
*/
validate(value) {
return this.#validator ? this.#validator(value) : true;
}
}

export default DataSchema;
Loading
Loading