@wordpress/abilities 0.26.0 → 0.27.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.
- package/build/api.cjs.map +1 -1
- package/build/store/index.cjs +11 -9
- package/build/store/index.cjs.map +1 -1
- package/build/validation.cjs +40 -9
- package/build/validation.cjs.map +1 -1
- package/build-module/api.mjs.map +1 -1
- package/build-module/validation.mjs +31 -2
- package/build-module/validation.mjs.map +1 -1
- package/build-types/validation.d.ts.map +1 -1
- package/package.json +5 -5
- package/src/tests/validation.test.ts +246 -0
- package/src/validation.ts +46 -9
package/build/api.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.cjs","names":["select","store","sprintf","validateValueFromSchema"],"sources":["../src/api.ts"],"sourcesContent":["import { dispatch, select } from '@wordpress/data';\nimport { sprintf } from '@wordpress/i18n';\nimport { store } from './store';\nimport type {\n\tAbility,\n\tAbilityCategory,\n\tAbilityCategoryArgs,\n\tAbilitiesQueryArgs,\n\tAbilityInput,\n\tAbilityOutput,\n} from './types';\nimport { validateValueFromSchema } from './validation';\n\n/**\n * Get all available abilities with optional filtering.\n *\n * @param args Optional query arguments for filtering abilities.\n * @return Array of matching abilities.\n */\nexport function getAbilities( args: AbilitiesQueryArgs = {} ): Ability[] {\n\treturn select( store ).getAbilities( args );\n}\n\n/**\n * Get a specific ability by name.\n *\n * @param name The ability name.\n * @return The ability or undefined if not found.\n */\nexport function getAbility( name: string ): Ability | undefined {\n\treturn select( store ).getAbility( name );\n}\n\n/**\n * Get all available ability categories.\n *\n * @return Array of categories.\n */\nexport function getAbilityCategories(): AbilityCategory[] {\n\treturn select( store ).getAbilityCategories();\n}\n\n/**\n * Get a specific ability category by slug.\n *\n * @param slug The category slug.\n * @return The category or undefined if not found.\n */\nexport function getAbilityCategory(\n\tslug: string\n): AbilityCategory | undefined {\n\treturn select( store ).getAbilityCategory( slug );\n}\n\n/**\n * Register a client-side ability.\n *\n * Client-side abilities are executed locally in the browser and must include\n * a callback function. The ability's category must already be registered.\n *\n * @param ability The ability definition including callback.\n * @throws {Error} If the ability fails validation.\n *\n * @example\n * ```js\n * registerAbility({\n * name: 'my-plugin/navigate',\n * label: 'Navigate to URL',\n * description: 'Navigates to a URL within WordPress admin',\n * category: 'navigation',\n * input_schema: {\n * type: 'object',\n * properties: {\n * url: { type: 'string' }\n * },\n * required: ['url']\n * },\n * callback: async ({ url }) => {\n * window.location.href = url;\n * return { success: true };\n * }\n * });\n * ```\n */\nexport function registerAbility( ability: Ability ): void {\n\tdispatch( store ).registerAbility( ability );\n}\n\n/**\n * Unregister a client-side ability from the store.\n *\n * @param name The ability name to unregister.\n * @throws {Error} If the ability is server-side and cannot be unregistered.\n */\nexport function unregisterAbility( name: string ): void {\n\tdispatch( store ).unregisterAbility( name );\n}\n\n/**\n * Register a client-side ability category.\n *\n * Use this when registering client-side abilities that belong to a category\n * not already defined by the server. Client-side categories are stored\n * alongside server-side categories in the same store.\n *\n * @param slug Category slug (lowercase alphanumeric with dashes only).\n * @param args Category arguments (label, description, optional meta).\n * @throws {Error} If the category fails validation.\n *\n * @example\n * ```js\n * // Register a new category for block editor abilities\n * registerAbilityCategory('block-editor', {\n * label: 'Block Editor',\n * description: 'Abilities for interacting with the WordPress block editor'\n * });\n *\n * // Then register abilities using this category\n * registerAbility({\n * name: 'my-plugin/insert-block',\n * label: 'Insert Block',\n * description: 'Inserts a block into the editor',\n * category: 'block-editor',\n * callback: async ({ blockType }) => {\n * // Implementation\n * return { success: true };\n * }\n * });\n * ```\n */\nexport function registerAbilityCategory(\n\tslug: string,\n\targs: AbilityCategoryArgs\n): void {\n\tdispatch( store ).registerAbilityCategory( slug, args );\n}\n\n/**\n * Unregister an ability category.\n *\n * @param slug The category slug to unregister.\n *\n * @example\n * ```js\n * unregisterAbilityCategory('block-editor');\n * ```\n */\nexport function unregisterAbilityCategory( slug: string ): void {\n\tdispatch( store ).unregisterAbilityCategory( slug );\n}\n\n/**\n * Execute an ability.\n *\n * Validates input and output against their schemas when defined. For\n * server-side abilities, input is validated on the client first to avoid\n * unnecessary network roundtrips, then both input and output are validated on\n * the server. The client also re-validates the output to ensure data\n * compatibility between server and client.\n *\n * @param name The ability name.\n * @param input Optional input parameters for the ability.\n * @return Promise resolving to the ability execution result.\n * @throws {Error} If the ability is not found, permission is denied, input or output validation fails, or execution throws.\n */\nexport async function executeAbility(\n\tname: string,\n\tinput?: AbilityInput\n): Promise< AbilityOutput > {\n\tconst ability = getAbility( name );\n\tif ( ! ability ) {\n\t\tthrow new Error( sprintf( 'Ability not found: %s', name ) );\n\t}\n\n\tif ( ! ability.callback ) {\n\t\tthrow new Error(\n\t\t\tsprintf(\n\t\t\t\t'Ability \"%s\" is missing callback. Please ensure the ability is properly registered.',\n\t\t\t\tability.name\n\t\t\t)\n\t\t);\n\t}\n\n\t// Check permission callback if defined\n\tif ( ability.permissionCallback ) {\n\t\tconst hasPermission = await ability.permissionCallback( input );\n\t\tif ( ! hasPermission ) {\n\t\t\tconst error = new Error(\n\t\t\t\tsprintf( 'Permission denied for ability: %s', ability.name )\n\t\t\t);\n\t\t\t( error as any ).code = 'ability_permission_denied';\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// Validate input\n\tif ( ability.input_schema ) {\n\t\tconst inputValidation = validateValueFromSchema(\n\t\t\tinput,\n\t\t\tability.input_schema,\n\t\t\t'input'\n\t\t);\n\t\tif ( inputValidation !== true ) {\n\t\t\tconst error = new Error(\n\t\t\t\tsprintf(\n\t\t\t\t\t'Ability \"%1$s\" has invalid input. Reason: %2$s',\n\t\t\t\t\tability.name,\n\t\t\t\t\tinputValidation\n\t\t\t\t)\n\t\t\t);\n\t\t\t( error as any ).code = 'ability_invalid_input';\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// Execute the ability\n\tlet result: AbilityOutput;\n\ttry {\n\t\tresult = await ability.callback( input );\n\t} catch ( error ) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error( `Error executing ability ${ ability.name }:`, error );\n\t\tthrow error;\n\t}\n\n\t// Validate output\n\tif ( ability.output_schema ) {\n\t\tconst outputValidation = validateValueFromSchema(\n\t\t\tresult,\n\t\t\tability.output_schema,\n\t\t\t'output'\n\t\t);\n\t\tif ( outputValidation !== true ) {\n\t\t\tconst error = new Error(\n\t\t\t\tsprintf(\n\t\t\t\t\t'Ability \"%1$s\" has invalid output. Reason: %2$s',\n\t\t\t\t\tability.name,\n\t\t\t\t\toutputValidation\n\t\t\t\t)\n\t\t\t);\n\t\t\t( error as any ).code = 'ability_invalid_output';\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\treturn result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmBA,SAAgB,aAAc,OAA2B,CAAC,GAAe;CACxE,QAAA,GAAOA,gBAAAA,OAAAA,CAAQC,iBAAAA,KAAM,CAAC,CAAC,aAAc,IAAK;AAC3C;;;;;;;AAQA,SAAgB,WAAY,MAAoC;CAC/D,QAAA,GAAOD,gBAAAA,OAAAA,CAAQC,iBAAAA,KAAM,CAAC,CAAC,WAAY,IAAK;AACzC;;;;;;AAOA,SAAgB,uBAA0C;CACzD,QAAA,GAAOD,gBAAAA,OAAAA,CAAQC,iBAAAA,KAAM,CAAC,CAAC,qBAAqB;AAC7C;;;;;;;AAQA,SAAgB,mBACf,MAC8B;CAC9B,QAAA,GAAOD,gBAAAA,OAAAA,CAAQC,iBAAAA,KAAM,CAAC,CAAC,mBAAoB,IAAK;AACjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,gBAAiB,SAAyB;
|
|
1
|
+
{"version":3,"file":"api.cjs","names":["select","store","dispatch","sprintf","validateValueFromSchema"],"sources":["../src/api.ts"],"sourcesContent":["import { dispatch, select } from '@wordpress/data';\nimport { sprintf } from '@wordpress/i18n';\nimport { store } from './store';\nimport type {\n\tAbility,\n\tAbilityCategory,\n\tAbilityCategoryArgs,\n\tAbilitiesQueryArgs,\n\tAbilityInput,\n\tAbilityOutput,\n} from './types';\nimport { validateValueFromSchema } from './validation';\n\n/**\n * Get all available abilities with optional filtering.\n *\n * @param args Optional query arguments for filtering abilities.\n * @return Array of matching abilities.\n */\nexport function getAbilities( args: AbilitiesQueryArgs = {} ): Ability[] {\n\treturn select( store ).getAbilities( args );\n}\n\n/**\n * Get a specific ability by name.\n *\n * @param name The ability name.\n * @return The ability or undefined if not found.\n */\nexport function getAbility( name: string ): Ability | undefined {\n\treturn select( store ).getAbility( name );\n}\n\n/**\n * Get all available ability categories.\n *\n * @return Array of categories.\n */\nexport function getAbilityCategories(): AbilityCategory[] {\n\treturn select( store ).getAbilityCategories();\n}\n\n/**\n * Get a specific ability category by slug.\n *\n * @param slug The category slug.\n * @return The category or undefined if not found.\n */\nexport function getAbilityCategory(\n\tslug: string\n): AbilityCategory | undefined {\n\treturn select( store ).getAbilityCategory( slug );\n}\n\n/**\n * Register a client-side ability.\n *\n * Client-side abilities are executed locally in the browser and must include\n * a callback function. The ability's category must already be registered.\n *\n * @param ability The ability definition including callback.\n * @throws {Error} If the ability fails validation.\n *\n * @example\n * ```js\n * registerAbility({\n * name: 'my-plugin/navigate',\n * label: 'Navigate to URL',\n * description: 'Navigates to a URL within WordPress admin',\n * category: 'navigation',\n * input_schema: {\n * type: 'object',\n * properties: {\n * url: { type: 'string' }\n * },\n * required: ['url']\n * },\n * callback: async ({ url }) => {\n * window.location.href = url;\n * return { success: true };\n * }\n * });\n * ```\n */\nexport function registerAbility( ability: Ability ): void {\n\tdispatch( store ).registerAbility( ability );\n}\n\n/**\n * Unregister a client-side ability from the store.\n *\n * @param name The ability name to unregister.\n * @throws {Error} If the ability is server-side and cannot be unregistered.\n */\nexport function unregisterAbility( name: string ): void {\n\tdispatch( store ).unregisterAbility( name );\n}\n\n/**\n * Register a client-side ability category.\n *\n * Use this when registering client-side abilities that belong to a category\n * not already defined by the server. Client-side categories are stored\n * alongside server-side categories in the same store.\n *\n * @param slug Category slug (lowercase alphanumeric with dashes only).\n * @param args Category arguments (label, description, optional meta).\n * @throws {Error} If the category fails validation.\n *\n * @example\n * ```js\n * // Register a new category for block editor abilities\n * registerAbilityCategory('block-editor', {\n * label: 'Block Editor',\n * description: 'Abilities for interacting with the WordPress block editor'\n * });\n *\n * // Then register abilities using this category\n * registerAbility({\n * name: 'my-plugin/insert-block',\n * label: 'Insert Block',\n * description: 'Inserts a block into the editor',\n * category: 'block-editor',\n * callback: async ({ blockType }) => {\n * // Implementation\n * return { success: true };\n * }\n * });\n * ```\n */\nexport function registerAbilityCategory(\n\tslug: string,\n\targs: AbilityCategoryArgs\n): void {\n\tdispatch( store ).registerAbilityCategory( slug, args );\n}\n\n/**\n * Unregister an ability category.\n *\n * @param slug The category slug to unregister.\n *\n * @example\n * ```js\n * unregisterAbilityCategory('block-editor');\n * ```\n */\nexport function unregisterAbilityCategory( slug: string ): void {\n\tdispatch( store ).unregisterAbilityCategory( slug );\n}\n\n/**\n * Execute an ability.\n *\n * Validates input and output against their schemas when defined. For\n * server-side abilities, input is validated on the client first to avoid\n * unnecessary network roundtrips, then both input and output are validated on\n * the server. The client also re-validates the output to ensure data\n * compatibility between server and client.\n *\n * @param name The ability name.\n * @param input Optional input parameters for the ability.\n * @return Promise resolving to the ability execution result.\n * @throws {Error} If the ability is not found, permission is denied, input or output validation fails, or execution throws.\n */\nexport async function executeAbility(\n\tname: string,\n\tinput?: AbilityInput\n): Promise< AbilityOutput > {\n\tconst ability = getAbility( name );\n\tif ( ! ability ) {\n\t\tthrow new Error( sprintf( 'Ability not found: %s', name ) );\n\t}\n\n\tif ( ! ability.callback ) {\n\t\tthrow new Error(\n\t\t\tsprintf(\n\t\t\t\t'Ability \"%s\" is missing callback. Please ensure the ability is properly registered.',\n\t\t\t\tability.name\n\t\t\t)\n\t\t);\n\t}\n\n\t// Check permission callback if defined\n\tif ( ability.permissionCallback ) {\n\t\tconst hasPermission = await ability.permissionCallback( input );\n\t\tif ( ! hasPermission ) {\n\t\t\tconst error = new Error(\n\t\t\t\tsprintf( 'Permission denied for ability: %s', ability.name )\n\t\t\t);\n\t\t\t( error as any ).code = 'ability_permission_denied';\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// Validate input\n\tif ( ability.input_schema ) {\n\t\tconst inputValidation = validateValueFromSchema(\n\t\t\tinput,\n\t\t\tability.input_schema,\n\t\t\t'input'\n\t\t);\n\t\tif ( inputValidation !== true ) {\n\t\t\tconst error = new Error(\n\t\t\t\tsprintf(\n\t\t\t\t\t'Ability \"%1$s\" has invalid input. Reason: %2$s',\n\t\t\t\t\tability.name,\n\t\t\t\t\tinputValidation\n\t\t\t\t)\n\t\t\t);\n\t\t\t( error as any ).code = 'ability_invalid_input';\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// Execute the ability\n\tlet result: AbilityOutput;\n\ttry {\n\t\tresult = await ability.callback( input );\n\t} catch ( error ) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error( `Error executing ability ${ ability.name }:`, error );\n\t\tthrow error;\n\t}\n\n\t// Validate output\n\tif ( ability.output_schema ) {\n\t\tconst outputValidation = validateValueFromSchema(\n\t\t\tresult,\n\t\t\tability.output_schema,\n\t\t\t'output'\n\t\t);\n\t\tif ( outputValidation !== true ) {\n\t\t\tconst error = new Error(\n\t\t\t\tsprintf(\n\t\t\t\t\t'Ability \"%1$s\" has invalid output. Reason: %2$s',\n\t\t\t\t\tability.name,\n\t\t\t\t\toutputValidation\n\t\t\t\t)\n\t\t\t);\n\t\t\t( error as any ).code = 'ability_invalid_output';\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\treturn result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmBA,SAAgB,aAAc,OAA2B,CAAC,GAAe;CACxE,QAAA,GAAOA,gBAAAA,OAAAA,CAAQC,iBAAAA,KAAM,CAAC,CAAC,aAAc,IAAK;AAC3C;;;;;;;AAQA,SAAgB,WAAY,MAAoC;CAC/D,QAAA,GAAOD,gBAAAA,OAAAA,CAAQC,iBAAAA,KAA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A,gBAAAA,QAAAA,CAAS,qCAAqC,QAAQ,IAAK,CAC5D;GACE,MAAe,OAAO;GACxB,MAAM;EACP;;CAID,IAAK,QAAQ,cAAe;EAC3B,MAAM,mBAAA,GAAkBC,gBAAAA,wBAAAA,CACvB,OACA,QAAQ,cACR,OACD;EACA,IAAK,oBAAoB,MAAO;GAC/B,MAAM,QAAQ,IAAI,OAAA,GACjBD,gBAAAA,QAAAA,CACC,oDACA,QAAQ,MACR,eACD,CACD;GACE,MAAe,OAAO;GACxB,MAAM;EACP;CACD;CAGA,IAAI;CACJ,IAAI;EACH,SAAS,MAAM,QAAQ,SAAU,KAAM;CACxC,SAAU,OAAQ;EAEjB,QAAQ,MAAO,2BAA4B,QAAQ,KAAM,IAAI,KAAM;EACnE,MAAM;CACP;CAGA,IAAK,QAAQ,eAAgB;EAC5B,MAAM,oBAAA,GAAmBC,gBAAAA,wBAAAA,CACxB,QACA,QAAQ,eACR,QACD;EACA,IAAK,qBAAqB,MAAO;GAChC,MAAM,QAAQ,IAAI,OAAA,GACjBD,gBAAAA,QAAAA,CACC,qDACA,QAAQ,MACR,gBACD,CACD;GACE,MAAe,OAAO;GACxB,MAAM;EACP;CACD;CAEA,OAAO;AACR"}
|
package/build/store/index.cjs
CHANGED
|
@@ -11,12 +11,14 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
|
11
11
|
var __getProtoOf = Object.getPrototypeOf;
|
|
12
12
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
13
13
|
var __copyProps = (to, from, except, desc) => {
|
|
14
|
-
if (from && typeof from === "object" || typeof from === "function")
|
|
15
|
-
key
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
14
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
15
|
+
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) {
|
|
16
|
+
desc = __getOwnPropDesc(from, key);
|
|
17
|
+
__defProp(to, key, {
|
|
18
|
+
get: desc && desc.get && !desc.configurable ? desc.get : () => from[key],
|
|
19
|
+
enumerable: !desc || desc.enumerable
|
|
20
|
+
});
|
|
21
|
+
}
|
|
20
22
|
}
|
|
21
23
|
return to;
|
|
22
24
|
};
|
|
@@ -26,12 +28,12 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
26
28
|
}) : target, mod));
|
|
27
29
|
let _wordpress_data = require("@wordpress/data");
|
|
28
30
|
let __reducer_ts = require("./reducer.cjs");
|
|
29
|
-
__reducer_ts = __toESM(__reducer_ts);
|
|
30
31
|
let __actions_ts = require("./actions.cjs");
|
|
31
|
-
__actions_ts = __toESM(__actions_ts);
|
|
32
32
|
let __selectors_ts = require("./selectors.cjs");
|
|
33
|
-
__selectors_ts = __toESM(__selectors_ts);
|
|
34
33
|
let __constants_ts = require("./constants.cjs");
|
|
34
|
+
__reducer_ts = __toESM(__reducer_ts);
|
|
35
|
+
__actions_ts = __toESM(__actions_ts);
|
|
36
|
+
__selectors_ts = __toESM(__selectors_ts);
|
|
35
37
|
// packages/abilities/src/store/index.ts
|
|
36
38
|
/**
|
|
37
39
|
* The abilities store definition.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["createReduxStore","STORE_NAME","register"],"sources":["../../src/store/index.ts"],"sourcesContent":["import { createReduxStore, register } from '@wordpress/data';\nimport reducer from './reducer';\nimport * as actions from './actions';\nimport * as selectors from './selectors';\nimport { STORE_NAME } from './constants';\n\n/**\n * The abilities store definition.\n */\nexport const store = createReduxStore( STORE_NAME, {\n\treducer,\n\tactions,\n\tselectors,\n} );\n\nregister( store );\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["createReduxStore","STORE_NAME","reducer","actions","selectors","register"],"sources":["../../src/store/index.ts"],"sourcesContent":["import { createReduxStore, register } from '@wordpress/data';\nimport reducer from './reducer';\nimport * as actions from './actions';\nimport * as selectors from './selectors';\nimport { STORE_NAME } from './constants';\n\n/**\n * The abilities store definition.\n */\nexport const store = createReduxStore( STORE_NAME, {\n\treducer,\n\tactions,\n\tselectors,\n} );\n\nregister( store );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,MAAa,SAAA,GAAQA,gBAAAA,iBAAAA,CAAkBC,eAAAA,YAAY;CAClDC,SAAAA,aAAAA;CACAC,SAAAA;CACAC,WAAAA;AACD,CAAE;CAEFC,GAAAA,gBAAAA,SAAAA,CAAU,KAAM"}
|
package/build/validation.cjs
CHANGED
|
@@ -11,12 +11,14 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
|
11
11
|
var __getProtoOf = Object.getPrototypeOf;
|
|
12
12
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
13
13
|
var __copyProps = (to, from, except, desc) => {
|
|
14
|
-
if (from && typeof from === "object" || typeof from === "function")
|
|
15
|
-
key
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
14
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
15
|
+
for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) {
|
|
16
|
+
desc = __getOwnPropDesc(from, key);
|
|
17
|
+
__defProp(to, key, {
|
|
18
|
+
get: desc && desc.get && !desc.configurable ? desc.get : () => from[key],
|
|
19
|
+
enumerable: !desc || desc.enumerable
|
|
20
|
+
});
|
|
21
|
+
}
|
|
20
22
|
}
|
|
21
23
|
return to;
|
|
22
24
|
};
|
|
@@ -25,8 +27,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
25
27
|
enumerable: true
|
|
26
28
|
}) : target, mod));
|
|
27
29
|
let ajv_draft_04 = require("ajv-draft-04");
|
|
28
|
-
ajv_draft_04 = __toESM(ajv_draft_04);
|
|
29
30
|
let ajv_formats = require("ajv-formats");
|
|
31
|
+
ajv_draft_04 = __toESM(ajv_draft_04);
|
|
30
32
|
ajv_formats = __toESM(ajv_formats);
|
|
31
33
|
// packages/abilities/src/validation.ts
|
|
32
34
|
/**
|
|
@@ -47,14 +49,43 @@ const ajv = new ajv_draft_04.default({
|
|
|
47
49
|
allowUnionTypes: true
|
|
48
50
|
});
|
|
49
51
|
(0, ajv_formats.default)(ajv, [
|
|
50
|
-
"date-time",
|
|
51
52
|
"email",
|
|
52
53
|
"hostname",
|
|
53
54
|
"ipv4",
|
|
54
55
|
"ipv6",
|
|
55
|
-
"uri",
|
|
56
56
|
"uuid"
|
|
57
57
|
]);
|
|
58
|
+
ajv.addFormat("date-time", ajv_formats.default.get("iso-date-time"));
|
|
59
|
+
/**
|
|
60
|
+
* Checks whether a value is an absolute URL, as the `uri` format requires.
|
|
61
|
+
*
|
|
62
|
+
* The URL parser of the platform decides, instead of the `uri` check of
|
|
63
|
+
* ajv-formats. That check follows RFC 3986 to the letter and is ASCII only, so
|
|
64
|
+
* it rejects URLs that WordPress serves and browsers open: a permalink under a
|
|
65
|
+
* permalink structure or a post type slug with non-ASCII characters, the URL of
|
|
66
|
+
* a file with a non-ASCII name, or any URL of a site whose address is an
|
|
67
|
+
* internationalized domain name saved as typed.
|
|
68
|
+
*
|
|
69
|
+
* WordPress declares `format: uri` on such values, for example the `link` of a
|
|
70
|
+
* post or a user in the output of the core abilities, and does not check that
|
|
71
|
+
* format when it validates on the server. A stricter check here would fail a
|
|
72
|
+
* call the server completed. Values that are not absolute URLs, such as an empty
|
|
73
|
+
* string or a relative URL, are still rejected.
|
|
74
|
+
*
|
|
75
|
+
* @see https://url.spec.whatwg.org/#valid-url-string
|
|
76
|
+
*
|
|
77
|
+
* @param value The string to check.
|
|
78
|
+
* @return Whether the value is an absolute URL.
|
|
79
|
+
*/
|
|
80
|
+
function isAbsoluteUrl(value) {
|
|
81
|
+
try {
|
|
82
|
+
new URL(value);
|
|
83
|
+
return true;
|
|
84
|
+
} catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
ajv.addFormat("uri", isAbsoluteUrl);
|
|
58
89
|
/**
|
|
59
90
|
* Formats AJV errors into a simple error message.
|
|
60
91
|
* The Abilities API will wrap this with ability_invalid_input/output to match the server side format.
|
package/build/validation.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,G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;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
|
+
{"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, [ 'email', 'hostname', 'ipv4', 'ipv6', 'uuid' ] );\n\n/*\n * The `date-time` format is checked with the `iso-date-time` check of\n * ajv-formats, which is the `date-time` check with the time zone offset made\n * optional.\n *\n * The `date-time` check requires the offset, as RFC 3339 does. WordPress does\n * not: `rest_parse_date()`, which validates the format on the server, accepts\n * `2026-10-21T09:30:00`, and the REST API returns `date` and `date_gmt` in\n * that form. With the strict check, a date that the server accepts and\n * returns fails validation on the client.\n */\najv.addFormat( 'date-time', addFormats.get( 'iso-date-time' ) );\n\n/**\n * Checks whether a value is an absolute URL, as the `uri` format requires.\n *\n * The URL parser of the platform decides, instead of the `uri` check of\n * ajv-formats. That check follows RFC 3986 to the letter and is ASCII only, so\n * it rejects URLs that WordPress serves and browsers open: a permalink under a\n * permalink structure or a post type slug with non-ASCII characters, the URL of\n * a file with a non-ASCII name, or any URL of a site whose address is an\n * internationalized domain name saved as typed.\n *\n * WordPress declares `format: uri` on such values, for example the `link` of a\n * post or a user in the output of the core abilities, and does not check that\n * format when it validates on the server. A stricter check here would fail a\n * call the server completed. Values that are not absolute URLs, such as an empty\n * string or a relative URL, are still rejected.\n *\n * @see https://url.spec.whatwg.org/#valid-url-string\n *\n * @param value The string to check.\n * @return Whether the value is an absolute URL.\n */\nfunction isAbsoluteUrl( value: string ): boolean {\n\ttry {\n\t\tnew URL( value );\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\najv.addFormat( 'uri', isAbsoluteUrl );\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;CAAE;CAAS;CAAY;CAAQ;CAAQ;AAAO,CAAE;AAajE,IAAI,UAAW,aAAaA,YAAAA,QAAW,IAAK,eAAgB,CAAE;;;;;;;;;;;;;;;;;;;;;;AAuB9D,SAAS,c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AyB;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"}
|
package/build-module/api.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.mjs","names":[],"sources":["../src/api.ts"],"sourcesContent":["import { dispatch, select } from '@wordpress/data';\nimport { sprintf } from '@wordpress/i18n';\nimport { store } from './store';\nimport type {\n\tAbility,\n\tAbilityCategory,\n\tAbilityCategoryArgs,\n\tAbilitiesQueryArgs,\n\tAbilityInput,\n\tAbilityOutput,\n} from './types';\nimport { validateValueFromSchema } from './validation';\n\n/**\n * Get all available abilities with optional filtering.\n *\n * @param args Optional query arguments for filtering abilities.\n * @return Array of matching abilities.\n */\nexport function getAbilities( args: AbilitiesQueryArgs = {} ): Ability[] {\n\treturn select( store ).getAbilities( args );\n}\n\n/**\n * Get a specific ability by name.\n *\n * @param name The ability name.\n * @return The ability or undefined if not found.\n */\nexport function getAbility( name: string ): Ability | undefined {\n\treturn select( store ).getAbility( name );\n}\n\n/**\n * Get all available ability categories.\n *\n * @return Array of categories.\n */\nexport function getAbilityCategories(): AbilityCategory[] {\n\treturn select( store ).getAbilityCategories();\n}\n\n/**\n * Get a specific ability category by slug.\n *\n * @param slug The category slug.\n * @return The category or undefined if not found.\n */\nexport function getAbilityCategory(\n\tslug: string\n): AbilityCategory | undefined {\n\treturn select( store ).getAbilityCategory( slug );\n}\n\n/**\n * Register a client-side ability.\n *\n * Client-side abilities are executed locally in the browser and must include\n * a callback function. The ability's category must already be registered.\n *\n * @param ability The ability definition including callback.\n * @throws {Error} If the ability fails validation.\n *\n * @example\n * ```js\n * registerAbility({\n * name: 'my-plugin/navigate',\n * label: 'Navigate to URL',\n * description: 'Navigates to a URL within WordPress admin',\n * category: 'navigation',\n * input_schema: {\n * type: 'object',\n * properties: {\n * url: { type: 'string' }\n * },\n * required: ['url']\n * },\n * callback: async ({ url }) => {\n * window.location.href = url;\n * return { success: true };\n * }\n * });\n * ```\n */\nexport function registerAbility( ability: Ability ): void {\n\tdispatch( store ).registerAbility( ability );\n}\n\n/**\n * Unregister a client-side ability from the store.\n *\n * @param name The ability name to unregister.\n * @throws {Error} If the ability is server-side and cannot be unregistered.\n */\nexport function unregisterAbility( name: string ): void {\n\tdispatch( store ).unregisterAbility( name );\n}\n\n/**\n * Register a client-side ability category.\n *\n * Use this when registering client-side abilities that belong to a category\n * not already defined by the server. Client-side categories are stored\n * alongside server-side categories in the same store.\n *\n * @param slug Category slug (lowercase alphanumeric with dashes only).\n * @param args Category arguments (label, description, optional meta).\n * @throws {Error} If the category fails validation.\n *\n * @example\n * ```js\n * // Register a new category for block editor abilities\n * registerAbilityCategory('block-editor', {\n * label: 'Block Editor',\n * description: 'Abilities for interacting with the WordPress block editor'\n * });\n *\n * // Then register abilities using this category\n * registerAbility({\n * name: 'my-plugin/insert-block',\n * label: 'Insert Block',\n * description: 'Inserts a block into the editor',\n * category: 'block-editor',\n * callback: async ({ blockType }) => {\n * // Implementation\n * return { success: true };\n * }\n * });\n * ```\n */\nexport function registerAbilityCategory(\n\tslug: string,\n\targs: AbilityCategoryArgs\n): void {\n\tdispatch( store ).registerAbilityCategory( slug, args );\n}\n\n/**\n * Unregister an ability category.\n *\n * @param slug The category slug to unregister.\n *\n * @example\n * ```js\n * unregisterAbilityCategory('block-editor');\n * ```\n */\nexport function unregisterAbilityCategory( slug: string ): void {\n\tdispatch( store ).unregisterAbilityCategory( slug );\n}\n\n/**\n * Execute an ability.\n *\n * Validates input and output against their schemas when defined. For\n * server-side abilities, input is validated on the client first to avoid\n * unnecessary network roundtrips, then both input and output are validated on\n * the server. The client also re-validates the output to ensure data\n * compatibility between server and client.\n *\n * @param name The ability name.\n * @param input Optional input parameters for the ability.\n * @return Promise resolving to the ability execution result.\n * @throws {Error} If the ability is not found, permission is denied, input or output validation fails, or execution throws.\n */\nexport async function executeAbility(\n\tname: string,\n\tinput?: AbilityInput\n): Promise< AbilityOutput > {\n\tconst ability = getAbility( name );\n\tif ( ! ability ) {\n\t\tthrow new Error( sprintf( 'Ability not found: %s', name ) );\n\t}\n\n\tif ( ! ability.callback ) {\n\t\tthrow new Error(\n\t\t\tsprintf(\n\t\t\t\t'Ability \"%s\" is missing callback. Please ensure the ability is properly registered.',\n\t\t\t\tability.name\n\t\t\t)\n\t\t);\n\t}\n\n\t// Check permission callback if defined\n\tif ( ability.permissionCallback ) {\n\t\tconst hasPermission = await ability.permissionCallback( input );\n\t\tif ( ! hasPermission ) {\n\t\t\tconst error = new Error(\n\t\t\t\tsprintf( 'Permission denied for ability: %s', ability.name )\n\t\t\t);\n\t\t\t( error as any ).code = 'ability_permission_denied';\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// Validate input\n\tif ( ability.input_schema ) {\n\t\tconst inputValidation = validateValueFromSchema(\n\t\t\tinput,\n\t\t\tability.input_schema,\n\t\t\t'input'\n\t\t);\n\t\tif ( inputValidation !== true ) {\n\t\t\tconst error = new Error(\n\t\t\t\tsprintf(\n\t\t\t\t\t'Ability \"%1$s\" has invalid input. Reason: %2$s',\n\t\t\t\t\tability.name,\n\t\t\t\t\tinputValidation\n\t\t\t\t)\n\t\t\t);\n\t\t\t( error as any ).code = 'ability_invalid_input';\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// Execute the ability\n\tlet result: AbilityOutput;\n\ttry {\n\t\tresult = await ability.callback( input );\n\t} catch ( error ) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error( `Error executing ability ${ ability.name }:`, error );\n\t\tthrow error;\n\t}\n\n\t// Validate output\n\tif ( ability.output_schema ) {\n\t\tconst outputValidation = validateValueFromSchema(\n\t\t\tresult,\n\t\t\tability.output_schema,\n\t\t\t'output'\n\t\t);\n\t\tif ( outputValidation !== true ) {\n\t\t\tconst error = new Error(\n\t\t\t\tsprintf(\n\t\t\t\t\t'Ability \"%1$s\" has invalid output. Reason: %2$s',\n\t\t\t\t\tability.name,\n\t\t\t\t\toutputValidation\n\t\t\t\t)\n\t\t\t);\n\t\t\t( error as any ).code = 'ability_invalid_output';\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\treturn result;\n}\n"],"mappings":";;;;;;;;;;;AAmBA,SAAgB,aAAc,OAA2B,CAAC,GAAe;CACxE,OAAO,OAAQ,KAAM,CAAC,CAAC,aAAc,IAAK;AAC3C;;;;;;;AAQA,SAAgB,WAAY,MAAoC;CAC/D,OAAO,OAAQ,KAAM,CAAC,CAAC,WAAY,IAAK;AACzC;;;;;;AAOA,SAAgB,uBAA0C;CACzD,OAAO,OAAQ,KAAM,CAAC,CAAC,qBAAqB;AAC7C;;;;;;;AAQA,SAAgB,mBACf,MAC8B;CAC9B,OAAO,OAAQ,KAAM,CAAC,CAAC,mBAAoB,IAAK;AACjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,gBAAiB,SAAyB;CACzD,SAAU,KAAM,CAAC,CAAC,gBAAiB,OAAQ;AAC5C;;;;;;;AAQA,SAAgB,kBAAmB,MAAqB;CACvD,SAAU,KAAM,CAAC,CAAC,kBAAmB,IAAK;AAC3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,wBACf,MACA,MACO;CACP,SAAU,KAAM,CAAC,CAAC,wBAAyB,MAAM,IAAK;AACvD;;;;;;;;;;;AAYA,SAAgB,0BAA2B,MAAqB;CAC/D,SAAU,KAAM,CAAC,CAAC,0BAA2B,IAAK;AACnD;;;;;;;;;;;;;;;AAgBA,eAAsB,eACrB,MACA,OAC2B;CAC3B,MAAM,UAAU,WAAY,IAAK;CACjC,IAAK,CAAE,SACN,MAAM,IAAI,MAAO,QAAS,yBAAyB,IAAK,CAAE;CAG3D,IAAK,CAAE,QAAQ,UACd,MAAM,IAAI,MACT,QACC,yFACA,QAAQ,IACT,CACD;CAID,IAAK,QAAQ,oBAEP;MAAA,CAAE,MADqB,QAAQ,mBAAoB,KAAM,GACvC;GACtB,MAAM,QAAQ,IAAI,MACjB,QAAS,qCAAqC,QAAQ,IAAK,CAC5D;
|
|
1
|
+
{"version":3,"file":"api.mjs","names":[],"sources":["../src/api.ts"],"sourcesContent":["import { dispatch, select } from '@wordpress/data';\nimport { sprintf } from '@wordpress/i18n';\nimport { store } from './store';\nimport type {\n\tAbility,\n\tAbilityCategory,\n\tAbilityCategoryArgs,\n\tAbilitiesQueryArgs,\n\tAbilityInput,\n\tAbilityOutput,\n} from './types';\nimport { validateValueFromSchema } from './validation';\n\n/**\n * Get all available abilities with optional filtering.\n *\n * @param args Optional query arguments for filtering abilities.\n * @return Array of matching abilities.\n */\nexport function getAbilities( args: AbilitiesQueryArgs = {} ): Ability[] {\n\treturn select( store ).getAbilities( args );\n}\n\n/**\n * Get a specific ability by name.\n *\n * @param name The ability name.\n * @return The ability or undefined if not found.\n */\nexport function getAbility( name: string ): Ability | undefined {\n\treturn select( store ).getAbility( name );\n}\n\n/**\n * Get all available ability categories.\n *\n * @return Array of categories.\n */\nexport function getAbilityCategories(): AbilityCategory[] {\n\treturn select( store ).getAbilityCategories();\n}\n\n/**\n * Get a specific ability category by slug.\n *\n * @param slug The category slug.\n * @return The category or undefined if not found.\n */\nexport function getAbilityCategory(\n\tslug: string\n): AbilityCategory | undefined {\n\treturn select( store ).getAbilityCategory( slug );\n}\n\n/**\n * Register a client-side ability.\n *\n * Client-side abilities are executed locally in the browser and must include\n * a callback function. The ability's category must already be registered.\n *\n * @param ability The ability definition including callback.\n * @throws {Error} If the ability fails validation.\n *\n * @example\n * ```js\n * registerAbility({\n * name: 'my-plugin/navigate',\n * label: 'Navigate to URL',\n * description: 'Navigates to a URL within WordPress admin',\n * category: 'navigation',\n * input_schema: {\n * type: 'object',\n * properties: {\n * url: { type: 'string' }\n * },\n * required: ['url']\n * },\n * callback: async ({ url }) => {\n * window.location.href = url;\n * return { success: true };\n * }\n * });\n * ```\n */\nexport function registerAbility( ability: Ability ): void {\n\tdispatch( store ).registerAbility( ability );\n}\n\n/**\n * Unregister a client-side ability from the store.\n *\n * @param name The ability name to unregister.\n * @throws {Error} If the ability is server-side and cannot be unregistered.\n */\nexport function unregisterAbility( name: string ): void {\n\tdispatch( store ).unregisterAbility( name );\n}\n\n/**\n * Register a client-side ability category.\n *\n * Use this when registering client-side abilities that belong to a category\n * not already defined by the server. Client-side categories are stored\n * alongside server-side categories in the same store.\n *\n * @param slug Category slug (lowercase alphanumeric with dashes only).\n * @param args Category arguments (label, description, optional meta).\n * @throws {Error} If the category fails validation.\n *\n * @example\n * ```js\n * // Register a new category for block editor abilities\n * registerAbilityCategory('block-editor', {\n * label: 'Block Editor',\n * description: 'Abilities for interacting with the WordPress block editor'\n * });\n *\n * // Then register abilities using this category\n * registerAbility({\n * name: 'my-plugin/insert-block',\n * label: 'Insert Block',\n * description: 'Inserts a block into the editor',\n * category: 'block-editor',\n * callback: async ({ blockType }) => {\n * // Implementation\n * return { success: true };\n * }\n * });\n * ```\n */\nexport function registerAbilityCategory(\n\tslug: string,\n\targs: AbilityCategoryArgs\n): void {\n\tdispatch( store ).registerAbilityCategory( slug, args );\n}\n\n/**\n * Unregister an ability category.\n *\n * @param slug The category slug to unregister.\n *\n * @example\n * ```js\n * unregisterAbilityCategory('block-editor');\n * ```\n */\nexport function unregisterAbilityCategory( slug: string ): void {\n\tdispatch( store ).unregisterAbilityCategory( slug );\n}\n\n/**\n * Execute an ability.\n *\n * Validates input and output against their schemas when defined. For\n * server-side abilities, input is validated on the client first to avoid\n * unnecessary network roundtrips, then both input and output are validated on\n * the server. The client also re-validates the output to ensure data\n * compatibility between server and client.\n *\n * @param name The ability name.\n * @param input Optional input parameters for the ability.\n * @return Promise resolving to the ability execution result.\n * @throws {Error} If the ability is not found, permission is denied, input or output validation fails, or execution throws.\n */\nexport async function executeAbility(\n\tname: string,\n\tinput?: AbilityInput\n): Promise< AbilityOutput > {\n\tconst ability = getAbility( name );\n\tif ( ! ability ) {\n\t\tthrow new Error( sprintf( 'Ability not found: %s', name ) );\n\t}\n\n\tif ( ! ability.callback ) {\n\t\tthrow new Error(\n\t\t\tsprintf(\n\t\t\t\t'Ability \"%s\" is missing callback. Please ensure the ability is properly registered.',\n\t\t\t\tability.name\n\t\t\t)\n\t\t);\n\t}\n\n\t// Check permission callback if defined\n\tif ( ability.permissionCallback ) {\n\t\tconst hasPermission = await ability.permissionCallback( input );\n\t\tif ( ! hasPermission ) {\n\t\t\tconst error = new Error(\n\t\t\t\tsprintf( 'Permission denied for ability: %s', ability.name )\n\t\t\t);\n\t\t\t( error as any ).code = 'ability_permission_denied';\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// Validate input\n\tif ( ability.input_schema ) {\n\t\tconst inputValidation = validateValueFromSchema(\n\t\t\tinput,\n\t\t\tability.input_schema,\n\t\t\t'input'\n\t\t);\n\t\tif ( inputValidation !== true ) {\n\t\t\tconst error = new Error(\n\t\t\t\tsprintf(\n\t\t\t\t\t'Ability \"%1$s\" has invalid input. Reason: %2$s',\n\t\t\t\t\tability.name,\n\t\t\t\t\tinputValidation\n\t\t\t\t)\n\t\t\t);\n\t\t\t( error as any ).code = 'ability_invalid_input';\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// Execute the ability\n\tlet result: AbilityOutput;\n\ttry {\n\t\tresult = await ability.callback( input );\n\t} catch ( error ) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.error( `Error executing ability ${ ability.name }:`, error );\n\t\tthrow error;\n\t}\n\n\t// Validate output\n\tif ( ability.output_schema ) {\n\t\tconst outputValidation = validateValueFromSchema(\n\t\t\tresult,\n\t\t\tability.output_schema,\n\t\t\t'output'\n\t\t);\n\t\tif ( outputValidation !== true ) {\n\t\t\tconst error = new Error(\n\t\t\t\tsprintf(\n\t\t\t\t\t'Ability \"%1$s\" has invalid output. Reason: %2$s',\n\t\t\t\t\tability.name,\n\t\t\t\t\toutputValidation\n\t\t\t\t)\n\t\t\t);\n\t\t\t( error as any ).code = 'ability_invalid_output';\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\treturn result;\n}\n"],"mappings":";;;;;;;;;;;AAmBA,SAAgB,aAAc,OAA2B,CAAC,GAAe;CACxE,OAAO,OAAQ,KAAM,CAAC,CAAC,aAAc,IAAK;AAC3C;;;;;;;AAQA,SAAgB,WAAY,MAAoC;CAC/D,OAAO,OAAQ,KAAM,CAAC,CAAC,WAAY,IAAK;AACzC;;;;;;AAOA,SAAgB,uBAA0C;CACzD,OAAO,OAAQ,KAAM,CAAC,CAAC,qBAAqB;AAC7C;;;;;;;AAQA,SAAgB,mBACf,MAC8B;CAC9B,OAAO,OAAQ,KAAM,CAAC,CAAC,mBAAoB,IAAK;AACjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,gBAAiB,SAAyB;CACzD,SAAU,KAAM,CAAC,CAAC,gBAAiB,OAAQ;AAC5C;;;;;;;AAQA,SAAgB,kBAAmB,MAAqB;CACvD,SAAU,KAAM,CAAC,CAAC,kBAAmB,IAAK;AAC3C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,wBACf,MACA,MACO;CACP,SAAU,KAAM,CAAC,CAAC,wBAAyB,MAAM,IAAK;AACvD;;;;;;;;;;;AAYA,SAAgB,0BAA2B,MAAqB;CAC/D,SAAU,KAAM,CAAC,CAAC,0BAA2B,IAAK;AACnD;;;;;;;;;;;;;;;AAgBA,eAAsB,eACrB,MACA,OAC2B;CAC3B,MAAM,UAAU,WAAY,IAAK;CACjC,IAAK,CAAE,SACN,MAAM,IAAI,MAAO,QAAS,yBAAyB,IAAK,CAAE;CAG3D,IAAK,CAAE,QAAQ,UACd,MAAM,IAAI,MACT,QACC,yFACA,QAAQ,IACT,CACD;CAID,IAAK,QAAQ,oBAEP;MAAA,CAAE,MADqB,QAAQ,mBAAoB,KAAM,GACvC;GACtB,MAAM,QAAQ,IAAI,MACjB,QAAS,qCAAqC,QAAQ,IAAK,CAC5D;GACE,MAAe,OAAO;GACxB,MAAM;EACP;;CAID,IAAK,QAAQ,cAAe;EAC3B,MAAM,kBAAkB,wBACvB,OACA,QAAQ,cACR,OACD;EACA,IAAK,oBAAoB,MAAO;GAC/B,MAAM,QAAQ,IAAI,MACjB,QACC,oDACA,QAAQ,MACR,eACD,CACD;GACE,MAAe,OAAO;GACxB,MAAM;EACP;CACD;CAGA,IAAI;CACJ,IAAI;EACH,SAAS,MAAM,QAAQ,SAAU,KAAM;CACxC,SAAU,OAAQ;EAEjB,QAAQ,MAAO,2BAA4B,QAAQ,KAAM,IAAI,KAAM;EACnE,MAAM;CACP;CAGA,IAAK,QAAQ,eAAgB;EAC5B,MAAM,mBAAmB,wBACxB,QACA,QAAQ,eACR,QACD;EACA,IAAK,qBAAqB,MAAO;GAChC,MAAM,QAAQ,IAAI,MACjB,QACC,qDACA,QAAQ,MACR,gBACD,CACD;GACE,MAAe,OAAO;GACxB,MAAM;EACP;CACD;CAEA,OAAO;AACR"}
|
|
@@ -19,14 +19,43 @@ const ajv = new Ajv({
|
|
|
19
19
|
allowUnionTypes: true
|
|
20
20
|
});
|
|
21
21
|
addFormats(ajv, [
|
|
22
|
-
"date-time",
|
|
23
22
|
"email",
|
|
24
23
|
"hostname",
|
|
25
24
|
"ipv4",
|
|
26
25
|
"ipv6",
|
|
27
|
-
"uri",
|
|
28
26
|
"uuid"
|
|
29
27
|
]);
|
|
28
|
+
ajv.addFormat("date-time", addFormats.get("iso-date-time"));
|
|
29
|
+
/**
|
|
30
|
+
* Checks whether a value is an absolute URL, as the `uri` format requires.
|
|
31
|
+
*
|
|
32
|
+
* The URL parser of the platform decides, instead of the `uri` check of
|
|
33
|
+
* ajv-formats. That check follows RFC 3986 to the letter and is ASCII only, so
|
|
34
|
+
* it rejects URLs that WordPress serves and browsers open: a permalink under a
|
|
35
|
+
* permalink structure or a post type slug with non-ASCII characters, the URL of
|
|
36
|
+
* a file with a non-ASCII name, or any URL of a site whose address is an
|
|
37
|
+
* internationalized domain name saved as typed.
|
|
38
|
+
*
|
|
39
|
+
* WordPress declares `format: uri` on such values, for example the `link` of a
|
|
40
|
+
* post or a user in the output of the core abilities, and does not check that
|
|
41
|
+
* format when it validates on the server. A stricter check here would fail a
|
|
42
|
+
* call the server completed. Values that are not absolute URLs, such as an empty
|
|
43
|
+
* string or a relative URL, are still rejected.
|
|
44
|
+
*
|
|
45
|
+
* @see https://url.spec.whatwg.org/#valid-url-string
|
|
46
|
+
*
|
|
47
|
+
* @param value The string to check.
|
|
48
|
+
* @return Whether the value is an absolute URL.
|
|
49
|
+
*/
|
|
50
|
+
function isAbsoluteUrl(value) {
|
|
51
|
+
try {
|
|
52
|
+
new URL(value);
|
|
53
|
+
return true;
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
ajv.addFormat("uri", isAbsoluteUrl);
|
|
30
59
|
/**
|
|
31
60
|
* Formats AJV errors into a simple error message.
|
|
32
61
|
* The Abilities API will wrap this with ability_invalid_input/output to match the server side format.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.mjs","names":[],"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,IAAI,IAAK;CACpB,aAAa;CACb,aAAa;CACb,kBAAkB;CAClB,WAAW;CACX,SAAS;CACT,iBAAiB;AAClB,CAAE;AAEF,WAAY,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,IAA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KAAK,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
|
+
{"version":3,"file":"validation.mjs","names":[],"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, [ 'email', 'hostname', 'ipv4', 'ipv6', 'uuid' ] );\n\n/*\n * The `date-time` format is checked with the `iso-date-time` check of\n * ajv-formats, which is the `date-time` check with the time zone offset made\n * optional.\n *\n * The `date-time` check requires the offset, as RFC 3339 does. WordPress does\n * not: `rest_parse_date()`, which validates the format on the server, accepts\n * `2026-10-21T09:30:00`, and the REST API returns `date` and `date_gmt` in\n * that form. With the strict check, a date that the server accepts and\n * returns fails validation on the client.\n */\najv.addFormat( 'date-time', addFormats.get( 'iso-date-time' ) );\n\n/**\n * Checks whether a value is an absolute URL, as the `uri` format requires.\n *\n * The URL parser of the platform decides, instead of the `uri` check of\n * ajv-formats. That check follows RFC 3986 to the letter and is ASCII only, so\n * it rejects URLs that WordPress serves and browsers open: a permalink under a\n * permalink structure or a post type slug with non-ASCII characters, the URL of\n * a file with a non-ASCII name, or any URL of a site whose address is an\n * internationalized domain name saved as typed.\n *\n * WordPress declares `format: uri` on such values, for example the `link` of a\n * post or a user in the output of the core abilities, and does not check that\n * format when it validates on the server. A stricter check here would fail a\n * call the server completed. Values that are not absolute URLs, such as an empty\n * string or a relative URL, are still rejected.\n *\n * @see https://url.spec.whatwg.org/#valid-url-string\n *\n * @param value The string to check.\n * @return Whether the value is an absolute URL.\n */\nfunction isAbsoluteUrl( value: string ): boolean {\n\ttry {\n\t\tnew URL( value );\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\najv.addFormat( 'uri', isAbsoluteUrl );\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,IAAI,IAAK;CACpB,aAAa;CACb,aAAa;CACb,kBAAkB;CAClB,WAAW;CACX,SAAS;CACT,iBAAiB;AAClB,CAAE;AAEF,WAAY,KAAK;CAAE;CAAS;CAAY;CAAQ;CAAQ;AAAO,CAAE;AAajE,IAAI,UAAW,aAAa,WAAW,IAAK,eAAgB,CAAE;;;;;;;;;;;;;;;;;;;;;;AAuB9D,SAAS,cAAe,OAAyB;CAChD,IAAI;EACH,IAAI,IAAK,KAAM;EACf,OAAO;CACR,QAAQ;EACP,OAAO;CACR;AACD;AAEA,IAAI,UAAW,OAAO,aAAc;;;;;;;;;AAUpC,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,KAAK,UAAW,CAAE,CAC/C,CAAC,CACA,KAAM,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validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AA2K/C;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CACtC,KAAK,EAAE,GAAG,EACV,IAAI,EAAE,MAAM,CAAE,MAAM,EAAE,GAAG,CAAE,EAC3B,KAAK,SAAK,GACR,IAAI,GAAG,eAAe,CAkDxB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wordpress/abilities",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.27.0",
|
|
4
4
|
"description": "JavaScript client for WordPress Abilities API.",
|
|
5
5
|
"author": "The WordPress Contributors",
|
|
6
6
|
"license": "GPL-2.0-or-later",
|
|
@@ -43,14 +43,14 @@
|
|
|
43
43
|
},
|
|
44
44
|
"types": "build-types",
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@wordpress/data": "^11.
|
|
47
|
-
"@wordpress/i18n": "^7.
|
|
46
|
+
"@wordpress/data": "^11.3.0",
|
|
47
|
+
"@wordpress/i18n": "^7.3.0",
|
|
48
48
|
"ajv": "^8.20.0",
|
|
49
49
|
"ajv-draft-04": "^1.0.0",
|
|
50
50
|
"ajv-formats": "^3.0.1"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
|
-
"vitest": "^5.1.
|
|
53
|
+
"vitest": "^5.1.1"
|
|
54
54
|
},
|
|
55
55
|
"peerDependencies": {
|
|
56
56
|
"@types/react": "^18 || ^19",
|
|
@@ -69,5 +69,5 @@
|
|
|
69
69
|
"publishConfig": {
|
|
70
70
|
"access": "public"
|
|
71
71
|
},
|
|
72
|
-
"gitHead": "
|
|
72
|
+
"gitHead": "7f19202f61aeba8f4bdce892a1a0df485ad76e2b"
|
|
73
73
|
}
|
|
@@ -196,6 +196,144 @@ describe( 'validateValueFromSchema', () => {
|
|
|
196
196
|
);
|
|
197
197
|
} );
|
|
198
198
|
|
|
199
|
+
// The forms of a date that `rest_parse_date()` accepts on the server.
|
|
200
|
+
it.each( [
|
|
201
|
+
[ 'a date in UTC', '2026-10-21T08:30:00Z' ],
|
|
202
|
+
[ 'a date with an offset', '2026-10-21T09:30:00+01:00' ],
|
|
203
|
+
[ 'a date with a negative offset', '2026-10-21T05:00:00-03:30' ],
|
|
204
|
+
[
|
|
205
|
+
'a date with a fraction of a second',
|
|
206
|
+
'2026-10-21T08:30:00.123Z',
|
|
207
|
+
],
|
|
208
|
+
[ 'a date without an offset', '2026-10-21T09:30:00' ],
|
|
209
|
+
[
|
|
210
|
+
'a date without an offset, with a fraction of a second',
|
|
211
|
+
'2026-10-21T09:30:00.123',
|
|
212
|
+
],
|
|
213
|
+
[
|
|
214
|
+
'a date without an offset, with a space before the time',
|
|
215
|
+
'2026-10-21 09:30:00',
|
|
216
|
+
],
|
|
217
|
+
] )( 'should accept %s as a date-time', ( _description, value ) => {
|
|
218
|
+
const schema = { type: 'string', format: 'date-time' };
|
|
219
|
+
expect( validateValueFromSchema( value, schema ) ).toBe( true );
|
|
220
|
+
} );
|
|
221
|
+
|
|
222
|
+
it.each( [
|
|
223
|
+
[ 'an empty string', '' ],
|
|
224
|
+
[ 'a date without a time', '2026-10-21' ],
|
|
225
|
+
[ 'a time without a date', '09:30:00' ],
|
|
226
|
+
[ 'a time without seconds', '2026-10-21T09:30' ],
|
|
227
|
+
[ 'a month that does not exist', '2026-13-01T09:30:00' ],
|
|
228
|
+
[ 'a day that does not exist', '2026-02-30T09:30:00' ],
|
|
229
|
+
[ 'an hour that does not exist', '2026-10-21T25:00:00' ],
|
|
230
|
+
[ 'a date in words', 'October 21, 2026' ],
|
|
231
|
+
] )( 'should reject %s as a date-time', ( _description, value ) => {
|
|
232
|
+
const schema = { type: 'string', format: 'date-time' };
|
|
233
|
+
expect( validateValueFromSchema( value, schema ) ).toBe(
|
|
234
|
+
'Invalid date.'
|
|
235
|
+
);
|
|
236
|
+
} );
|
|
237
|
+
|
|
238
|
+
it( 'should validate the dates in an input shaped like the input of a core ability', () => {
|
|
239
|
+
// The shape proposed for `core/content-create`: a date in the site's time, in GMT, or both.
|
|
240
|
+
const schema = {
|
|
241
|
+
type: 'object',
|
|
242
|
+
required: [ 'data' ],
|
|
243
|
+
properties: {
|
|
244
|
+
data: {
|
|
245
|
+
type: 'object',
|
|
246
|
+
properties: {
|
|
247
|
+
title: { type: 'string' },
|
|
248
|
+
date: {
|
|
249
|
+
type: 'object',
|
|
250
|
+
additionalProperties: false,
|
|
251
|
+
minProperties: 1,
|
|
252
|
+
properties: {
|
|
253
|
+
site: {
|
|
254
|
+
type: 'string',
|
|
255
|
+
format: 'date-time',
|
|
256
|
+
},
|
|
257
|
+
gmt: {
|
|
258
|
+
type: 'string',
|
|
259
|
+
format: 'date-time',
|
|
260
|
+
},
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
},
|
|
264
|
+
},
|
|
265
|
+
},
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
// Without an offset: 09:30 in the site's time, as `date` is read in the REST API.
|
|
269
|
+
expect(
|
|
270
|
+
validateValueFromSchema(
|
|
271
|
+
{
|
|
272
|
+
data: {
|
|
273
|
+
title: 'Launch notes',
|
|
274
|
+
date: { site: '2026-10-21T09:30:00' },
|
|
275
|
+
},
|
|
276
|
+
},
|
|
277
|
+
schema,
|
|
278
|
+
'input'
|
|
279
|
+
)
|
|
280
|
+
).toBe( true );
|
|
281
|
+
|
|
282
|
+
// With an offset: the same moment, whatever the time zone of the site.
|
|
283
|
+
expect(
|
|
284
|
+
validateValueFromSchema(
|
|
285
|
+
{
|
|
286
|
+
data: {
|
|
287
|
+
title: 'Launch notes',
|
|
288
|
+
date: {
|
|
289
|
+
site: '2026-10-21T09:30:00+01:00',
|
|
290
|
+
gmt: '2026-10-21T08:30:00Z',
|
|
291
|
+
},
|
|
292
|
+
},
|
|
293
|
+
},
|
|
294
|
+
schema,
|
|
295
|
+
'input'
|
|
296
|
+
)
|
|
297
|
+
).toBe( true );
|
|
298
|
+
|
|
299
|
+
expect(
|
|
300
|
+
validateValueFromSchema(
|
|
301
|
+
{
|
|
302
|
+
data: {
|
|
303
|
+
title: 'Launch notes',
|
|
304
|
+
date: { site: '2026-10-21' },
|
|
305
|
+
},
|
|
306
|
+
},
|
|
307
|
+
schema,
|
|
308
|
+
'input'
|
|
309
|
+
)
|
|
310
|
+
).toBe( 'Invalid date.' );
|
|
311
|
+
} );
|
|
312
|
+
|
|
313
|
+
it( 'should validate the dates in a result that has them in the form the REST API returns', () => {
|
|
314
|
+
// `date` and `date_gmt` of a post in the REST API have no offset.
|
|
315
|
+
const schema = {
|
|
316
|
+
type: 'object',
|
|
317
|
+
properties: {
|
|
318
|
+
id: { type: 'integer' },
|
|
319
|
+
date: { type: 'string', format: 'date-time' },
|
|
320
|
+
date_gmt: { type: 'string', format: 'date-time' },
|
|
321
|
+
},
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
expect(
|
|
325
|
+
validateValueFromSchema(
|
|
326
|
+
{
|
|
327
|
+
id: 1,
|
|
328
|
+
date: '2026-10-21T09:30:00',
|
|
329
|
+
date_gmt: '2026-10-21T08:30:00',
|
|
330
|
+
},
|
|
331
|
+
schema,
|
|
332
|
+
'output'
|
|
333
|
+
)
|
|
334
|
+
).toBe( true );
|
|
335
|
+
} );
|
|
336
|
+
|
|
199
337
|
it( 'should validate UUID format', () => {
|
|
200
338
|
const schema = { type: 'string', format: 'uuid' };
|
|
201
339
|
expect(
|
|
@@ -241,6 +379,114 @@ describe( 'validateValueFromSchema', () => {
|
|
|
241
379
|
' is not a valid URI.'
|
|
242
380
|
);
|
|
243
381
|
} );
|
|
382
|
+
|
|
383
|
+
// The forms a WordPress URL takes in the output of an ability.
|
|
384
|
+
it.each( [
|
|
385
|
+
[
|
|
386
|
+
'a pretty permalink',
|
|
387
|
+
'https://example.com/2026/11/hello-world/',
|
|
388
|
+
],
|
|
389
|
+
[ 'a plain permalink', 'https://example.com/?p=123' ],
|
|
390
|
+
[
|
|
391
|
+
'a plain permalink of a custom post type',
|
|
392
|
+
'https://example.com/?post_type=book&p=5',
|
|
393
|
+
],
|
|
394
|
+
[
|
|
395
|
+
'a percent-encoded slug',
|
|
396
|
+
'https://example.com/%e6%96%87%e7%ab%a0/',
|
|
397
|
+
],
|
|
398
|
+
[ 'a local site with a port', 'http://localhost:8889/?page_id=2' ],
|
|
399
|
+
[
|
|
400
|
+
'an avatar with query arguments',
|
|
401
|
+
'https://secure.gravatar.com/avatar/0bc83cb571cd1c50ba6f3e8a78ef1346?s=96&d=mm&r=g',
|
|
402
|
+
],
|
|
403
|
+
[
|
|
404
|
+
'a permalink structure with non-ASCII characters',
|
|
405
|
+
'https://example.com/блог/hello-world/',
|
|
406
|
+
],
|
|
407
|
+
[
|
|
408
|
+
'a post type slug with non-ASCII characters',
|
|
409
|
+
'https://example.com/produkte-größe/stuhl/',
|
|
410
|
+
],
|
|
411
|
+
[
|
|
412
|
+
'an internationalized domain name',
|
|
413
|
+
'https://例え.jp/hello-world/',
|
|
414
|
+
],
|
|
415
|
+
[
|
|
416
|
+
'an internationalized domain name in Punycode',
|
|
417
|
+
'https://xn--r8jz45g.jp/hello-world/',
|
|
418
|
+
],
|
|
419
|
+
[
|
|
420
|
+
'a file with a non-ASCII name',
|
|
421
|
+
'https://example.com/wp-content/uploads/2026/11/写真.jpg',
|
|
422
|
+
],
|
|
423
|
+
] )( 'should accept %s as a URI', ( _description, value ) => {
|
|
424
|
+
const schema = { type: 'string', format: 'uri' };
|
|
425
|
+
expect( validateValueFromSchema( value, schema ) ).toBe( true );
|
|
426
|
+
} );
|
|
427
|
+
|
|
428
|
+
it.each( [
|
|
429
|
+
[ 'an empty string', '' ],
|
|
430
|
+
[ 'a root-relative URL', '/2026/11/hello-world/' ],
|
|
431
|
+
[ 'a protocol-relative URL', '//example.com/hello-world/' ],
|
|
432
|
+
[ 'a URL without a host', 'https://' ],
|
|
433
|
+
[ 'a host with a space', 'https://exa mple.com/' ],
|
|
434
|
+
] )( 'should reject %s as a URI', ( _description, value ) => {
|
|
435
|
+
const schema = { type: 'string', format: 'uri' };
|
|
436
|
+
expect( validateValueFromSchema( value, schema ) ).toBe(
|
|
437
|
+
' is not a valid URI.'
|
|
438
|
+
);
|
|
439
|
+
} );
|
|
440
|
+
|
|
441
|
+
it( 'should validate the links in a result shaped like the output of a core ability', () => {
|
|
442
|
+
// The shape of `core/content-query`: a page of posts, each with a `link`.
|
|
443
|
+
const schema = {
|
|
444
|
+
type: 'object',
|
|
445
|
+
required: [ 'items' ],
|
|
446
|
+
properties: {
|
|
447
|
+
items: {
|
|
448
|
+
type: 'array',
|
|
449
|
+
items: {
|
|
450
|
+
type: 'object',
|
|
451
|
+
properties: {
|
|
452
|
+
id: { type: 'integer' },
|
|
453
|
+
link: { type: 'string', format: 'uri' },
|
|
454
|
+
},
|
|
455
|
+
},
|
|
456
|
+
},
|
|
457
|
+
},
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
expect(
|
|
461
|
+
validateValueFromSchema(
|
|
462
|
+
{
|
|
463
|
+
items: [
|
|
464
|
+
{ id: 1, link: 'https://example.com/hello-world/' },
|
|
465
|
+
{
|
|
466
|
+
id: 2,
|
|
467
|
+
link: 'https://example.com/блог/привет-мир/',
|
|
468
|
+
},
|
|
469
|
+
{ id: 3, link: 'https://例え.jp/?p=3' },
|
|
470
|
+
],
|
|
471
|
+
},
|
|
472
|
+
schema,
|
|
473
|
+
'output'
|
|
474
|
+
)
|
|
475
|
+
).toBe( true );
|
|
476
|
+
|
|
477
|
+
expect(
|
|
478
|
+
validateValueFromSchema(
|
|
479
|
+
{
|
|
480
|
+
items: [
|
|
481
|
+
{ id: 1, link: 'https://example.com/hello-world/' },
|
|
482
|
+
{ id: 2, link: '/hello-world/' },
|
|
483
|
+
],
|
|
484
|
+
},
|
|
485
|
+
schema,
|
|
486
|
+
'output'
|
|
487
|
+
)
|
|
488
|
+
).toBe( 'output[items][1][link] is not a valid URI.' );
|
|
489
|
+
} );
|
|
244
490
|
} );
|
|
245
491
|
|
|
246
492
|
describe( 'pattern validation', () => {
|
package/src/validation.ts
CHANGED
|
@@ -20,15 +20,52 @@ const ajv = new Ajv( {
|
|
|
20
20
|
allowUnionTypes: true, // Allow anyOf without explicit type
|
|
21
21
|
} );
|
|
22
22
|
|
|
23
|
-
addFormats( ajv, [
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
23
|
+
addFormats( ajv, [ 'email', 'hostname', 'ipv4', 'ipv6', 'uuid' ] );
|
|
24
|
+
|
|
25
|
+
/*
|
|
26
|
+
* The `date-time` format is checked with the `iso-date-time` check of
|
|
27
|
+
* ajv-formats, which is the `date-time` check with the time zone offset made
|
|
28
|
+
* optional.
|
|
29
|
+
*
|
|
30
|
+
* The `date-time` check requires the offset, as RFC 3339 does. WordPress does
|
|
31
|
+
* not: `rest_parse_date()`, which validates the format on the server, accepts
|
|
32
|
+
* `2026-10-21T09:30:00`, and the REST API returns `date` and `date_gmt` in
|
|
33
|
+
* that form. With the strict check, a date that the server accepts and
|
|
34
|
+
* returns fails validation on the client.
|
|
35
|
+
*/
|
|
36
|
+
ajv.addFormat( 'date-time', addFormats.get( 'iso-date-time' ) );
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Checks whether a value is an absolute URL, as the `uri` format requires.
|
|
40
|
+
*
|
|
41
|
+
* The URL parser of the platform decides, instead of the `uri` check of
|
|
42
|
+
* ajv-formats. That check follows RFC 3986 to the letter and is ASCII only, so
|
|
43
|
+
* it rejects URLs that WordPress serves and browsers open: a permalink under a
|
|
44
|
+
* permalink structure or a post type slug with non-ASCII characters, the URL of
|
|
45
|
+
* a file with a non-ASCII name, or any URL of a site whose address is an
|
|
46
|
+
* internationalized domain name saved as typed.
|
|
47
|
+
*
|
|
48
|
+
* WordPress declares `format: uri` on such values, for example the `link` of a
|
|
49
|
+
* post or a user in the output of the core abilities, and does not check that
|
|
50
|
+
* format when it validates on the server. A stricter check here would fail a
|
|
51
|
+
* call the server completed. Values that are not absolute URLs, such as an empty
|
|
52
|
+
* string or a relative URL, are still rejected.
|
|
53
|
+
*
|
|
54
|
+
* @see https://url.spec.whatwg.org/#valid-url-string
|
|
55
|
+
*
|
|
56
|
+
* @param value The string to check.
|
|
57
|
+
* @return Whether the value is an absolute URL.
|
|
58
|
+
*/
|
|
59
|
+
function isAbsoluteUrl( value: string ): boolean {
|
|
60
|
+
try {
|
|
61
|
+
new URL( value );
|
|
62
|
+
return true;
|
|
63
|
+
} catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
ajv.addFormat( 'uri', isAbsoluteUrl );
|
|
32
69
|
|
|
33
70
|
/**
|
|
34
71
|
* Formats AJV errors into a simple error message.
|