@wordpress/abilities 0.23.0 → 0.25.0

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.
Files changed (44) hide show
  1. package/build/api.cjs +176 -122
  2. package/build/api.cjs.map +1 -7
  3. package/build/index.cjs +73 -52
  4. package/build/store/actions.cjs +119 -187
  5. package/build/store/actions.cjs.map +1 -7
  6. package/build/store/constants.cjs +23 -47
  7. package/build/store/constants.cjs.map +1 -7
  8. package/build/store/index.cjs +36 -40
  9. package/build/store/index.cjs.map +1 -7
  10. package/build/store/reducer.cjs +102 -94
  11. package/build/store/reducer.cjs.map +1 -7
  12. package/build/store/selectors.cjs +49 -58
  13. package/build/store/selectors.cjs.map +1 -7
  14. package/build/store/types.cjs +4 -18
  15. package/build/types.cjs +4 -18
  16. package/build/validation.cjs +122 -137
  17. package/build/validation.cjs.map +1 -7
  18. package/build-module/api.mjs +161 -87
  19. package/build-module/api.mjs.map +1 -7
  20. package/build-module/index.mjs +2 -26
  21. package/build-module/store/actions.mjs +112 -167
  22. package/build-module/store/actions.mjs.map +1 -7
  23. package/build-module/store/constants.mjs +13 -17
  24. package/build-module/store/constants.mjs.map +1 -7
  25. package/build-module/store/index.mjs +11 -9
  26. package/build-module/store/index.mjs.map +1 -7
  27. package/build-module/store/reducer.mjs +97 -78
  28. package/build-module/store/reducer.mjs.map +1 -7
  29. package/build-module/store/selectors.mjs +42 -31
  30. package/build-module/store/selectors.mjs.map +1 -7
  31. package/build-module/store/types.mjs +0 -1
  32. package/build-module/types.mjs +0 -1
  33. package/build-module/validation.mjs +101 -109
  34. package/build-module/validation.mjs.map +1 -7
  35. package/build-types/index.d.ts +1 -1
  36. package/package.json +7 -8
  37. package/src/index.ts +1 -1
  38. package/CHANGELOG.md +0 -65
  39. package/build/index.cjs.map +0 -7
  40. package/build/store/types.cjs.map +0 -7
  41. package/build/types.cjs.map +0 -7
  42. package/build-module/index.mjs.map +0 -7
  43. package/build-module/store/types.mjs.map +0 -7
  44. package/build-module/types.mjs.map +0 -7
@@ -1,153 +1,138 @@
1
1
  "use strict";
2
+ Object.defineProperties(exports, {
3
+ __esModule: { value: true },
4
+ [Symbol.toStringTag]: { value: "Module" }
5
+ });
6
+ // \0rolldown/runtime.js
2
7
  var __create = Object.create;
3
8
  var __defProp = Object.defineProperty;
4
9
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
10
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
11
  var __getProtoOf = Object.getPrototypeOf;
7
12
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
13
  var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
14
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
15
+ key = keys[i];
16
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
17
+ get: ((k) => from[k]).bind(null, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ return to;
19
22
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
24
+ value: mod,
25
+ enumerable: true
26
+ }) : target, mod));
27
+ let ajv_draft_04 = require("ajv-draft-04");
28
+ ajv_draft_04 = __toESM(ajv_draft_04);
29
+ let ajv_formats = require("ajv-formats");
30
+ ajv_formats = __toESM(ajv_formats);
30
31
  // packages/abilities/src/validation.ts
31
- var validation_exports = {};
32
- __export(validation_exports, {
33
- validateValueFromSchema: () => validateValueFromSchema
32
+ /**
33
+ * Schema validation for client-side ability input and output schemas using AJV and ajv-formats.
34
+ *
35
+ * This utility provides validation for JSON Schema draft-04.
36
+ * Rules are configured to support the intersection of common rules between JSON Schema draft-04, WordPress (a subset of JSON Schema draft-04),
37
+ * and various providers like OpenAI and Anthropic.
38
+ *
39
+ * @see https://developer.wordpress.org/rest-api/extending-the-rest-api/schema/#json-schema-basics
40
+ */
41
+ const ajv = new ajv_draft_04.default({
42
+ coerceTypes: false,
43
+ useDefaults: true,
44
+ removeAdditional: false,
45
+ allErrors: true,
46
+ verbose: true,
47
+ allowUnionTypes: true
34
48
  });
35
- module.exports = __toCommonJS(validation_exports);
36
- var import_ajv_draft_04 = __toESM(require("ajv-draft-04"));
37
- var import_ajv_formats = __toESM(require("ajv-formats"));
38
- var ajv = new import_ajv_draft_04.default({
39
- coerceTypes: false,
40
- // No type coercion - AI should send proper JSON
41
- useDefaults: true,
42
- removeAdditional: false,
43
- // Keep additional properties
44
- allErrors: true,
45
- verbose: true,
46
- allowUnionTypes: true
47
- // Allow anyOf without explicit type
48
- });
49
- (0, import_ajv_formats.default)(ajv, [
50
- "date-time",
51
- "email",
52
- "hostname",
53
- "ipv4",
54
- "ipv6",
55
- "uri",
56
- "uuid"
49
+ (0, ajv_formats.default)(ajv, [
50
+ "date-time",
51
+ "email",
52
+ "hostname",
53
+ "ipv4",
54
+ "ipv6",
55
+ "uri",
56
+ "uuid"
57
57
  ]);
58
+ /**
59
+ * Formats AJV errors into a simple error message.
60
+ * The Abilities API will wrap this with ability_invalid_input/output to match the server side format.
61
+ *
62
+ * @param ajvError The AJV validation error.
63
+ * @param param The base parameter name.
64
+ * @return Simple error message string.
65
+ */
58
66
  function formatAjvError(ajvError, param) {
59
- const instancePath = ajvError.instancePath ? ajvError.instancePath.replace(/\//g, "][").replace(/^\]\[/, "[") + "]" : "";
60
- const fullParam = param + instancePath;
61
- switch (ajvError.keyword) {
62
- case "type":
63
- return `${fullParam} is not of type ${ajvError.params.type}.`;
64
- case "required":
65
- return `${ajvError.params.missingProperty} is a required property of ${fullParam}.`;
66
- case "additionalProperties":
67
- return `${ajvError.params.additionalProperty} is not a valid property of Object.`;
68
- case "enum":
69
- const enumValues = ajvError.params.allowedValues.map(
70
- (v) => typeof v === "string" ? v : JSON.stringify(v)
71
- ).join(", ");
72
- return ajvError.params.allowedValues.length === 1 ? `${fullParam} is not ${enumValues}.` : `${fullParam} is not one of ${enumValues}.`;
73
- case "pattern":
74
- return `${fullParam} does not match pattern ${ajvError.params.pattern}.`;
75
- case "format":
76
- const format = ajvError.params.format;
77
- const formatMessages = {
78
- email: "Invalid email address.",
79
- "date-time": "Invalid date.",
80
- uuid: `${fullParam} is not a valid UUID.`,
81
- ipv4: `${fullParam} is not a valid IP address.`,
82
- ipv6: `${fullParam} is not a valid IP address.`,
83
- hostname: `${fullParam} is not a valid hostname.`,
84
- uri: `${fullParam} is not a valid URI.`
85
- };
86
- return formatMessages[format] || `Invalid ${format}.`;
87
- case "minimum":
88
- case "exclusiveMinimum":
89
- return ajvError.keyword === "exclusiveMinimum" ? `${fullParam} must be greater than ${ajvError.params.limit}` : `${fullParam} must be greater than or equal to ${ajvError.params.limit}`;
90
- case "maximum":
91
- case "exclusiveMaximum":
92
- return ajvError.keyword === "exclusiveMaximum" ? `${fullParam} must be less than ${ajvError.params.limit}` : `${fullParam} must be less than or equal to ${ajvError.params.limit}`;
93
- case "multipleOf":
94
- return `${fullParam} must be a multiple of ${ajvError.params.multipleOf}.`;
95
- case "anyOf":
96
- case "oneOf":
97
- return `${fullParam} is invalid (failed ${ajvError.keyword} validation).`;
98
- case "minLength":
99
- return `${fullParam} must be at least ${ajvError.params.limit} character${ajvError.params.limit === 1 ? "" : "s"} long.`;
100
- case "maxLength":
101
- return `${fullParam} must be at most ${ajvError.params.limit} character${ajvError.params.limit === 1 ? "" : "s"} long.`;
102
- case "minItems":
103
- return `${fullParam} must contain at least ${ajvError.params.limit} item${ajvError.params.limit === 1 ? "" : "s"}.`;
104
- case "maxItems":
105
- return `${fullParam} must contain at most ${ajvError.params.limit} item${ajvError.params.limit === 1 ? "" : "s"}.`;
106
- case "uniqueItems":
107
- return `${fullParam} has duplicate items.`;
108
- case "minProperties":
109
- return `${fullParam} must contain at least ${ajvError.params.limit} propert${ajvError.params.limit === 1 ? "y" : "ies"}.`;
110
- case "maxProperties":
111
- return `${fullParam} must contain at most ${ajvError.params.limit} propert${ajvError.params.limit === 1 ? "y" : "ies"}.`;
112
- default:
113
- return ajvError.message || `${fullParam} is invalid (failed ${ajvError.keyword} validation).`;
114
- }
67
+ const fullParam = param + (ajvError.instancePath ? ajvError.instancePath.replace(/\//g, "][").replace(/^\]\[/, "[") + "]" : "");
68
+ switch (ajvError.keyword) {
69
+ case "type": return `${fullParam} is not of type ${ajvError.params.type}.`;
70
+ case "required": return `${ajvError.params.missingProperty} is a required property of ${fullParam}.`;
71
+ case "additionalProperties": return `${ajvError.params.additionalProperty} is not a valid property of Object.`;
72
+ case "enum":
73
+ const enumValues = ajvError.params.allowedValues.map((v) => typeof v === "string" ? v : JSON.stringify(v)).join(", ");
74
+ return ajvError.params.allowedValues.length === 1 ? `${fullParam} is not ${enumValues}.` : `${fullParam} is not one of ${enumValues}.`;
75
+ case "pattern": return `${fullParam} does not match pattern ${ajvError.params.pattern}.`;
76
+ case "format":
77
+ const format = ajvError.params.format;
78
+ return {
79
+ email: "Invalid email address.",
80
+ "date-time": "Invalid date.",
81
+ uuid: `${fullParam} is not a valid UUID.`,
82
+ ipv4: `${fullParam} is not a valid IP address.`,
83
+ ipv6: `${fullParam} is not a valid IP address.`,
84
+ hostname: `${fullParam} is not a valid hostname.`,
85
+ uri: `${fullParam} is not a valid URI.`
86
+ }[format] || `Invalid ${format}.`;
87
+ case "minimum":
88
+ case "exclusiveMinimum": return ajvError.keyword === "exclusiveMinimum" ? `${fullParam} must be greater than ${ajvError.params.limit}` : `${fullParam} must be greater than or equal to ${ajvError.params.limit}`;
89
+ case "maximum":
90
+ case "exclusiveMaximum": return ajvError.keyword === "exclusiveMaximum" ? `${fullParam} must be less than ${ajvError.params.limit}` : `${fullParam} must be less than or equal to ${ajvError.params.limit}`;
91
+ case "multipleOf": return `${fullParam} must be a multiple of ${ajvError.params.multipleOf}.`;
92
+ case "anyOf":
93
+ case "oneOf": return `${fullParam} is invalid (failed ${ajvError.keyword} validation).`;
94
+ case "minLength": return `${fullParam} must be at least ${ajvError.params.limit} character${ajvError.params.limit === 1 ? "" : "s"} long.`;
95
+ case "maxLength": return `${fullParam} must be at most ${ajvError.params.limit} character${ajvError.params.limit === 1 ? "" : "s"} long.`;
96
+ case "minItems": return `${fullParam} must contain at least ${ajvError.params.limit} item${ajvError.params.limit === 1 ? "" : "s"}.`;
97
+ case "maxItems": return `${fullParam} must contain at most ${ajvError.params.limit} item${ajvError.params.limit === 1 ? "" : "s"}.`;
98
+ case "uniqueItems": return `${fullParam} has duplicate items.`;
99
+ case "minProperties": return `${fullParam} must contain at least ${ajvError.params.limit} propert${ajvError.params.limit === 1 ? "y" : "ies"}.`;
100
+ case "maxProperties": return `${fullParam} must contain at most ${ajvError.params.limit} propert${ajvError.params.limit === 1 ? "y" : "ies"}.`;
101
+ default: return ajvError.message || `${fullParam} is invalid (failed ${ajvError.keyword} validation).`;
102
+ }
115
103
  }
104
+ /**
105
+ * Validates a value against a JSON Schema.
106
+ *
107
+ * @param value The value to validate.
108
+ * @param args The JSON Schema to validate against.
109
+ * @param param Optional parameter name for error messages.
110
+ * @return True if valid, error message string if invalid.
111
+ */
116
112
  function validateValueFromSchema(value, args, param = "") {
117
- if (!args || typeof args !== "object") {
118
- console.warn(`Schema must be an object. Received ${typeof args}.`);
119
- return true;
120
- }
121
- if (!args.type && !args.anyOf && !args.oneOf) {
122
- console.warn(
123
- `The "type" schema keyword for ${param || "value"} is required.`
124
- );
125
- return true;
126
- }
127
- try {
128
- const { default: defaultValue, ...schemaWithoutDefault } = args;
129
- const validate = ajv.compile(schemaWithoutDefault);
130
- const valid = validate(value === void 0 ? defaultValue : value);
131
- if (valid) {
132
- return true;
133
- }
134
- if (validate.errors && validate.errors.length > 0) {
135
- const anyOfError = validate.errors.find(
136
- (e) => e.keyword === "anyOf" || e.keyword === "oneOf"
137
- );
138
- if (anyOfError) {
139
- return formatAjvError(anyOfError, param);
140
- }
141
- return formatAjvError(validate.errors[0], param);
142
- }
143
- return `${param} is invalid.`;
144
- } catch (error) {
145
- console.error("Schema compilation error:", error);
146
- return "Invalid schema provided for validation.";
147
- }
113
+ if (!args || typeof args !== "object") {
114
+ console.warn(`Schema must be an object. Received ${typeof args}.`);
115
+ return true;
116
+ }
117
+ if (!args.type && !args.anyOf && !args.oneOf) {
118
+ console.warn(`The "type" schema keyword for ${param || "value"} is required.`);
119
+ return true;
120
+ }
121
+ try {
122
+ const { default: defaultValue, ...schemaWithoutDefault } = args;
123
+ const validate = ajv.compile(schemaWithoutDefault);
124
+ if (validate(value === void 0 ? defaultValue : value)) return true;
125
+ if (validate.errors && validate.errors.length > 0) {
126
+ const anyOfError = validate.errors.find((e) => e.keyword === "anyOf" || e.keyword === "oneOf");
127
+ if (anyOfError) return formatAjvError(anyOfError, param);
128
+ return formatAjvError(validate.errors[0], param);
129
+ }
130
+ return `${param} is invalid.`;
131
+ } catch (error) {
132
+ console.error("Schema compilation error:", error);
133
+ return "Invalid schema provided for validation.";
134
+ }
148
135
  }
149
- // Annotate the CommonJS export names for ESM import in node:
150
- 0 && (module.exports = {
151
- validateValueFromSchema
152
- });
153
- //# sourceMappingURL=validation.cjs.map
136
+ exports.validateValueFromSchema = validateValueFromSchema;
137
+
138
+ //# sourceMappingURL=validation.cjs.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/validation.ts"],
4
- "sourcesContent": ["/**\n * Schema validation for client-side ability input and output schemas using AJV and ajv-formats.\n *\n * This utility provides validation for JSON Schema draft-04.\n * Rules are configured to support the intersection of common rules between JSON Schema draft-04, WordPress (a subset of JSON Schema draft-04),\n * and various providers like OpenAI and Anthropic.\n *\n * @see https://developer.wordpress.org/rest-api/extending-the-rest-api/schema/#json-schema-basics\n */\nimport Ajv from 'ajv-draft-04';\nimport addFormats from 'ajv-formats';\nimport type { ValidationError } from './types';\n\nconst ajv = new Ajv( {\n\tcoerceTypes: false, // No type coercion - AI should send proper JSON\n\tuseDefaults: true,\n\tremoveAdditional: false, // Keep additional properties\n\tallErrors: true,\n\tverbose: true,\n\tallowUnionTypes: true, // Allow anyOf without explicit type\n} );\n\naddFormats( ajv, [\n\t'date-time',\n\t'email',\n\t'hostname',\n\t'ipv4',\n\t'ipv6',\n\t'uri',\n\t'uuid',\n] );\n\n/**\n * Formats AJV errors into a simple error message.\n * The Abilities API will wrap this with ability_invalid_input/output to match the server side format.\n *\n * @param ajvError The AJV validation error.\n * @param param The base parameter name.\n * @return Simple error message string.\n */\nfunction formatAjvError( ajvError: any, param: string ): string {\n\t// Convert AJV's instancePath format (/0/prop) to an array like format to better match WordPress ([0][prop])\n\tconst instancePath = ajvError.instancePath\n\t\t? ajvError.instancePath.replace( /\\//g, '][' ).replace( /^\\]\\[/, '[' ) +\n\t\t\t']'\n\t\t: '';\n\tconst fullParam = param + instancePath;\n\n\tswitch ( ajvError.keyword ) {\n\t\tcase 'type':\n\t\t\treturn `${ fullParam } is not of type ${ ajvError.params.type }.`;\n\n\t\tcase 'required':\n\t\t\treturn `${ ajvError.params.missingProperty } is a required property of ${ fullParam }.`;\n\n\t\tcase 'additionalProperties':\n\t\t\treturn `${ ajvError.params.additionalProperty } is not a valid property of Object.`;\n\n\t\tcase 'enum':\n\t\t\tconst enumValues = ajvError.params.allowedValues\n\t\t\t\t.map( ( v: any ) =>\n\t\t\t\t\ttypeof v === 'string' ? v : JSON.stringify( v )\n\t\t\t\t)\n\t\t\t\t.join( ', ' );\n\t\t\treturn ajvError.params.allowedValues.length === 1\n\t\t\t\t? `${ fullParam } is not ${ enumValues }.`\n\t\t\t\t: `${ fullParam } is not one of ${ enumValues }.`;\n\n\t\tcase 'pattern':\n\t\t\treturn `${ fullParam } does not match pattern ${ ajvError.params.pattern }.`;\n\n\t\tcase 'format':\n\t\t\tconst format = ajvError.params.format;\n\t\t\tconst formatMessages: Record< string, string > = {\n\t\t\t\temail: 'Invalid email address.',\n\t\t\t\t'date-time': 'Invalid date.',\n\t\t\t\tuuid: `${ fullParam } is not a valid UUID.`,\n\t\t\t\tipv4: `${ fullParam } is not a valid IP address.`,\n\t\t\t\tipv6: `${ fullParam } is not a valid IP address.`,\n\t\t\t\thostname: `${ fullParam } is not a valid hostname.`,\n\t\t\t\turi: `${ fullParam } is not a valid URI.`,\n\t\t\t};\n\t\t\treturn formatMessages[ format ] || `Invalid ${ format }.`;\n\n\t\tcase 'minimum':\n\t\tcase 'exclusiveMinimum':\n\t\t\treturn ajvError.keyword === 'exclusiveMinimum'\n\t\t\t\t? `${ fullParam } must be greater than ${ ajvError.params.limit }`\n\t\t\t\t: `${ fullParam } must be greater than or equal to ${ ajvError.params.limit }`;\n\n\t\tcase 'maximum':\n\t\tcase 'exclusiveMaximum':\n\t\t\treturn ajvError.keyword === 'exclusiveMaximum'\n\t\t\t\t? `${ fullParam } must be less than ${ ajvError.params.limit }`\n\t\t\t\t: `${ fullParam } must be less than or equal to ${ ajvError.params.limit }`;\n\n\t\tcase 'multipleOf':\n\t\t\treturn `${ fullParam } must be a multiple of ${ ajvError.params.multipleOf }.`;\n\n\t\tcase 'anyOf':\n\t\tcase 'oneOf':\n\t\t\treturn `${ fullParam } is invalid (failed ${ ajvError.keyword } validation).`;\n\n\t\tcase 'minLength':\n\t\t\treturn `${ fullParam } must be at least ${\n\t\t\t\tajvError.params.limit\n\t\t\t} character${ ajvError.params.limit === 1 ? '' : 's' } long.`;\n\n\t\tcase 'maxLength':\n\t\t\treturn `${ fullParam } must be at most ${\n\t\t\t\tajvError.params.limit\n\t\t\t} character${ ajvError.params.limit === 1 ? '' : 's' } long.`;\n\n\t\tcase 'minItems':\n\t\t\treturn `${ fullParam } must contain at least ${\n\t\t\t\tajvError.params.limit\n\t\t\t} item${ ajvError.params.limit === 1 ? '' : 's' }.`;\n\n\t\tcase 'maxItems':\n\t\t\treturn `${ fullParam } must contain at most ${\n\t\t\t\tajvError.params.limit\n\t\t\t} item${ ajvError.params.limit === 1 ? '' : 's' }.`;\n\n\t\tcase 'uniqueItems':\n\t\t\treturn `${ fullParam } has duplicate items.`;\n\n\t\tcase 'minProperties':\n\t\t\treturn `${ fullParam } must contain at least ${\n\t\t\t\tajvError.params.limit\n\t\t\t} propert${ ajvError.params.limit === 1 ? 'y' : 'ies' }.`;\n\n\t\tcase 'maxProperties':\n\t\t\treturn `${ fullParam } must contain at most ${\n\t\t\t\tajvError.params.limit\n\t\t\t} propert${ ajvError.params.limit === 1 ? 'y' : 'ies' }.`;\n\n\t\tdefault:\n\t\t\t// Fallback for any unhandled validation keywords\n\t\t\treturn (\n\t\t\t\tajvError.message ||\n\t\t\t\t`${ fullParam } is invalid (failed ${ ajvError.keyword } validation).`\n\t\t\t);\n\t}\n}\n\n/**\n * Validates a value against a JSON Schema.\n *\n * @param value The value to validate.\n * @param args The JSON Schema to validate against.\n * @param param Optional parameter name for error messages.\n * @return True if valid, error message string if invalid.\n */\nexport function validateValueFromSchema(\n\tvalue: any,\n\targs: Record< string, any >,\n\tparam = ''\n): true | ValidationError {\n\t// WordPress server expects schema to be an array/object\n\tif ( ! args || typeof args !== 'object' ) {\n\t\t// WordPress issues a _doing_it_wrong for invalid schema\n\t\t// Match this behavior with console.warn on client-side\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn( `Schema must be an object. Received ${ typeof args }.` );\n\t\t// Continue validation, treating as valid (matching server behavior)\n\t\treturn true;\n\t}\n\n\t// Type validation - WordPress REST API requires type to be set\n\tif ( ! args.type && ! args.anyOf && ! args.oneOf ) {\n\t\t// WordPress issues a _doing_it_wrong but continues\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t`The \"type\" schema keyword for ${ param || 'value' } is required.`\n\t\t);\n\t\treturn true;\n\t}\n\n\ttry {\n\t\tconst { default: defaultValue, ...schemaWithoutDefault } = args;\n\t\tconst validate = ajv.compile( schemaWithoutDefault );\n\t\tconst valid = validate( value === undefined ? defaultValue : value );\n\n\t\tif ( valid ) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Return the first error as a simple message string\n\t\t// The API will wrap this with ability_invalid_input/output\n\t\tif ( validate.errors && validate.errors.length > 0 ) {\n\t\t\t// For anyOf/oneOf, look for the more specific error\n\t\t\tconst anyOfError = validate.errors.find(\n\t\t\t\t( e ) => e.keyword === 'anyOf' || e.keyword === 'oneOf'\n\t\t\t);\n\t\t\tif ( anyOfError ) {\n\t\t\t\treturn formatAjvError( anyOfError, param );\n\t\t\t}\n\t\t\treturn formatAjvError( validate.errors[ 0 ], param );\n\t\t}\n\n\t\treturn `${ param } is invalid.`;\n\t} catch ( error ) {\n\t\t// Handle schema compilation errors\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error( 'Schema compilation error:', error );\n\t\treturn 'Invalid schema provided for validation.';\n\t}\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,0BAAgB;AAChB,yBAAuB;AAGvB,IAAM,MAAM,IAAI,oBAAAA,QAAK;AAAA,EACpB,aAAa;AAAA;AAAA,EACb,aAAa;AAAA,EACb,kBAAkB;AAAA;AAAA,EAClB,WAAW;A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ACiB;AAEzB,MAAK,CAAE,QAAQ,OAAO,SAAS,UAAW;AAIzC,YAAQ,KAAM,sCAAuC,OAAO,IAAK,GAAI;AAErE,WAAO;AAAA,EACR;AAGA,MAAK,CAAE,KAAK,QAAQ,CAAE,KAAK,SAAS,CAAE,KAAK,OAAQ;AAGlD,YAAQ;AAAA,MACP,iCAAkC,SAAS,OAAQ;AAAA,IACpD;AACA,WAAO;AAAA,EACR;AAEA,MAAI;AACH,UAAM,EAAE,SAAS,cAAc,GAAG,qBAAqB,IAAI;AAC3D,UAAM,WAAW,IAAI,QAAS,oBAAqB;AACnD,UAAM,QAAQ,SAAU,UAAU,SAAY,eAAe,KAAM;AAEnE,QAAK,OAAQ;AACZ,aAAO;AAAA,IACR;AAIA,QAAK,SAAS,UAAU,SAAS,OAAO,SAAS,GAAI;AAEpD,YAAM,aAAa,SAAS,OAAO;AAAA,QAClC,CAAE,MAAO,EAAE,YAAY,WAAW,EAAE,YAAY;AAAA,MACjD;AACA,UAAK,YAAa;AACjB,eAAO,eAAgB,YAAY,KAAM;AAAA,MAC1C;AACA,aAAO,eAAgB,SAAS,OAAQ,CAAE,GAAG,KAAM;AAAA,IACpD;AAEA,WAAO,GAAI,KAAM;AAAA,EAClB,SAAU,OAAQ;AAGjB,YAAQ,MAAO,6BAA6B,KAAM;AAClD,WAAO;AAAA,EACR;AACD;",
6
- "names": ["Ajv", "addFormats"]
7
- }
1
+ {"version":3,"file":"validation.cjs","names":["Ajv","addFormats"],"sources":["../src/validation.ts"],"sourcesContent":["/**\n * Schema validation for client-side ability input and output schemas using AJV and ajv-formats.\n *\n * This utility provides validation for JSON Schema draft-04.\n * Rules are configured to support the intersection of common rules between JSON Schema draft-04, WordPress (a subset of JSON Schema draft-04),\n * and various providers like OpenAI and Anthropic.\n *\n * @see https://developer.wordpress.org/rest-api/extending-the-rest-api/schema/#json-schema-basics\n */\nimport Ajv from 'ajv-draft-04';\nimport addFormats from 'ajv-formats';\nimport type { ValidationError } from './types';\n\nconst ajv = new Ajv( {\n\tcoerceTypes: false, // No type coercion - AI should send proper JSON\n\tuseDefaults: true,\n\tremoveAdditional: false, // Keep additional properties\n\tallErrors: true,\n\tverbose: true,\n\tallowUnionTypes: true, // Allow anyOf without explicit type\n} );\n\naddFormats( ajv, [\n\t'date-time',\n\t'email',\n\t'hostname',\n\t'ipv4',\n\t'ipv6',\n\t'uri',\n\t'uuid',\n] );\n\n/**\n * Formats AJV errors into a simple error message.\n * The Abilities API will wrap this with ability_invalid_input/output to match the server side format.\n *\n * @param ajvError The AJV validation error.\n * @param param The base parameter name.\n * @return Simple error message string.\n */\nfunction formatAjvError( ajvError: any, param: string ): string {\n\t// Convert AJV's instancePath format (/0/prop) to an array like format to better match WordPress ([0][prop])\n\tconst instancePath = ajvError.instancePath\n\t\t? ajvError.instancePath.replace( /\\//g, '][' ).replace( /^\\]\\[/, '[' ) +\n\t\t\t']'\n\t\t: '';\n\tconst fullParam = param + instancePath;\n\n\tswitch ( ajvError.keyword ) {\n\t\tcase 'type':\n\t\t\treturn `${ fullParam } is not of type ${ ajvError.params.type }.`;\n\n\t\tcase 'required':\n\t\t\treturn `${ ajvError.params.missingProperty } is a required property of ${ fullParam }.`;\n\n\t\tcase 'additionalProperties':\n\t\t\treturn `${ ajvError.params.additionalProperty } is not a valid property of Object.`;\n\n\t\tcase 'enum':\n\t\t\tconst enumValues = ajvError.params.allowedValues\n\t\t\t\t.map( ( v: any ) =>\n\t\t\t\t\ttypeof v === 'string' ? v : JSON.stringify( v )\n\t\t\t\t)\n\t\t\t\t.join( ', ' );\n\t\t\treturn ajvError.params.allowedValues.length === 1\n\t\t\t\t? `${ fullParam } is not ${ enumValues }.`\n\t\t\t\t: `${ fullParam } is not one of ${ enumValues }.`;\n\n\t\tcase 'pattern':\n\t\t\treturn `${ fullParam } does not match pattern ${ ajvError.params.pattern }.`;\n\n\t\tcase 'format':\n\t\t\tconst format = ajvError.params.format;\n\t\t\tconst formatMessages: Record< string, string > = {\n\t\t\t\temail: 'Invalid email address.',\n\t\t\t\t'date-time': 'Invalid date.',\n\t\t\t\tuuid: `${ fullParam } is not a valid UUID.`,\n\t\t\t\tipv4: `${ fullParam } is not a valid IP address.`,\n\t\t\t\tipv6: `${ fullParam } is not a valid IP address.`,\n\t\t\t\thostname: `${ fullParam } is not a valid hostname.`,\n\t\t\t\turi: `${ fullParam } is not a valid URI.`,\n\t\t\t};\n\t\t\treturn formatMessages[ format ] || `Invalid ${ format }.`;\n\n\t\tcase 'minimum':\n\t\tcase 'exclusiveMinimum':\n\t\t\treturn ajvError.keyword === 'exclusiveMinimum'\n\t\t\t\t? `${ fullParam } must be greater than ${ ajvError.params.limit }`\n\t\t\t\t: `${ fullParam } must be greater than or equal to ${ ajvError.params.limit }`;\n\n\t\tcase 'maximum':\n\t\tcase 'exclusiveMaximum':\n\t\t\treturn ajvError.keyword === 'exclusiveMaximum'\n\t\t\t\t? `${ fullParam } must be less than ${ ajvError.params.limit }`\n\t\t\t\t: `${ fullParam } must be less than or equal to ${ ajvError.params.limit }`;\n\n\t\tcase 'multipleOf':\n\t\t\treturn `${ fullParam } must be a multiple of ${ ajvError.params.multipleOf }.`;\n\n\t\tcase 'anyOf':\n\t\tcase 'oneOf':\n\t\t\treturn `${ fullParam } is invalid (failed ${ ajvError.keyword } validation).`;\n\n\t\tcase 'minLength':\n\t\t\treturn `${ fullParam } must be at least ${\n\t\t\t\tajvError.params.limit\n\t\t\t} character${ ajvError.params.limit === 1 ? '' : 's' } long.`;\n\n\t\tcase 'maxLength':\n\t\t\treturn `${ fullParam } must be at most ${\n\t\t\t\tajvError.params.limit\n\t\t\t} character${ ajvError.params.limit === 1 ? '' : 's' } long.`;\n\n\t\tcase 'minItems':\n\t\t\treturn `${ fullParam } must contain at least ${\n\t\t\t\tajvError.params.limit\n\t\t\t} item${ ajvError.params.limit === 1 ? '' : 's' }.`;\n\n\t\tcase 'maxItems':\n\t\t\treturn `${ fullParam } must contain at most ${\n\t\t\t\tajvError.params.limit\n\t\t\t} item${ ajvError.params.limit === 1 ? '' : 's' }.`;\n\n\t\tcase 'uniqueItems':\n\t\t\treturn `${ fullParam } has duplicate items.`;\n\n\t\tcase 'minProperties':\n\t\t\treturn `${ fullParam } must contain at least ${\n\t\t\t\tajvError.params.limit\n\t\t\t} propert${ ajvError.params.limit === 1 ? 'y' : 'ies' }.`;\n\n\t\tcase 'maxProperties':\n\t\t\treturn `${ fullParam } must contain at most ${\n\t\t\t\tajvError.params.limit\n\t\t\t} propert${ ajvError.params.limit === 1 ? 'y' : 'ies' }.`;\n\n\t\tdefault:\n\t\t\t// Fallback for any unhandled validation keywords\n\t\t\treturn (\n\t\t\t\tajvError.message ||\n\t\t\t\t`${ fullParam } is invalid (failed ${ ajvError.keyword } validation).`\n\t\t\t);\n\t}\n}\n\n/**\n * Validates a value against a JSON Schema.\n *\n * @param value The value to validate.\n * @param args The JSON Schema to validate against.\n * @param param Optional parameter name for error messages.\n * @return True if valid, error message string if invalid.\n */\nexport function validateValueFromSchema(\n\tvalue: any,\n\targs: Record< string, any >,\n\tparam = ''\n): true | ValidationError {\n\t// WordPress server expects schema to be an array/object\n\tif ( ! args || typeof args !== 'object' ) {\n\t\t// WordPress issues a _doing_it_wrong for invalid schema\n\t\t// Match this behavior with console.warn on client-side\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn( `Schema must be an object. Received ${ typeof args }.` );\n\t\t// Continue validation, treating as valid (matching server behavior)\n\t\treturn true;\n\t}\n\n\t// Type validation - WordPress REST API requires type to be set\n\tif ( ! args.type && ! args.anyOf && ! args.oneOf ) {\n\t\t// WordPress issues a _doing_it_wrong but continues\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.warn(\n\t\t\t`The \"type\" schema keyword for ${ param || 'value' } is required.`\n\t\t);\n\t\treturn true;\n\t}\n\n\ttry {\n\t\tconst { default: defaultValue, ...schemaWithoutDefault } = args;\n\t\tconst validate = ajv.compile( schemaWithoutDefault );\n\t\tconst valid = validate( value === undefined ? defaultValue : value );\n\n\t\tif ( valid ) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Return the first error as a simple message string\n\t\t// The API will wrap this with ability_invalid_input/output\n\t\tif ( validate.errors && validate.errors.length > 0 ) {\n\t\t\t// For anyOf/oneOf, look for the more specific error\n\t\t\tconst anyOfError = validate.errors.find(\n\t\t\t\t( e ) => e.keyword === 'anyOf' || e.keyword === 'oneOf'\n\t\t\t);\n\t\t\tif ( anyOfError ) {\n\t\t\t\treturn formatAjvError( anyOfError, param );\n\t\t\t}\n\t\t\treturn formatAjvError( validate.errors[ 0 ], param );\n\t\t}\n\n\t\treturn `${ param } is invalid.`;\n\t} catch ( error ) {\n\t\t// Handle schema compilation errors\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error( 'Schema compilation error:', error );\n\t\treturn 'Invalid schema provided for validation.';\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,MAAM,IAAIA,aAAAA,QAAK;CACpB,aAAa;CACb,aAAa;CACb,kBAAkB;CAClB,WAAW;CACX,SAAS;CACT,iBAAiB;AAClB,CAAE;CAEFC,GAAAA,YAAAA,QAAAA,CAAY,KAAK;CAChB;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAE;;;;;;;;;AAUF,SAAS,eAAgB,UAAe,OAAwB;CAM/D,MAAM,YAAY,SAJG,SAAS,eAC3B,SAAS,aAAa,QAAS,OAAO,IAAK,CAAC,CAAC,QAAS,SAAS,GAAI,IACpE,MACC;CAGH,QAAS,SAAS,SAAlB;EACC,KAAK,QACJ,OAAO,GAAI,UAAW,kBAAmB,SAAS,OAAO,KAAM;EAEhE,KAAK,YACJ,OAAO,GAAI,SAAS,OAAO,gBAAiB,6BAA8B,UAAW;EAEtF,KAAK,wBACJ,OAAO,GAAI,SAAS,OAAO,mBAAoB;EAEhD,KAAK;GACJ,MAAM,aAAa,SAAS,OAAO,cACjC,KAAO,MACP,OAAO,MAAM,WAAW,IAAI,KA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,IAAK;EAElD,KAAK,eACJ,OAAO,GAAI,UAAW;EAEvB,KAAK,iBACJ,OAAO,GAAI,UAAW,yBACrB,SAAS,OAAO,MAChB,UAAW,SAAS,OAAO,UAAU,IAAI,MAAM,MAAO;EAExD,KAAK,iBACJ,OAAO,GAAI,UAAW,wBACrB,SAAS,OAAO,MAChB,UAAW,SAAS,OAAO,UAAU,IAAI,MAAM,MAAO;EAExD,SAEC,OACC,SAAS,WACT,GAAI,UAAW,sBAAuB,SAAS,QAAS;CAE3D;AACD;;;;;;;;;AAUA,SAAgB,wBACf,OACA,MACA,QAAQ,IACiB;CAEzB,IAAK,CAAE,QAAQ,OAAO,SAAS,UAAW;EAIzC,QAAQ,KAAM,sCAAuC,OAAO,KAAM,EAAG;EAErE,OAAO;CACR;CAGA,IAAK,CAAE,KAAK,QAAQ,CAAE,KAAK,SAAS,CAAE,KAAK,OAAQ;EAGlD,QAAQ,KACP,iCAAkC,SAAS,QAAS,cACrD;EACA,OAAO;CACR;CAEA,IAAI;EACH,MAAM,EAAE,SAAS,cAAc,GAAG,yBAAyB;EAC3D,MAAM,WAAW,IAAI,QAAS,oBAAqB;EAGnD,IAFc,SAAU,UAAU,KAAA,IAAY,eAAe,KAEpD,GACR,OAAO;EAKR,IAAK,SAAS,UAAU,SAAS,OAAO,SAAS,GAAI;GAEpD,MAAM,aAAa,SAAS,OAAO,MAChC,MAAO,EAAE,YAAY,WAAW,EAAE,YAAY,OACjD;GACA,IAAK,YACJ,OAAO,eAAgB,YAAY,KAAM;GAE1C,OAAO,eAAgB,SAAS,OAAQ,IAAK,KAAM;EACpD;EAEA,OAAO,GAAI,MAAO;CACnB,SAAU,OAAQ;EAGjB,QAAQ,MAAO,6BAA6B,KAAM;EAClD,OAAO;CACR;AACD"}
@@ -1,109 +1,183 @@
1
- // packages/abilities/src/api.ts
2
1
  import { dispatch, select } from "@wordpress/data";
3
2
  import { sprintf } from "@wordpress/i18n";
4
3
  import { store } from "./store/index.mjs";
5
4
  import { validateValueFromSchema } from "./validation.mjs";
5
+ // packages/abilities/src/api.ts
6
+ /**
7
+ * Get all available abilities with optional filtering.
8
+ *
9
+ * @param args Optional query arguments for filtering abilities.
10
+ * @return Array of matching abilities.
11
+ */
6
12
  function getAbilities(args = {}) {
7
- return select(store).getAbilities(args);
13
+ return select(store).getAbilities(args);
8
14
  }
15
+ /**
16
+ * Get a specific ability by name.
17
+ *
18
+ * @param name The ability name.
19
+ * @return The ability or undefined if not found.
20
+ */
9
21
  function getAbility(name) {
10
- return select(store).getAbility(name);
22
+ return select(store).getAbility(name);
11
23
  }
24
+ /**
25
+ * Get all available ability categories.
26
+ *
27
+ * @return Array of categories.
28
+ */
12
29
  function getAbilityCategories() {
13
- return select(store).getAbilityCategories();
30
+ return select(store).getAbilityCategories();
14
31
  }
32
+ /**
33
+ * Get a specific ability category by slug.
34
+ *
35
+ * @param slug The category slug.
36
+ * @return The category or undefined if not found.
37
+ */
15
38
  function getAbilityCategory(slug) {
16
- return select(store).getAbilityCategory(slug);
39
+ return select(store).getAbilityCategory(slug);
17
40
  }
41
+ /**
42
+ * Register a client-side ability.
43
+ *
44
+ * Client-side abilities are executed locally in the browser and must include
45
+ * a callback function. The ability's category must already be registered.
46
+ *
47
+ * @param ability The ability definition including callback.
48
+ * @throws {Error} If the ability fails validation.
49
+ *
50
+ * @example
51
+ * ```js
52
+ * registerAbility({
53
+ * name: 'my-plugin/navigate',
54
+ * label: 'Navigate to URL',
55
+ * description: 'Navigates to a URL within WordPress admin',
56
+ * category: 'navigation',
57
+ * input_schema: {
58
+ * type: 'object',
59
+ * properties: {
60
+ * url: { type: 'string' }
61
+ * },
62
+ * required: ['url']
63
+ * },
64
+ * callback: async ({ url }) => {
65
+ * window.location.href = url;
66
+ * return { success: true };
67
+ * }
68
+ * });
69
+ * ```
70
+ */
18
71
  function registerAbility(ability) {
19
- dispatch(store).registerAbility(ability);
72
+ dispatch(store).registerAbility(ability);
20
73
  }
74
+ /**
75
+ * Unregister a client-side ability from the store.
76
+ *
77
+ * @param name The ability name to unregister.
78
+ * @throws {Error} If the ability is server-side and cannot be unregistered.
79
+ */
21
80
  function unregisterAbility(name) {
22
- dispatch(store).unregisterAbility(name);
81
+ dispatch(store).unregisterAbility(name);
23
82
  }
83
+ /**
84
+ * Register a client-side ability category.
85
+ *
86
+ * Use this when registering client-side abilities that belong to a category
87
+ * not already defined by the server. Client-side categories are stored
88
+ * alongside server-side categories in the same store.
89
+ *
90
+ * @param slug Category slug (lowercase alphanumeric with dashes only).
91
+ * @param args Category arguments (label, description, optional meta).
92
+ * @throws {Error} If the category fails validation.
93
+ *
94
+ * @example
95
+ * ```js
96
+ * // Register a new category for block editor abilities
97
+ * registerAbilityCategory('block-editor', {
98
+ * label: 'Block Editor',
99
+ * description: 'Abilities for interacting with the WordPress block editor'
100
+ * });
101
+ *
102
+ * // Then register abilities using this category
103
+ * registerAbility({
104
+ * name: 'my-plugin/insert-block',
105
+ * label: 'Insert Block',
106
+ * description: 'Inserts a block into the editor',
107
+ * category: 'block-editor',
108
+ * callback: async ({ blockType }) => {
109
+ * // Implementation
110
+ * return { success: true };
111
+ * }
112
+ * });
113
+ * ```
114
+ */
24
115
  function registerAbilityCategory(slug, args) {
25
- dispatch(store).registerAbilityCategory(slug, args);
116
+ dispatch(store).registerAbilityCategory(slug, args);
26
117
  }
118
+ /**
119
+ * Unregister an ability category.
120
+ *
121
+ * @param slug The category slug to unregister.
122
+ *
123
+ * @example
124
+ * ```js
125
+ * unregisterAbilityCategory('block-editor');
126
+ * ```
127
+ */
27
128
  function unregisterAbilityCategory(slug) {
28
- dispatch(store).unregisterAbilityCategory(slug);
129
+ dispatch(store).unregisterAbilityCategory(slug);
29
130
  }
131
+ /**
132
+ * Execute an ability.
133
+ *
134
+ * Validates input and output against their schemas when defined. For
135
+ * server-side abilities, input is validated on the client first to avoid
136
+ * unnecessary network roundtrips, then both input and output are validated on
137
+ * the server. The client also re-validates the output to ensure data
138
+ * compatibility between server and client.
139
+ *
140
+ * @param name The ability name.
141
+ * @param input Optional input parameters for the ability.
142
+ * @return Promise resolving to the ability execution result.
143
+ * @throws {Error} If the ability is not found, permission is denied, input or output validation fails, or execution throws.
144
+ */
30
145
  async function executeAbility(name, input) {
31
- const ability = getAbility(name);
32
- if (!ability) {
33
- throw new Error(sprintf("Ability not found: %s", name));
34
- }
35
- if (!ability.callback) {
36
- throw new Error(
37
- sprintf(
38
- 'Ability "%s" is missing callback. Please ensure the ability is properly registered.',
39
- ability.name
40
- )
41
- );
42
- }
43
- if (ability.permissionCallback) {
44
- const hasPermission = await ability.permissionCallback(input);
45
- if (!hasPermission) {
46
- const error = new Error(
47
- sprintf("Permission denied for ability: %s", ability.name)
48
- );
49
- error.code = "ability_permission_denied";
50
- throw error;
51
- }
52
- }
53
- if (ability.input_schema) {
54
- const inputValidation = validateValueFromSchema(
55
- input,
56
- ability.input_schema,
57
- "input"
58
- );
59
- if (inputValidation !== true) {
60
- const error = new Error(
61
- sprintf(
62
- 'Ability "%1$s" has invalid input. Reason: %2$s',
63
- ability.name,
64
- inputValidation
65
- )
66
- );
67
- error.code = "ability_invalid_input";
68
- throw error;
69
- }
70
- }
71
- let result;
72
- try {
73
- result = await ability.callback(input);
74
- } catch (error) {
75
- console.error(`Error executing ability ${ability.name}:`, error);
76
- throw error;
77
- }
78
- if (ability.output_schema) {
79
- const outputValidation = validateValueFromSchema(
80
- result,
81
- ability.output_schema,
82
- "output"
83
- );
84
- if (outputValidation !== true) {
85
- const error = new Error(
86
- sprintf(
87
- 'Ability "%1$s" has invalid output. Reason: %2$s',
88
- ability.name,
89
- outputValidation
90
- )
91
- );
92
- error.code = "ability_invalid_output";
93
- throw error;
94
- }
95
- }
96
- return result;
146
+ const ability = getAbility(name);
147
+ if (!ability) throw new Error(sprintf("Ability not found: %s", name));
148
+ if (!ability.callback) throw new Error(sprintf("Ability \"%s\" is missing callback. Please ensure the ability is properly registered.", ability.name));
149
+ if (ability.permissionCallback) {
150
+ if (!await ability.permissionCallback(input)) {
151
+ const error = new Error(sprintf("Permission denied for ability: %s", ability.name));
152
+ error.code = "ability_permission_denied";
153
+ throw error;
154
+ }
155
+ }
156
+ if (ability.input_schema) {
157
+ const inputValidation = validateValueFromSchema(input, ability.input_schema, "input");
158
+ if (inputValidation !== true) {
159
+ const error = new Error(sprintf("Ability \"%1$s\" has invalid input. Reason: %2$s", ability.name, inputValidation));
160
+ error.code = "ability_invalid_input";
161
+ throw error;
162
+ }
163
+ }
164
+ let result;
165
+ try {
166
+ result = await ability.callback(input);
167
+ } catch (error) {
168
+ console.error(`Error executing ability ${ability.name}:`, error);
169
+ throw error;
170
+ }
171
+ if (ability.output_schema) {
172
+ const outputValidation = validateValueFromSchema(result, ability.output_schema, "output");
173
+ if (outputValidation !== true) {
174
+ const error = new Error(sprintf("Ability \"%1$s\" has invalid output. Reason: %2$s", ability.name, outputValidation));
175
+ error.code = "ability_invalid_output";
176
+ throw error;
177
+ }
178
+ }
179
+ return result;
97
180
  }
98
- export {
99
- executeAbility,
100
- getAbilities,
101
- getAbility,
102
- getAbilityCategories,
103
- getAbilityCategory,
104
- registerAbility,
105
- registerAbilityCategory,
106
- unregisterAbility,
107
- unregisterAbilityCategory
108
- };
109
- //# sourceMappingURL=api.mjs.map
181
+ export { executeAbility, getAbilities, getAbility, getAbilityCategories, getAbilityCategory, registerAbility, registerAbilityCategory, unregisterAbility, unregisterAbilityCategory };
182
+
183
+ //# sourceMappingURL=api.mjs.map