@slates/provider 1.0.0-rc.7 → 1.0.0-rc.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/index.cjs +1588 -2
  2. package/dist/index.d.cts +602 -0
  3. package/dist/index.d.ts +602 -9
  4. package/dist/index.module.js +1519 -2
  5. package/package.json +7 -5
  6. package/src/action/action.ts +16 -3
  7. package/src/action/builder.ts +21 -4
  8. package/src/action/index.ts +2 -2
  9. package/src/action/scopes.test.ts +77 -0
  10. package/src/action/scopes.ts +101 -0
  11. package/src/action/tool.ts +8 -4
  12. package/src/action/trigger.ts +11 -11
  13. package/src/auth/auth.ts +3 -3
  14. package/src/auth/types.ts +7 -6
  15. package/src/axios/index.ts +55 -23
  16. package/src/axios/trace.ts +443 -0
  17. package/src/config/config.ts +3 -3
  18. package/src/context/context.ts +29 -2
  19. package/src/context/hook.ts +1 -1
  20. package/src/error/axios.ts +219 -0
  21. package/src/error/base.test.ts +178 -0
  22. package/src/error/base.ts +108 -2
  23. package/src/error/declaration.ts +7 -2
  24. package/src/error/defaults.ts +50 -0
  25. package/src/error/index.ts +3 -0
  26. package/src/error/service.ts +160 -0
  27. package/src/error/types.ts +73 -0
  28. package/src/error/utils.ts +155 -0
  29. package/src/logger/logger.test.ts +57 -0
  30. package/src/logger/logger.ts +72 -11
  31. package/src/specification/slate.ts +2 -2
  32. package/src/specification/specification.ts +2 -2
  33. package/dist/action/action.d.ts +0 -98
  34. package/dist/action/action.d.ts.map +0 -1
  35. package/dist/action/builder.d.ts +0 -27
  36. package/dist/action/builder.d.ts.map +0 -1
  37. package/dist/action/index.d.ts +0 -5
  38. package/dist/action/index.d.ts.map +0 -1
  39. package/dist/action/tool.d.ts +0 -14
  40. package/dist/action/tool.d.ts.map +0 -1
  41. package/dist/action/trigger.d.ts +0 -32
  42. package/dist/action/trigger.d.ts.map +0 -1
  43. package/dist/auth/auth.d.ts +0 -30
  44. package/dist/auth/auth.d.ts.map +0 -1
  45. package/dist/auth/index.d.ts +0 -3
  46. package/dist/auth/index.d.ts.map +0 -1
  47. package/dist/auth/types.d.ts +0 -150
  48. package/dist/auth/types.d.ts.map +0 -1
  49. package/dist/axios/index.d.ts +0 -4
  50. package/dist/axios/index.d.ts.map +0 -1
  51. package/dist/config/config.d.ts +0 -26
  52. package/dist/config/config.d.ts.map +0 -1
  53. package/dist/config/index.d.ts +0 -2
  54. package/dist/config/index.d.ts.map +0 -1
  55. package/dist/context/context.d.ts +0 -20
  56. package/dist/context/context.d.ts.map +0 -1
  57. package/dist/context/hook.d.ts +0 -4
  58. package/dist/context/hook.d.ts.map +0 -1
  59. package/dist/context/index.d.ts +0 -3
  60. package/dist/context/index.d.ts.map +0 -1
  61. package/dist/error/base.d.ts +0 -5
  62. package/dist/error/base.d.ts.map +0 -1
  63. package/dist/error/declaration.d.ts +0 -6
  64. package/dist/error/declaration.d.ts.map +0 -1
  65. package/dist/error/index.d.ts +0 -3
  66. package/dist/error/index.d.ts.map +0 -1
  67. package/dist/index.cjs.map +0 -1
  68. package/dist/index.d.ts.map +0 -1
  69. package/dist/index.modern.js +0 -2
  70. package/dist/index.modern.js.map +0 -1
  71. package/dist/index.module.js.map +0 -1
  72. package/dist/index.umd.js +0 -2
  73. package/dist/index.umd.js.map +0 -1
  74. package/dist/logger/index.d.ts +0 -2
  75. package/dist/logger/index.d.ts.map +0 -1
  76. package/dist/logger/logger.d.ts +0 -20
  77. package/dist/logger/logger.d.ts.map +0 -1
  78. package/dist/specification/index.d.ts +0 -3
  79. package/dist/specification/index.d.ts.map +0 -1
  80. package/dist/specification/slate.d.ts +0 -15
  81. package/dist/specification/slate.d.ts.map +0 -1
  82. package/dist/specification/specification.d.ts +0 -30
  83. package/dist/specification/specification.d.ts.map +0 -1
  84. package/dist/specification/zero.d.ts +0 -13
  85. package/dist/specification/zero.d.ts.map +0 -1
  86. package/dist/tokens.d.ts +0 -34
  87. package/dist/tokens.d.ts.map +0 -1
@@ -1,2 +1,1519 @@
1
- import t from"axios";import{AsyncLocalStorage as e}from"async_hooks";import{encode as n}from"@toon-format/toon";import r from"zod";function i(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function o(t,e){if(!{}.hasOwnProperty.call(t,e))throw new TypeError("attempted to use private field on non-instance");return t}var u=0;function a(t){return"__private_"+u+++"_"+t}function c(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,g(r.key),r)}}function s(t,e,n){return e&&c(t.prototype,e),n&&c(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function h(){return h=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},h.apply(null,arguments)}function f(t){return f=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},f(t)}function l(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,d(t,e)}function p(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(p=function(){return!!t})()}function d(t,e){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},d(t,e)}function g(t){var e=function(t){if("object"!=typeof t||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var n=e.call(t,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t);return"symbol"==typeof e?e:e+""}function y(t){var e="function"==typeof Map?new Map:void 0;return y=function(t){if(null===t||!function(t){try{return-1!==Function.toString.call(t).indexOf("[native code]")}catch(e){return"function"==typeof t}}(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,n)}function n(){return function(t,e,n){if(p())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,e);var i=new(t.bind.apply(t,r));return n&&d(i,n.prototype),i}(t,arguments,f(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),d(n,t)},y(t)}var v=/*#__PURE__*/function(){return s(function(t,e,n,r,i){this.type=void 0,this._spec=void 0,this._inputSchema=void 0,this._outputSchema=void 0,this._params=void 0,this.type=t,this._spec=e,this._inputSchema=n,this._outputSchema=r,this._params=i},[{key:"configSchema",get:function(){return this._spec.configSchema}},{key:"inputSchema",get:function(){return this._inputSchema}},{key:"outputSchema",get:function(){return this._outputSchema}},{key:"parameters",get:function(){return this._params}},{key:"key",get:function(){return this._params.key}},{key:"name",get:function(){return this._params.name}},{key:"description",get:function(){return this._params.description}},{key:"tags",get:function(){return this._params.tags}},{key:"instructions",get:function(){return this._params.instructions}},{key:"constraints",get:function(){return this._params.constraints}},{key:"metadata",get:function(){return this._params.metadata}}])}(),b=/*#__PURE__*/function(t){function e(e){var n;return(n=t.call(this,e)||this).name="SlateError",n}return l(e,t),e.is=function(t){return t instanceof e},e}(/*#__PURE__*/y(Error)),m=/*#__PURE__*/function(t){function e(e){var n;return(n=t.call(this,"[Declaration Error]: "+e)||this).name="SlateError.DeclarationError",n}return l(e,t),e.is=function(t){return t instanceof e},e}(b),w=/*#__PURE__*/a("configSchema"),k=/*#__PURE__*/a("authSchema"),O=/*#__PURE__*/a("inputSchema"),S=/*#__PURE__*/a("outputSchema"),_=/*#__PURE__*/a("toolParams"),j=/*#__PURE__*/a("triggerParams"),P=/*#__PURE__*/function(){function t(t,e,n,r){this.type=void 0,this.spec=void 0,this.params=void 0,this.factory=void 0,Object.defineProperty(this,w,{writable:!0,value:void 0}),Object.defineProperty(this,k,{writable:!0,value:void 0}),Object.defineProperty(this,O,{writable:!0,value:null}),Object.defineProperty(this,S,{writable:!0,value:null}),Object.defineProperty(this,_,{writable:!0,value:null}),Object.defineProperty(this,j,{writable:!0,value:null}),this.type=t,this.spec=e,this.params=n,this.factory=r,o(this,w)[w]=e.configSchema,o(this,k)[k]=e.authSchema}var e=t.prototype;return e.input=function(t){return o(this,O)[O]=t,this},e.output=function(t){return o(this,S)[S]=t,this},e.handleInvocation=function(t){if("tool"!==this.type)throw new m("handleInvocation can only be set for tool actions");return o(this,_)[_]={type:"tool",handleInvocation:t},this},e.webhook=function(t){if("trigger"!==this.type)throw new m("handleEvent can only be set for trigger actions");return o(this,j)[j]={type:"trigger",source:"webhook",handleEvent:t.handleEvent,handleRequest:t.handleRequest,autoRegisterWebhook:t.autoRegisterWebhook,autoUnregisterWebhook:t.autoUnregisterWebhook},this},e.polling=function(t){if("trigger"!==this.type)throw new m("handleEvent can only be set for trigger actions");return o(this,j)[j]={type:"trigger",source:"polling",polling:t.options,pollEvents:t.pollEvents,handleEvent:t.handleEvent},this},e.build=function(){if(!o(this,O)[O])throw new m("Input schema is not defined");if(!o(this,S)[S])throw new m("Output schema is not defined");if("tool"===this.type&&!o(this,_)[_])throw new m("Tool invocation handler is not defined");if("trigger"===this.type&&!o(this,j)[j])throw new m("Trigger event handlers are not defined");return this.factory(h({},this.params,{configSchema:o(this,w)[w],authSchema:o(this,k)[k],inputSchema:o(this,O)[O],outputSchema:o(this,S)[S]},o(this,_)[_],o(this,j)[j]))},t}(),E=/*#__PURE__*/a("handleInvocation"),A=/*#__PURE__*/function(t){function e(e,n,r,i){var u;return u=t.call(this,"tool",e,n,r,i)||this,Object.defineProperty(u,E,{writable:!0,value:void 0}),o(u,E)[E]=i.handleInvocation,u}return l(e,t),e.create=function(t,n){return new P("tool",t,n,function(n){if("tool"!=n.type)throw new Error("Invalid action type for tool");return new e(t,n.inputSchema,n.outputSchema,n)})},s(e,[{key:"handleInvocation",get:function(){return o(this,E)[E]}}])}(v),R=function(t,e){return A.create(t,e)},I=600,W=/*#__PURE__*/a("source"),q=/*#__PURE__*/a("polling"),C=/*#__PURE__*/a("handleEvent"),T=/*#__PURE__*/a("handleRequest"),U=/*#__PURE__*/a("pollEvents"),x=/*#__PURE__*/a("autoRegisterWebhook"),z=/*#__PURE__*/a("autoUnregisterWebhook"),D=/*#__PURE__*/function(t){function e(e,n,r,i){var u;return u=t.call(this,"trigger",e,n,r,i)||this,Object.defineProperty(u,W,{writable:!0,value:void 0}),Object.defineProperty(u,q,{writable:!0,value:void 0}),Object.defineProperty(u,C,{writable:!0,value:void 0}),Object.defineProperty(u,T,{writable:!0,value:void 0}),Object.defineProperty(u,U,{writable:!0,value:void 0}),Object.defineProperty(u,x,{writable:!0,value:void 0}),Object.defineProperty(u,z,{writable:!0,value:void 0}),o(u,W)[W]=i.source,o(u,q)[q]=i.polling||{intervalInSeconds:600},o(u,C)[C]=i.handleEvent,o(u,T)[T]=i.handleRequest,o(u,U)[U]=i.pollEvents,o(u,x)[x]=i.autoRegisterWebhook,o(u,z)[z]=i.autoUnregisterWebhook,u}return l(e,t),e.create=function(t,n){return new P("trigger",t,n,function(n){if("trigger"!=n.type)throw new Error("Invalid action type for trigger");return new e(t,n.inputSchema,n.outputSchema,n)})},s(e,[{key:"polling",get:function(){return o(this,q)[q]}},{key:"source",get:function(){return o(this,W)[W]}},{key:"handleEvent",get:function(){return o(this,C)[C]}},{key:"handleRequest",get:function(){return o(this,T)[T]}},{key:"pollEvents",get:function(){return o(this,U)[U]}},{key:"autoRegisterWebhook",get:function(){return o(this,x)[x]}},{key:"autoUnregisterWebhook",get:function(){return o(this,z)[z]}}])}(v),F=function(t,e){return D.create(t,e)},M=/*#__PURE__*/a("outputSchema"),N=/*#__PURE__*/a("authStack"),B=/*#__PURE__*/function(){function t(){Object.defineProperty(this,M,{writable:!0,value:null}),Object.defineProperty(this,N,{writable:!0,value:[]})}t.create=function(){return new t};var e=t.prototype;return e.output=function(t){return o(this,M)[M]=t,this},e.addAuth=function(t){if(o(this,N)[N].map(function(t){return t.key}).includes(t.key))throw new Error('Auth with key "'+t.key+'" already exists in the auth stack');return o(this,N)[N].push(t),this},e.addOauth=function(t){return this.addAuth(t),this},e.addTokenAuth=function(t){return this.addAuth(t),this},e.addServiceAccountAuth=function(t){return this.addAuth(t),this},e.addCustomAuth=function(t){return this.addAuth(t),this},e.addNone=function(){return this.addAuth({type:"auth.none",name:"No Authentication",key:"none"}),this},s(t,[{key:"authStack",get:function(){return o(this,N)[N].filter(function(t){return"auth.none"!=t.type})}},{key:"outputSchema",get:function(){if(!o(this,M)[M])throw new Error("Output schema is not defined for this auth");return o(this,M)[M]}}])}(),X=function(){return B.create()},$=new e,G=function(t,e){return $.run(t,e)},H=function(){var t=$.getStore();if(!t)throw new Error("No Slate context is available");return t};t.interceptors.request.use(function(t){var e=H().specification;return t.headers.set("User-Agent","slates.dev@1.0.0/"+e.key),t.headers.set("X-Slates-Provider",e.key),t},function(t){return Promise.reject(t)});var J=function(e){var n=t.create(h({},e,{headers:h({},null==e?void 0:e.headers)}));return n.interceptors.request.use(function(t){var e=H().specification;return t.headers.set("User-Agent","slates.dev@1.0.0/"+e.key),t.headers.set("X-Slates-Provider",e.key),t},function(t){return Promise.reject(t)}),n},K=J(),L=/*#__PURE__*/a("configSchema"),Q=/*#__PURE__*/a("configChanged"),V=/*#__PURE__*/a("getDefaultConfig"),Y=/*#__PURE__*/function(){function t(t){Object.defineProperty(this,L,{writable:!0,value:void 0}),Object.defineProperty(this,Q,{writable:!0,value:null}),Object.defineProperty(this,V,{writable:!0,value:null}),o(this,L)[L]=t}t.create=function(e){return new t(e)};var e=t.prototype;return e.config=function(t){return o(this,L)[L]=t,this},e.onConfigChanged=function(t){return o(this,Q)[Q]=t,this},e.getDefaultConfig=function(t){return o(this,V)[V]=t,this},s(t,[{key:"configSchema",get:function(){return o(this,L)[L]}},{key:"handlers",get:function(){return{configChanged:o(this,Q)[Q],getDefaultConfig:o(this,V)[V]}}}])}(),Z=function(t){return Y.create(t)},tt=/*#__PURE__*/a("config"),et=/*#__PURE__*/a("input"),nt=/*#__PURE__*/a("auth"),rt=/*#__PURE__*/function(){function t(t,e,n,r,i){this.spec=void 0,this.logger=void 0,Object.defineProperty(this,tt,{writable:!0,value:void 0}),Object.defineProperty(this,et,{writable:!0,value:void 0}),Object.defineProperty(this,nt,{writable:!0,value:void 0}),this.spec=r,this.logger=i,o(this,tt)[tt]=t,o(this,et)[et]=e,o(this,nt)[nt]=n}var e=t.prototype;return e.info=function(t){this.logger.info(t)},e.warn=function(t){this.logger.warn(t)},e.error=function(t){this.logger.error(t)},e.progress=function(t){this.logger.progress(t)},s(t,[{key:"specification",get:function(){return this.spec}},{key:"config",get:function(){return Object.freeze(o(this,tt)[tt])}},{key:"input",get:function(){return Object.freeze(o(this,et)[et])}},{key:"event",get:function(){return Object.freeze(o(this,et)[et])}},{key:"state",get:function(){return Object.freeze(o(this,et)[et].state)}},{key:"request",get:function(){return Object.freeze(o(this,et)[et].request)}},{key:"auth",get:function(){return Object.freeze(o(this,nt)[nt])}}])}(),it=function(t){return"object"==typeof t?null===t?"null":t instanceof Error?"[ERROR]: "+t.name+": "+t.message+"\n"+t.stack:n(t):String(t)},ot=/*#__PURE__*/a("logs"),ut=/*#__PURE__*/a("listeners"),at=/*#__PURE__*/a("timer"),ct=/*#__PURE__*/function(){function t(t){var e;void 0===t&&(t=[]),Object.defineProperty(this,ot,{writable:!0,value:[]}),Object.defineProperty(this,ut,{writable:!0,value:[]}),Object.defineProperty(this,at,{writable:!0,value:null}),(e=o(this,ut)[ut]).push.apply(e,t)}var e=t.prototype;return e.flush=function(){if(o(this,at)[at]&&clearTimeout(o(this,at)[at]),0!==o(this,ot)[ot].length)for(var t,e=function(t){var e="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(e)return(e=e.call(t)).next.bind(e);if(Array.isArray(t)||(e=function(t,e){if(t){if("string"==typeof t)return i(t,e);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?i(t,e):void 0}}(t))){e&&(t=e);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(o(this,ut)[ut]);!(t=e()).done;)(0,t.value)(o(this,ot)[ot])},e.scheduleFlush=function(){var t=this;o(this,at)[at]||(o(this,at)[at]=setTimeout(function(){t.flush(),o(t,at)[at]=null},10))},e.log=function(t,e){o(this,ot)[ot].push({type:t,timestamp:new Date,message:it(e)}),this.scheduleFlush()},e.info=function(){this.log("info",[].slice.call(arguments).flat())},e.warn=function(){this.log("warn",[].slice.call(arguments).flat())},e.error=function(){this.log("error",[].slice.call(arguments).flat())},e.progress=function(){this.log("progress",[].slice.call(arguments).flat())},t}(),st=/*#__PURE__*/function(){function t(t,e){this._spec=void 0,this._actions=void 0,this._spec=t,this._actions=e}return t.create=function(e){return new t(e.spec,[].concat(e.triggers,e.tools))},s(t,[{key:"spec",get:function(){return this._spec}},{key:"actions",get:function(){return this._actions}}])}(),ht=/*#__PURE__*/function(){function t(t,e,n){this._config=void 0,this._auth=void 0,this._params=void 0,this._config=t,this._auth=e,this._params=n}return t.create=function(e){return new t(e.config,e.auth,e)},s(t,[{key:"configSchema",get:function(){return this._config.configSchema}},{key:"authSchema",get:function(){return"outputSchema"in this._auth?this._auth.outputSchema:r.object({})}},{key:"config",get:function(){return this._config}},{key:"auth",get:function(){return this._auth}},{key:"parameters",get:function(){return this._params}},{key:"key",get:function(){return this._params.key}},{key:"name",get:function(){return this._params.name}},{key:"description",get:function(){return this._params.description}}])}(),ft=function(t){return ht.create(t)};export{st as Slate,v as SlateAction,B as SlateAuth,Y as SlateConfig,rt as SlateContext,m as SlateDeclarationError,I as SlateDefaultPollingIntervalSeconds,b as SlateError,ct as SlateLogger,ht as SlateSpecification,A as SlateTool,D as SlateTrigger,X as auth,K as axios,Z as config,J as createAxios,H as getCurrentContext,G as runWithContext,ft as spec,R as tool,F as trigger};
2
- //# sourceMappingURL=index.module.js.map
1
+ // src/action/action.ts
2
+ var SlateAction = class {
3
+ constructor(type, _spec, _inputSchema, _outputSchema, _params) {
4
+ this.type = type;
5
+ this._spec = _spec;
6
+ this._inputSchema = _inputSchema;
7
+ this._outputSchema = _outputSchema;
8
+ this._params = _params;
9
+ }
10
+ type;
11
+ _spec;
12
+ _inputSchema;
13
+ _outputSchema;
14
+ _params;
15
+ get configSchema() {
16
+ return this._spec.configSchema;
17
+ }
18
+ get inputSchema() {
19
+ return this._inputSchema;
20
+ }
21
+ get outputSchema() {
22
+ return this._outputSchema;
23
+ }
24
+ get parameters() {
25
+ return this._params;
26
+ }
27
+ get key() {
28
+ return this._params.key;
29
+ }
30
+ get name() {
31
+ return this._params.name;
32
+ }
33
+ get description() {
34
+ return this._params.description;
35
+ }
36
+ get tags() {
37
+ return this._params.tags;
38
+ }
39
+ get instructions() {
40
+ return this._params.instructions;
41
+ }
42
+ get constraints() {
43
+ return this._params.constraints;
44
+ }
45
+ get metadata() {
46
+ return this._params.metadata;
47
+ }
48
+ get scopes() {
49
+ return this._params.scopes;
50
+ }
51
+ };
52
+
53
+ // src/error/axios.ts
54
+ import { isAxiosError } from "axios";
55
+
56
+ // src/context/hook.ts
57
+ import { AsyncLocalStorage } from "async_hooks";
58
+ var asyncLocalStorage = new AsyncLocalStorage();
59
+ var runWithContext = (context, fn) => {
60
+ return asyncLocalStorage.run(context, fn);
61
+ };
62
+ var getCurrentContext = () => {
63
+ let context = asyncLocalStorage.getStore();
64
+ if (!context) {
65
+ throw new Error("No Slate context is available");
66
+ }
67
+ return context;
68
+ };
69
+
70
+ // src/error/defaults.ts
71
+ var DEFAULT_CODE = "internal.unexpected";
72
+ var DEFAULT_MESSAGES = {
73
+ "declaration.invalid_definition": "The slate definition is invalid.",
74
+ "context.missing": "No Slate context is available.",
75
+ "input.invalid": "The provided input is invalid.",
76
+ "request.bad": "The request is invalid.",
77
+ "request.invalid_version": "The requested version is invalid.",
78
+ "request.precondition_failed": "The request precondition failed.",
79
+ "request.not_acceptable": "The request is not acceptable.",
80
+ "request.rate_limited": "Too many requests were made in a short period of time.",
81
+ "config.invalid": "The provided configuration is invalid.",
82
+ "auth.required": "Authentication is required.",
83
+ "auth.invalid": "Authentication failed.",
84
+ "auth.expired": "Authentication has expired.",
85
+ "permission.denied": "Permission was denied.",
86
+ "resource.not_found": "The requested resource was not found.",
87
+ "resource.conflict": "The requested resource is in conflict.",
88
+ "resource.gone": "The requested resource is no longer available.",
89
+ "payment.required": "Payment is required to continue.",
90
+ "operation.not_implemented": "The requested operation is not implemented.",
91
+ "upstream.invalid_request": "The upstream service rejected the request.",
92
+ "upstream.rate_limited": "The upstream service rate limited the request.",
93
+ "upstream.timeout": "The upstream service timed out.",
94
+ "upstream.network_error": "A network error occurred while contacting the upstream service.",
95
+ "upstream.unavailable": "The upstream service is unavailable.",
96
+ "upstream.invalid_response": "The upstream service returned an invalid response.",
97
+ "upstream.error": "The upstream service returned an error.",
98
+ "transport.invoke_failed": "The provider transport failed.",
99
+ "internal.timeout": "The operation timed out.",
100
+ "internal.unexpected": "An unexpected internal error occurred."
101
+ };
102
+ var SERVICE_ERROR_CODE_MAP = {
103
+ invalid_data: "input.invalid",
104
+ bad_request: "request.bad",
105
+ not_found: "resource.not_found",
106
+ unauthorized: "auth.required",
107
+ forbidden: "permission.denied",
108
+ invalid_version: "request.invalid_version",
109
+ conflict: "resource.conflict",
110
+ gone: "resource.gone",
111
+ payment_required: "payment.required",
112
+ precondition_failed: "request.precondition_failed",
113
+ not_acceptable: "request.not_acceptable",
114
+ not_implemented: "operation.not_implemented",
115
+ too_many_requests: "request.rate_limited",
116
+ timeout: "internal.timeout",
117
+ internal_server_error: "internal.unexpected"
118
+ };
119
+
120
+ // src/error/utils.ts
121
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
122
+ var normalizeKind = (code, kind) => {
123
+ if (kind) return kind;
124
+ if (code.startsWith("declaration.")) return "declaration";
125
+ if (code.startsWith("input.")) return "validation";
126
+ if (code.startsWith("request.")) return "request";
127
+ if (code.startsWith("config.")) return "config";
128
+ if (code.startsWith("auth.") || code.startsWith("permission.")) return "auth";
129
+ if (code.startsWith("resource.")) return "resource";
130
+ if (code.startsWith("payment.")) return "payment";
131
+ if (code.startsWith("transport.")) return "transport";
132
+ if (code.startsWith("upstream.")) return "upstream";
133
+ return "internal";
134
+ };
135
+ var normalizeStatus = (code, status) => {
136
+ if (status) return status;
137
+ if (code === "input.invalid" || code === "request.bad" || code === "config.invalid")
138
+ return 400;
139
+ if (code === "request.invalid_version") return 400;
140
+ if (code === "auth.required" || code === "auth.invalid" || code === "auth.expired")
141
+ return 401;
142
+ if (code === "payment.required") return 402;
143
+ if (code === "permission.denied") return 403;
144
+ if (code === "resource.not_found") return 404;
145
+ if (code === "resource.conflict") return 409;
146
+ if (code === "resource.gone") return 410;
147
+ if (code === "request.not_acceptable") return 406;
148
+ if (code === "request.precondition_failed") return 412;
149
+ if (code === "request.rate_limited" || code === "upstream.rate_limited") return 429;
150
+ if (code === "operation.not_implemented") return 501;
151
+ if (code === "upstream.invalid_request") return 400;
152
+ if (code === "upstream.timeout" || code === "internal.timeout") return 504;
153
+ if (code === "upstream.unavailable") return 503;
154
+ if (code === "upstream.error") return 502;
155
+ return void 0;
156
+ };
157
+ var normalizeRetryable = (code, retryable) => {
158
+ if (typeof retryable === "boolean") return retryable;
159
+ return code === "request.rate_limited" || code === "upstream.rate_limited" || code === "upstream.timeout" || code === "upstream.network_error" || code === "upstream.unavailable" || code === "upstream.error" || code === "transport.invoke_failed" || code === "internal.timeout";
160
+ };
161
+ var getDefaultMessage = (code, message) => {
162
+ if (message && message.trim()) return message;
163
+ return DEFAULT_MESSAGES[code] ?? DEFAULT_MESSAGES[DEFAULT_CODE];
164
+ };
165
+ var cleanRecord = (value) => {
166
+ if (!value) return void 0;
167
+ let entries = Object.entries(value).filter(([, entry]) => entry !== void 0);
168
+ if (entries.length === 0) return void 0;
169
+ return Object.fromEntries(entries);
170
+ };
171
+ var mergeRecords = (left, right) => {
172
+ if (!left && !right) return void 0;
173
+ return cleanRecord({
174
+ ...left ?? {},
175
+ ...right ?? {}
176
+ });
177
+ };
178
+ var mergeSlateErrorData = (base, override) => {
179
+ if (!override) return base;
180
+ return {
181
+ ...base,
182
+ ...override,
183
+ provider: cleanRecord({
184
+ ...base.provider ?? {},
185
+ ...override.provider ?? {}
186
+ }),
187
+ upstream: cleanRecord({
188
+ ...base.upstream ?? {},
189
+ ...override.upstream ?? {}
190
+ }),
191
+ baggage: mergeRecords(base.baggage, override.baggage),
192
+ issues: override.issues ?? base.issues
193
+ };
194
+ };
195
+ var sanitizeForBaggage = (value, depth = 0) => {
196
+ if (value == null) return value;
197
+ if (depth >= 4) return "[truncated]";
198
+ if (typeof value === "string") {
199
+ return value.length > 2e3 ? `${value.slice(0, 2e3)}...[truncated]` : value;
200
+ }
201
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
202
+ return value;
203
+ }
204
+ if (Array.isArray(value)) {
205
+ return value.slice(0, 20).map((item) => sanitizeForBaggage(item, depth + 1));
206
+ }
207
+ if (isRecord(value)) {
208
+ return Object.fromEntries(
209
+ Object.entries(value).slice(0, 30).map(([key, entry]) => [key, sanitizeForBaggage(entry, depth + 1)])
210
+ );
211
+ }
212
+ return String(value);
213
+ };
214
+ var normalizeSlateErrorInput = (input) => {
215
+ let code = input.code || DEFAULT_CODE;
216
+ return {
217
+ code,
218
+ message: getDefaultMessage(code, input.message),
219
+ kind: normalizeKind(code, input.kind),
220
+ retryable: normalizeRetryable(code, input.retryable),
221
+ status: normalizeStatus(code, input.status ?? input.upstream?.status),
222
+ issues: input.issues,
223
+ provider: cleanRecord(input.provider),
224
+ upstream: cleanRecord({
225
+ ...input.upstream,
226
+ status: input.upstream?.status ?? input.status
227
+ }),
228
+ baggage: cleanRecord(input.baggage)
229
+ };
230
+ };
231
+ var isSlateErrorResponse = (error) => {
232
+ if (!isRecord(error)) return false;
233
+ return typeof error.code === "string" && typeof error.message === "string";
234
+ };
235
+
236
+ // src/error/axios.ts
237
+ var getResponseField = (value, key) => {
238
+ if (!isRecord(value)) return void 0;
239
+ return value[key];
240
+ };
241
+ var getNestedMessage = (value) => {
242
+ if (typeof value === "string") return value;
243
+ if (!isRecord(value)) return void 0;
244
+ let message = getResponseField(value, "message");
245
+ if (typeof message === "string" && message.trim()) return message;
246
+ let description = getResponseField(value, "description");
247
+ if (typeof description === "string" && description.trim()) return description;
248
+ let error = getResponseField(value, "error");
249
+ if (typeof error === "string" && error.trim()) return error;
250
+ if (isRecord(error)) {
251
+ let nested = getNestedMessage(error);
252
+ if (nested) return nested;
253
+ }
254
+ let errorDescription = getResponseField(value, "error_description");
255
+ if (typeof errorDescription === "string" && errorDescription.trim()) {
256
+ return errorDescription;
257
+ }
258
+ return void 0;
259
+ };
260
+ var getNestedCode = (value) => {
261
+ if (!isRecord(value)) return void 0;
262
+ let directCode = getResponseField(value, "code");
263
+ if (typeof directCode === "string" && directCode.trim()) return directCode;
264
+ let errorCode = getResponseField(value, "error_code");
265
+ if (typeof errorCode === "string" && errorCode.trim()) return errorCode;
266
+ let type = getResponseField(value, "type");
267
+ if (typeof type === "string" && type.trim()) return type;
268
+ let error = getResponseField(value, "error");
269
+ if (typeof error === "string" && error.trim()) return error;
270
+ if (isRecord(error)) return getNestedCode(error);
271
+ return void 0;
272
+ };
273
+ var getNestedType = (value) => {
274
+ if (!isRecord(value)) return void 0;
275
+ let type = getResponseField(value, "type");
276
+ if (typeof type === "string" && type.trim()) return type;
277
+ let error = getResponseField(value, "error");
278
+ if (isRecord(error)) {
279
+ let nestedType = getNestedType(error);
280
+ if (nestedType) return nestedType;
281
+ }
282
+ return void 0;
283
+ };
284
+ var getHeaderValue = (headers, key) => {
285
+ if (!headers) return void 0;
286
+ if (typeof headers.get === "function") {
287
+ let value = headers.get(key);
288
+ if (typeof value === "string" && value.trim()) return value;
289
+ }
290
+ if (isRecord(headers)) {
291
+ for (let [headerKey, headerValue] of Object.entries(headers)) {
292
+ if (headerKey.toLowerCase() !== key.toLowerCase()) continue;
293
+ if (typeof headerValue === "string" && headerValue.trim()) return headerValue;
294
+ if (Array.isArray(headerValue)) {
295
+ let first = headerValue.find((item) => typeof item === "string" && item.trim());
296
+ if (typeof first === "string") return first;
297
+ }
298
+ }
299
+ }
300
+ return void 0;
301
+ };
302
+ var buildRequestUrl = (error) => {
303
+ let baseURL = error.config?.baseURL;
304
+ let url = error.config?.url;
305
+ if (!url) return void 0;
306
+ if (!baseURL) return url;
307
+ try {
308
+ return new URL(url, baseURL).toString();
309
+ } catch {
310
+ return url;
311
+ }
312
+ };
313
+ var getProviderDefaults = () => {
314
+ try {
315
+ let ctx = getCurrentContext();
316
+ return {
317
+ provider: {
318
+ key: ctx.specification.key
319
+ }
320
+ };
321
+ } catch {
322
+ return {};
323
+ }
324
+ };
325
+ var inferAxiosCode = (error, data) => {
326
+ let status = error.response?.status;
327
+ let axiosCode = error.code?.toUpperCase();
328
+ let remoteCode = getNestedCode(data)?.toLowerCase();
329
+ if (axiosCode === "ECONNABORTED" || axiosCode === "ETIMEDOUT" || status === 408 || remoteCode?.includes("timeout")) {
330
+ return "upstream.timeout";
331
+ }
332
+ if (!error.response) {
333
+ return "upstream.network_error";
334
+ }
335
+ if (status === 401) return "auth.invalid";
336
+ if (status === 403) {
337
+ return remoteCode?.includes("rate") ? "upstream.rate_limited" : "permission.denied";
338
+ }
339
+ if (status === 404) return "resource.not_found";
340
+ if (status === 409) return "resource.conflict";
341
+ if (status === 422 || status === 400) return "upstream.invalid_request";
342
+ if (status === 429) return "upstream.rate_limited";
343
+ if (status === 502 || status === 503 || status === 504) return "upstream.unavailable";
344
+ if (status && status >= 500) return "upstream.error";
345
+ return "upstream.error";
346
+ };
347
+ var inferAxiosMessage = (error, data, code) => {
348
+ return getNestedMessage(data) ?? error.response?.statusText ?? error.message ?? getDefaultMessage(code);
349
+ };
350
+ var inferAxiosRetryable = (error, code) => {
351
+ let headerValue = getHeaderValue(error.response?.headers, "retry-after");
352
+ if (headerValue) return true;
353
+ return normalizeRetryable(code, void 0);
354
+ };
355
+ var isAxiosErrorLike = (error) => isAxiosError(error);
356
+ var inferSlateErrorFromAxios = (error, options = {}) => {
357
+ let responseData = error.response ? options.extractResponseData?.(error.response) ?? error.response.data : void 0;
358
+ let code = inferAxiosCode(error, responseData);
359
+ return normalizeSlateErrorInput({
360
+ ...getProviderDefaults(),
361
+ ...options.defaults,
362
+ code: options.defaults?.code ?? code,
363
+ message: options.defaults?.message ?? inferAxiosMessage(error, responseData, code),
364
+ kind: options.defaults?.kind ?? normalizeKind(options.defaults?.code ?? code),
365
+ retryable: options.defaults?.retryable ?? inferAxiosRetryable(error, options.defaults?.code ?? code),
366
+ status: options.defaults?.status ?? error.response?.status,
367
+ provider: {
368
+ ...getProviderDefaults().provider,
369
+ ...options.defaults?.provider ?? {}
370
+ },
371
+ upstream: {
372
+ ...options.defaults?.upstream ?? {},
373
+ status: error.response?.status ?? options.defaults?.upstream?.status,
374
+ code: getNestedCode(responseData) ?? options.defaults?.upstream?.code,
375
+ type: getNestedType(responseData) ?? options.defaults?.upstream?.type,
376
+ requestId: getHeaderValue(error.response?.headers, "x-request-id") ?? getHeaderValue(error.response?.headers, "request-id") ?? getHeaderValue(error.response?.headers, "x-correlation-id") ?? options.defaults?.upstream?.requestId,
377
+ method: error.config?.method?.toUpperCase() ?? options.defaults?.upstream?.method,
378
+ url: buildRequestUrl(error) ?? options.defaults?.upstream?.url
379
+ },
380
+ baggage: mergeRecords(options.defaults?.baggage, {
381
+ axiosCode: error.code,
382
+ response: sanitizeForBaggage(responseData)
383
+ })
384
+ });
385
+ };
386
+
387
+ // src/error/service.ts
388
+ import { isServiceError } from "@lowerdeck/error";
389
+ var SERVICE_ERROR_DATA_RESERVED_KEYS = /* @__PURE__ */ new Set([
390
+ "status",
391
+ "code",
392
+ "message",
393
+ "hint",
394
+ "description",
395
+ "reason",
396
+ "errors",
397
+ "object",
398
+ "ok"
399
+ ]);
400
+ var isStructuredValue = (value) => (typeof value === "object" || typeof value === "function") && value !== null;
401
+ var mapServiceErrorCodeByStatus = (status) => {
402
+ if (status === 400) return "request.bad";
403
+ if (status === 401) return "auth.required";
404
+ if (status === 402) return "payment.required";
405
+ if (status === 403) return "permission.denied";
406
+ if (status === 404) return "resource.not_found";
407
+ if (status === 406) return "request.not_acceptable";
408
+ if (status === 409) return "resource.conflict";
409
+ if (status === 410) return "resource.gone";
410
+ if (status === 412) return "request.precondition_failed";
411
+ if (status === 429) return "request.rate_limited";
412
+ if (status === 501) return "operation.not_implemented";
413
+ if (status === 504) return "internal.timeout";
414
+ if (status && status >= 500) return "internal.unexpected";
415
+ return DEFAULT_CODE;
416
+ };
417
+ var normalizeServiceErrorIssues = (errors) => {
418
+ if (!Array.isArray(errors)) return void 0;
419
+ let issues = errors.map((error) => {
420
+ if (!isRecord(error)) {
421
+ return {
422
+ message: String(error)
423
+ };
424
+ }
425
+ let path = Array.isArray(error.path) ? error.path.map((entry) => String(entry)) : void 0;
426
+ return {
427
+ ...error,
428
+ path,
429
+ code: typeof error.code === "string" ? error.code : void 0,
430
+ message: typeof error.message === "string" ? error.message : typeof error.hint === "string" ? error.hint : "Validation issue"
431
+ };
432
+ });
433
+ return issues.length > 0 ? issues : void 0;
434
+ };
435
+ var getServiceErrorBaggage = (data) => {
436
+ let extraEntries = Object.entries(data).filter(([key]) => !SERVICE_ERROR_DATA_RESERVED_KEYS.has(key));
437
+ return cleanRecord({
438
+ serviceError: {
439
+ code: data.code,
440
+ status: data.status,
441
+ hint: data.hint,
442
+ description: data.description,
443
+ reason: data.reason
444
+ },
445
+ ...extraEntries.length > 0 ? {
446
+ serviceErrorData: sanitizeForBaggage(Object.fromEntries(extraEntries))
447
+ } : {}
448
+ });
449
+ };
450
+ var mapServiceErrorCode = (code, status) => SERVICE_ERROR_CODE_MAP[code] ?? mapServiceErrorCodeByStatus(status);
451
+ var isServiceErrorData = (value) => isRecord(value) && typeof value.status === "number" && typeof value.code === "string" && typeof value.message === "string" && !("config" in value) && !("request" in value) && !("response" in value) && !("isAxiosError" in value);
452
+ var getServiceErrorData = (error) => {
453
+ if (isServiceError(error)) {
454
+ return isServiceErrorData(error.data) ? error.data : null;
455
+ }
456
+ if (isServiceErrorData(error)) {
457
+ return error;
458
+ }
459
+ if (isStructuredValue(error) && "data" in error && isServiceErrorData(error.data)) {
460
+ return error.data;
461
+ }
462
+ if (isStructuredValue(error) && "toResponse" in error && typeof error.toResponse === "function") {
463
+ let response = error.toResponse();
464
+ return isServiceErrorData(response) ? response : null;
465
+ }
466
+ return null;
467
+ };
468
+ var mapServiceErrorToSlateErrorInput = (error, defaults = {}) => {
469
+ let data = getServiceErrorData(error);
470
+ if (!data) {
471
+ return {
472
+ code: defaults.code ?? DEFAULT_CODE,
473
+ message: defaults.message ?? "An unexpected internal error occurred.",
474
+ kind: defaults.kind,
475
+ retryable: defaults.retryable,
476
+ status: defaults.status,
477
+ provider: defaults.provider,
478
+ upstream: defaults.upstream,
479
+ baggage: defaults.baggage
480
+ };
481
+ }
482
+ let code = defaults.code ?? mapServiceErrorCode(data.code, data.status);
483
+ return {
484
+ code,
485
+ message: defaults.message ?? data.message,
486
+ kind: defaults.kind ?? normalizeKind(code),
487
+ retryable: defaults.retryable ?? normalizeRetryable(code),
488
+ status: defaults.status ?? data.status,
489
+ issues: defaults.issues ?? normalizeServiceErrorIssues(data.errors),
490
+ provider: defaults.provider,
491
+ upstream: defaults.upstream,
492
+ baggage: cleanRecord({
493
+ ...defaults.baggage ?? {},
494
+ ...getServiceErrorBaggage(data)
495
+ })
496
+ };
497
+ };
498
+
499
+ // src/error/base.ts
500
+ var SlateError = class _SlateError extends Error {
501
+ cause;
502
+ data;
503
+ constructor(input) {
504
+ let normalized = normalizeSlateErrorInput(input);
505
+ super(normalized.message);
506
+ this.name = "SlateError";
507
+ this.data = normalized;
508
+ this.cause = input.cause;
509
+ }
510
+ get code() {
511
+ return this.data.code;
512
+ }
513
+ get kind() {
514
+ return this.data.kind;
515
+ }
516
+ get status() {
517
+ return this.data.status;
518
+ }
519
+ get retryable() {
520
+ return this.data.retryable;
521
+ }
522
+ toResponse() {
523
+ return {
524
+ ...this.data
525
+ };
526
+ }
527
+ toJSON() {
528
+ return this.toResponse();
529
+ }
530
+ static is(error) {
531
+ return error instanceof _SlateError;
532
+ }
533
+ static fromUnknown(error, defaults = {}) {
534
+ if (_SlateError.is(error)) return error;
535
+ if (isSlateErrorResponse(error)) return new _SlateError({ ...defaults, ...error });
536
+ if (getServiceErrorData(error)) return _SlateError.fromServiceError(error, defaults);
537
+ if (isAxiosErrorLike(error)) return _SlateError.fromAxios(error, { defaults });
538
+ if (error instanceof Error) {
539
+ return new _SlateError({
540
+ code: defaults.code ?? DEFAULT_CODE,
541
+ message: error.message,
542
+ kind: defaults.kind,
543
+ retryable: defaults.retryable,
544
+ status: defaults.status,
545
+ issues: defaults.issues,
546
+ provider: defaults.provider,
547
+ upstream: defaults.upstream,
548
+ baggage: mergeRecords(defaults.baggage, {
549
+ originalName: error.name
550
+ }),
551
+ cause: error
552
+ });
553
+ }
554
+ return new _SlateError({
555
+ code: defaults.code ?? DEFAULT_CODE,
556
+ message: getDefaultMessage(defaults.code ?? DEFAULT_CODE, defaults.message),
557
+ kind: defaults.kind,
558
+ retryable: defaults.retryable,
559
+ status: defaults.status,
560
+ issues: defaults.issues,
561
+ provider: defaults.provider,
562
+ upstream: defaults.upstream,
563
+ baggage: mergeRecords(defaults.baggage, {
564
+ originalValue: sanitizeForBaggage(error)
565
+ })
566
+ });
567
+ }
568
+ static fromServiceError(error, defaults = {}) {
569
+ return new _SlateError(mapServiceErrorToSlateErrorInput(error, defaults));
570
+ }
571
+ static fromAxios(error, options = {}) {
572
+ if (_SlateError.is(error)) return error;
573
+ if (getServiceErrorData(error))
574
+ return _SlateError.fromServiceError(error, options.defaults);
575
+ if (!isAxiosErrorLike(error)) return _SlateError.fromUnknown(error, options.defaults);
576
+ let inferred = inferSlateErrorFromAxios(error, options);
577
+ let mapped = options.mapAxiosError?.(error, inferred);
578
+ if (_SlateError.is(mapped)) return mapped;
579
+ return new _SlateError(mergeSlateErrorData(inferred, mapped ?? void 0));
580
+ }
581
+ };
582
+ var createSlateError = (input) => new SlateError(input);
583
+
584
+ // src/error/declaration.ts
585
+ var SlateDeclarationError = class _SlateDeclarationError extends SlateError {
586
+ constructor(message, input = {}) {
587
+ super({
588
+ code: "declaration.invalid_definition",
589
+ kind: "declaration",
590
+ message,
591
+ ...input
592
+ });
593
+ this.name = "SlateError.DeclarationError";
594
+ }
595
+ static is(error) {
596
+ return error instanceof _SlateDeclarationError;
597
+ }
598
+ };
599
+
600
+ // src/action/scopes.ts
601
+ var scopeClause = (...scopes) => {
602
+ assertScopeValues(scopes);
603
+ return {
604
+ OR: [...scopes]
605
+ };
606
+ };
607
+ var anyOf = (...scopes) => ({
608
+ AND: [scopeClause(...scopes)]
609
+ });
610
+ var allOf = (...inputs) => {
611
+ let AND = inputs.flatMap((input) => normalizeScopes(input).AND);
612
+ return validateScopes({ AND });
613
+ };
614
+ var mergeScopes = (...inputs) => {
615
+ let AND = inputs.flatMap((input) => input ? input.AND : []);
616
+ if (AND.length === 0) {
617
+ return void 0;
618
+ }
619
+ return validateScopes({ AND });
620
+ };
621
+ var validateScopes = (scopes) => {
622
+ if (!Array.isArray(scopes.AND) || scopes.AND.length === 0) {
623
+ throw new SlateDeclarationError("Action scopes must include at least one AND clause");
624
+ }
625
+ return {
626
+ AND: scopes.AND.map((clause) => normalizeClause(clause))
627
+ };
628
+ };
629
+ var normalizeScopes = (input) => {
630
+ if (isScopes(input)) {
631
+ return validateScopes(input);
632
+ }
633
+ return {
634
+ AND: [normalizeClause(input)]
635
+ };
636
+ };
637
+ var normalizeClause = (input) => {
638
+ if (typeof input === "string") {
639
+ return scopeClause(input);
640
+ }
641
+ if (Array.isArray(input)) {
642
+ return scopeClause(...input);
643
+ }
644
+ if (!isClause(input)) {
645
+ throw new SlateDeclarationError("Action scope clauses must be strings or OR clauses");
646
+ }
647
+ assertScopeValues(input.OR);
648
+ return {
649
+ OR: [...input.OR]
650
+ };
651
+ };
652
+ var assertScopeValues = (scopes) => {
653
+ if (scopes.length === 0) {
654
+ throw new SlateDeclarationError("Each action scope clause must include at least one OR scope");
655
+ }
656
+ for (let scope of scopes) {
657
+ if (typeof scope !== "string" || scope.trim().length === 0) {
658
+ throw new SlateDeclarationError("Action scopes must be non-empty strings");
659
+ }
660
+ }
661
+ };
662
+ var isClause = (value) => typeof value === "object" && value !== null && "OR" in value && Array.isArray(value.OR);
663
+ var isScopes = (value) => typeof value === "object" && value !== null && "AND" in value && Array.isArray(value.AND);
664
+
665
+ // src/action/builder.ts
666
+ var SlateActionBuilder = class {
667
+ constructor(type, spec2, params, factory) {
668
+ this.type = type;
669
+ this.spec = spec2;
670
+ this.params = params;
671
+ this.factory = factory;
672
+ this.#configSchema = spec2.configSchema;
673
+ this.#authSchema = spec2.authSchema;
674
+ }
675
+ type;
676
+ spec;
677
+ params;
678
+ factory;
679
+ #configSchema;
680
+ #authSchema;
681
+ #inputSchema = null;
682
+ #outputSchema = null;
683
+ #scopes;
684
+ #toolParams = null;
685
+ #triggerParams = null;
686
+ input(schema) {
687
+ this.#inputSchema = schema;
688
+ return this;
689
+ }
690
+ output(schema) {
691
+ this.#outputSchema = schema;
692
+ return this;
693
+ }
694
+ scopes(scopes) {
695
+ validateScopes(scopes);
696
+ this.#scopes = scopes;
697
+ return this;
698
+ }
699
+ handleInvocation(handler) {
700
+ if (this.type !== "tool") {
701
+ throw new SlateDeclarationError("handleInvocation can only be set for tool actions");
702
+ }
703
+ this.#toolParams = {
704
+ type: "tool",
705
+ handleInvocation: handler
706
+ };
707
+ return this;
708
+ }
709
+ webhook(props) {
710
+ if (this.type !== "trigger") {
711
+ throw new SlateDeclarationError("handleEvent can only be set for trigger actions");
712
+ }
713
+ this.#triggerParams = {
714
+ type: "trigger",
715
+ source: "webhook",
716
+ handleEvent: props.handleEvent,
717
+ handleRequest: props.handleRequest,
718
+ autoRegisterWebhook: props.autoRegisterWebhook,
719
+ autoUnregisterWebhook: props.autoUnregisterWebhook
720
+ };
721
+ return this;
722
+ }
723
+ polling(props) {
724
+ if (this.type !== "trigger") {
725
+ throw new SlateDeclarationError("handleEvent can only be set for trigger actions");
726
+ }
727
+ this.#triggerParams = {
728
+ type: "trigger",
729
+ source: "polling",
730
+ polling: props.options,
731
+ pollEvents: props.pollEvents,
732
+ handleEvent: props.handleEvent
733
+ };
734
+ return this;
735
+ }
736
+ build() {
737
+ let scopes = this.#scopes ?? this.params.scopes;
738
+ if (scopes) {
739
+ validateScopes(scopes);
740
+ }
741
+ if (!this.#inputSchema) {
742
+ throw new SlateDeclarationError("Input schema is not defined");
743
+ }
744
+ if (!this.#outputSchema) {
745
+ throw new SlateDeclarationError("Output schema is not defined");
746
+ }
747
+ if (this.type === "tool" && !this.#toolParams) {
748
+ throw new SlateDeclarationError("Tool invocation handler is not defined");
749
+ }
750
+ if (this.type === "trigger" && !this.#triggerParams) {
751
+ throw new SlateDeclarationError("Trigger event handlers are not defined");
752
+ }
753
+ return this.factory({
754
+ ...this.params,
755
+ scopes,
756
+ configSchema: this.#configSchema,
757
+ authSchema: this.#authSchema,
758
+ inputSchema: this.#inputSchema,
759
+ outputSchema: this.#outputSchema,
760
+ ...this.#toolParams,
761
+ ...this.#triggerParams
762
+ });
763
+ }
764
+ };
765
+
766
+ // src/action/tool.ts
767
+ var SlateTool = class _SlateTool extends SlateAction {
768
+ #handleInvocation;
769
+ constructor(spec2, inputSchema, outputSchema, params) {
770
+ super("tool", spec2, inputSchema, outputSchema, params);
771
+ this.#handleInvocation = params.handleInvocation;
772
+ }
773
+ static create(spec2, params) {
774
+ return new SlateActionBuilder("tool", spec2, params, (params2) => {
775
+ if (params2.type !== "tool") throw new Error("Invalid action type for tool");
776
+ return new _SlateTool(spec2, params2.inputSchema, params2.outputSchema, params2);
777
+ });
778
+ }
779
+ get handleInvocation() {
780
+ return this.#handleInvocation;
781
+ }
782
+ };
783
+ var tool = (spec2, params) => SlateTool.create(spec2, params);
784
+
785
+ // src/action/trigger.ts
786
+ var SlateDefaultPollingIntervalSeconds = 60 * 10;
787
+ var SlateTrigger = class _SlateTrigger extends SlateAction {
788
+ #source;
789
+ #polling;
790
+ #handleEvent;
791
+ #handleRequest;
792
+ #pollEvents;
793
+ #autoRegisterWebhook;
794
+ #autoUnregisterWebhook;
795
+ constructor(spec2, inputSchema, outputSchema, params) {
796
+ super("trigger", spec2, inputSchema, outputSchema, params);
797
+ this.#source = params.source;
798
+ this.#polling = params.polling || {
799
+ intervalInSeconds: SlateDefaultPollingIntervalSeconds
800
+ };
801
+ this.#handleEvent = params.handleEvent;
802
+ this.#handleRequest = params.handleRequest;
803
+ this.#pollEvents = params.pollEvents;
804
+ this.#autoRegisterWebhook = params.autoRegisterWebhook;
805
+ this.#autoUnregisterWebhook = params.autoUnregisterWebhook;
806
+ }
807
+ static create(spec2, params) {
808
+ return new SlateActionBuilder("trigger", spec2, params, (params2) => {
809
+ if (params2.type !== "trigger") throw new Error("Invalid action type for trigger");
810
+ return new _SlateTrigger(spec2, params2.inputSchema, params2.outputSchema, params2);
811
+ });
812
+ }
813
+ get polling() {
814
+ return this.#polling;
815
+ }
816
+ get source() {
817
+ return this.#source;
818
+ }
819
+ get handleEvent() {
820
+ return this.#handleEvent;
821
+ }
822
+ get handleRequest() {
823
+ return this.#handleRequest;
824
+ }
825
+ get pollEvents() {
826
+ return this.#pollEvents;
827
+ }
828
+ get autoRegisterWebhook() {
829
+ return this.#autoRegisterWebhook;
830
+ }
831
+ get autoUnregisterWebhook() {
832
+ return this.#autoUnregisterWebhook;
833
+ }
834
+ };
835
+ var trigger = (spec2, params) => SlateTrigger.create(spec2, params);
836
+
837
+ // src/auth/auth.ts
838
+ var SlateAuth = class _SlateAuth {
839
+ #outputSchema = null;
840
+ #authStack = [];
841
+ constructor() {
842
+ }
843
+ static create() {
844
+ return new _SlateAuth();
845
+ }
846
+ output(schema) {
847
+ this.#outputSchema = schema;
848
+ return this;
849
+ }
850
+ addAuth(auth2) {
851
+ let existingKeys = this.#authStack.map((a) => a.key);
852
+ if (existingKeys.includes(auth2.key)) {
853
+ throw new Error(`Auth with key "${auth2.key}" already exists in the auth stack`);
854
+ }
855
+ this.#authStack.push(auth2);
856
+ return this;
857
+ }
858
+ addOauth(auth2) {
859
+ this.addAuth(auth2);
860
+ return this;
861
+ }
862
+ addTokenAuth(auth2) {
863
+ this.addAuth(auth2);
864
+ return this;
865
+ }
866
+ addServiceAccountAuth(auth2) {
867
+ this.addAuth(auth2);
868
+ return this;
869
+ }
870
+ addCustomAuth(auth2) {
871
+ this.addAuth(auth2);
872
+ return this;
873
+ }
874
+ addNone() {
875
+ this.addAuth({
876
+ type: "auth.none",
877
+ name: "No Authentication",
878
+ key: "none"
879
+ });
880
+ return this;
881
+ }
882
+ get authStack() {
883
+ return this.#authStack.filter((a) => a.type !== "auth.none");
884
+ }
885
+ get outputSchema() {
886
+ if (!this.#outputSchema) {
887
+ throw new Error("Output schema is not defined for this auth");
888
+ }
889
+ return this.#outputSchema;
890
+ }
891
+ };
892
+ var auth = () => SlateAuth.create();
893
+
894
+ // src/axios/index.ts
895
+ import baseAxios, { getAdapter, isAxiosError as isAxiosError2 } from "axios";
896
+
897
+ // src/axios/trace.ts
898
+ var traceDraftsByConfig = /* @__PURE__ */ new WeakMap();
899
+ var traceDraftsByHeaders = /* @__PURE__ */ new WeakMap();
900
+ var TRACE_TEXT_LIMIT = 10 * 1024;
901
+ var REDACTED_VALUE = "[redacted]";
902
+ var STRUCTURED_DEPTH_LIMIT = 6;
903
+ var STRUCTURED_ENTRY_LIMIT = 50;
904
+ var SECRET_KEY_PATTERN = /(authorization|proxy[-_]?authorization|token|secret|password|passwd|api[-_]?key|access[-_]?token|refresh[-_]?token|client[-_]?secret|session|cookie|set-cookie|private[-_]?key|signature|sig|credential)/i;
905
+ var SAFE_HEADER_NAMES = /* @__PURE__ */ new Set([
906
+ "accept",
907
+ "accept-encoding",
908
+ "cache-control",
909
+ "content-encoding",
910
+ "content-language",
911
+ "content-length",
912
+ "content-type",
913
+ "etag",
914
+ "if-modified-since",
915
+ "if-none-match",
916
+ "last-modified",
917
+ "location",
918
+ "request-id",
919
+ "retry-after",
920
+ "user-agent",
921
+ "x-correlation-id",
922
+ "x-request-id",
923
+ "x-slates-provider"
924
+ ]);
925
+ var SAFE_HEADER_PREFIXES = ["ratelimit-", "x-ratelimit-"];
926
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
927
+ var isObjectLike = (value) => typeof value === "object" && value !== null;
928
+ var normalizeContentType = (value) => value?.split(";")[0]?.trim().toLowerCase() || void 0;
929
+ var isTextContentType = (contentType) => !contentType || /(^text\/)|json|xml|html|javascript|graphql|x-www-form-urlencoded|svg/.test(contentType);
930
+ var isSafeHeaderName = (name) => {
931
+ let normalized = name.toLowerCase();
932
+ if (SECRET_KEY_PATTERN.test(normalized)) return false;
933
+ if (SAFE_HEADER_NAMES.has(normalized)) return true;
934
+ return SAFE_HEADER_PREFIXES.some((prefix) => normalized.startsWith(prefix));
935
+ };
936
+ var truncateText = (text) => {
937
+ if (text.length <= TRACE_TEXT_LIMIT) {
938
+ return { text, truncated: false };
939
+ }
940
+ return {
941
+ text: `${text.slice(0, TRACE_TEXT_LIMIT)}...[truncated]`,
942
+ truncated: true
943
+ };
944
+ };
945
+ var sanitizeFreeText = (text) => text.replace(
946
+ /\b(Bearer|Basic)\s+[A-Za-z0-9\-._~+/]+=*/gi,
947
+ (_match, prefix) => `${prefix} ${REDACTED_VALUE}`
948
+ ).replace(
949
+ /((?:api[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|password|passwd|token|secret|signature|sig)=)([^&\s]+)/gi,
950
+ `$1${REDACTED_VALUE}`
951
+ ).replace(
952
+ /("(?:(?:api[_-]?key)|(?:access[_-]?token)|(?:refresh[_-]?token)|(?:client[_-]?secret)|password|passwd|token|secret|signature|sig)"\s*:\s*")([^"]+)(")/gi,
953
+ `$1${REDACTED_VALUE}$3`
954
+ );
955
+ var sanitizeScalar = (value) => truncateText(sanitizeFreeText(value));
956
+ var redactStructuredValue = (value, depth = 0) => {
957
+ if (value == null) return value;
958
+ if (depth >= STRUCTURED_DEPTH_LIMIT) return "[truncated]";
959
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
960
+ return typeof value === "string" ? sanitizeFreeText(value) : value;
961
+ }
962
+ if (Array.isArray(value)) {
963
+ return value.slice(0, STRUCTURED_ENTRY_LIMIT).map((entry) => redactStructuredValue(entry, depth + 1));
964
+ }
965
+ if (isRecord2(value)) {
966
+ return Object.fromEntries(
967
+ Object.entries(value).slice(0, STRUCTURED_ENTRY_LIMIT).map(([key, entry]) => [
968
+ key,
969
+ SECRET_KEY_PATTERN.test(key) ? REDACTED_VALUE : redactStructuredValue(entry, depth + 1)
970
+ ])
971
+ );
972
+ }
973
+ return String(value);
974
+ };
975
+ var maybeParseJson = (text, contentType) => {
976
+ let trimmed = text.trim();
977
+ if (!trimmed) return null;
978
+ if (!contentType?.includes("json") && !/^[\[{]/.test(trimmed)) {
979
+ return null;
980
+ }
981
+ try {
982
+ return JSON.parse(trimmed);
983
+ } catch {
984
+ return null;
985
+ }
986
+ };
987
+ var sanitizeTextBody = (text, contentType) => {
988
+ if (!text) return void 0;
989
+ let normalizedContentType = normalizeContentType(contentType);
990
+ let parsedJson = maybeParseJson(text, normalizedContentType);
991
+ let normalizedText = parsedJson !== null ? JSON.stringify(redactStructuredValue(parsedJson)) : sanitizeFreeText(text);
992
+ let { text: truncatedText, truncated } = truncateText(normalizedText);
993
+ return {
994
+ ...normalizedContentType ? { contentType: normalizedContentType } : {},
995
+ text: truncatedText,
996
+ ...truncated ? { truncated: true } : {}
997
+ };
998
+ };
999
+ var isBinaryLike = (value) => {
1000
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(value)) return true;
1001
+ if (value instanceof ArrayBuffer) return true;
1002
+ if (ArrayBuffer.isView(value)) return true;
1003
+ if (typeof Blob !== "undefined" && value instanceof Blob) return true;
1004
+ if (typeof FormData !== "undefined" && value instanceof FormData) return true;
1005
+ return false;
1006
+ };
1007
+ var serializeTextBody = (value, contentType) => {
1008
+ let normalizedContentType = normalizeContentType(contentType);
1009
+ if (value == null || isBinaryLike(value) || !isTextContentType(normalizedContentType)) {
1010
+ return void 0;
1011
+ }
1012
+ if (typeof value === "string") {
1013
+ return sanitizeTextBody(value, normalizedContentType);
1014
+ }
1015
+ if (value instanceof URLSearchParams) {
1016
+ return sanitizeTextBody(value.toString(), normalizedContentType);
1017
+ }
1018
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
1019
+ return sanitizeTextBody(String(value), normalizedContentType);
1020
+ }
1021
+ if (Array.isArray(value) || isRecord2(value)) {
1022
+ return sanitizeTextBody(JSON.stringify(redactStructuredValue(value)), "application/json");
1023
+ }
1024
+ return void 0;
1025
+ };
1026
+ var buildUrl = (baseURL, url) => {
1027
+ if (!url) return "";
1028
+ if (!baseURL) return url;
1029
+ try {
1030
+ return new URL(url, baseURL).toString();
1031
+ } catch {
1032
+ return url;
1033
+ }
1034
+ };
1035
+ var sanitizeUrl = (value) => {
1036
+ if (!value) return value;
1037
+ try {
1038
+ let url = new URL(value);
1039
+ for (let key of Array.from(url.searchParams.keys())) {
1040
+ if (SECRET_KEY_PATTERN.test(key)) {
1041
+ url.searchParams.set(key, REDACTED_VALUE);
1042
+ }
1043
+ }
1044
+ return url.toString();
1045
+ } catch {
1046
+ return value.replace(
1047
+ /([?&]([^=&#]+)=)([^&#]+)/g,
1048
+ (_match, prefix, key, rawValue) => SECRET_KEY_PATTERN.test(key) ? `${prefix}${REDACTED_VALUE}` : `${prefix}${rawValue}`
1049
+ );
1050
+ }
1051
+ };
1052
+ var flattenHeaderValue = (value) => {
1053
+ if (typeof value === "string") return value;
1054
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
1055
+ if (Array.isArray(value)) {
1056
+ let normalized = value.map((entry) => flattenHeaderValue(entry)).filter((entry) => typeof entry === "string" && entry.length > 0);
1057
+ return normalized.length > 0 ? normalized.join(", ") : void 0;
1058
+ }
1059
+ return void 0;
1060
+ };
1061
+ var headerEntries = (headers) => {
1062
+ if (!headers) return [];
1063
+ if (typeof headers.toJSON === "function") {
1064
+ let json = headers.toJSON();
1065
+ if (isRecord2(json)) {
1066
+ return Object.entries(json).map(([key, value]) => {
1067
+ let flattened = flattenHeaderValue(value);
1068
+ return flattened ? [key, flattened] : null;
1069
+ }).filter((entry) => entry !== null);
1070
+ }
1071
+ }
1072
+ if (typeof headers.entries === "function") {
1073
+ return Array.from(
1074
+ headers.entries()
1075
+ ).map(([key, value]) => [key, value]);
1076
+ }
1077
+ if (isRecord2(headers)) {
1078
+ return Object.entries(headers).map(([key, value]) => {
1079
+ let flattened = flattenHeaderValue(value);
1080
+ return flattened ? [key, flattened] : null;
1081
+ }).filter((entry) => entry !== null);
1082
+ }
1083
+ return [];
1084
+ };
1085
+ var sanitizeHeaders = (headers) => {
1086
+ let entries = headerEntries(headers).map(([key, value]) => [key.toLowerCase(), sanitizeScalar(value).text]).filter(([key]) => isSafeHeaderName(key));
1087
+ if (entries.length === 0) return void 0;
1088
+ return Object.fromEntries(entries);
1089
+ };
1090
+ var getContentType = (headers) => headerEntries(headers).find(([key]) => key.toLowerCase() === "content-type")?.[1];
1091
+ var takeTraceDraft = (config2) => {
1092
+ if (!config2) return void 0;
1093
+ let draft = config2.__slatesHttpTraceDraft ?? (isObjectLike(config2) ? traceDraftsByConfig.get(config2) : void 0) ?? (isObjectLike(config2.headers) ? traceDraftsByHeaders.get(config2.headers) : void 0);
1094
+ if (!draft) return void 0;
1095
+ return draft;
1096
+ };
1097
+ var clearTraceDraft = (config2, draft) => {
1098
+ if (!config2) return;
1099
+ if (config2.__slatesHttpTraceDraft === draft) {
1100
+ delete config2.__slatesHttpTraceDraft;
1101
+ }
1102
+ if (isObjectLike(config2)) {
1103
+ traceDraftsByConfig.delete(config2);
1104
+ }
1105
+ if (isObjectLike(config2.headers)) {
1106
+ traceDraftsByHeaders.delete(config2.headers);
1107
+ }
1108
+ };
1109
+ var attachHttpTraceDraft = (config2, context) => {
1110
+ let traceAwareConfig = config2;
1111
+ let contentType = getContentType(config2.headers);
1112
+ traceAwareConfig.__slatesHttpTraceDraft = {
1113
+ context,
1114
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1115
+ startedAtMs: Date.now(),
1116
+ request: {
1117
+ method: (config2.method ?? "GET").toUpperCase(),
1118
+ url: sanitizeUrl(buildUrl(config2.baseURL, config2.url)),
1119
+ ...sanitizeHeaders(config2.headers) ? { headers: sanitizeHeaders(config2.headers) } : {},
1120
+ ...serializeTextBody(config2.data, contentType) ? { body: serializeTextBody(config2.data, contentType) } : {}
1121
+ }
1122
+ };
1123
+ if (isObjectLike(traceAwareConfig)) {
1124
+ traceDraftsByConfig.set(traceAwareConfig, traceAwareConfig.__slatesHttpTraceDraft);
1125
+ }
1126
+ if (isObjectLike(traceAwareConfig.headers)) {
1127
+ traceDraftsByHeaders.set(
1128
+ traceAwareConfig.headers,
1129
+ traceAwareConfig.__slatesHttpTraceDraft
1130
+ );
1131
+ }
1132
+ return config2;
1133
+ };
1134
+ var recordHttpTraceFromResponse = (response) => {
1135
+ let config2 = response.config;
1136
+ let draft = takeTraceDraft(config2);
1137
+ if (!draft) return response;
1138
+ clearTraceDraft(config2, draft);
1139
+ let contentType = getContentType(response.headers);
1140
+ draft.context.recordHttpTrace({
1141
+ startedAt: draft.startedAt,
1142
+ durationMs: Math.max(Date.now() - draft.startedAtMs, 0),
1143
+ request: draft.request,
1144
+ response: {
1145
+ status: response.status,
1146
+ ...response.statusText ? { statusText: response.statusText } : {},
1147
+ ...sanitizeHeaders(response.headers) ? { headers: sanitizeHeaders(response.headers) } : {},
1148
+ ...serializeTextBody(response.data, contentType) ? { body: serializeTextBody(response.data, contentType) } : {}
1149
+ }
1150
+ });
1151
+ return response;
1152
+ };
1153
+ var recordHttpTraceFromError = (error) => {
1154
+ let config2 = error.config;
1155
+ let draft = takeTraceDraft(config2);
1156
+ if (!draft) return;
1157
+ clearTraceDraft(config2, draft);
1158
+ let responseContentType = getContentType(error.response?.headers);
1159
+ draft.context.recordHttpTrace({
1160
+ startedAt: draft.startedAt,
1161
+ durationMs: Math.max(Date.now() - draft.startedAtMs, 0),
1162
+ request: draft.request,
1163
+ ...error.response ? {
1164
+ response: {
1165
+ status: error.response.status,
1166
+ ...error.response.statusText ? { statusText: error.response.statusText } : {},
1167
+ ...sanitizeHeaders(error.response.headers) ? { headers: sanitizeHeaders(error.response.headers) } : {},
1168
+ ...serializeTextBody(error.response.data, responseContentType) ? { body: serializeTextBody(error.response.data, responseContentType) } : {}
1169
+ }
1170
+ } : {},
1171
+ error: {
1172
+ ...error.code ? { code: error.code } : {},
1173
+ message: error.message
1174
+ }
1175
+ });
1176
+ };
1177
+
1178
+ // src/axios/index.ts
1179
+ var applySlateInterceptors = (instance, errorMapping) => {
1180
+ instance.interceptors.request.use(
1181
+ (request) => {
1182
+ let ctx = getCurrentContext();
1183
+ let spec2 = ctx.specification;
1184
+ request.headers.set("User-Agent", `slates.dev@1.0.0/${spec2.key}`);
1185
+ request.headers.set("X-Slates-Provider", spec2.key);
1186
+ let tracedRequest = attachHttpTraceDraft(request, ctx);
1187
+ if (!tracedRequest.__slatesTraceAdapterWrapped) {
1188
+ let adapter = getAdapter(tracedRequest.adapter ?? baseAxios.defaults.adapter);
1189
+ tracedRequest.adapter = async (config2) => {
1190
+ try {
1191
+ let response = await adapter(config2);
1192
+ return recordHttpTraceFromResponse(response);
1193
+ } catch (error) {
1194
+ if (isAxiosError2(error)) {
1195
+ recordHttpTraceFromError(error);
1196
+ }
1197
+ throw error;
1198
+ }
1199
+ };
1200
+ tracedRequest.__slatesTraceAdapterWrapped = true;
1201
+ }
1202
+ return tracedRequest;
1203
+ },
1204
+ (error) => Promise.reject(error)
1205
+ );
1206
+ instance.interceptors.response.use(
1207
+ (response) => response,
1208
+ (error) => Promise.reject(SlateError.fromAxios(error, errorMapping))
1209
+ );
1210
+ };
1211
+ applySlateInterceptors(baseAxios);
1212
+ var createAxios = (config2) => {
1213
+ let { errorMapping, ...axiosConfig } = config2 ?? {};
1214
+ let instance = baseAxios.create({
1215
+ ...axiosConfig,
1216
+ headers: {
1217
+ ...axiosConfig.headers
1218
+ }
1219
+ });
1220
+ applySlateInterceptors(instance, errorMapping);
1221
+ return instance;
1222
+ };
1223
+ var axios = createAxios();
1224
+
1225
+ // src/config/config.ts
1226
+ var SlateConfig = class _SlateConfig {
1227
+ #configSchema;
1228
+ #configChanged = null;
1229
+ #getDefaultConfig = null;
1230
+ constructor(schema) {
1231
+ this.#configSchema = schema;
1232
+ }
1233
+ static create(schema) {
1234
+ return new _SlateConfig(schema);
1235
+ }
1236
+ config(schema) {
1237
+ this.#configSchema = schema;
1238
+ return this;
1239
+ }
1240
+ onConfigChanged(handler) {
1241
+ this.#configChanged = handler;
1242
+ return this;
1243
+ }
1244
+ getDefaultConfig(getter) {
1245
+ this.#getDefaultConfig = getter;
1246
+ return this;
1247
+ }
1248
+ get configSchema() {
1249
+ return this.#configSchema;
1250
+ }
1251
+ get handlers() {
1252
+ return {
1253
+ configChanged: this.#configChanged,
1254
+ getDefaultConfig: this.#getDefaultConfig
1255
+ };
1256
+ }
1257
+ };
1258
+ var config = (schema) => SlateConfig.create(schema);
1259
+
1260
+ // src/context/context.ts
1261
+ var SlateContext = class {
1262
+ constructor(config2, input, auth2, spec2, logger) {
1263
+ this.spec = spec2;
1264
+ this.logger = logger;
1265
+ this.#config = config2;
1266
+ this.#input = input;
1267
+ this.#auth = auth2;
1268
+ }
1269
+ spec;
1270
+ logger;
1271
+ #config;
1272
+ #input;
1273
+ #auth;
1274
+ #httpTraces = [];
1275
+ get specification() {
1276
+ return this.spec;
1277
+ }
1278
+ get config() {
1279
+ return Object.freeze(this.#config);
1280
+ }
1281
+ get input() {
1282
+ return Object.freeze(this.#input);
1283
+ }
1284
+ get event() {
1285
+ return Object.freeze(this.#input);
1286
+ }
1287
+ get state() {
1288
+ return Object.freeze(this.#input.state);
1289
+ }
1290
+ get request() {
1291
+ return Object.freeze(this.#input.request);
1292
+ }
1293
+ get auth() {
1294
+ return Object.freeze(this.#auth);
1295
+ }
1296
+ recordHttpTrace(trace) {
1297
+ this.#httpTraces.push(trace);
1298
+ }
1299
+ getHttpTraces() {
1300
+ return this.#httpTraces.map((trace) => ({
1301
+ ...trace,
1302
+ request: {
1303
+ ...trace.request,
1304
+ ...trace.request.headers ? { headers: { ...trace.request.headers } } : {},
1305
+ ...trace.request.body ? { body: { ...trace.request.body } } : {}
1306
+ },
1307
+ ...trace.response ? {
1308
+ response: {
1309
+ ...trace.response,
1310
+ ...trace.response.headers ? { headers: { ...trace.response.headers } } : {},
1311
+ ...trace.response.body ? { body: { ...trace.response.body } } : {}
1312
+ }
1313
+ } : {},
1314
+ ...trace.error ? { error: { ...trace.error } } : {}
1315
+ }));
1316
+ }
1317
+ info(message) {
1318
+ this.logger.info(message);
1319
+ }
1320
+ warn(message) {
1321
+ this.logger.warn(message);
1322
+ }
1323
+ error(message) {
1324
+ this.logger.error(message);
1325
+ }
1326
+ progress(message) {
1327
+ this.logger.progress(message);
1328
+ }
1329
+ };
1330
+
1331
+ // src/logger/logger.ts
1332
+ import { encode } from "@toon-format/toon";
1333
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1334
+ var normalizeMessage = (message) => {
1335
+ if (Array.isArray(message)) {
1336
+ let parts = message.map((part) => normalizeMessage(part));
1337
+ let combinedMessage = parts.map((part) => part.message).filter(Boolean).join(" ").trim();
1338
+ let dataParts = parts.map((part) => {
1339
+ if (part.data) {
1340
+ return {
1341
+ message: part.message,
1342
+ ...part.data
1343
+ };
1344
+ }
1345
+ return part.message;
1346
+ }).filter(Boolean);
1347
+ return {
1348
+ message: combinedMessage || "Log entry",
1349
+ data: dataParts.length > 0 ? { parts: dataParts } : void 0
1350
+ };
1351
+ }
1352
+ if (typeof message === "object") {
1353
+ if (message === null) return { message: "null" };
1354
+ if (message instanceof Error) {
1355
+ return {
1356
+ message: `${message.name}: ${message.message}`,
1357
+ data: {
1358
+ error: {
1359
+ name: message.name,
1360
+ message: message.message,
1361
+ stack: message.stack
1362
+ }
1363
+ }
1364
+ };
1365
+ }
1366
+ if (isRecord3(message) && typeof message.message === "string") {
1367
+ let { message: text, ...data } = message;
1368
+ return {
1369
+ message: text || "Log entry",
1370
+ data: Object.keys(data).length > 0 ? data : void 0
1371
+ };
1372
+ }
1373
+ return {
1374
+ message: encode(message),
1375
+ data: isRecord3(message) ? message : void 0
1376
+ };
1377
+ }
1378
+ return { message: String(message) };
1379
+ };
1380
+ var SlateLogger = class {
1381
+ #logs = [];
1382
+ #listeners = [];
1383
+ #timer = null;
1384
+ constructor(listeners = []) {
1385
+ this.#listeners.push(...listeners);
1386
+ }
1387
+ flush() {
1388
+ if (this.#timer) clearTimeout(this.#timer);
1389
+ if (this.#logs.length === 0) return;
1390
+ let logs = this.#logs.splice(0);
1391
+ for (let listener of this.#listeners) {
1392
+ listener(logs);
1393
+ }
1394
+ }
1395
+ scheduleFlush() {
1396
+ if (this.#timer) return;
1397
+ this.#timer = setTimeout(() => {
1398
+ this.flush();
1399
+ this.#timer = null;
1400
+ }, 10);
1401
+ }
1402
+ log(type, message) {
1403
+ let normalized = normalizeMessage(message);
1404
+ this.#logs.push({
1405
+ type,
1406
+ timestamp: /* @__PURE__ */ new Date(),
1407
+ message: normalized.message,
1408
+ data: normalized.data
1409
+ });
1410
+ this.scheduleFlush();
1411
+ }
1412
+ info(...message) {
1413
+ this.log("info", message.length === 1 ? message[0] : message.flat());
1414
+ }
1415
+ warn(...message) {
1416
+ this.log("warn", message.length === 1 ? message[0] : message.flat());
1417
+ }
1418
+ error(...message) {
1419
+ this.log("error", message.length === 1 ? message[0] : message.flat());
1420
+ }
1421
+ progress(...message) {
1422
+ this.log("progress", message.length === 1 ? message[0] : message.flat());
1423
+ }
1424
+ };
1425
+
1426
+ // src/specification/slate.ts
1427
+ var Slate = class _Slate {
1428
+ constructor(_spec, _actions) {
1429
+ this._spec = _spec;
1430
+ this._actions = _actions;
1431
+ }
1432
+ _spec;
1433
+ _actions;
1434
+ static create(params) {
1435
+ return new _Slate(params.spec, [...params.triggers, ...params.tools]);
1436
+ }
1437
+ get spec() {
1438
+ return this._spec;
1439
+ }
1440
+ get actions() {
1441
+ return this._actions;
1442
+ }
1443
+ };
1444
+
1445
+ // src/specification/specification.ts
1446
+ import z from "zod";
1447
+ var SlateSpecification = class _SlateSpecification {
1448
+ constructor(_config, _auth, _params) {
1449
+ this._config = _config;
1450
+ this._auth = _auth;
1451
+ this._params = _params;
1452
+ }
1453
+ _config;
1454
+ _auth;
1455
+ _params;
1456
+ static create(params) {
1457
+ return new _SlateSpecification(params.config, params.auth, params);
1458
+ }
1459
+ get configSchema() {
1460
+ return this._config.configSchema;
1461
+ }
1462
+ get authSchema() {
1463
+ return "outputSchema" in this._auth ? this._auth.outputSchema : z.object({});
1464
+ }
1465
+ get config() {
1466
+ return this._config;
1467
+ }
1468
+ get auth() {
1469
+ return this._auth;
1470
+ }
1471
+ get parameters() {
1472
+ return this._params;
1473
+ }
1474
+ get key() {
1475
+ return this._params.key;
1476
+ }
1477
+ get name() {
1478
+ return this._params.name;
1479
+ }
1480
+ get description() {
1481
+ return this._params.description;
1482
+ }
1483
+ };
1484
+ var spec = (params) => SlateSpecification.create(params);
1485
+ export {
1486
+ Slate,
1487
+ SlateAction,
1488
+ SlateAuth,
1489
+ SlateConfig,
1490
+ SlateContext,
1491
+ SlateDeclarationError,
1492
+ SlateDefaultPollingIntervalSeconds,
1493
+ SlateError,
1494
+ SlateLogger,
1495
+ SlateSpecification,
1496
+ SlateTool,
1497
+ SlateTrigger,
1498
+ allOf,
1499
+ anyOf,
1500
+ auth,
1501
+ axios,
1502
+ config,
1503
+ createAxios,
1504
+ createSlateError,
1505
+ getCurrentContext,
1506
+ getServiceErrorData,
1507
+ inferSlateErrorFromAxios,
1508
+ isAxiosErrorLike,
1509
+ isServiceErrorData,
1510
+ mapServiceErrorCode,
1511
+ mapServiceErrorToSlateErrorInput,
1512
+ mergeScopes,
1513
+ runWithContext,
1514
+ scopeClause,
1515
+ spec,
1516
+ tool,
1517
+ trigger,
1518
+ validateScopes
1519
+ };