@stigg/typescript-mcp 0.1.0-alpha.9 → 0.1.0-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/auth.d.mts.map +1 -1
- package/auth.d.ts.map +1 -1
- package/code-tool-paths.cjs +8 -0
- package/code-tool-paths.cjs.map +1 -0
- package/code-tool-paths.d.cts +2 -0
- package/code-tool-paths.d.cts.map +1 -0
- package/code-tool-types.d.mts.map +1 -1
- package/code-tool-types.d.ts.map +1 -1
- package/code-tool-worker.d.mts +5 -0
- package/code-tool-worker.d.mts.map +1 -0
- package/code-tool-worker.d.ts +5 -0
- package/code-tool-worker.d.ts.map +1 -0
- package/code-tool-worker.js +370 -0
- package/code-tool-worker.js.map +1 -0
- package/code-tool-worker.mjs +332 -0
- package/code-tool-worker.mjs.map +1 -0
- package/code-tool.d.mts +8 -2
- package/code-tool.d.mts.map +1 -1
- package/code-tool.d.ts +8 -2
- package/code-tool.d.ts.map +1 -1
- package/code-tool.js +266 -37
- package/code-tool.js.map +1 -1
- package/code-tool.mjs +233 -37
- package/code-tool.mjs.map +1 -1
- package/docs-search-tool.d.mts +5 -3
- package/docs-search-tool.d.mts.map +1 -1
- package/docs-search-tool.d.ts +5 -3
- package/docs-search-tool.d.ts.map +1 -1
- package/docs-search-tool.js +53 -4
- package/docs-search-tool.js.map +1 -1
- package/docs-search-tool.mjs +52 -4
- package/docs-search-tool.mjs.map +1 -1
- package/http.d.mts +2 -4
- package/http.d.mts.map +1 -1
- package/http.d.ts +2 -4
- package/http.d.ts.map +1 -1
- package/http.js +123 -40
- package/http.js.map +1 -1
- package/http.mjs +123 -40
- package/http.mjs.map +1 -1
- package/index.js +13 -12
- package/index.js.map +1 -1
- package/index.mjs +13 -12
- package/index.mjs.map +1 -1
- package/instructions.d.mts +5 -0
- package/instructions.d.mts.map +1 -0
- package/instructions.d.ts +5 -0
- package/instructions.d.ts.map +1 -0
- package/instructions.js +61 -0
- package/instructions.js.map +1 -0
- package/instructions.mjs +55 -0
- package/instructions.mjs.map +1 -0
- package/local-docs-search.d.mts +28 -0
- package/local-docs-search.d.mts.map +1 -0
- package/local-docs-search.d.ts +28 -0
- package/local-docs-search.d.ts.map +1 -0
- package/local-docs-search.js +5385 -0
- package/local-docs-search.js.map +1 -0
- package/local-docs-search.mjs +5345 -0
- package/local-docs-search.mjs.map +1 -0
- package/logger.d.mts +7 -0
- package/logger.d.mts.map +1 -0
- package/logger.d.ts +7 -0
- package/logger.d.ts.map +1 -0
- package/logger.js +29 -0
- package/logger.js.map +1 -0
- package/logger.mjs +22 -0
- package/logger.mjs.map +1 -0
- package/methods.d.mts.map +1 -1
- package/methods.d.ts.map +1 -1
- package/methods.js +312 -42
- package/methods.js.map +1 -1
- package/methods.mjs +312 -42
- package/methods.mjs.map +1 -1
- package/options.d.mts +7 -0
- package/options.d.mts.map +1 -1
- package/options.d.ts +7 -0
- package/options.d.ts.map +1 -1
- package/options.js +42 -0
- package/options.js.map +1 -1
- package/options.mjs +42 -0
- package/options.mjs.map +1 -1
- package/package.json +58 -7
- package/server.d.mts +10 -1
- package/server.d.mts.map +1 -1
- package/server.d.ts +10 -1
- package/server.d.ts.map +1 -1
- package/server.js +72 -47
- package/server.js.map +1 -1
- package/server.mjs +72 -47
- package/server.mjs.map +1 -1
- package/src/code-tool-paths.cts +5 -0
- package/src/code-tool-types.ts +1 -0
- package/src/code-tool-worker.ts +383 -0
- package/src/code-tool.ts +302 -47
- package/src/docs-search-tool.ts +81 -11
- package/src/http.ts +131 -42
- package/src/index.ts +15 -13
- package/src/instructions.ts +83 -0
- package/src/local-docs-search.ts +6399 -0
- package/src/logger.ts +28 -0
- package/src/methods.ts +312 -42
- package/src/options.ts +56 -0
- package/src/server.ts +85 -58
- package/src/stdio.ts +6 -2
- package/src/types.ts +3 -0
- package/src/util.ts +2 -2
- package/stdio.d.mts.map +1 -1
- package/stdio.d.ts.map +1 -1
- package/stdio.js +6 -2
- package/stdio.js.map +1 -1
- package/stdio.mjs +6 -2
- package/stdio.mjs.map +1 -1
- package/types.d.mts +6 -0
- package/types.d.mts.map +1 -1
- package/types.d.ts +6 -0
- package/types.d.ts.map +1 -1
- package/types.js.map +1 -1
- package/types.mjs.map +1 -1
- package/util.js +2 -2
- package/util.js.map +1 -1
- package/util.mjs +2 -2
- package/util.mjs.map +1 -1
package/server.mjs
CHANGED
|
@@ -4,39 +4,15 @@ import { CallToolRequestSchema, ListToolsRequestSchema, SetLevelRequestSchema, }
|
|
|
4
4
|
import Stigg from '@stigg/typescript';
|
|
5
5
|
import { codeTool } from "./code-tool.mjs";
|
|
6
6
|
import docsSearchTool from "./docs-search-tool.mjs";
|
|
7
|
+
import { setLocalSearch } from "./docs-search-tool.mjs";
|
|
8
|
+
import { LocalDocsSearch } from "./local-docs-search.mjs";
|
|
9
|
+
import { getInstructions } from "./instructions.mjs";
|
|
7
10
|
import { blockedMethodsForCodeTool } from "./methods.mjs";
|
|
8
|
-
|
|
9
|
-
async function getInstructions(stainlessApiKey) {
|
|
10
|
-
// Setting the stainless API key is optional, but may be required
|
|
11
|
-
// to authenticate requests to the Stainless API.
|
|
12
|
-
const response = await fetch(readEnv('CODE_MODE_INSTRUCTIONS_URL') ?? 'https://api.stainless.com/api/ai/instructions/stigg', {
|
|
13
|
-
method: 'GET',
|
|
14
|
-
headers: { ...(stainlessApiKey && { Authorization: stainlessApiKey }) },
|
|
15
|
-
});
|
|
16
|
-
let instructions;
|
|
17
|
-
if (!response.ok) {
|
|
18
|
-
console.warn('Warning: failed to retrieve MCP server instructions. Proceeding with default instructions...');
|
|
19
|
-
instructions = `
|
|
20
|
-
This is the stigg MCP server. You will use Code Mode to help the user perform
|
|
21
|
-
actions. You can use search_docs tool to learn about how to take action with this server. Then,
|
|
22
|
-
you will write TypeScript code using the execute tool take action. It is CRITICAL that you be
|
|
23
|
-
thoughtful and deliberate when executing code. Always try to entirely solve the problem in code
|
|
24
|
-
block: it can be as long as you need to get the job done!
|
|
25
|
-
`;
|
|
26
|
-
}
|
|
27
|
-
instructions ??= (await response.json()).instructions;
|
|
28
|
-
instructions = `
|
|
29
|
-
The current time in Unix timestamps is ${Date.now()}.
|
|
30
|
-
|
|
31
|
-
${instructions}
|
|
32
|
-
`;
|
|
33
|
-
return instructions;
|
|
34
|
-
}
|
|
35
|
-
export const newMcpServer = async (stainlessApiKey) => new McpServer({
|
|
11
|
+
export const newMcpServer = async ({ stainlessApiKey, customInstructionsPath, }) => new McpServer({
|
|
36
12
|
name: 'stigg_typescript_api',
|
|
37
|
-
version: '0.1.0-
|
|
13
|
+
version: '0.1.0-beta.10',
|
|
38
14
|
}, {
|
|
39
|
-
instructions: await getInstructions(stainlessApiKey),
|
|
15
|
+
instructions: await getInstructions({ stainlessApiKey, customInstructionsPath }),
|
|
40
16
|
capabilities: { tools: {}, logging: {} },
|
|
41
17
|
});
|
|
42
18
|
/**
|
|
@@ -57,14 +33,38 @@ export async function initMcpServer(params) {
|
|
|
57
33
|
warn: logAtLevel('warning'),
|
|
58
34
|
error: logAtLevel('error'),
|
|
59
35
|
};
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
36
|
+
if (params.mcpOptions?.docsSearchMode === 'local') {
|
|
37
|
+
const docsDir = params.mcpOptions?.docsDir;
|
|
38
|
+
const localSearch = await LocalDocsSearch.create(docsDir ? { docsDir } : undefined);
|
|
39
|
+
setLocalSearch(localSearch);
|
|
40
|
+
}
|
|
41
|
+
let _client;
|
|
42
|
+
let _clientError;
|
|
43
|
+
let _logLevel;
|
|
44
|
+
const getClient = () => {
|
|
45
|
+
if (_clientError)
|
|
46
|
+
throw _clientError;
|
|
47
|
+
if (!_client) {
|
|
48
|
+
try {
|
|
49
|
+
_client = new Stigg({
|
|
50
|
+
logger,
|
|
51
|
+
...params.clientOptions,
|
|
52
|
+
defaultHeaders: {
|
|
53
|
+
...params.clientOptions?.defaultHeaders,
|
|
54
|
+
'X-Stainless-MCP': 'true',
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
if (_logLevel) {
|
|
58
|
+
_client = _client.withOptions({ logLevel: _logLevel });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
catch (e) {
|
|
62
|
+
_clientError = e instanceof Error ? e : new Error(String(e));
|
|
63
|
+
throw _clientError;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return _client;
|
|
67
|
+
};
|
|
68
68
|
const providedTools = selectTools(params.mcpOptions);
|
|
69
69
|
const toolMap = Object.fromEntries(providedTools.map((mcpTool) => [mcpTool.tool.name, mcpTool]));
|
|
70
70
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
@@ -78,35 +78,58 @@ export async function initMcpServer(params) {
|
|
|
78
78
|
if (!mcpTool) {
|
|
79
79
|
throw new Error(`Unknown tool: ${name}`);
|
|
80
80
|
}
|
|
81
|
+
let client;
|
|
82
|
+
try {
|
|
83
|
+
client = getClient();
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
return {
|
|
87
|
+
content: [
|
|
88
|
+
{
|
|
89
|
+
type: 'text',
|
|
90
|
+
text: `Failed to initialize client: ${error instanceof Error ? error.message : String(error)}`,
|
|
91
|
+
},
|
|
92
|
+
],
|
|
93
|
+
isError: true,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
81
96
|
return executeHandler({
|
|
82
97
|
handler: mcpTool.handler,
|
|
83
98
|
reqContext: {
|
|
84
99
|
client,
|
|
85
100
|
stainlessApiKey: params.stainlessApiKey ?? params.mcpOptions?.stainlessApiKey,
|
|
101
|
+
upstreamClientEnvs: params.upstreamClientEnvs,
|
|
102
|
+
mcpSessionId: params.mcpSessionId,
|
|
103
|
+
mcpClientInfo: params.mcpClientInfo,
|
|
86
104
|
},
|
|
87
105
|
args,
|
|
88
106
|
});
|
|
89
107
|
});
|
|
90
108
|
server.setRequestHandler(SetLevelRequestSchema, async (request) => {
|
|
91
109
|
const { level } = request.params;
|
|
110
|
+
let logLevel;
|
|
92
111
|
switch (level) {
|
|
93
112
|
case 'debug':
|
|
94
|
-
|
|
113
|
+
logLevel = 'debug';
|
|
95
114
|
break;
|
|
96
115
|
case 'info':
|
|
97
|
-
|
|
116
|
+
logLevel = 'info';
|
|
98
117
|
break;
|
|
99
118
|
case 'notice':
|
|
100
119
|
case 'warning':
|
|
101
|
-
|
|
120
|
+
logLevel = 'warn';
|
|
102
121
|
break;
|
|
103
122
|
case 'error':
|
|
104
|
-
|
|
123
|
+
logLevel = 'error';
|
|
105
124
|
break;
|
|
106
125
|
default:
|
|
107
|
-
|
|
126
|
+
logLevel = 'off';
|
|
108
127
|
break;
|
|
109
128
|
}
|
|
129
|
+
_logLevel = logLevel;
|
|
130
|
+
if (_client) {
|
|
131
|
+
_client = _client.withOptions({ logLevel });
|
|
132
|
+
}
|
|
110
133
|
return {};
|
|
111
134
|
});
|
|
112
135
|
}
|
|
@@ -114,11 +137,13 @@ export async function initMcpServer(params) {
|
|
|
114
137
|
* Selects the tools to include in the MCP Server based on the provided options.
|
|
115
138
|
*/
|
|
116
139
|
export function selectTools(options) {
|
|
117
|
-
const includedTools = [
|
|
118
|
-
|
|
140
|
+
const includedTools = [];
|
|
141
|
+
if (options?.includeCodeTool ?? true) {
|
|
142
|
+
includedTools.push(codeTool({
|
|
119
143
|
blockedMethods: blockedMethodsForCodeTool(options),
|
|
120
|
-
|
|
121
|
-
|
|
144
|
+
codeExecutionMode: options?.codeExecutionMode ?? 'stainless-sandbox',
|
|
145
|
+
}));
|
|
146
|
+
}
|
|
122
147
|
if (options?.includeDocsTools ?? true) {
|
|
123
148
|
includedTools.push(docsSearchTool);
|
|
124
149
|
}
|
package/server.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.mjs","sourceRoot":"","sources":["src/server.ts"],"names":[],"mappings":"AAAA,sFAAsF;
|
|
1
|
+
{"version":3,"file":"server.mjs","sourceRoot":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YACP,cAAc,EAAE,yBAAyB,CAAC,OAAO,CAAC;YAClD,iBAAiB,EAAE,OAAO,EAAE,iBAAiB,IAAI,mBAAmB;SACrE,CAAC,CACH,CAAC;IACJ,CAAC;IACD,IAAI,OAAO,EAAE,gBAAgB,IAAI,IAAI,EAAE,CAAC;QACtC,aAAa,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IACrC,CAAC;IACD,OAAO,aAAa,CAAC;AACvB,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,EACnC,OAAO,EACP,UAAU,EACV,IAAI,GAKL;IACC,OAAO,MAAM,OAAO,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,IAAI,IAAI,EAAE,EAAE,CAAC,CAAC;AACzD,CAAC"}
|
package/src/code-tool-types.ts
CHANGED
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
2
|
+
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import util from 'node:util';
|
|
5
|
+
import Fuse from 'fuse.js';
|
|
6
|
+
import ts from 'typescript';
|
|
7
|
+
import { WorkerOutput } from './code-tool-types';
|
|
8
|
+
import { Stigg, ClientOptions } from '@stigg/typescript';
|
|
9
|
+
|
|
10
|
+
async function tseval(code: string) {
|
|
11
|
+
return import('data:application/typescript;charset=utf-8;base64,' + Buffer.from(code).toString('base64'));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function getRunFunctionSource(code: string): {
|
|
15
|
+
type: 'declaration' | 'expression';
|
|
16
|
+
client: string | undefined;
|
|
17
|
+
code: string;
|
|
18
|
+
} | null {
|
|
19
|
+
const sourceFile = ts.createSourceFile('code.ts', code, ts.ScriptTarget.Latest, true);
|
|
20
|
+
const printer = ts.createPrinter();
|
|
21
|
+
|
|
22
|
+
for (const statement of sourceFile.statements) {
|
|
23
|
+
// Check for top-level function declarations
|
|
24
|
+
if (ts.isFunctionDeclaration(statement)) {
|
|
25
|
+
if (statement.name?.text === 'run') {
|
|
26
|
+
return {
|
|
27
|
+
type: 'declaration',
|
|
28
|
+
client: statement.parameters[0]?.name.getText(),
|
|
29
|
+
code: printer.printNode(ts.EmitHint.Unspecified, statement.body!, sourceFile),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Check for variable declarations: const run = () => {} or const run = function() {}
|
|
35
|
+
if (ts.isVariableStatement(statement)) {
|
|
36
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
37
|
+
if (
|
|
38
|
+
ts.isIdentifier(declaration.name) &&
|
|
39
|
+
declaration.name.text === 'run' &&
|
|
40
|
+
// Check if it's initialized with a function
|
|
41
|
+
declaration.initializer &&
|
|
42
|
+
(ts.isFunctionExpression(declaration.initializer) || ts.isArrowFunction(declaration.initializer))
|
|
43
|
+
) {
|
|
44
|
+
return {
|
|
45
|
+
type: 'expression',
|
|
46
|
+
client: declaration.initializer.parameters[0]?.name.getText(),
|
|
47
|
+
code: printer.printNode(ts.EmitHint.Unspecified, declaration.initializer, sourceFile),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function getTSDiagnostics(code: string): string[] {
|
|
58
|
+
const functionSource = getRunFunctionSource(code)!;
|
|
59
|
+
const codeWithImport = [
|
|
60
|
+
'import { Stigg } from "@stigg/typescript";',
|
|
61
|
+
functionSource.type === 'declaration' ?
|
|
62
|
+
`async function run(${functionSource.client}: Stigg)`
|
|
63
|
+
: `const run: (${functionSource.client}: Stigg) => Promise<unknown> =`,
|
|
64
|
+
functionSource.code,
|
|
65
|
+
].join('\n');
|
|
66
|
+
const sourcePath = path.resolve('code.ts');
|
|
67
|
+
const ast = ts.createSourceFile(sourcePath, codeWithImport, ts.ScriptTarget.Latest, true);
|
|
68
|
+
const options = ts.getDefaultCompilerOptions();
|
|
69
|
+
options.target = ts.ScriptTarget.Latest;
|
|
70
|
+
options.module = ts.ModuleKind.NodeNext;
|
|
71
|
+
options.moduleResolution = ts.ModuleResolutionKind.NodeNext;
|
|
72
|
+
const host = ts.createCompilerHost(options, true);
|
|
73
|
+
const newHost: typeof host = {
|
|
74
|
+
...host,
|
|
75
|
+
getSourceFile: (...args) => {
|
|
76
|
+
if (path.resolve(args[0]) === sourcePath) {
|
|
77
|
+
return ast;
|
|
78
|
+
}
|
|
79
|
+
return host.getSourceFile(...args);
|
|
80
|
+
},
|
|
81
|
+
readFile: (...args) => {
|
|
82
|
+
if (path.resolve(args[0]) === sourcePath) {
|
|
83
|
+
return codeWithImport;
|
|
84
|
+
}
|
|
85
|
+
return host.readFile(...args);
|
|
86
|
+
},
|
|
87
|
+
fileExists: (...args) => {
|
|
88
|
+
if (path.resolve(args[0]) === sourcePath) {
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
return host.fileExists(...args);
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
const program = ts.createProgram({
|
|
95
|
+
options,
|
|
96
|
+
rootNames: [sourcePath],
|
|
97
|
+
host: newHost,
|
|
98
|
+
});
|
|
99
|
+
const diagnostics = ts.getPreEmitDiagnostics(program, ast);
|
|
100
|
+
return diagnostics.map((d) => {
|
|
101
|
+
const message = ts.flattenDiagnosticMessageText(d.messageText, '\n');
|
|
102
|
+
if (!d.file || !d.start) return `- ${message}`;
|
|
103
|
+
const { line: lineNumber } = ts.getLineAndCharacterOfPosition(d.file, d.start);
|
|
104
|
+
const line = codeWithImport.split('\n').at(lineNumber)?.trim();
|
|
105
|
+
return line ? `- ${message}\n ${line}` : `- ${message}`;
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const fuse = new Fuse(
|
|
110
|
+
[
|
|
111
|
+
'client.v1.customers.archive',
|
|
112
|
+
'client.v1.customers.checkEntitlement',
|
|
113
|
+
'client.v1.customers.import',
|
|
114
|
+
'client.v1.customers.list',
|
|
115
|
+
'client.v1.customers.listResources',
|
|
116
|
+
'client.v1.customers.provision',
|
|
117
|
+
'client.v1.customers.retrieve',
|
|
118
|
+
'client.v1.customers.retrieveEntitlements',
|
|
119
|
+
'client.v1.customers.unarchive',
|
|
120
|
+
'client.v1.customers.update',
|
|
121
|
+
'client.v1.customers.paymentMethod.attach',
|
|
122
|
+
'client.v1.customers.paymentMethod.detach',
|
|
123
|
+
'client.v1.customers.promotionalEntitlements.create',
|
|
124
|
+
'client.v1.customers.promotionalEntitlements.list',
|
|
125
|
+
'client.v1.customers.promotionalEntitlements.revoke',
|
|
126
|
+
'client.v1.customers.integrations.link',
|
|
127
|
+
'client.v1.customers.integrations.list',
|
|
128
|
+
'client.v1.customers.integrations.retrieve',
|
|
129
|
+
'client.v1.customers.integrations.unlink',
|
|
130
|
+
'client.v1.customers.integrations.update',
|
|
131
|
+
'client.v1.subscriptions.cancel',
|
|
132
|
+
'client.v1.subscriptions.delegate',
|
|
133
|
+
'client.v1.subscriptions.import',
|
|
134
|
+
'client.v1.subscriptions.list',
|
|
135
|
+
'client.v1.subscriptions.migrate',
|
|
136
|
+
'client.v1.subscriptions.preview',
|
|
137
|
+
'client.v1.subscriptions.provision',
|
|
138
|
+
'client.v1.subscriptions.retrieve',
|
|
139
|
+
'client.v1.subscriptions.transfer',
|
|
140
|
+
'client.v1.subscriptions.update',
|
|
141
|
+
'client.v1.subscriptions.futureUpdate.cancelPendingPayment',
|
|
142
|
+
'client.v1.subscriptions.futureUpdate.cancelSchedule',
|
|
143
|
+
'client.v1.subscriptions.usage.chargeUsage',
|
|
144
|
+
'client.v1.subscriptions.usage.sync',
|
|
145
|
+
'client.v1.subscriptions.invoice.markAsPaid',
|
|
146
|
+
'client.v1.coupons.archiveCoupon',
|
|
147
|
+
'client.v1.coupons.create',
|
|
148
|
+
'client.v1.coupons.list',
|
|
149
|
+
'client.v1.coupons.retrieve',
|
|
150
|
+
'client.v1.coupons.updateCoupon',
|
|
151
|
+
'client.v1.events.report',
|
|
152
|
+
'client.v1.credits.getAutoRecharge',
|
|
153
|
+
'client.v1.credits.getUsage',
|
|
154
|
+
'client.v1.credits.listLedger',
|
|
155
|
+
'client.v1.credits.grants.create',
|
|
156
|
+
'client.v1.credits.grants.list',
|
|
157
|
+
'client.v1.credits.grants.void',
|
|
158
|
+
'client.v1.credits.customCurrencies.archive',
|
|
159
|
+
'client.v1.credits.customCurrencies.create',
|
|
160
|
+
'client.v1.credits.customCurrencies.list',
|
|
161
|
+
'client.v1.credits.customCurrencies.listAssociatedEntities',
|
|
162
|
+
'client.v1.credits.customCurrencies.unarchive',
|
|
163
|
+
'client.v1.credits.customCurrencies.update',
|
|
164
|
+
'client.v1.features.archiveFeature',
|
|
165
|
+
'client.v1.features.createFeature',
|
|
166
|
+
'client.v1.features.listFeatures',
|
|
167
|
+
'client.v1.features.retrieveFeature',
|
|
168
|
+
'client.v1.features.unarchiveFeature',
|
|
169
|
+
'client.v1.features.updateFeature',
|
|
170
|
+
'client.v1.addons.archive',
|
|
171
|
+
'client.v1.addons.create',
|
|
172
|
+
'client.v1.addons.createDraft',
|
|
173
|
+
'client.v1.addons.list',
|
|
174
|
+
'client.v1.addons.listCharges',
|
|
175
|
+
'client.v1.addons.publish',
|
|
176
|
+
'client.v1.addons.removeDraft',
|
|
177
|
+
'client.v1.addons.retrieve',
|
|
178
|
+
'client.v1.addons.update',
|
|
179
|
+
'client.v1.addons.entitlements.create',
|
|
180
|
+
'client.v1.addons.entitlements.delete',
|
|
181
|
+
'client.v1.addons.entitlements.list',
|
|
182
|
+
'client.v1.addons.entitlements.update',
|
|
183
|
+
'client.v1.plans.archive',
|
|
184
|
+
'client.v1.plans.create',
|
|
185
|
+
'client.v1.plans.createDraft',
|
|
186
|
+
'client.v1.plans.list',
|
|
187
|
+
'client.v1.plans.listCharges',
|
|
188
|
+
'client.v1.plans.listOverageCharges',
|
|
189
|
+
'client.v1.plans.publish',
|
|
190
|
+
'client.v1.plans.removeDraft',
|
|
191
|
+
'client.v1.plans.retrieve',
|
|
192
|
+
'client.v1.plans.update',
|
|
193
|
+
'client.v1.plans.entitlements.create',
|
|
194
|
+
'client.v1.plans.entitlements.delete',
|
|
195
|
+
'client.v1.plans.entitlements.list',
|
|
196
|
+
'client.v1.plans.entitlements.update',
|
|
197
|
+
'client.v1.usage.history',
|
|
198
|
+
'client.v1.usage.report',
|
|
199
|
+
'client.v1.products.archiveProduct',
|
|
200
|
+
'client.v1.products.createProduct',
|
|
201
|
+
'client.v1.products.duplicateProduct',
|
|
202
|
+
'client.v1.products.listProducts',
|
|
203
|
+
'client.v1.products.unarchiveProduct',
|
|
204
|
+
'client.v1.products.updateProduct',
|
|
205
|
+
'client.v1Beta.customers.entitlements.check',
|
|
206
|
+
'client.v1Beta.customers.entities.archive',
|
|
207
|
+
'client.v1Beta.customers.entities.list',
|
|
208
|
+
'client.v1Beta.customers.entities.retrieve',
|
|
209
|
+
'client.v1Beta.customers.entities.unarchive',
|
|
210
|
+
'client.v1Beta.customers.entities.upsert',
|
|
211
|
+
'client.v1Beta.customers.assignments.list',
|
|
212
|
+
'client.v1Beta.customers.assignments.upsert',
|
|
213
|
+
'client.v1Beta.entityTypes.list',
|
|
214
|
+
'client.v1Beta.entityTypes.upsert',
|
|
215
|
+
],
|
|
216
|
+
{ threshold: 1, shouldSort: true },
|
|
217
|
+
);
|
|
218
|
+
|
|
219
|
+
function getMethodSuggestions(fullyQualifiedMethodName: string): string[] {
|
|
220
|
+
return fuse
|
|
221
|
+
.search(fullyQualifiedMethodName)
|
|
222
|
+
.map(({ item }) => item)
|
|
223
|
+
.slice(0, 5);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const proxyToObj = new WeakMap<any, any>();
|
|
227
|
+
const objToProxy = new WeakMap<any, any>();
|
|
228
|
+
|
|
229
|
+
type ClientProxyConfig = {
|
|
230
|
+
path: string[];
|
|
231
|
+
isBelievedBad?: boolean;
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
function makeSdkProxy<T extends object>(obj: T, { path, isBelievedBad = false }: ClientProxyConfig): T {
|
|
235
|
+
let proxy: T = objToProxy.get(obj);
|
|
236
|
+
|
|
237
|
+
if (!proxy) {
|
|
238
|
+
proxy = new Proxy(obj, {
|
|
239
|
+
get(target, prop, receiver) {
|
|
240
|
+
const propPath = [...path, String(prop)];
|
|
241
|
+
const value = Reflect.get(target, prop, receiver);
|
|
242
|
+
|
|
243
|
+
if (isBelievedBad || (!(prop in target) && value === undefined)) {
|
|
244
|
+
// If we're accessing a path that doesn't exist, it will probably eventually error.
|
|
245
|
+
// Let's proxy it and mark it bad so that we can control the error message.
|
|
246
|
+
// We proxy an empty class so that an invocation or construction attempt is possible.
|
|
247
|
+
return makeSdkProxy(class {}, { path: propPath, isBelievedBad: true });
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
|
|
251
|
+
return makeSdkProxy(value, { path: propPath, isBelievedBad });
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
return value;
|
|
255
|
+
},
|
|
256
|
+
|
|
257
|
+
apply(target, thisArg, args) {
|
|
258
|
+
if (isBelievedBad || typeof target !== 'function') {
|
|
259
|
+
const fullyQualifiedMethodName = path.join('.');
|
|
260
|
+
const suggestions = getMethodSuggestions(fullyQualifiedMethodName);
|
|
261
|
+
throw new Error(
|
|
262
|
+
`${fullyQualifiedMethodName} is not a function. Did you mean: ${suggestions.join(', ')}`,
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
return Reflect.apply(target, proxyToObj.get(thisArg) ?? thisArg, args);
|
|
267
|
+
},
|
|
268
|
+
|
|
269
|
+
construct(target, args, newTarget) {
|
|
270
|
+
if (isBelievedBad || typeof target !== 'function') {
|
|
271
|
+
const fullyQualifiedMethodName = path.join('.');
|
|
272
|
+
const suggestions = getMethodSuggestions(fullyQualifiedMethodName);
|
|
273
|
+
throw new Error(
|
|
274
|
+
`${fullyQualifiedMethodName} is not a constructor. Did you mean: ${suggestions.join(', ')}`,
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
return Reflect.construct(target, args, newTarget);
|
|
279
|
+
},
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
objToProxy.set(obj, proxy);
|
|
283
|
+
proxyToObj.set(proxy, obj);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return proxy;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function parseError(code: string, error: unknown): string | undefined {
|
|
290
|
+
if (!(error instanceof Error)) return;
|
|
291
|
+
const cause = error.cause instanceof Error ? `: ${error.cause.message}` : '';
|
|
292
|
+
const message = error.name ? `${error.name}: ${error.message}${cause}` : `${error.message}${cause}`;
|
|
293
|
+
try {
|
|
294
|
+
// Deno uses V8; the first "<anonymous>:LINE:COLUMN" is the top of stack.
|
|
295
|
+
const lineNumber = error.stack?.match(/<anonymous>:([0-9]+):[0-9]+/)?.[1];
|
|
296
|
+
// -1 for the zero-based indexing
|
|
297
|
+
const line =
|
|
298
|
+
lineNumber &&
|
|
299
|
+
code
|
|
300
|
+
.split('\n')
|
|
301
|
+
.at(parseInt(lineNumber, 10) - 1)
|
|
302
|
+
?.trim();
|
|
303
|
+
return line ? `${message}\n at line ${lineNumber}\n ${line}` : message;
|
|
304
|
+
} catch {
|
|
305
|
+
return message;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const fetch = async (req: Request): Promise<Response> => {
|
|
310
|
+
const { opts, code } = (await req.json()) as { opts: ClientOptions; code: string };
|
|
311
|
+
|
|
312
|
+
const runFunctionSource = code ? getRunFunctionSource(code) : null;
|
|
313
|
+
if (!runFunctionSource) {
|
|
314
|
+
const message =
|
|
315
|
+
code ?
|
|
316
|
+
'The code is missing a top-level `run` function.'
|
|
317
|
+
: 'The code argument is missing. Provide one containing a top-level `run` function.';
|
|
318
|
+
return Response.json(
|
|
319
|
+
{
|
|
320
|
+
is_error: true,
|
|
321
|
+
result: `${message} Write code within this template:\n\n\`\`\`\nasync function run(client) {\n // Fill this out\n}\n\`\`\``,
|
|
322
|
+
log_lines: [],
|
|
323
|
+
err_lines: [],
|
|
324
|
+
} satisfies WorkerOutput,
|
|
325
|
+
{ status: 400, statusText: 'Code execution error' },
|
|
326
|
+
);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const diagnostics = getTSDiagnostics(code);
|
|
330
|
+
if (diagnostics.length > 0) {
|
|
331
|
+
return Response.json(
|
|
332
|
+
{
|
|
333
|
+
is_error: true,
|
|
334
|
+
result: `The code contains TypeScript diagnostics:\n${diagnostics.join('\n')}`,
|
|
335
|
+
log_lines: [],
|
|
336
|
+
err_lines: [],
|
|
337
|
+
} satisfies WorkerOutput,
|
|
338
|
+
{ status: 400, statusText: 'Code execution error' },
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const client = new Stigg({
|
|
343
|
+
...opts,
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
const log_lines: string[] = [];
|
|
347
|
+
const err_lines: string[] = [];
|
|
348
|
+
const originalConsole = globalThis.console;
|
|
349
|
+
globalThis.console = {
|
|
350
|
+
...originalConsole,
|
|
351
|
+
log: (...args: unknown[]) => {
|
|
352
|
+
log_lines.push(util.format(...args));
|
|
353
|
+
},
|
|
354
|
+
error: (...args: unknown[]) => {
|
|
355
|
+
err_lines.push(util.format(...args));
|
|
356
|
+
},
|
|
357
|
+
};
|
|
358
|
+
try {
|
|
359
|
+
let run_ = async (client: any) => {};
|
|
360
|
+
run_ = (await tseval(`${code}\nexport default run;`)).default;
|
|
361
|
+
const result = await run_(makeSdkProxy(client, { path: ['client'] }));
|
|
362
|
+
return Response.json({
|
|
363
|
+
is_error: false,
|
|
364
|
+
result,
|
|
365
|
+
log_lines,
|
|
366
|
+
err_lines,
|
|
367
|
+
} satisfies WorkerOutput);
|
|
368
|
+
} catch (e) {
|
|
369
|
+
return Response.json(
|
|
370
|
+
{
|
|
371
|
+
is_error: true,
|
|
372
|
+
result: parseError(code, e),
|
|
373
|
+
log_lines,
|
|
374
|
+
err_lines,
|
|
375
|
+
} satisfies WorkerOutput,
|
|
376
|
+
{ status: 400, statusText: 'Code execution error' },
|
|
377
|
+
);
|
|
378
|
+
} finally {
|
|
379
|
+
globalThis.console = originalConsole;
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
export default { fetch };
|