From ad01e3b4995f70cef6f079bf9229bd3547143c25 Mon Sep 17 00:00:00 2001 From: maz Date: Sat, 29 Jun 2024 19:28:40 +0900 Subject: [PATCH] incorporated review comments --- ...efaultTestDeployAssert9C0D2DFC.assets.json | 10 +- ...aultTestDeployAssert9C0D2DFC.template.json | 151 +++- .../index.js | 645 +++++++----------- ...ke-model-guardrail-trace-integ.assets.json | 4 +- ...-model-guardrail-trace-integ.template.json | 109 ++- .../manifest.json | 16 +- .../tree.json | 307 +++++---- .../integ.invoke-model-guardrail-trace.ts | 35 +- .../lib/bedrock/guardrail.ts | 48 ++ .../lib/bedrock/invoke-model.ts | 47 +- .../aws-stepfunctions-tasks/lib/index.ts | 1 + .../test/bedrock/invoke-model.test.ts | 61 +- 12 files changed, 763 insertions(+), 671 deletions(-) rename packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/{asset.cfdb46b4f2c6702b4a1cc8e23ca426e8de43d13567e73a8453d01c1176393814.bundle => asset.3cef2cdbb46b3821e641ffb8b9af9731af5f7e4a9e857ab633dbcd9023de724d.bundle}/index.js (99%) create mode 100644 packages/aws-cdk-lib/aws-stepfunctions-tasks/lib/bedrock/guardrail.ts diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/InvokeModelDefaultTestDeployAssert9C0D2DFC.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/InvokeModelDefaultTestDeployAssert9C0D2DFC.assets.json index 898bb4d3ac740..64f21ef39439e 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/InvokeModelDefaultTestDeployAssert9C0D2DFC.assets.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/InvokeModelDefaultTestDeployAssert9C0D2DFC.assets.json @@ -1,20 +1,20 @@ { "version": "36.0.0", "files": { - "cfdb46b4f2c6702b4a1cc8e23ca426e8de43d13567e73a8453d01c1176393814": { + "3cef2cdbb46b3821e641ffb8b9af9731af5f7e4a9e857ab633dbcd9023de724d": { "source": { - "path": "asset.cfdb46b4f2c6702b4a1cc8e23ca426e8de43d13567e73a8453d01c1176393814.bundle", + "path": "asset.3cef2cdbb46b3821e641ffb8b9af9731af5f7e4a9e857ab633dbcd9023de724d.bundle", "packaging": "zip" }, "destinations": { "current_account-current_region": { "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", - "objectKey": "cfdb46b4f2c6702b4a1cc8e23ca426e8de43d13567e73a8453d01c1176393814.zip", + "objectKey": "3cef2cdbb46b3821e641ffb8b9af9731af5f7e4a9e857ab633dbcd9023de724d.zip", "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" } } }, - "3a0b72de92a2e446cc0eeedf84a692699302ab2dadb6870030551eec68fa0657": { + "703a8012ea44b20bd7f5450c27c27ebecf09b7f47342877fdd1c582a7f4e354f": { "source": { "path": "InvokeModelDefaultTestDeployAssert9C0D2DFC.template.json", "packaging": "file" @@ -22,7 +22,7 @@ "destinations": { "current_account-current_region": { "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", - "objectKey": "3a0b72de92a2e446cc0eeedf84a692699302ab2dadb6870030551eec68fa0657.json", + "objectKey": "703a8012ea44b20bd7f5450c27c27ebecf09b7f47342877fdd1c582a7f4e354f.json", "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" } } diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/InvokeModelDefaultTestDeployAssert9C0D2DFC.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/InvokeModelDefaultTestDeployAssert9C0D2DFC.template.json index ecb0f95df35a0..b8b169632956d 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/InvokeModelDefaultTestDeployAssert9C0D2DFC.template.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/InvokeModelDefaultTestDeployAssert9C0D2DFC.template.json @@ -30,7 +30,7 @@ } }, "flattenResponse": "false", - "salt": "1717304821989" + "salt": "1719656519047" }, "UpdateReplacePolicy": "Delete", "DeletionPolicy": "Delete" @@ -232,12 +232,20 @@ "SingletonFunction1488541a7b23466481b69b4408076b81HandlerCD40AE9F": { "Type": "AWS::Lambda::Function", "Properties": { - "Runtime": "nodejs18.x", + "Runtime": { + "Fn::FindInMap": [ + "LatestNodeRuntimeMap", + { + "Ref": "AWS::Region" + }, + "value" + ] + }, "Code": { "S3Bucket": { "Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}" }, - "S3Key": "cfdb46b4f2c6702b4a1cc8e23ca426e8de43d13567e73a8453d01c1176393814.zip" + "S3Key": "3cef2cdbb46b3821e641ffb8b9af9731af5f7e4a9e857ab633dbcd9023de724d.zip" }, "Timeout": 120, "Handler": "index.handler", @@ -302,12 +310,20 @@ "SingletonFunction76b3e830a873425f8453eddd85c86925Handler81461ECE": { "Type": "AWS::Lambda::Function", "Properties": { - "Runtime": "nodejs18.x", + "Runtime": { + "Fn::FindInMap": [ + "LatestNodeRuntimeMap", + { + "Ref": "AWS::Region" + }, + "value" + ] + }, "Code": { "S3Bucket": { "Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}" }, - "S3Key": "cfdb46b4f2c6702b4a1cc8e23ca426e8de43d13567e73a8453d01c1176393814.zip" + "S3Key": "3cef2cdbb46b3821e641ffb8b9af9731af5f7e4a9e857ab633dbcd9023de724d.zip" }, "Timeout": 120, "Handler": "index.isComplete", @@ -344,12 +360,20 @@ "SingletonFunction5c1898e096fb4e3e95d5f6c67f3ce41aHandlerADF3E6EA": { "Type": "AWS::Lambda::Function", "Properties": { - "Runtime": "nodejs18.x", + "Runtime": { + "Fn::FindInMap": [ + "LatestNodeRuntimeMap", + { + "Ref": "AWS::Region" + }, + "value" + ] + }, "Code": { "S3Bucket": { "Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}" }, - "S3Key": "cfdb46b4f2c6702b4a1cc8e23ca426e8de43d13567e73a8453d01c1176393814.zip" + "S3Key": "3cef2cdbb46b3821e641ffb8b9af9731af5f7e4a9e857ab633dbcd9023de724d.zip" }, "Timeout": 120, "Handler": "index.onTimeout", @@ -390,7 +414,7 @@ "outputPaths": [ "executionArn" ], - "salt": "1717304821990" + "salt": "1719656519049" }, "UpdateReplacePolicy": "Delete", "DeletionPolicy": "Delete" @@ -428,7 +452,7 @@ } }, "flattenResponse": "false", - "salt": "1717304821990" + "salt": "1719656519049" }, "DependsOn": [ "AwsApiCallStepFunctionsstartExecutionc5cc0786542148808c24d8ebf111c7aa" @@ -582,6 +606,115 @@ } } }, + "Mappings": { + "LatestNodeRuntimeMap": { + "af-south-1": { + "value": "nodejs20.x" + }, + "ap-east-1": { + "value": "nodejs20.x" + }, + "ap-northeast-1": { + "value": "nodejs20.x" + }, + "ap-northeast-2": { + "value": "nodejs20.x" + }, + "ap-northeast-3": { + "value": "nodejs20.x" + }, + "ap-south-1": { + "value": "nodejs20.x" + }, + "ap-south-2": { + "value": "nodejs20.x" + }, + "ap-southeast-1": { + "value": "nodejs20.x" + }, + "ap-southeast-2": { + "value": "nodejs20.x" + }, + "ap-southeast-3": { + "value": "nodejs20.x" + }, + "ap-southeast-4": { + "value": "nodejs20.x" + }, + "ca-central-1": { + "value": "nodejs20.x" + }, + "cn-north-1": { + "value": "nodejs18.x" + }, + "cn-northwest-1": { + "value": "nodejs18.x" + }, + "eu-central-1": { + "value": "nodejs20.x" + }, + "eu-central-2": { + "value": "nodejs20.x" + }, + "eu-north-1": { + "value": "nodejs20.x" + }, + "eu-south-1": { + "value": "nodejs20.x" + }, + "eu-south-2": { + "value": "nodejs20.x" + }, + "eu-west-1": { + "value": "nodejs20.x" + }, + "eu-west-2": { + "value": "nodejs20.x" + }, + "eu-west-3": { + "value": "nodejs20.x" + }, + "il-central-1": { + "value": "nodejs20.x" + }, + "me-central-1": { + "value": "nodejs20.x" + }, + "me-south-1": { + "value": "nodejs20.x" + }, + "sa-east-1": { + "value": "nodejs20.x" + }, + "us-east-1": { + "value": "nodejs20.x" + }, + "us-east-2": { + "value": "nodejs20.x" + }, + "us-gov-east-1": { + "value": "nodejs18.x" + }, + "us-gov-west-1": { + "value": "nodejs18.x" + }, + "us-iso-east-1": { + "value": "nodejs18.x" + }, + "us-iso-west-1": { + "value": "nodejs18.x" + }, + "us-isob-east-1": { + "value": "nodejs18.x" + }, + "us-west-1": { + "value": "nodejs20.x" + }, + "us-west-2": { + "value": "nodejs20.x" + } + } + }, "Parameters": { "BootstrapVersion": { "Type": "AWS::SSM::Parameter::Value", diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/asset.cfdb46b4f2c6702b4a1cc8e23ca426e8de43d13567e73a8453d01c1176393814.bundle/index.js b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/asset.3cef2cdbb46b3821e641ffb8b9af9731af5f7e4a9e857ab633dbcd9023de724d.bundle/index.js similarity index 99% rename from packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/asset.cfdb46b4f2c6702b4a1cc8e23ca426e8de43d13567e73a8453d01c1176393814.bundle/index.js rename to packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/asset.3cef2cdbb46b3821e641ffb8b9af9731af5f7e4a9e857ab633dbcd9023de724d.bundle/index.js index d99ddf1f7e394..a1206ea985dc1 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/asset.cfdb46b4f2c6702b4a1cc8e23ca426e8de43d13567e73a8453d01c1176393814.bundle/index.js +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/asset.3cef2cdbb46b3821e641ffb8b9af9731af5f7e4a9e857ab633dbcd9023de724d.bundle/index.js @@ -863,9 +863,8 @@ function __extends(d, b) { } function __rest(s, e) { var t = {}; - for (var p in s) - if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) @@ -875,12 +874,8 @@ function __rest(s, e) { } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") - r = Reflect.decorate(decorators, target, key, desc); - else - for (var i = decorators.length - 1; i >= 0; i--) - if (d = decorators[i]) - r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { @@ -890,8 +885,7 @@ function __param(paramIndex, decorator) { } function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { - if (f !== void 0 && typeof f !== "function") - throw new TypeError("Function expected"); + if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; @@ -900,36 +894,25 @@ function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, e var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; - for (var p in contextIn) - context[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) - context.access[p] = contextIn.access[p]; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function(f) { - if (done) - throw new TypeError("Cannot add initializers after decoration has completed"); + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { - if (result === void 0) - continue; - if (result === null || typeof result !== "object") - throw new TypeError("Object expected"); - if (_ = accept(result.get)) - descriptor.get = _; - if (_ = accept(result.set)) - descriptor.set = _; - if (_ = accept(result.init)) - initializers.unshift(_); + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { - if (kind === "field") - initializers.unshift(_); - else - descriptor[key] = _; + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; } } - if (target) - Object.defineProperty(target, contextIn.name, descriptor); + if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; } function __runInitializers(thisArg, initializers, value) { @@ -943,13 +926,11 @@ function __propKey(x) { return typeof x === "symbol" ? x : "".concat(x); } function __setFunctionName(f, name, prefix) { - if (typeof name === "symbol") - name = name.description ? "[".concat(name.description, "]") : ""; + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); } function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") - return Reflect.metadata(metadataKey, metadataValue); + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { @@ -980,8 +961,7 @@ function __awaiter(thisArg, _arguments, P, generator) { } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { - if (t[0] & 1) - throw t[1]; + if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { @@ -993,103 +973,88 @@ function __generator(thisArg, body) { }; } function step(op) { - if (f) - throw new TypeError("Generator is already executing."); - while (g && (g = 0, op[0] && (_ = 0)), _) - try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) - return t; - if (y = 0, t) - op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: - case 1: + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; t = op; break; - case 4: - _.label++; - return { value: op[1], done: false }; - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) - _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; } - if (op[0] & 5) - throw op[1]; + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __exportStar(m, o) { - for (var p in m) - if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) - __createBinding(o, m, p); + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) - return m.call(o); - if (o && typeof o.length === "number") - return { - next: function() { - if (o && i >= o.length) - o = void 0; - return { value: o && o[i++], done: !o }; - } - }; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function() { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) - return o; + if (!m) return o; var i = m.call(o), r, ar = [], e; try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) - ar.push(r.value); + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error }; } finally { try { - if (r && !r.done && (m = i["return"])) - m.call(i); + if (r && !r.done && (m = i["return"])) m.call(i); } finally { - if (e) - throw e.error; + if (e) throw e.error; } } return ar; @@ -1100,41 +1065,44 @@ function __spread() { return ar; } function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) - s += arguments[i].length; + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) - for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) - ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; } + } return to.concat(ar || Array.prototype.slice.call(from)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() { return this; }, i; - function verb(n) { - if (g[n]) + function awaitReturn(f) { + return function(v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { i[n] = function(v) { return new Promise(function(a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; + if (f) i[n] = f(i[n]); + } } function resume(n, v) { try { @@ -1153,8 +1121,7 @@ function __asyncGenerator(thisArg, _arguments, generator) { resume("throw", value); } function settle(f, v) { - if (f(v), q.shift(), q.length) - resume(q[0][0], q[0][1]); + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { @@ -1171,8 +1138,7 @@ function __asyncDelegator(o) { } } function __asyncValues(o) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; @@ -1199,13 +1165,10 @@ function __makeTemplateObject(cooked, raw) { return cooked; } function __importStar(mod) { - if (mod && mod.__esModule) - return mod; + if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { - for (var k in mod) - if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) - __createBinding(result, mod, k); + for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; @@ -1214,43 +1177,41 @@ function __importDefault(mod) { return mod && mod.__esModule ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; } function __classPrivateFieldIn(state, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") - throw new TypeError("Cannot use 'in' operator on non-object"); + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); return typeof state === "function" ? receiver === state : state.has(receiver); } function __addDisposableResource(env, value, async) { if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") - throw new TypeError("Object expected."); - var dispose; + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; if (async) { - if (!Symbol.asyncDispose) - throw new TypeError("Symbol.asyncDispose is not defined."); + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); dispose = value[Symbol.asyncDispose]; } if (dispose === void 0) { - if (!Symbol.dispose) - throw new TypeError("Symbol.dispose is not defined."); + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); dispose = value[Symbol.dispose]; + if (async) inner = dispose; } - if (typeof dispose !== "function") - throw new TypeError("Object not disposable."); + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { + try { + inner.call(this); + } catch (e) { + return Promise.reject(e); + } + }; env.stack.push({ value, dispose, async }); } else if (async) { env.stack.push({ async: true }); @@ -1267,17 +1228,15 @@ function __disposeResources(env) { var rec = env.stack.pop(); try { var result = rec.dispose && rec.dispose.call(rec.value); - if (rec.async) - return Promise.resolve(result).then(next, function(e) { - fail(e); - return next(); - }); + if (rec.async) return Promise.resolve(result).then(next, function(e) { + fail(e); + return next(); + }); } catch (e) { fail(e); } } - if (env.hasError) - throw env.error; + if (env.hasError) throw env.error; } return next(); } @@ -1288,9 +1247,7 @@ var init_tslib_es6 = __esm({ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { d2.__proto__ = b2; } || function(d2, b2) { - for (var p in b2) - if (Object.prototype.hasOwnProperty.call(b2, p)) - d2[p] = b2[p]; + for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; }; return extendStatics(d, b); }; @@ -1298,17 +1255,14 @@ var init_tslib_es6 = __esm({ __assign = Object.assign || function __assign2(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; - for (var p in s) - if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; __createBinding = Object.create ? function(o, m, k, k2) { - if (k2 === void 0) - k2 = k; + if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { @@ -1317,8 +1271,7 @@ var init_tslib_es6 = __esm({ } Object.defineProperty(o, k2, desc); } : function(o, m, k, k2) { - if (k2 === void 0) - k2 = k; + if (k2 === void 0) k2 = k; o[k2] = m[k]; }; __setModuleDefault = Object.create ? function(o, v) { @@ -9792,8 +9745,7 @@ var require_validator = __commonJS({ if (xmlData[i] === "<" && xmlData[i + 1] === "?") { i += 2; i = readPI(xmlData, i); - if (i.err) - return i; + if (i.err) return i; } else if (xmlData[i] === "<") { let tagStartPos = i; i++; @@ -9879,8 +9831,7 @@ var require_validator = __commonJS({ continue; } else if (xmlData[i + 1] === "?") { i = readPI(xmlData, ++i); - if (i.err) - return i; + if (i.err) return i; } else { break; } @@ -10148,13 +10099,11 @@ var require_xmlNode = __commonJS({ this[":@"] = {}; } add(key, val2) { - if (key === "__proto__") - key = "#__proto__"; + if (key === "__proto__") key = "#__proto__"; this.child.push({ [key]: val2 }); } addChild(node) { - if (node.tagname === "__proto__") - node.tagname = "#__proto__"; + if (node.tagname === "__proto__") node.tagname = "#__proto__"; if (node[":@"] && Object.keys(node[":@"]).length > 0) { this.child.push({ [node.tagname]: node.child, [":@"]: node[":@"] }); } else { @@ -10187,16 +10136,11 @@ var require_DocTypeReader = __commonJS({ regx: RegExp(`&${entityName};`, "g"), val }; - } else if (hasBody && isElement(xmlData, i)) - i += 8; - else if (hasBody && isAttlist(xmlData, i)) - i += 8; - else if (hasBody && isNotation(xmlData, i)) - i += 9; - else if (isComment) - comment = true; - else - throw new Error("Invalid DOCTYPE"); + } else if (hasBody && isElement(xmlData, i)) i += 8; + else if (hasBody && isAttlist(xmlData, i)) i += 8; + else if (hasBody && isNotation(xmlData, i)) i += 9; + else if (isComment) comment = true; + else throw new Error("Invalid DOCTYPE"); angleBracketsCount++; exp = ""; } else if (xmlData[i] === ">") { @@ -10231,8 +10175,7 @@ var require_DocTypeReader = __commonJS({ entityName2 += xmlData[i]; } entityName2 = entityName2.trim(); - if (entityName2.indexOf(" ") !== -1) - throw new Error("External entites are not supported"); + if (entityName2.indexOf(" ") !== -1) throw new Error("External entites are not supported"); const startChar = xmlData[i++]; let val2 = ""; for (; i < xmlData.length && xmlData[i] !== startChar; i++) { @@ -10241,28 +10184,23 @@ var require_DocTypeReader = __commonJS({ return [entityName2, val2, i]; } function isComment(xmlData, i) { - if (xmlData[i + 1] === "!" && xmlData[i + 2] === "-" && xmlData[i + 3] === "-") - return true; + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "-" && xmlData[i + 3] === "-") return true; return false; } function isEntity(xmlData, i) { - if (xmlData[i + 1] === "!" && xmlData[i + 2] === "E" && xmlData[i + 3] === "N" && xmlData[i + 4] === "T" && xmlData[i + 5] === "I" && xmlData[i + 6] === "T" && xmlData[i + 7] === "Y") - return true; + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "E" && xmlData[i + 3] === "N" && xmlData[i + 4] === "T" && xmlData[i + 5] === "I" && xmlData[i + 6] === "T" && xmlData[i + 7] === "Y") return true; return false; } function isElement(xmlData, i) { - if (xmlData[i + 1] === "!" && xmlData[i + 2] === "E" && xmlData[i + 3] === "L" && xmlData[i + 4] === "E" && xmlData[i + 5] === "M" && xmlData[i + 6] === "E" && xmlData[i + 7] === "N" && xmlData[i + 8] === "T") - return true; + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "E" && xmlData[i + 3] === "L" && xmlData[i + 4] === "E" && xmlData[i + 5] === "M" && xmlData[i + 6] === "E" && xmlData[i + 7] === "N" && xmlData[i + 8] === "T") return true; return false; } function isAttlist(xmlData, i) { - if (xmlData[i + 1] === "!" && xmlData[i + 2] === "A" && xmlData[i + 3] === "T" && xmlData[i + 4] === "T" && xmlData[i + 5] === "L" && xmlData[i + 6] === "I" && xmlData[i + 7] === "S" && xmlData[i + 8] === "T") - return true; + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "A" && xmlData[i + 3] === "T" && xmlData[i + 4] === "T" && xmlData[i + 5] === "L" && xmlData[i + 6] === "I" && xmlData[i + 7] === "S" && xmlData[i + 8] === "T") return true; return false; } function isNotation(xmlData, i) { - if (xmlData[i + 1] === "!" && xmlData[i + 2] === "N" && xmlData[i + 3] === "O" && xmlData[i + 4] === "T" && xmlData[i + 5] === "A" && xmlData[i + 6] === "T" && xmlData[i + 7] === "I" && xmlData[i + 8] === "O" && xmlData[i + 9] === "N") - return true; + if (xmlData[i + 1] === "!" && xmlData[i + 2] === "N" && xmlData[i + 3] === "O" && xmlData[i + 4] === "T" && xmlData[i + 5] === "A" && xmlData[i + 6] === "T" && xmlData[i + 7] === "I" && xmlData[i + 8] === "O" && xmlData[i + 9] === "N") return true; return false; } function validateEntityName(name) { @@ -10295,11 +10233,9 @@ var require_strnum = __commonJS({ }; function toNumber(str, options = {}) { options = Object.assign({}, consider, options); - if (!str || typeof str !== "string") - return str; + if (!str || typeof str !== "string") return str; let trimmedStr = str.trim(); - if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) - return str; + if (options.skipLike !== void 0 && options.skipLike.test(trimmedStr)) return str; else if (options.hex && hexRegex.test(trimmedStr)) { return Number.parseInt(trimmedStr, 16); } else { @@ -10309,45 +10245,30 @@ var require_strnum = __commonJS({ const leadingZeros = match[2]; let numTrimmedByZeros = trimZeros(match[3]); const eNotation = match[4] || match[6]; - if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") - return str; - else if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") - return str; + if (!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str; + else if (!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str; else { const num = Number(trimmedStr); const numStr = "" + num; if (numStr.search(/[eE]/) !== -1) { - if (options.eNotation) - return num; - else - return str; + if (options.eNotation) return num; + else return str; } else if (eNotation) { - if (options.eNotation) - return num; - else - return str; + if (options.eNotation) return num; + else return str; } else if (trimmedStr.indexOf(".") !== -1) { - if (numStr === "0" && numTrimmedByZeros === "") - return num; - else if (numStr === numTrimmedByZeros) - return num; - else if (sign && numStr === "-" + numTrimmedByZeros) - return num; - else - return str; + if (numStr === "0" && numTrimmedByZeros === "") return num; + else if (numStr === numTrimmedByZeros) return num; + else if (sign && numStr === "-" + numTrimmedByZeros) return num; + else return str; } if (leadingZeros) { - if (numTrimmedByZeros === numStr) - return num; - else if (sign + numTrimmedByZeros === numStr) - return num; - else - return str; + if (numTrimmedByZeros === numStr) return num; + else if (sign + numTrimmedByZeros === numStr) return num; + else return str; } - if (trimmedStr === numStr) - return num; - else if (trimmedStr === sign + numStr) - return num; + if (trimmedStr === numStr) return num; + else if (trimmedStr === sign + numStr) return num; return str; } } else { @@ -10358,12 +10279,9 @@ var require_strnum = __commonJS({ function trimZeros(numStr) { if (numStr && numStr.indexOf(".") !== -1) { numStr = numStr.replace(/0+$/, ""); - if (numStr === ".") - numStr = "0"; - else if (numStr[0] === ".") - numStr = "0" + numStr; - else if (numStr[numStr.length - 1] === ".") - numStr = numStr.substr(0, numStr.length - 1); + if (numStr === ".") numStr = "0"; + else if (numStr[0] === ".") numStr = "0" + numStr; + else if (numStr[numStr.length - 1] === ".") numStr = numStr.substr(0, numStr.length - 1); return numStr; } return numStr; @@ -10437,8 +10355,7 @@ var require_OrderedObjParser = __commonJS({ val2 = val2.trim(); } if (val2.length > 0) { - if (!escapeEntities) - val2 = this.replaceEntitiesValue(val2); + if (!escapeEntities) val2 = this.replaceEntitiesValue(val2); const newval = this.options.tagValueProcessor(tagName, val2, jPath, hasAttributes, isLeafNode); if (newval === null || newval === void 0) { return val2; @@ -10484,8 +10401,7 @@ var require_OrderedObjParser = __commonJS({ if (this.options.transformAttributeName) { aName = this.options.transformAttributeName(aName); } - if (aName === "__proto__") - aName = "#__proto__"; + if (aName === "__proto__") aName = "#__proto__"; if (oldVal !== void 0) { if (this.options.trimValues) { oldVal = oldVal.trim(); @@ -10560,8 +10476,7 @@ var require_OrderedObjParser = __commonJS({ i = closeIndex; } else if (xmlData[i + 1] === "?") { let tagData = readTagExp(xmlData, i, false, "?>"); - if (!tagData) - throw new Error("Pi Tag is not closed."); + if (!tagData) throw new Error("Pi Tag is not closed."); textData = this.saveTextToParentTag(textData, currentNode, jPath); if (this.options.ignoreDeclaration && tagData.tagName === "?xml" || this.options.ignorePiTags) { } else { @@ -10593,8 +10508,7 @@ var require_OrderedObjParser = __commonJS({ currentNode.add(this.options.cdataPropName, [{ [this.options.textNodeName]: tagExp }]); } else { let val2 = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true); - if (val2 == void 0) - val2 = ""; + if (val2 == void 0) val2 = ""; currentNode.add(this.options.textNodeName, val2); } i = closeIndex + 2; @@ -10628,8 +10542,7 @@ var require_OrderedObjParser = __commonJS({ i = result.closeIndex; } else { const result2 = this.readStopNodeData(xmlData, tagName, closeIndex + 1); - if (!result2) - throw new Error(`Unexpected end of ${tagName}`); + if (!result2) throw new Error(`Unexpected end of ${tagName}`); i = result2.i; tagContent = result2.tagContent; } @@ -10711,8 +10624,7 @@ var require_OrderedObjParser = __commonJS({ }; function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) { if (textData) { - if (isLeafNode === void 0) - isLeafNode = Object.keys(currentNode.child).length === 0; + if (isLeafNode === void 0) isLeafNode = Object.keys(currentNode.child).length === 0; textData = this.parseTextData( textData, currentNode.tagname, @@ -10731,8 +10643,7 @@ var require_OrderedObjParser = __commonJS({ const allNodesExp = "*." + currentTagName; for (const stopNodePath in stopNodes) { const stopNodeExp = stopNodes[stopNodePath]; - if (allNodesExp === stopNodeExp || jPath === stopNodeExp) - return true; + if (allNodesExp === stopNodeExp || jPath === stopNodeExp) return true; } return false; } @@ -10742,8 +10653,7 @@ var require_OrderedObjParser = __commonJS({ for (let index = i; index < xmlData.length; index++) { let ch = xmlData[index]; if (attrBoundary) { - if (ch === attrBoundary) - attrBoundary = ""; + if (ch === attrBoundary) attrBoundary = ""; } else if (ch === '"' || ch === "'") { attrBoundary = ch; } else if (ch === closingChar[0]) { @@ -10776,8 +10686,7 @@ var require_OrderedObjParser = __commonJS({ } function readTagExp(xmlData, i, removeNSPrefix, closingChar = ">") { const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar); - if (!result) - return; + if (!result) return; let tagExp = result.data; const closeIndex = result.index; const separatorIndex = tagExp.search(/\s/); @@ -10844,12 +10753,9 @@ var require_OrderedObjParser = __commonJS({ function parseValue(val2, shouldParse, options) { if (shouldParse && typeof val2 === "string") { const newval = val2.trim(); - if (newval === "true") - return true; - else if (newval === "false") - return false; - else - return toNumber(val2, options); + if (newval === "true") return true; + else if (newval === "false") return false; + else return toNumber(val2, options); } else { if (util.isExist(val2)) { return val2; @@ -10876,15 +10782,11 @@ var require_node2json = __commonJS({ const tagObj = arr[i]; const property = propName(tagObj); let newJpath = ""; - if (jPath === void 0) - newJpath = property; - else - newJpath = jPath + "." + property; + if (jPath === void 0) newJpath = property; + else newJpath = jPath + "." + property; if (property === options.textNodeName) { - if (text === void 0) - text = tagObj[property]; - else - text += "" + tagObj[property]; + if (text === void 0) text = tagObj[property]; + else text += "" + tagObj[property]; } else if (property === void 0) { continue; } else if (tagObj[property]) { @@ -10895,10 +10797,8 @@ var require_node2json = __commonJS({ } else if (Object.keys(val2).length === 1 && val2[options.textNodeName] !== void 0 && !options.alwaysCreateTextNode) { val2 = val2[options.textNodeName]; } else if (Object.keys(val2).length === 0) { - if (options.alwaysCreateTextNode) - val2[options.textNodeName] = ""; - else - val2 = ""; + if (options.alwaysCreateTextNode) val2[options.textNodeName] = ""; + else val2 = ""; } if (compressedObj[property] !== void 0 && compressedObj.hasOwnProperty(property)) { if (!Array.isArray(compressedObj[property])) { @@ -10915,18 +10815,15 @@ var require_node2json = __commonJS({ } } if (typeof text === "string") { - if (text.length > 0) - compressedObj[options.textNodeName] = text; - } else if (text !== void 0) - compressedObj[options.textNodeName] = text; + if (text.length > 0) compressedObj[options.textNodeName] = text; + } else if (text !== void 0) compressedObj[options.textNodeName] = text; return compressedObj; } function propName(obj) { const keys = Object.keys(obj); for (let i = 0; i < keys.length; i++) { const key = keys[i]; - if (key !== ":@") - return key; + if (key !== ":@") return key; } } function assignAttributes(obj, attrMap, jpath, options) { @@ -10983,8 +10880,7 @@ var require_XMLParser = __commonJS({ throw new Error("XML data is accepted in String or Bytes[] form."); } if (validationOption) { - if (validationOption === true) - validationOption = {}; + if (validationOption === true) validationOption = {}; const result = validator.validate(xmlData, validationOption); if (result !== true) { throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`); @@ -10993,10 +10889,8 @@ var require_XMLParser = __commonJS({ const orderedObjParser = new OrderedObjParser(this.options); orderedObjParser.addExternalEntities(this.externalEntities); const orderedResult = orderedObjParser.parseXml(xmlData); - if (this.options.preserveOrder || orderedResult === void 0) - return orderedResult; - else - return prettify(orderedResult, this.options); + if (this.options.preserveOrder || orderedResult === void 0) return orderedResult; + else return prettify(orderedResult, this.options); } /** * Add Entity which is not by default supported by this library @@ -11037,10 +10931,8 @@ var require_orderedJs2Xml = __commonJS({ const tagObj = arr[i]; const tagName = propName(tagObj); let newJPath = ""; - if (jPath.length === 0) - newJPath = tagName; - else - newJPath = `${jPath}.${tagName}`; + if (jPath.length === 0) newJPath = tagName; + else newJPath = `${jPath}.${tagName}`; if (tagName === options.textNodeName) { let tagText = tagObj[tagName]; if (!isStopNode(newJPath, options)) { @@ -11081,10 +10973,8 @@ var require_orderedJs2Xml = __commonJS({ const tagStart = indentation + `<${tagName}${attStr}`; const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation); if (options.unpairedTags.indexOf(tagName) !== -1) { - if (options.suppressUnpairedNode) - xmlStr += tagStart + ">"; - else - xmlStr += tagStart + "/>"; + if (options.suppressUnpairedNode) xmlStr += tagStart + ">"; + else xmlStr += tagStart + "/>"; } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) { xmlStr += tagStart + "/>"; } else if (tagValue && tagValue.endsWith(">")) { @@ -11106,8 +10996,7 @@ var require_orderedJs2Xml = __commonJS({ const keys = Object.keys(obj); for (let i = 0; i < keys.length; i++) { const key = keys[i]; - if (key !== ":@") - return key; + if (key !== ":@") return key; } } function attr_to_str(attrMap, options) { @@ -11129,8 +11018,7 @@ var require_orderedJs2Xml = __commonJS({ jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1); let tagName = jPath.substr(jPath.lastIndexOf(".") + 1); for (let index in options.stopNodes) { - if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) - return true; + if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true; } return false; } @@ -11227,10 +11115,8 @@ var require_json2xml = __commonJS({ for (let key in jObj) { if (typeof jObj[key] === "undefined") { } else if (jObj[key] === null) { - if (key[0] === "?") - val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar; - else - val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar; + if (key[0] === "?") val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar; + else val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar; } else if (jObj[key] instanceof Date) { val2 += this.buildTextValNode(jObj[key], key, "", level); } else if (typeof jObj[key] !== "object") { @@ -11252,10 +11138,8 @@ var require_json2xml = __commonJS({ const item = jObj[key][j]; if (typeof item === "undefined") { } else if (item === null) { - if (key[0] === "?") - val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar; - else - val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar; + if (key[0] === "?") val2 += this.indentate(level) + "<" + key + "?" + this.tagEndChar; + else val2 += this.indentate(level) + "<" + key + "/" + this.tagEndChar; } else if (typeof item === "object") { if (this.options.oneListGroup) { listTagVal += this.j2x(item, level + 1).val; @@ -11289,8 +11173,7 @@ var require_json2xml = __commonJS({ val2 = this.replaceEntitiesValue(val2); if (this.options.suppressBooleanAttributes && val2 === "true") { return " " + attrName; - } else - return " " + attrName + '="' + val2 + '"'; + } else return " " + attrName + '="' + val2 + '"'; }; function processTextOrObjNode(object, key, level) { const result = this.j2x(object, level + 1); @@ -11302,8 +11185,7 @@ var require_json2xml = __commonJS({ } Builder.prototype.buildObjectNode = function(val2, key, attrStr, level) { if (val2 === "") { - if (key[0] === "?") - return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar; + if (key[0] === "?") return this.indentate(level) + "<" + key + attrStr + "?" + this.tagEndChar; else { return this.indentate(level) + "<" + key + attrStr + this.closeTag(key) + this.tagEndChar; } @@ -11326,8 +11208,7 @@ var require_json2xml = __commonJS({ Builder.prototype.closeTag = function(key) { let closeTag = ""; if (this.options.unpairedTags.indexOf(key) !== -1) { - if (!this.options.suppressUnpairedNode) - closeTag = "/"; + if (!this.options.suppressUnpairedNode) closeTag = "/"; } else if (this.options.suppressEmptyNode) { closeTag = "/"; } else { @@ -22857,8 +22738,7 @@ var require_lib2 = __commonJS({ const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); return function(V, opts) { - if (!opts) - opts = {}; + if (!opts) opts = {}; let x = +V; if (opts.enforceRange) { if (!Number.isFinite(x)) { @@ -22872,10 +22752,8 @@ var require_lib2 = __commonJS({ } if (!isNaN(x) && opts.clamp) { x = evenRound(x); - if (x < lowerBound) - x = lowerBound; - if (x > upperBound) - x = upperBound; + if (x < lowerBound) x = lowerBound; + if (x > upperBound) x = upperBound; return x; } if (!Number.isFinite(x) || x === 0) { @@ -22926,8 +22804,7 @@ var require_lib2 = __commonJS({ conversions["float"] = conversions["double"]; conversions["unrestricted float"] = conversions["unrestricted double"]; conversions["DOMString"] = function(V, opts) { - if (!opts) - opts = {}; + if (!opts) opts = {}; if (opts.treatNullAsEmptyString && V === null) { return ""; } @@ -23164,8 +23041,7 @@ var require_tr46 = __commonJS({ } } } - if (result.error) - return null; + if (result.error) return null; return labels.join("."); }; module2.exports.toUnicode = function(domain_name, useSTD3) { @@ -24576,8 +24452,7 @@ var require_URL = __commonJS({ return obj; }, setup(obj, constructorArgs, privateData) { - if (!privateData) - privateData = {}; + if (!privateData) privateData = {}; privateData.wrapper = obj; obj[impl] = new Impl.implementation(constructorArgs, privateData); obj[impl][utils.wrapperSymbol] = obj; @@ -24616,18 +24491,14 @@ var require_safer = __commonJS({ var safer = {}; var key; for (key in buffer) { - if (!buffer.hasOwnProperty(key)) - continue; - if (key === "SlowBuffer" || key === "Buffer") - continue; + if (!buffer.hasOwnProperty(key)) continue; + if (key === "SlowBuffer" || key === "Buffer") continue; safer[key] = buffer[key]; } var Safer = safer.Buffer = {}; for (key in Buffer2) { - if (!Buffer2.hasOwnProperty(key)) - continue; - if (key === "allocUnsafe" || key === "allocUnsafeSlow") - continue; + if (!Buffer2.hasOwnProperty(key)) continue; + if (key === "allocUnsafe" || key === "allocUnsafeSlow") continue; Safer[key] = Buffer2[key]; } safer.Buffer.prototype = Buffer2.prototype; @@ -25075,14 +24946,10 @@ var require_utf32 = __commonJS({ return "utf-32be"; } } - if (b[0] !== 0 || b[1] > 16) - invalidBE++; - if (b[3] !== 0 || b[2] > 16) - invalidLE++; - if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) - bmpCharsBE++; - if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) - bmpCharsLE++; + if (b[0] !== 0 || b[1] > 16) invalidBE++; + if (b[3] !== 0 || b[2] > 16) invalidLE++; + if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) bmpCharsBE++; + if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) bmpCharsLE++; b.length = 0; charsProcessed++; if (charsProcessed >= 100) { @@ -25091,10 +24958,8 @@ var require_utf32 = __commonJS({ } } } - if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) - return "utf-32be"; - if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) - return "utf-32le"; + if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return "utf-32be"; + if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return "utf-32le"; return defaultEncoding || "utf-32le"; } } @@ -25214,15 +25079,11 @@ var require_utf16 = __commonJS({ b.push(buf[j]); if (b.length === 2) { if (charsProcessed === 0) { - if (b[0] === 255 && b[1] === 254) - return "utf-16le"; - if (b[0] === 254 && b[1] === 255) - return "utf-16be"; + if (b[0] === 255 && b[1] === 254) return "utf-16le"; + if (b[0] === 254 && b[1] === 255) return "utf-16be"; } - if (b[0] === 0 && b[1] !== 0) - asciiCharsBE++; - if (b[0] !== 0 && b[1] === 0) - asciiCharsLE++; + if (b[0] === 0 && b[1] !== 0) asciiCharsBE++; + if (b[0] !== 0 && b[1] === 0) asciiCharsLE++; b.length = 0; charsProcessed++; if (charsProcessed >= 100) { @@ -25231,10 +25092,8 @@ var require_utf16 = __commonJS({ } } } - if (asciiCharsBE > asciiCharsLE) - return "utf-16be"; - if (asciiCharsBE < asciiCharsLE) - return "utf-16le"; + if (asciiCharsBE > asciiCharsLE) return "utf-16be"; + if (asciiCharsBE < asciiCharsLE) return "utf-16le"; return defaultEncoding || "utf-16le"; } } @@ -26185,10 +26044,8 @@ var require_dbcs_codec = __commonJS({ this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); } this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; - if (this.defCharSB === UNASSIGNED) - this.defCharSB = this.encodeTable[0]["?"]; - if (this.defCharSB === UNASSIGNED) - this.defCharSB = "?".charCodeAt(0); + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]["?"]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); } DBCSCodec.prototype.encoder = DBCSEncoder; DBCSCodec.prototype.decoder = DBCSDecoder; @@ -26269,8 +26126,7 @@ var require_dbcs_codec = __commonJS({ node = this.encodeTableSeq[SEQ_START - bucket[low]]; } else { node = {}; - if (bucket[low] !== UNASSIGNED) - node[DEF_CHAR] = bucket[low]; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; bucket[low] = SEQ_START - this.encodeTableSeq.length; this.encodeTableSeq.push(node); } @@ -26327,8 +26183,7 @@ var require_dbcs_codec = __commonJS({ var newBuf = Buffer2.alloc(str.length * (this.gb18030 ? 4 : 3)), leadSurrogate = this.leadSurrogate, seqObj = this.seqObj, nextChar = -1, i2 = 0, j = 0; while (true) { if (nextChar === -1) { - if (i2 == str.length) - break; + if (i2 == str.length) break; var uCode = str.charCodeAt(i2++); } else { var uCode = nextChar; @@ -28069,8 +27924,7 @@ var require_streams = __commonJS({ return done(new Error("Iconv encoding stream needs strings as its input.")); try { var res = this.conv.write(chunk); - if (res && res.length) - this.push(res); + if (res && res.length) this.push(res); done(); } catch (e) { done(e); @@ -28079,8 +27933,7 @@ var require_streams = __commonJS({ IconvLiteEncoderStream.prototype._flush = function(done) { try { var res = this.conv.end(); - if (res && res.length) - this.push(res); + if (res && res.length) this.push(res); done(); } catch (e) { done(e); @@ -28111,8 +27964,7 @@ var require_streams = __commonJS({ return done(new Error("Iconv decoding stream needs buffers as its input.")); try { var res = this.conv.write(chunk); - if (res && res.length) - this.push(res, this.encoding); + if (res && res.length) this.push(res, this.encoding); done(); } catch (e) { done(e); @@ -28121,8 +27973,7 @@ var require_streams = __commonJS({ IconvLiteDecoderStream.prototype._flush = function(done) { try { var res = this.conv.end(); - if (res && res.length) - this.push(res, this.encoding); + if (res && res.length) this.push(res, this.encoding); done(); } catch (e) { done(e); @@ -28458,16 +28309,13 @@ var require_lib4 = __commonJS({ body = null; } else if (isURLSearchParams(body)) { body = Buffer.from(body.toString()); - } else if (isBlob(body)) - ; - else if (Buffer.isBuffer(body)) - ; + } else if (isBlob(body)) ; + else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === "[object ArrayBuffer]") { body = Buffer.from(body); } else if (ArrayBuffer.isView(body)) { body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); - } else if (body instanceof Stream) - ; + } else if (body instanceof Stream) ; else { body = Buffer.from(String(body)); } @@ -28810,8 +28658,7 @@ var require_lib4 = __commonJS({ } return; } - if (init == null) - ; + if (init == null) ; else if (typeof init === "object") { const method = init[Symbol.iterator]; if (method != null) { @@ -29193,8 +29040,7 @@ var require_lib4 = __commonJS({ } } let signal = isRequest(input) ? input.signal : null; - if ("signal" in init) - signal = init.signal; + if ("signal" in init) signal = init.signal; if (signal != null && !isAbortSignal(signal)) { throw new TypeError("Expected signal to be an instanceof AbortSignal"); } @@ -29331,8 +29177,7 @@ var require_lib4 = __commonJS({ if (request2.body && request2.body instanceof Stream.Readable) { destroyStream(request2.body, error); } - if (!response || !response.body) - return; + if (!response || !response.body) return; response.body.emit("error", error); }; if (signal && signal.aborted) { @@ -29350,8 +29195,7 @@ var require_lib4 = __commonJS({ } function finalize() { req.abort(); - if (signal) - signal.removeEventListener("abort", abortAndFinalize); + if (signal) signal.removeEventListener("abort", abortAndFinalize); clearTimeout(reqTimeout); } if (request2.timeout) { @@ -29460,8 +29304,7 @@ var require_lib4 = __commonJS({ } } res.once("end", function() { - if (signal) - signal.removeEventListener("abort", abortAndFinalize); + if (signal) signal.removeEventListener("abort", abortAndFinalize); }); let body = res.pipe(new PassThrough$1()); const response_options = { @@ -31154,8 +30997,7 @@ var require_lib5 = __commonJS({ "../aws-custom-resource-sdk-adapter/lib/index.js"(exports2) { "use strict"; var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) { - if (k2 === void 0) - k2 = k; + if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { @@ -31164,14 +31006,11 @@ var require_lib5 = __commonJS({ } Object.defineProperty(o, k2, desc); } : function(o, m, k, k2) { - if (k2 === void 0) - k2 = k; + if (k2 === void 0) k2 = k; o[k2] = m[k]; }); var __exportStar2 = exports2 && exports2.__exportStar || function(m, exports3) { - for (var p in m) - if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) - __createBinding2(exports3, m, p); + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p); }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.normalizeActionName = exports2.normalizeServiceName = exports2.findV3ClientConstructor = exports2.coerceApiParameters = void 0; diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ.assets.json index 12d09a1f6668c..4002498c98163 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ.assets.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ.assets.json @@ -1,7 +1,7 @@ { "version": "36.0.0", "files": { - "575e5b852e6ff6fcf9dc3ea3b5ca454762829e7bbe6bd03fd2d6d287eaa6c486": { + "269be7f0a4effa5d89845f9d3573f5d6bff6e3b197c0be7ef013843754f73bde": { "source": { "path": "aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ.template.json", "packaging": "file" @@ -9,7 +9,7 @@ "destinations": { "current_account-current_region": { "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", - "objectKey": "575e5b852e6ff6fcf9dc3ea3b5ca454762829e7bbe6bd03fd2d6d287eaa6c486.json", + "objectKey": "269be7f0a4effa5d89845f9d3573f5d6bff6e3b197c0be7ef013843754f73bde.json", "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" } } diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ.template.json index 98368e916e7bb..59b88269adb2e 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ.template.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ.template.json @@ -24,6 +24,17 @@ } } }, + "GuardrailVersion": { + "Type": "AWS::Bedrock::GuardrailVersion", + "Properties": { + "GuardrailIdentifier": { + "Fn::GetAtt": [ + "Guardrail", + "GuardrailId" + ] + } + } + }, "StateMachineRoleB840431D": { "Type": "AWS::IAM::Role", "Properties": { @@ -69,32 +80,60 @@ { "Action": "bedrock:ApplyGuardrail", "Effect": "Allow", - "Resource": { - "Fn::Join": [ - "", - [ - "arn:", - { - "Ref": "AWS::Partition" - }, - ":bedrock:", - { - "Ref": "AWS::Region" - }, - ":", - { - "Ref": "AWS::AccountId" - }, - ":guardrail/", - { - "Fn::GetAtt": [ - "Guardrail", - "GuardrailId" - ] - } + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":guardrail/", + { + "Fn::GetAtt": [ + "Guardrail", + "GuardrailArn" + ] + } + ] ] - ] - } + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":guardrail/", + { + "Fn::GetAtt": [ + "Guardrail", + "GuardrailId" + ] + } + ] + ] + } + ] } ], "Version": "2012-10-17" @@ -114,7 +153,7 @@ "Fn::Join": [ "", [ - "{\"StartAt\":\"Prompt\",\"States\":{\"Prompt\":{\"End\":true,\"Type\":\"Task\",\"ResultPath\":\"$\",\"ResultSelector\":{\"output.$\":\"$.Body.results[0].outputText\"},\"Resource\":\"arn:", + "{\"StartAt\":\"Prompt1\",\"States\":{\"Prompt1\":{\"Next\":\"Prompt2\",\"Type\":\"Task\",\"ResultPath\":\"$\",\"ResultSelector\":{\"output.$\":\"$.Body.results[0].outputText\"},\"Resource\":\"arn:", { "Ref": "AWS::Partition" }, @@ -133,14 +172,26 @@ "GuardrailId" ] }, - "\",\"GuardrailVersion\":\"", + "\",\"GuardrailVersion\":\"DRAFT\",\"Trace\":\"ENABLED\"}},\"Prompt2\":{\"End\":true,\"Type\":\"Task\",\"ResultPath\":\"$\",\"ResultSelector\":{\"output.$\":\"$.Body.results[0].outputText\"},\"Resource\":\"arn:", + { + "Ref": "AWS::Partition" + }, + ":states:::bedrock:invokeModel\",\"Parameters\":{\"ModelId\":\"arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:", + { + "Ref": "AWS::Region" + }, + "::foundation-model/amazon.titan-text-express-v1\",\"Body\":{\"inputText\":\"test attack\",\"textGenerationConfig\":{\"maxTokenCount\":100,\"temperature\":1}},\"GuardrailIdentifier\":\"", { "Fn::GetAtt": [ "Guardrail", - "Version" + "GuardrailArn" ] }, - "\",\"Trace\":\"ENABLED\"}}},\"TimeoutSeconds\":30}" + "\",\"GuardrailVersion\":\"1\",\"Trace\":\"ENABLED\"}}},\"TimeoutSeconds\":30}" ] ] }, diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/manifest.json b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/manifest.json index 35eded1a7eb9a..9dfcb5fc7d6c7 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/manifest.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/manifest.json @@ -18,7 +18,7 @@ "validateOnSynth": false, "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", - "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/575e5b852e6ff6fcf9dc3ea3b5ca454762829e7bbe6bd03fd2d6d287eaa6c486.json", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/269be7f0a4effa5d89845f9d3573f5d6bff6e3b197c0be7ef013843754f73bde.json", "requiresBootstrapStackVersion": 6, "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", "additionalDependencies": [ @@ -40,6 +40,12 @@ "data": "Guardrail" } ], + "/aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ/GuardrailVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "GuardrailVersion" + } + ], "/aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ/StateMachine/Role/Resource": [ { "type": "aws:cdk:logicalId", @@ -96,7 +102,7 @@ "validateOnSynth": false, "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", - "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/3a0b72de92a2e446cc0eeedf84a692699302ab2dadb6870030551eec68fa0657.json", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/703a8012ea44b20bd7f5450c27c27ebecf09b7f47342877fdd1c582a7f4e354f.json", "requiresBootstrapStackVersion": 6, "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", "additionalDependencies": [ @@ -161,6 +167,12 @@ "data": "SingletonFunction1488541a7b23466481b69b4408076b81HandlerCD40AE9F" } ], + "/InvokeModel/DefaultTest/DeployAssert/LatestNodeRuntimeMap": [ + { + "type": "aws:cdk:logicalId", + "data": "LatestNodeRuntimeMap" + } + ], "/InvokeModel/DefaultTest/DeployAssert/SingletonFunction76b3e830a873425f8453eddd85c86925/Role": [ { "type": "aws:cdk:logicalId", diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/tree.json b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/tree.json index 9290e045061a3..e75fdb936eab3 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/tree.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.js.snapshot/tree.json @@ -36,16 +36,43 @@ } }, "constructInfo": { - "fqn": "aws-cdk-lib.aws_bedrock.CfnGuardrail", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, - "Prompt": { - "id": "Prompt", - "path": "aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ/Prompt", + "GuardrailVersion": { + "id": "GuardrailVersion", + "path": "aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ/GuardrailVersion", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::Bedrock::GuardrailVersion", + "aws:cdk:cloudformation:props": { + "guardrailIdentifier": { + "Fn::GetAtt": [ + "Guardrail", + "GuardrailId" + ] + } + } + }, "constructInfo": { - "fqn": "aws-cdk-lib.aws_stepfunctions.TaskStateBase", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" + } + }, + "Prompt1": { + "id": "Prompt1", + "path": "aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ/Prompt1", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.3.0" + } + }, + "Prompt2": { + "id": "Prompt2", + "path": "aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ/Prompt2", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "StateMachine": { @@ -60,8 +87,8 @@ "id": "ImportRole", "path": "aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ/StateMachine/Role/ImportRole", "constructInfo": { - "fqn": "aws-cdk-lib.Resource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "Resource": { @@ -85,8 +112,8 @@ } }, "constructInfo": { - "fqn": "aws-cdk-lib.aws_iam.CfnRole", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "DefaultPolicy": { @@ -124,32 +151,60 @@ { "Action": "bedrock:ApplyGuardrail", "Effect": "Allow", - "Resource": { - "Fn::Join": [ - "", - [ - "arn:", - { - "Ref": "AWS::Partition" - }, - ":bedrock:", - { - "Ref": "AWS::Region" - }, - ":", - { - "Ref": "AWS::AccountId" - }, - ":guardrail/", - { - "Fn::GetAtt": [ - "Guardrail", - "GuardrailId" - ] - } + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":guardrail/", + { + "Fn::GetAtt": [ + "Guardrail", + "GuardrailArn" + ] + } + ] ] - ] - } + }, + { + "Fn::Join": [ + "", + [ + "arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:", + { + "Ref": "AWS::Region" + }, + ":", + { + "Ref": "AWS::AccountId" + }, + ":guardrail/", + { + "Fn::GetAtt": [ + "Guardrail", + "GuardrailId" + ] + } + ] + ] + } + ] } ], "Version": "2012-10-17" @@ -163,20 +218,20 @@ } }, "constructInfo": { - "fqn": "aws-cdk-lib.aws_iam.CfnPolicy", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, "constructInfo": { - "fqn": "aws-cdk-lib.aws_iam.Policy", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, "constructInfo": { - "fqn": "aws-cdk-lib.aws_iam.Role", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "Resource": { @@ -189,7 +244,7 @@ "Fn::Join": [ "", [ - "{\"StartAt\":\"Prompt\",\"States\":{\"Prompt\":{\"End\":true,\"Type\":\"Task\",\"ResultPath\":\"$\",\"ResultSelector\":{\"output.$\":\"$.Body.results[0].outputText\"},\"Resource\":\"arn:", + "{\"StartAt\":\"Prompt1\",\"States\":{\"Prompt1\":{\"Next\":\"Prompt2\",\"Type\":\"Task\",\"ResultPath\":\"$\",\"ResultSelector\":{\"output.$\":\"$.Body.results[0].outputText\"},\"Resource\":\"arn:", { "Ref": "AWS::Partition" }, @@ -208,14 +263,26 @@ "GuardrailId" ] }, - "\",\"GuardrailVersion\":\"", + "\",\"GuardrailVersion\":\"DRAFT\",\"Trace\":\"ENABLED\"}},\"Prompt2\":{\"End\":true,\"Type\":\"Task\",\"ResultPath\":\"$\",\"ResultSelector\":{\"output.$\":\"$.Body.results[0].outputText\"},\"Resource\":\"arn:", + { + "Ref": "AWS::Partition" + }, + ":states:::bedrock:invokeModel\",\"Parameters\":{\"ModelId\":\"arn:", + { + "Ref": "AWS::Partition" + }, + ":bedrock:", + { + "Ref": "AWS::Region" + }, + "::foundation-model/amazon.titan-text-express-v1\",\"Body\":{\"inputText\":\"test attack\",\"textGenerationConfig\":{\"maxTokenCount\":100,\"temperature\":1}},\"GuardrailIdentifier\":\"", { "Fn::GetAtt": [ "Guardrail", - "Version" + "GuardrailArn" ] }, - "\",\"Trace\":\"ENABLED\"}}},\"TimeoutSeconds\":30}" + "\",\"GuardrailVersion\":\"1\",\"Trace\":\"ENABLED\"}}},\"TimeoutSeconds\":30}" ] ] }, @@ -228,14 +295,14 @@ } }, "constructInfo": { - "fqn": "aws-cdk-lib.aws_stepfunctions.CfnStateMachine", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, "constructInfo": { - "fqn": "aws-cdk-lib.aws_stepfunctions.StateMachine", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "Exports": { @@ -246,8 +313,8 @@ "id": "Output{\"Ref\":\"StateMachine2E01A3A5\"}", "path": "aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ/Exports/Output{\"Ref\":\"StateMachine2E01A3A5\"}", "constructInfo": { - "fqn": "aws-cdk-lib.CfnOutput", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, @@ -260,22 +327,22 @@ "id": "BootstrapVersion", "path": "aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ/BootstrapVersion", "constructInfo": { - "fqn": "aws-cdk-lib.CfnParameter", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "CheckBootstrapVersion": { "id": "CheckBootstrapVersion", "path": "aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ/CheckBootstrapVersion", "constructInfo": { - "fqn": "aws-cdk-lib.CfnRule", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, "constructInfo": { - "fqn": "aws-cdk-lib.Stack", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "InvokeModel": { @@ -328,14 +395,14 @@ "id": "Default", "path": "InvokeModel/DefaultTest/DeployAssert/AwsApiCallStepFunctionsdescribeStateMachinec5cc0786542148808c24d8ebf111c7aa/Default/Default", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, "constructInfo": { - "fqn": "aws-cdk-lib.CustomResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "WaitFor": { @@ -358,8 +425,8 @@ "id": "Invoke", "path": "InvokeModel/DefaultTest/DeployAssert/AwsApiCallStepFunctionsdescribeStateMachinec5cc0786542148808c24d8ebf111c7aa/WaitFor/IsCompleteProvider/Invoke", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, @@ -384,8 +451,8 @@ "id": "Invoke", "path": "InvokeModel/DefaultTest/DeployAssert/AwsApiCallStepFunctionsdescribeStateMachinec5cc0786542148808c24d8ebf111c7aa/WaitFor/TimeoutProvider/Invoke", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, @@ -398,16 +465,16 @@ "id": "Role", "path": "InvokeModel/DefaultTest/DeployAssert/AwsApiCallStepFunctionsdescribeStateMachinec5cc0786542148808c24d8ebf111c7aa/WaitFor/Role", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "Resource": { "id": "Resource", "path": "InvokeModel/DefaultTest/DeployAssert/AwsApiCallStepFunctionsdescribeStateMachinec5cc0786542148808c24d8ebf111c7aa/WaitFor/Resource", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, @@ -420,8 +487,8 @@ "id": "AssertionResults", "path": "InvokeModel/DefaultTest/DeployAssert/AwsApiCallStepFunctionsdescribeStateMachinec5cc0786542148808c24d8ebf111c7aa/AssertionResults", "constructInfo": { - "fqn": "aws-cdk-lib.CfnOutput", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, @@ -438,24 +505,24 @@ "id": "Staging", "path": "InvokeModel/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Staging", "constructInfo": { - "fqn": "aws-cdk-lib.AssetStaging", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "Role": { "id": "Role", "path": "InvokeModel/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Role", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "Handler": { "id": "Handler", "path": "InvokeModel/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Handler", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, @@ -464,6 +531,14 @@ "version": "10.3.0" } }, + "LatestNodeRuntimeMap": { + "id": "LatestNodeRuntimeMap", + "path": "InvokeModel/DefaultTest/DeployAssert/LatestNodeRuntimeMap", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.3.0" + } + }, "SingletonFunction76b3e830a873425f8453eddd85c86925": { "id": "SingletonFunction76b3e830a873425f8453eddd85c86925", "path": "InvokeModel/DefaultTest/DeployAssert/SingletonFunction76b3e830a873425f8453eddd85c86925", @@ -472,24 +547,24 @@ "id": "Staging", "path": "InvokeModel/DefaultTest/DeployAssert/SingletonFunction76b3e830a873425f8453eddd85c86925/Staging", "constructInfo": { - "fqn": "aws-cdk-lib.AssetStaging", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "Role": { "id": "Role", "path": "InvokeModel/DefaultTest/DeployAssert/SingletonFunction76b3e830a873425f8453eddd85c86925/Role", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "Handler": { "id": "Handler", "path": "InvokeModel/DefaultTest/DeployAssert/SingletonFunction76b3e830a873425f8453eddd85c86925/Handler", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, @@ -506,24 +581,24 @@ "id": "Staging", "path": "InvokeModel/DefaultTest/DeployAssert/SingletonFunction5c1898e096fb4e3e95d5f6c67f3ce41a/Staging", "constructInfo": { - "fqn": "aws-cdk-lib.AssetStaging", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "Role": { "id": "Role", "path": "InvokeModel/DefaultTest/DeployAssert/SingletonFunction5c1898e096fb4e3e95d5f6c67f3ce41a/Role", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "Handler": { "id": "Handler", "path": "InvokeModel/DefaultTest/DeployAssert/SingletonFunction5c1898e096fb4e3e95d5f6c67f3ce41a/Handler", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, @@ -562,14 +637,14 @@ "id": "Default", "path": "InvokeModel/DefaultTest/DeployAssert/AwsApiCallStepFunctionsstartExecutionc5cc0786542148808c24d8ebf111c7aa/Default/Default", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, "constructInfo": { - "fqn": "aws-cdk-lib.CustomResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, @@ -608,14 +683,14 @@ "id": "Default", "path": "InvokeModel/DefaultTest/DeployAssert/AwsApiCallStepFunctionsdescribeExecution7e7cfa5e3c60aef760b5fbff9448d868/Default/Default", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, "constructInfo": { - "fqn": "aws-cdk-lib.CustomResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "WaitFor": { @@ -638,8 +713,8 @@ "id": "Invoke", "path": "InvokeModel/DefaultTest/DeployAssert/AwsApiCallStepFunctionsdescribeExecution7e7cfa5e3c60aef760b5fbff9448d868/WaitFor/IsCompleteProvider/Invoke", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, @@ -664,8 +739,8 @@ "id": "Invoke", "path": "InvokeModel/DefaultTest/DeployAssert/AwsApiCallStepFunctionsdescribeExecution7e7cfa5e3c60aef760b5fbff9448d868/WaitFor/TimeoutProvider/Invoke", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, @@ -678,16 +753,16 @@ "id": "Role", "path": "InvokeModel/DefaultTest/DeployAssert/AwsApiCallStepFunctionsdescribeExecution7e7cfa5e3c60aef760b5fbff9448d868/WaitFor/Role", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "Resource": { "id": "Resource", "path": "InvokeModel/DefaultTest/DeployAssert/AwsApiCallStepFunctionsdescribeExecution7e7cfa5e3c60aef760b5fbff9448d868/WaitFor/Resource", "constructInfo": { - "fqn": "aws-cdk-lib.CfnResource", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, @@ -700,8 +775,8 @@ "id": "AssertionResults", "path": "InvokeModel/DefaultTest/DeployAssert/AwsApiCallStepFunctionsdescribeExecution7e7cfa5e3c60aef760b5fbff9448d868/AssertionResults", "constructInfo": { - "fqn": "aws-cdk-lib.CfnOutput", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, @@ -714,22 +789,22 @@ "id": "BootstrapVersion", "path": "InvokeModel/DefaultTest/DeployAssert/BootstrapVersion", "constructInfo": { - "fqn": "aws-cdk-lib.CfnParameter", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } }, "CheckBootstrapVersion": { "id": "CheckBootstrapVersion", "path": "InvokeModel/DefaultTest/DeployAssert/CheckBootstrapVersion", "constructInfo": { - "fqn": "aws-cdk-lib.CfnRule", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, "constructInfo": { - "fqn": "aws-cdk-lib.Stack", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } }, @@ -754,8 +829,8 @@ } }, "constructInfo": { - "fqn": "aws-cdk-lib.App", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.3.0" } } } \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.ts b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.ts index 75b57bc08d2d0..0bd416fd484dd 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.ts +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-stepfunctions-tasks/test/bedrock/integ.invoke-model-guardrail-trace.ts @@ -2,7 +2,7 @@ import * as bedrock from 'aws-cdk-lib/aws-bedrock'; import * as sfn from 'aws-cdk-lib/aws-stepfunctions'; import * as cdk from 'aws-cdk-lib'; import { ExpectedResult, IntegTest } from '@aws-cdk/integ-tests-alpha'; -import { BedrockInvokeModel } from 'aws-cdk-lib/aws-stepfunctions-tasks'; +import { BedrockInvokeModel, Guardrail } from 'aws-cdk-lib/aws-stepfunctions-tasks'; const app = new cdk.App(); const stack = new cdk.Stack(app, 'aws-stepfunctions-tasks-bedrock-invoke-model-guardrail-trace-integ'); @@ -27,7 +27,12 @@ const guardrail = new bedrock.CfnGuardrail(stack, 'Guardrail', { }, }); -const prompt = new BedrockInvokeModel(stack, 'Prompt', { +// Create Version 1 +new bedrock.CfnGuardrailVersion(stack, 'GuardrailVersion', { + guardrailIdentifier: guardrail.attrGuardrailId, +}); + +const prompt1 = new BedrockInvokeModel(stack, 'Prompt1', { model, body: sfn.TaskInput.fromObject( { @@ -38,10 +43,26 @@ const prompt = new BedrockInvokeModel(stack, 'Prompt', { }, }, ), - guardrail: { - guardrailIdentifier: guardrail.attrGuardrailId, - guardrailVersion: guardrail.attrVersion, + guardrail: Guardrail.enableDraft(guardrail.attrGuardrailId), + traceEnabled: true, + resultSelector: { + output: sfn.JsonPath.stringAt('$.Body.results[0].outputText'), }, + resultPath: '$', +}); + +const prompt2 = new BedrockInvokeModel(stack, 'Prompt2', { + model, + body: sfn.TaskInput.fromObject( + { + inputText: 'test attack', + textGenerationConfig: { + maxTokenCount: 100, + temperature: 1, + }, + }, + ), + guardrail: Guardrail.enable(guardrail.attrGuardrailArn, 1), traceEnabled: true, resultSelector: { output: sfn.JsonPath.stringAt('$.Body.results[0].outputText'), @@ -49,7 +70,7 @@ const prompt = new BedrockInvokeModel(stack, 'Prompt', { resultPath: '$', }); -const chain = sfn.Chain.start(prompt); +const chain = sfn.Chain.start(prompt1).next(prompt2); const stateMachine = new sfn.StateMachine(stack, 'StateMachine', { definitionBody: sfn.DefinitionBody.fromChainable(chain), @@ -88,5 +109,3 @@ describe.expect(ExpectedResult.objectLike({ interval: cdk.Duration.seconds(10), totalTimeout: cdk.Duration.minutes(5), }); - -app.synth(); diff --git a/packages/aws-cdk-lib/aws-stepfunctions-tasks/lib/bedrock/guardrail.ts b/packages/aws-cdk-lib/aws-stepfunctions-tasks/lib/bedrock/guardrail.ts new file mode 100644 index 0000000000000..3a422ee690623 --- /dev/null +++ b/packages/aws-cdk-lib/aws-stepfunctions-tasks/lib/bedrock/guardrail.ts @@ -0,0 +1,48 @@ +import { Token } from '../../../core'; + +/** + * Guradrail settings for BedrockInvokeModel + */ +export class Guardrail { + /** + * Enable guardrail + * + * @param identifier The id or arn of the guardrail. + * @param version The version of the guardrail. + */ + public static enable(identifier: string, version: number): Guardrail { + if (!Token.isUnresolved(version)) { + if (version < 1 || version > 99999999) { + throw new Error(`\`version\` must be between 1 and 99999999, got ${version}.`); + } + } + return new Guardrail(identifier, version.toString()); + } + + /** + * Enable guardrail with DRAFT version + * + * @param identifier The identifier of the guardrail. Must be between 1 and 2048 characters in length. + */ + public static enableDraft(identifier: string): Guardrail { + return new Guardrail(identifier, 'DRAFT'); + } + + /** + * @param guardrailIdentifier The identitifier of guardrail. + * @param guardrailVersion The version of guardrail. + */ + private constructor(public readonly guardrailIdentifier: string, public readonly guardrailVersion: string) { + if (!Token.isUnresolved(guardrailIdentifier)) { + const guardrailPattern = /^(([a-z0-9]+)|(arn:aws(-[^:]+)?:bedrock:[a-z0-9-]{1,20}:[0-9]{12}:guardrail\/[a-z0-9]+))$/; + + if (!guardrailPattern.test(guardrailIdentifier)) { + throw new Error(`You must set guardrailIdentifier to the id or the arn of Guardrail, got ${guardrailIdentifier}`); + } + + if (guardrailIdentifier.length > 2048) { + throw new Error(`\`guardrailIdentifier\` length must be between 0 and 2048, got ${guardrailIdentifier.length}.`); + } + } + } +} diff --git a/packages/aws-cdk-lib/aws-stepfunctions-tasks/lib/bedrock/invoke-model.ts b/packages/aws-cdk-lib/aws-stepfunctions-tasks/lib/bedrock/invoke-model.ts index f71e061067305..f831cf606c8c5 100644 --- a/packages/aws-cdk-lib/aws-stepfunctions-tasks/lib/bedrock/invoke-model.ts +++ b/packages/aws-cdk-lib/aws-stepfunctions-tasks/lib/bedrock/invoke-model.ts @@ -1,9 +1,10 @@ import { Construct } from 'constructs'; +import { Guardrail } from './guardrail'; import * as bedrock from '../../../aws-bedrock'; import * as iam from '../../../aws-iam'; import * as s3 from '../../../aws-s3'; import * as sfn from '../../../aws-stepfunctions'; -import { Stack, Token } from '../../../core'; +import { Stack } from '../../../core'; import { integrationResourceArn, validatePatternSupported } from '../private/task-utils'; /** @@ -41,21 +42,6 @@ export interface BedrockInvokeModelOutputProps { readonly s3Location?: s3.Location; } -/** - * Properties for the guardrail. - */ -export interface Guardrail { - /** - * The unique identifier of the guardrail that you want to use. - */ - readonly guardrailIdentifier: string; - - /** - * The version number for the guardrail. - */ - readonly guardrailVersion: string; -} - /** * Properties for invoking a Bedrock Model */ @@ -101,6 +87,7 @@ export interface BedrockInvokeModelProps extends sfn.TaskStateBaseProps { * * @see https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html * @default 'application/json' + * @deprecated This property does not require configuration because the only acceptable value is 'application/json'. */ readonly contentType?: string; @@ -173,8 +160,6 @@ export class BedrockInvokeModel extends sfn.TaskStateBase { throw new Error('Output S3 object version is not supported.'); } - this.validateGuardrail(props); - this.taskPolicies = this.renderPolicyStatements(); } @@ -270,30 +255,4 @@ export class BedrockInvokeModel extends sfn.TaskStateBase { }), }; } - - private validateGuardrail(props: BedrockInvokeModelProps) { - if (!props.guardrail) return; - - const { guardrailIdentifier, guardrailVersion } = props.guardrail; - - if (!Token.isUnresolved(guardrailIdentifier)) { - const guardrailPattern = /^(([a-z0-9]+)|(arn:aws(-[^:]+)?:bedrock:[a-z0-9-]{1,20}:[0-9]{12}:guardrail\/[a-z0-9]+))$/; - if (!guardrailPattern.test(guardrailIdentifier)) { - throw new Error(`You must set guardrailIdentifier to the id or the arn of Guardrail, got ${guardrailIdentifier}`); - } - if (props.contentType !== 'application/json') { - throw new Error(`You must set contentType to \'application/json\' when using guardrail, got '${props.contentType}'.`); - } - if (guardrailIdentifier.length > 2048) { - throw new Error(`\`guardrailIdentifier\` length must be between 0 and 2048, got ${guardrailIdentifier.length}.`); - } - - } - - const guardrailVersionPattern = /^(([1-9][0-9]{0,7})|(DRAFT))$/; - if (!Token.isUnresolved(guardrailVersion) && !guardrailVersionPattern.test(guardrailVersion)) { - throw new Error(`\`guardrailVersion\` must be either 'DRAFT' or a string representing a number between 1 and 99999999, got ${guardrailVersion}.`); - } - - } } diff --git a/packages/aws-cdk-lib/aws-stepfunctions-tasks/lib/index.ts b/packages/aws-cdk-lib/aws-stepfunctions-tasks/lib/index.ts index 99447e123ac67..7477df0071ecb 100644 --- a/packages/aws-cdk-lib/aws-stepfunctions-tasks/lib/index.ts +++ b/packages/aws-cdk-lib/aws-stepfunctions-tasks/lib/index.ts @@ -55,5 +55,6 @@ export * from './apigateway'; export * from './eventbridge/put-events'; export * from './aws-sdk/call-aws-service'; export * from './bedrock/invoke-model'; +export * from './bedrock/guardrail'; export * from './http/invoke'; export * from './mediaconvert/create-job'; diff --git a/packages/aws-cdk-lib/aws-stepfunctions-tasks/test/bedrock/invoke-model.test.ts b/packages/aws-cdk-lib/aws-stepfunctions-tasks/test/bedrock/invoke-model.test.ts index 4b8e01b19a18f..10c21e187549b 100644 --- a/packages/aws-cdk-lib/aws-stepfunctions-tasks/test/bedrock/invoke-model.test.ts +++ b/packages/aws-cdk-lib/aws-stepfunctions-tasks/test/bedrock/invoke-model.test.ts @@ -2,6 +2,7 @@ import { Template, Match } from '../../../assertions'; import * as bedrock from '../../../aws-bedrock'; import * as sfn from '../../../aws-stepfunctions'; import * as cdk from '../../../core'; +import { Guardrail } from '../../lib/bedrock/guardrail'; import { BedrockInvokeModel } from '../../lib/bedrock/invoke-model'; describe('Invoke Model', () => { @@ -369,16 +370,12 @@ describe('Invoke Model', () => { // WHEN const task = new BedrockInvokeModel(stack, 'Invoke', { model, - contentType: 'application/json', body: sfn.TaskInput.fromObject( { prompt: 'Hello world', }, ), - guardrail: { - guardrailIdentifier: 'arn:aws:bedrock:us-turbo-2:123456789012:guardrail/testid', - guardrailVersion: 'DRAFT', - }, + guardrail: Guardrail.enableDraft('arn:aws:bedrock:us-turbo-2:123456789012:guardrail/testid'), }); new sfn.StateMachine(stack, 'StateMachine', { @@ -406,7 +403,6 @@ describe('Invoke Model', () => { Body: { prompt: 'Hello world', }, - ContentType: 'application/json', GuardrailIdentifier: 'arn:aws:bedrock:us-turbo-2:123456789012:guardrail/testid', GuardrailVersion: 'DRAFT', }, @@ -438,16 +434,12 @@ describe('Invoke Model', () => { // WHEN const task = new BedrockInvokeModel(stack, 'Invoke', { model, - contentType: 'application/json', body: sfn.TaskInput.fromObject( { prompt: 'Hello world', }, ), - guardrail: { - guardrailIdentifier: 'testid', - guardrailVersion: 'DRAFT', - }, + guardrail: Guardrail.enable('testid', 3), }); new sfn.StateMachine(stack, 'StateMachine', { @@ -475,9 +467,8 @@ describe('Invoke Model', () => { Body: { prompt: 'Hello world', }, - ContentType: 'application/json', GuardrailIdentifier: 'testid', - GuardrailVersion: 'DRAFT', + GuardrailVersion: '3', }, }); @@ -527,16 +518,12 @@ describe('Invoke Model', () => { // WHEN new BedrockInvokeModel(stack, 'Invoke', { model, - contentType: 'application/json', body: sfn.TaskInput.fromObject( { prompt: 'Hello world', }, ), - guardrail: { - guardrailIdentifier: 'invalid-id', - guardrailVersion: 'DRAFT', - }, + guardrail: Guardrail.enableDraft('invalid-id'), }); // THEN }).toThrow('You must set guardrailIdentifier to the id or the arn of Guardrail, got invalid-id'); @@ -552,16 +539,12 @@ describe('Invoke Model', () => { // WHEN new BedrockInvokeModel(stack, 'Invoke', { model, - contentType: 'application/json', body: sfn.TaskInput.fromObject( { prompt: 'Hello world', }, ), - guardrail: { - guardrailIdentifier, - guardrailVersion: 'DRAFT', - }, + guardrail: Guardrail.enableDraft(guardrailIdentifier), }); // THEN }).toThrow(`\`guardrailIdentifier\` length must be between 0 and 2048, got ${guardrailIdentifier.length}.`); @@ -576,43 +559,15 @@ describe('Invoke Model', () => { // WHEN const task = new BedrockInvokeModel(stack, 'Invoke', { model, - contentType: 'application/json', - body: sfn.TaskInput.fromObject( - { - prompt: 'Hello world', - }, - ), - guardrail: { - guardrailIdentifier: 'abcdef', - guardrailVersion: 'test', - }, - }); - // THEN - }).toThrow('`guardrailVersion` must be either \'DRAFT\' or a string representing a number between 1 and 99999999, got test.'); - }); - - test('guardrail fails when contentType is not \'application/json\'', () => { - // GIVEN - const stack = new cdk.Stack(); - const model = bedrock.ProvisionedModel.fromProvisionedModelArn(stack, 'Imported', 'arn:aws:bedrock:us-turbo-2:123456789012:provisioned-model/abc-123'); - - expect(() => { - // WHEN - const task = new BedrockInvokeModel(stack, 'Invoke', { - model, - contentType: 'text/plain', body: sfn.TaskInput.fromObject( { prompt: 'Hello world', }, ), - guardrail: { - guardrailIdentifier: 'abcdef', - guardrailVersion: 'DRAFT', - }, + guardrail: Guardrail.enable('abcde', 0), }); // THEN - }).toThrow('You must set contentType to \'application/json\' when using guardrail, got \'text/plain\'.'); + }).toThrow('\`version\` must be between 1 and 99999999, got 0.'); }); test('trace configuration', () => {