@agent-native/actions 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -2
- package/dist/chunk-4X4LYULO.js +108 -0
- package/dist/chunk-4X4LYULO.js.map +1 -0
- package/dist/chunk-D66CG6AI.js +265 -0
- package/dist/chunk-D66CG6AI.js.map +1 -0
- package/dist/chunk-KWA4U6DI.js +273 -0
- package/dist/chunk-KWA4U6DI.js.map +1 -0
- package/dist/chunk-SXOEFWAM.js +147 -0
- package/dist/chunk-SXOEFWAM.js.map +1 -0
- package/dist/cli.js +1765 -0
- package/dist/cli.js.map +1 -0
- package/dist/client-C87WZhlZ.d.ts +223 -0
- package/dist/client.d.ts +70 -0
- package/dist/client.js +110 -0
- package/dist/client.js.map +1 -0
- package/dist/contract.d.ts +251 -0
- package/dist/contract.js +372 -0
- package/dist/contract.js.map +1 -0
- package/dist/index.d.ts +251 -0
- package/dist/index.js +704 -0
- package/dist/index.js.map +1 -0
- package/dist/next-config.d.ts +16 -0
- package/dist/next-config.js +46 -0
- package/dist/next-config.js.map +1 -0
- package/dist/next-pages.d.ts +12 -0
- package/dist/next-pages.js +13 -0
- package/dist/next-pages.js.map +1 -0
- package/dist/next-server.d.ts +41 -0
- package/dist/next-server.js +96 -0
- package/dist/next-server.js.map +1 -0
- package/dist/next.d.ts +39 -0
- package/dist/next.js +68 -0
- package/dist/next.js.map +1 -0
- package/dist/nuxt.d.ts +17 -0
- package/dist/nuxt.js +22 -0
- package/dist/nuxt.js.map +1 -0
- package/dist/react.d.ts +50 -0
- package/dist/react.js +194 -0
- package/dist/react.js.map +1 -0
- package/dist/registry-CIe_aYoE.d.ts +263 -0
- package/dist/solid.d.ts +39 -0
- package/dist/solid.js +229 -0
- package/dist/solid.js.map +1 -0
- package/dist/svelte-server.d.ts +23 -0
- package/dist/svelte-server.js +33 -0
- package/dist/svelte-server.js.map +1 -0
- package/dist/svelte.d.ts +53 -0
- package/dist/svelte.js +244 -0
- package/dist/svelte.js.map +1 -0
- package/dist/vite.d.ts +30 -0
- package/dist/vite.js +131 -0
- package/dist/vite.js.map +1 -0
- package/dist/vue-server.d.ts +20 -0
- package/dist/vue-server.js +26 -0
- package/dist/vue-server.js.map +1 -0
- package/dist/vue.d.ts +64 -0
- package/dist/vue.js +250 -0
- package/dist/vue.js.map +1 -0
- package/dist/webmcp.d.ts +19 -0
- package/dist/webmcp.js +36 -0
- package/dist/webmcp.js.map +1 -0
- package/package.json +172 -4
- package/skills/agent-native-actions/SKILL.md +76 -0
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ActionError,
|
|
3
|
+
ActionPostCommitError
|
|
4
|
+
} from "./chunk-4X4LYULO.js";
|
|
5
|
+
|
|
6
|
+
// src/schema.ts
|
|
7
|
+
function isPlainRecord(value) {
|
|
8
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9
|
+
}
|
|
10
|
+
function formatIssuePath(path) {
|
|
11
|
+
if (!path || path.length === 0) return "";
|
|
12
|
+
return path.map(
|
|
13
|
+
(segment) => typeof segment === "object" && "key" in segment ? String(segment.key) : String(segment)
|
|
14
|
+
).join(".");
|
|
15
|
+
}
|
|
16
|
+
async function validateInputSchema(schema, rawInput, actionName) {
|
|
17
|
+
const result = await schema["~standard"].validate(rawInput);
|
|
18
|
+
if (result.issues) {
|
|
19
|
+
const formatted = result.issues.map((issue) => {
|
|
20
|
+
const pathStr = formatIssuePath(issue.path);
|
|
21
|
+
return pathStr ? `${pathStr}: ${issue.message}` : issue.message;
|
|
22
|
+
});
|
|
23
|
+
throw new ActionError(
|
|
24
|
+
`Invalid input for "${actionName}": ${formatted.join("; ")}`,
|
|
25
|
+
{
|
|
26
|
+
statusCode: 400,
|
|
27
|
+
errorCode: "invalid_input",
|
|
28
|
+
details: {
|
|
29
|
+
issues: result.issues.map((issue) => ({
|
|
30
|
+
path: formatIssuePath(issue.path),
|
|
31
|
+
message: issue.message
|
|
32
|
+
}))
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
return result.value;
|
|
38
|
+
}
|
|
39
|
+
async function validateOutputSchema(schema, rawOutput, actionName) {
|
|
40
|
+
const result = await schema["~standard"].validate(rawOutput);
|
|
41
|
+
if (result.issues) {
|
|
42
|
+
const formatted = result.issues.map((issue) => {
|
|
43
|
+
const pathStr = formatIssuePath(issue.path);
|
|
44
|
+
return pathStr ? `${pathStr}: ${issue.message}` : issue.message;
|
|
45
|
+
});
|
|
46
|
+
throw new ActionPostCommitError(
|
|
47
|
+
`Action "${actionName}" returned output that violated outputSchema: ${formatted.join("; ")}`,
|
|
48
|
+
void 0,
|
|
49
|
+
{
|
|
50
|
+
issues: result.issues.map((issue) => ({
|
|
51
|
+
path: formatIssuePath(issue.path),
|
|
52
|
+
message: issue.message
|
|
53
|
+
}))
|
|
54
|
+
}
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
return result.value;
|
|
58
|
+
}
|
|
59
|
+
function schemaToJsonSchema(schema, mode, explicitOverride) {
|
|
60
|
+
if (mode === "input" && explicitOverride) {
|
|
61
|
+
return structuredClone(explicitOverride);
|
|
62
|
+
}
|
|
63
|
+
if (!schema) {
|
|
64
|
+
return mode === "input" ? { type: "object", properties: {}, additionalProperties: false } : null;
|
|
65
|
+
}
|
|
66
|
+
const standard = schema["~standard"];
|
|
67
|
+
const converter = mode === "input" ? standard.jsonSchema?.input : standard.jsonSchema?.output;
|
|
68
|
+
if (typeof converter !== "function") {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
const converted = converter({ target: "draft-2020-12" });
|
|
72
|
+
if (!isPlainRecord(converted)) {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
const copy = structuredClone(converted);
|
|
76
|
+
delete copy["$schema"];
|
|
77
|
+
return copy;
|
|
78
|
+
}
|
|
79
|
+
function normalizeLlmToolInput(rawInput, jsonSchema) {
|
|
80
|
+
if (!isPlainRecord(rawInput) || !jsonSchema) {
|
|
81
|
+
return rawInput;
|
|
82
|
+
}
|
|
83
|
+
const properties = isPlainRecord(jsonSchema["properties"]) ? jsonSchema["properties"] : null;
|
|
84
|
+
if (!properties) {
|
|
85
|
+
return rawInput;
|
|
86
|
+
}
|
|
87
|
+
const required = new Set(
|
|
88
|
+
Array.isArray(jsonSchema["required"]) ? jsonSchema["required"].filter(
|
|
89
|
+
(item) => typeof item === "string"
|
|
90
|
+
) : []
|
|
91
|
+
);
|
|
92
|
+
const out = {};
|
|
93
|
+
for (const [key, value] of Object.entries(rawInput)) {
|
|
94
|
+
const fieldSchema = isPlainRecord(properties[key]) ? properties[key] : null;
|
|
95
|
+
if (!fieldSchema) {
|
|
96
|
+
out[key] = value;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
const fieldType = fieldSchema["type"];
|
|
100
|
+
const allowsNull = fieldType === "null" || Array.isArray(fieldType) && fieldType.includes("null") || Array.isArray(fieldSchema["anyOf"]) && fieldSchema["anyOf"].some(
|
|
101
|
+
(branch) => isPlainRecord(branch) && branch["type"] === "null"
|
|
102
|
+
);
|
|
103
|
+
if (value === null && !required.has(key) && !allowsNull) {
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (typeof value === "string" && (fieldType === "object" || fieldType === "array")) {
|
|
107
|
+
const trimmed = value.trim();
|
|
108
|
+
if (fieldType === "object" && trimmed.startsWith("{") && trimmed.endsWith("}") || fieldType === "array" && trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
|
109
|
+
try {
|
|
110
|
+
const parsed = JSON.parse(trimmed);
|
|
111
|
+
out[key] = fieldType === "object" ? normalizeLlmToolInput(parsed, fieldSchema) : parsed;
|
|
112
|
+
continue;
|
|
113
|
+
} catch {
|
|
114
|
+
out[key] = value;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (isPlainRecord(value) && fieldType === "object") {
|
|
120
|
+
out[key] = normalizeLlmToolInput(value, fieldSchema);
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
out[key] = value;
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/action.ts
|
|
129
|
+
function defineAction(definition) {
|
|
130
|
+
return {
|
|
131
|
+
...definition,
|
|
132
|
+
__agentNativeAction: true
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
function createActionBuilder() {
|
|
136
|
+
return function defineTypedAction(definition) {
|
|
137
|
+
return {
|
|
138
|
+
...definition,
|
|
139
|
+
__agentNativeAction: true
|
|
140
|
+
};
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function isDefinedAction(value) {
|
|
144
|
+
return typeof value === "object" && value !== null && "__agentNativeAction" in value && value.__agentNativeAction === true && typeof value.run === "function";
|
|
145
|
+
}
|
|
146
|
+
function resolveActionHttpMethod(action) {
|
|
147
|
+
if (action.http === false) return null;
|
|
148
|
+
if (action.http && action.http.method) return action.http.method;
|
|
149
|
+
return "POST";
|
|
150
|
+
}
|
|
151
|
+
function resolveActionHttpPath(name, action) {
|
|
152
|
+
if (action.http === false) return null;
|
|
153
|
+
if (action.http && action.http.path) {
|
|
154
|
+
return action.http.path.replace(/^\/+/, "");
|
|
155
|
+
}
|
|
156
|
+
return name;
|
|
157
|
+
}
|
|
158
|
+
function isActionReadOnly(action) {
|
|
159
|
+
if (typeof action.readOnly === "boolean") return action.readOnly;
|
|
160
|
+
return resolveActionHttpMethod(action) === "GET";
|
|
161
|
+
}
|
|
162
|
+
async function executeAction(options) {
|
|
163
|
+
const {
|
|
164
|
+
name,
|
|
165
|
+
action,
|
|
166
|
+
ctx,
|
|
167
|
+
caller,
|
|
168
|
+
approvalToken,
|
|
169
|
+
approved,
|
|
170
|
+
verifyApproval,
|
|
171
|
+
middleware = [],
|
|
172
|
+
onAfterMutate,
|
|
173
|
+
onError
|
|
174
|
+
} = options;
|
|
175
|
+
let committed = false;
|
|
176
|
+
try {
|
|
177
|
+
let candidateInput = options.rawInput;
|
|
178
|
+
if (caller === "mcp" || caller === "agent") {
|
|
179
|
+
const jsonSchema = schemaToJsonSchema(
|
|
180
|
+
action.schema,
|
|
181
|
+
"input",
|
|
182
|
+
action.toolSchema
|
|
183
|
+
);
|
|
184
|
+
candidateInput = normalizeLlmToolInput(candidateInput, jsonSchema);
|
|
185
|
+
}
|
|
186
|
+
const inputToValidate = candidateInput ?? {};
|
|
187
|
+
const validatedInput = action.schema ? await validateInputSchema(action.schema, inputToValidate, name) : inputToValidate;
|
|
188
|
+
if (action.authorize) {
|
|
189
|
+
const allowed = await action.authorize(validatedInput, ctx);
|
|
190
|
+
if (!allowed) {
|
|
191
|
+
throw new ActionError(`Not authorized to run action "${name}".`, {
|
|
192
|
+
statusCode: 403,
|
|
193
|
+
errorCode: "forbidden"
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (action.needsApproval !== void 0) {
|
|
198
|
+
const required = typeof action.needsApproval === "function" ? await action.needsApproval(validatedInput, ctx) : Boolean(action.needsApproval);
|
|
199
|
+
if (required) {
|
|
200
|
+
let isApproved = false;
|
|
201
|
+
if (verifyApproval) {
|
|
202
|
+
isApproved = Boolean(
|
|
203
|
+
await verifyApproval({
|
|
204
|
+
actionName: name,
|
|
205
|
+
input: validatedInput,
|
|
206
|
+
ctx,
|
|
207
|
+
caller,
|
|
208
|
+
...approvalToken !== void 0 ? { approvalToken } : {}
|
|
209
|
+
})
|
|
210
|
+
);
|
|
211
|
+
} else if (approved === true) {
|
|
212
|
+
isApproved = true;
|
|
213
|
+
}
|
|
214
|
+
if (!isApproved) {
|
|
215
|
+
throw new ActionError(
|
|
216
|
+
`Action "${name}" requires explicit human approval before executing.`,
|
|
217
|
+
{
|
|
218
|
+
statusCode: 403,
|
|
219
|
+
errorCode: "approval_required",
|
|
220
|
+
details: {
|
|
221
|
+
action: name,
|
|
222
|
+
input: validatedInput
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const runCore = async () => action.run(validatedInput, ctx);
|
|
230
|
+
const dispatch = middleware.reduceRight(
|
|
231
|
+
(next, mw) => () => mw({ name, input: validatedInput, ctx, caller, next }),
|
|
232
|
+
runCore
|
|
233
|
+
);
|
|
234
|
+
const rawResult = await dispatch();
|
|
235
|
+
committed = true;
|
|
236
|
+
const validatedResult = action.outputSchema ? await validateOutputSchema(action.outputSchema, rawResult, name) : rawResult;
|
|
237
|
+
if (onAfterMutate && !isActionReadOnly(action)) {
|
|
238
|
+
try {
|
|
239
|
+
await onAfterMutate({
|
|
240
|
+
name,
|
|
241
|
+
input: validatedInput,
|
|
242
|
+
result: validatedResult,
|
|
243
|
+
ctx,
|
|
244
|
+
caller
|
|
245
|
+
});
|
|
246
|
+
} catch (hookError) {
|
|
247
|
+
throw new ActionPostCommitError(
|
|
248
|
+
`Action "${name}" succeeded, but post-mutation hook failed.`,
|
|
249
|
+
hookError
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return validatedResult;
|
|
254
|
+
} catch (error) {
|
|
255
|
+
onError?.(error, { name, caller, ctx, committed });
|
|
256
|
+
throw error;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export {
|
|
261
|
+
validateInputSchema,
|
|
262
|
+
validateOutputSchema,
|
|
263
|
+
schemaToJsonSchema,
|
|
264
|
+
normalizeLlmToolInput,
|
|
265
|
+
defineAction,
|
|
266
|
+
createActionBuilder,
|
|
267
|
+
isDefinedAction,
|
|
268
|
+
resolveActionHttpMethod,
|
|
269
|
+
resolveActionHttpPath,
|
|
270
|
+
isActionReadOnly,
|
|
271
|
+
executeAction
|
|
272
|
+
};
|
|
273
|
+
//# sourceMappingURL=chunk-KWA4U6DI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/schema.ts","../src/action.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nimport { ActionError, ActionPostCommitError } from \"./errors.js\";\nimport type { JsonSchemaObject } from \"./types.js\";\n\ninterface StandardJsonSchemaCapability {\n jsonSchema?: {\n input?: (options: { target: string }) => unknown;\n output?: (options: { target: string }) => unknown;\n };\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction formatIssuePath(\n path: ReadonlyArray<PropertyKey | StandardSchemaV1.PathSegment> | undefined,\n): string {\n if (!path || path.length === 0) return \"\";\n return path\n .map((segment) =>\n typeof segment === \"object\" && \"key\" in segment\n ? String(segment.key)\n : String(segment),\n )\n .join(\".\");\n}\n\nexport async function validateInputSchema<TSchema extends StandardSchemaV1>(\n schema: TSchema,\n rawInput: unknown,\n actionName: string,\n): Promise<StandardSchemaV1.InferOutput<TSchema>> {\n const result = await schema[\"~standard\"].validate(rawInput);\n if (result.issues) {\n const formatted = result.issues.map((issue) => {\n const pathStr = formatIssuePath(issue.path);\n return pathStr ? `${pathStr}: ${issue.message}` : issue.message;\n });\n throw new ActionError(\n `Invalid input for \"${actionName}\": ${formatted.join(\"; \")}`,\n {\n statusCode: 400,\n errorCode: \"invalid_input\",\n details: {\n issues: result.issues.map((issue) => ({\n path: formatIssuePath(issue.path),\n message: issue.message,\n })),\n },\n },\n );\n }\n return result.value;\n}\n\nexport async function validateOutputSchema<TSchema extends StandardSchemaV1>(\n schema: TSchema,\n rawOutput: unknown,\n actionName: string,\n): Promise<StandardSchemaV1.InferOutput<TSchema>> {\n const result = await schema[\"~standard\"].validate(rawOutput);\n if (result.issues) {\n const formatted = result.issues.map((issue) => {\n const pathStr = formatIssuePath(issue.path);\n return pathStr ? `${pathStr}: ${issue.message}` : issue.message;\n });\n throw new ActionPostCommitError(\n `Action \"${actionName}\" returned output that violated outputSchema: ${formatted.join(\"; \")}`,\n undefined,\n {\n issues: result.issues.map((issue) => ({\n path: formatIssuePath(issue.path),\n message: issue.message,\n })),\n },\n );\n }\n return result.value;\n}\n\nexport function schemaToJsonSchema(\n schema: StandardSchemaV1 | undefined,\n mode: \"input\" | \"output\",\n explicitOverride?: JsonSchemaObject,\n): JsonSchemaObject | null {\n if (mode === \"input\" && explicitOverride) {\n return structuredClone(explicitOverride);\n }\n if (!schema) {\n return mode === \"input\"\n ? { type: \"object\", properties: {}, additionalProperties: false }\n : null;\n }\n\n const standard = schema[\"~standard\"] as StandardSchemaV1.Props &\n StandardJsonSchemaCapability;\n const converter =\n mode === \"input\" ? standard.jsonSchema?.input : standard.jsonSchema?.output;\n\n if (typeof converter !== \"function\") {\n return null;\n }\n\n const converted = converter({ target: \"draft-2020-12\" });\n if (!isPlainRecord(converted)) {\n return null;\n }\n const copy = structuredClone(converted);\n delete copy[\"$schema\"];\n return copy;\n}\n\n/**\n * Normalize common LLM strict-mode quirks where optional fields are sent as\n * `null` or stringified JSON objects/arrays when the JSON Schema does not\n * expect those types.\n */\nexport function normalizeLlmToolInput(\n rawInput: unknown,\n jsonSchema: JsonSchemaObject | null,\n): unknown {\n if (!isPlainRecord(rawInput) || !jsonSchema) {\n return rawInput;\n }\n const properties = isPlainRecord(jsonSchema[\"properties\"])\n ? jsonSchema[\"properties\"]\n : null;\n if (!properties) {\n return rawInput;\n }\n const required = new Set(\n Array.isArray(jsonSchema[\"required\"])\n ? jsonSchema[\"required\"].filter(\n (item): item is string => typeof item === \"string\",\n )\n : [],\n );\n\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(rawInput)) {\n const fieldSchema = isPlainRecord(properties[key]) ? properties[key] : null;\n if (!fieldSchema) {\n out[key] = value;\n continue;\n }\n\n const fieldType = fieldSchema[\"type\"];\n const allowsNull =\n fieldType === \"null\" ||\n (Array.isArray(fieldType) && fieldType.includes(\"null\")) ||\n (Array.isArray(fieldSchema[\"anyOf\"]) &&\n fieldSchema[\"anyOf\"].some(\n (branch) => isPlainRecord(branch) && branch[\"type\"] === \"null\",\n ));\n\n if (value === null && !required.has(key) && !allowsNull) {\n continue;\n }\n\n if (\n typeof value === \"string\" &&\n (fieldType === \"object\" || fieldType === \"array\")\n ) {\n const trimmed = value.trim();\n if (\n (fieldType === \"object\" &&\n trimmed.startsWith(\"{\") &&\n trimmed.endsWith(\"}\")) ||\n (fieldType === \"array\" &&\n trimmed.startsWith(\"[\") &&\n trimmed.endsWith(\"]\"))\n ) {\n try {\n const parsed: unknown = JSON.parse(trimmed);\n out[key] =\n fieldType === \"object\"\n ? normalizeLlmToolInput(parsed, fieldSchema)\n : parsed;\n continue;\n } catch {\n out[key] = value;\n continue;\n }\n }\n }\n\n if (isPlainRecord(value) && fieldType === \"object\") {\n out[key] = normalizeLlmToolInput(value, fieldSchema);\n continue;\n }\n\n out[key] = value;\n }\n return out;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nimport { ActionError, ActionPostCommitError } from \"./errors.js\";\nimport {\n normalizeLlmToolInput,\n schemaToJsonSchema,\n validateInputSchema,\n validateOutputSchema,\n} from \"./schema.js\";\nimport type {\n ActionAfterMutateInfo,\n ActionApprovalVerifier,\n ActionCaller,\n ActionDefinition,\n ActionErrorInfo,\n ActionHttpMethod,\n ActionMapEntry,\n ActionMiddleware,\n DefaultActionContext,\n DefinedAction,\n} from \"./types.js\";\n\nexport function defineAction<\n TSchema extends StandardSchemaV1 | undefined = undefined,\n TOutputSchema extends StandardSchemaV1 | undefined = undefined,\n TReturn = unknown,\n TCtx = DefaultActionContext,\n>(\n definition: ActionDefinition<TSchema, TOutputSchema, TReturn, TCtx>,\n): DefinedAction<TSchema, TOutputSchema, TReturn, TCtx> {\n return {\n ...definition,\n __agentNativeAction: true,\n };\n}\n\n/**\n * Create an app-local `defineAction` helper pre-bound to your app's context type\n * (e.g. `{ user: SessionUser | null; orgId: string | null }`), so `ctx` is\n * strongly typed inside every `actions/*.ts` file.\n */\nexport function createActionBuilder<TCtx>() {\n return function defineTypedAction<\n TSchema extends StandardSchemaV1 | undefined = undefined,\n TOutputSchema extends StandardSchemaV1 | undefined = undefined,\n TReturn = unknown,\n >(\n definition: ActionDefinition<TSchema, TOutputSchema, TReturn, TCtx>,\n ): DefinedAction<TSchema, TOutputSchema, TReturn, TCtx> {\n return {\n ...definition,\n __agentNativeAction: true,\n };\n };\n}\n\nexport function isDefinedAction(value: unknown): value is DefinedAction {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"__agentNativeAction\" in value &&\n (value as { __agentNativeAction?: unknown }).__agentNativeAction === true &&\n typeof (value as { run?: unknown }).run === \"function\"\n );\n}\n\nexport function resolveActionHttpMethod(\n action: Pick<ActionMapEntry<never>, \"http\">,\n): ActionHttpMethod | null {\n if (action.http === false) return null;\n if (action.http && action.http.method) return action.http.method;\n return \"POST\";\n}\n\nexport function resolveActionHttpPath(\n name: string,\n action: Pick<ActionMapEntry<never>, \"http\">,\n): string | null {\n if (action.http === false) return null;\n if (action.http && action.http.path) {\n return action.http.path.replace(/^\\/+/, \"\");\n }\n return name;\n}\n\nexport function isActionReadOnly(\n action: Pick<ActionMapEntry<never>, \"readOnly\" | \"http\">,\n): boolean {\n if (typeof action.readOnly === \"boolean\") return action.readOnly;\n return resolveActionHttpMethod(action) === \"GET\";\n}\n\nexport interface ExecuteActionOptions<TCtx> {\n name: string;\n action: ActionMapEntry<TCtx>;\n rawInput: unknown;\n ctx: TCtx;\n caller: ActionCaller;\n approvalToken?: string;\n approved?: boolean;\n verifyApproval?: ActionApprovalVerifier<TCtx>;\n middleware?: readonly ActionMiddleware<TCtx>[];\n onAfterMutate?: (info: ActionAfterMutateInfo<TCtx>) => void | Promise<void>;\n onError?: (error: unknown, info: ActionErrorInfo<TCtx>) => void;\n}\n\n/**\n * Single checked execution pipeline shared by HTTP, direct `.call()`, CLI,\n * MCP, and AI SDK tools:\n *\n * 1. Normalize LLM input quirks (for `mcp` and `agent` callers only)\n * 2. Validate input once through Standard Schema\n * 3. Run `authorize(input, ctx)` -> 403 `forbidden` before approval or `run`\n * 4. Evaluate `needsApproval(input, ctx)` -> 403 `approval_required` unless verified\n * 5. Run middleware chain + `run(input, ctx)`\n * 6. Validate `outputSchema` and fire `onAfterMutate` (failures raise `ActionPostCommitError`)\n */\nexport async function executeAction<TCtx>(\n options: ExecuteActionOptions<TCtx>,\n): Promise<unknown> {\n const {\n name,\n action,\n ctx,\n caller,\n approvalToken,\n approved,\n verifyApproval,\n middleware = [],\n onAfterMutate,\n onError,\n } = options;\n\n let committed = false;\n\n try {\n let candidateInput = options.rawInput;\n if (caller === \"mcp\" || caller === \"agent\") {\n const jsonSchema = schemaToJsonSchema(\n action.schema,\n \"input\",\n action.toolSchema,\n );\n candidateInput = normalizeLlmToolInput(candidateInput, jsonSchema);\n }\n\n const inputToValidate = candidateInput ?? {};\n const validatedInput = action.schema\n ? await validateInputSchema(action.schema, inputToValidate, name)\n : inputToValidate;\n\n if (action.authorize) {\n const allowed = await action.authorize(validatedInput as never, ctx);\n if (!allowed) {\n throw new ActionError(`Not authorized to run action \"${name}\".`, {\n statusCode: 403,\n errorCode: \"forbidden\",\n });\n }\n }\n\n if (action.needsApproval !== undefined) {\n const required =\n typeof action.needsApproval === \"function\"\n ? await action.needsApproval(validatedInput as never, ctx)\n : Boolean(action.needsApproval);\n\n if (required) {\n let isApproved = false;\n if (verifyApproval) {\n isApproved = Boolean(\n await verifyApproval({\n actionName: name,\n input: validatedInput,\n ctx,\n caller,\n ...(approvalToken !== undefined ? { approvalToken } : {}),\n }),\n );\n } else if (approved === true) {\n isApproved = true;\n }\n\n if (!isApproved) {\n throw new ActionError(\n `Action \"${name}\" requires explicit human approval before executing.`,\n {\n statusCode: 403,\n errorCode: \"approval_required\",\n details: {\n action: name,\n input: validatedInput,\n },\n },\n );\n }\n }\n }\n\n const runCore = async (): Promise<unknown> =>\n action.run(validatedInput as never, ctx);\n\n const dispatch = middleware.reduceRight<() => Promise<unknown>>(\n (next, mw) => () =>\n mw({ name, input: validatedInput, ctx, caller, next }),\n runCore,\n );\n\n const rawResult = await dispatch();\n committed = true;\n\n const validatedResult = action.outputSchema\n ? await validateOutputSchema(action.outputSchema, rawResult, name)\n : rawResult;\n\n if (onAfterMutate && !isActionReadOnly(action)) {\n try {\n await onAfterMutate({\n name,\n input: validatedInput,\n result: validatedResult,\n ctx,\n caller,\n });\n } catch (hookError) {\n throw new ActionPostCommitError(\n `Action \"${name}\" succeeded, but post-mutation hook failed.`,\n hookError,\n );\n }\n }\n\n return validatedResult;\n } catch (error) {\n onError?.(error, { name, caller, ctx, committed });\n throw error;\n }\n}\n"],"mappings":";;;;;;AAYA,SAAS,cAAc,OAAkD;AACvE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,gBACP,MACQ;AACR,MAAI,CAAC,QAAQ,KAAK,WAAW,EAAG,QAAO;AACvC,SAAO,KACJ;AAAA,IAAI,CAAC,YACJ,OAAO,YAAY,YAAY,SAAS,UACpC,OAAO,QAAQ,GAAG,IAClB,OAAO,OAAO;AAAA,EACpB,EACC,KAAK,GAAG;AACb;AAEA,eAAsB,oBACpB,QACA,UACA,YACgD;AAChD,QAAM,SAAS,MAAM,OAAO,WAAW,EAAE,SAAS,QAAQ;AAC1D,MAAI,OAAO,QAAQ;AACjB,UAAM,YAAY,OAAO,OAAO,IAAI,CAAC,UAAU;AAC7C,YAAM,UAAU,gBAAgB,MAAM,IAAI;AAC1C,aAAO,UAAU,GAAG,OAAO,KAAK,MAAM,OAAO,KAAK,MAAM;AAAA,IAC1D,CAAC;AACD,UAAM,IAAI;AAAA,MACR,sBAAsB,UAAU,MAAM,UAAU,KAAK,IAAI,CAAC;AAAA,MAC1D;AAAA,QACE,YAAY;AAAA,QACZ,WAAW;AAAA,QACX,SAAS;AAAA,UACP,QAAQ,OAAO,OAAO,IAAI,CAAC,WAAW;AAAA,YACpC,MAAM,gBAAgB,MAAM,IAAI;A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B,GAAG;AAEzC,UAAM,WAAW,WAAW;AAAA,MAC1B,CAAC,MAAM,OAAO,MACZ,GAAG,EAAE,MAAM,OAAO,gBAAgB,KAAK,QAAQ,KAAK,CAAC;AAAA,MACvD;AAAA,IACF;AAEA,UAAM,YAAY,MAAM,SAAS;AACjC,gBAAY;AAEZ,UAAM,kBAAkB,OAAO,eAC3B,MAAM,qBAAqB,OAAO,cAAc,WAAW,IAAI,IAC/D;AAEJ,QAAI,iBAAiB,CAAC,iBAAiB,MAAM,GAAG;AAC9C,UAAI;AACF,cAAM,cAAc;AAAA,UAClB;AAAA,UACA,OAAO;AAAA,UACP,QAAQ;AAAA,UACR;AAAA,UACA;AAAA,QACF,CAAC;AAAA,MACH,SAAS,WAAW;AAClB,cAAM,IAAI;AAAA,UACR,WAAW,IAAI;AAAA,UACf;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,cAAU,OAAO,EAAE,MAAM,QAAQ,KAAK,UAAU,CAAC;AACjD,UAAM;AAAA,EACR;AACF;","names":[]}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// src/codegen.ts
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
var SKIP_FILES = /* @__PURE__ */ new Set([
|
|
5
|
+
"context",
|
|
6
|
+
"helpers",
|
|
7
|
+
"index",
|
|
8
|
+
"registry",
|
|
9
|
+
"run",
|
|
10
|
+
"types",
|
|
11
|
+
"utils"
|
|
12
|
+
]);
|
|
13
|
+
var ACTION_EXTENSIONS = /* @__PURE__ */ new Set([".ts", ".tsx", ".mts", ".js", ".mjs"]);
|
|
14
|
+
function toValidIdentifier(name, index) {
|
|
15
|
+
const cleaned = name.replace(/[^A-Za-z0-9_$]/g, "_");
|
|
16
|
+
return `action_${index}_${cleaned}`;
|
|
17
|
+
}
|
|
18
|
+
function toPosixRelative(fromDir, targetFile) {
|
|
19
|
+
const withoutExt = targetFile.replace(/\.(?:tsx?|mts|mjs|js)$/, "");
|
|
20
|
+
const rel = path.relative(fromDir, withoutExt).split(path.sep).join("/");
|
|
21
|
+
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
22
|
+
}
|
|
23
|
+
function scanActionsDirectory(projectRoot, options = {}) {
|
|
24
|
+
const actionsDir = path.resolve(projectRoot, options.actionsDir ?? "actions");
|
|
25
|
+
const generatedDir = path.resolve(
|
|
26
|
+
projectRoot,
|
|
27
|
+
options.generatedDir ?? ".generated"
|
|
28
|
+
);
|
|
29
|
+
if (!fs.existsSync(actionsDir)) {
|
|
30
|
+
return { actions: [], contextFile: null };
|
|
31
|
+
}
|
|
32
|
+
let contextFile = null;
|
|
33
|
+
const entries = fs.readdirSync(actionsDir, { withFileTypes: true }).filter((entry) => entry.isFile()).sort((a, b) => a.name.localeCompare(b.name));
|
|
34
|
+
const seenNames = /* @__PURE__ */ new Map();
|
|
35
|
+
const actions = [];
|
|
36
|
+
for (const entry of entries) {
|
|
37
|
+
if (entry.name.endsWith(".d.ts") || entry.name.includes(".spec.") || entry.name.includes(".test.") || entry.name.startsWith("_") || entry.name.startsWith(".")) {
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
const ext = path.extname(entry.name);
|
|
41
|
+
if (!ACTION_EXTENSIONS.has(ext)) continue;
|
|
42
|
+
const baseName = entry.name.slice(0, -ext.length);
|
|
43
|
+
const fullPath = path.join(actionsDir, entry.name);
|
|
44
|
+
if (baseName === "context") {
|
|
45
|
+
contextFile = fullPath;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (SKIP_FILES.has(baseName)) continue;
|
|
49
|
+
const existing = seenNames.get(baseName);
|
|
50
|
+
if (existing) {
|
|
51
|
+
throw new Error(
|
|
52
|
+
`Duplicate action name "${baseName}" found in ${existing} and ${fullPath}.`
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
seenNames.set(baseName, fullPath);
|
|
56
|
+
actions.push({
|
|
57
|
+
name: baseName,
|
|
58
|
+
filePath: fullPath,
|
|
59
|
+
relativeImport: toPosixRelative(generatedDir, fullPath),
|
|
60
|
+
identifier: toValidIdentifier(baseName, actions.length)
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
return { actions, contextFile };
|
|
64
|
+
}
|
|
65
|
+
function generateActionArtifacts(options) {
|
|
66
|
+
const generatedDir = path.resolve(
|
|
67
|
+
options.projectRoot,
|
|
68
|
+
options.generatedDir ?? ".generated"
|
|
69
|
+
);
|
|
70
|
+
const scan = scanActionsDirectory(options.projectRoot, {
|
|
71
|
+
...options.actionsDir ? { actionsDir: options.actionsDir } : {},
|
|
72
|
+
...options.generatedDir ? { generatedDir: options.generatedDir } : {}
|
|
73
|
+
});
|
|
74
|
+
fs.mkdirSync(generatedDir, { recursive: true });
|
|
75
|
+
const importLines = scan.actions.map(
|
|
76
|
+
(action) => `import ${action.identifier} from ${JSON.stringify(action.relativeImport)};`
|
|
77
|
+
);
|
|
78
|
+
const contextImport = scan.contextFile ? `import * as actionContextModule from ${JSON.stringify(toPosixRelative(generatedDir, scan.contextFile))};` : "";
|
|
79
|
+
const entriesLines = scan.actions.map(
|
|
80
|
+
(action) => ` ${JSON.stringify(action.name)}: ${action.identifier},`
|
|
81
|
+
);
|
|
82
|
+
const createContextLine = scan.contextFile ? ` ...(typeof actionContextModule.createContext === "function" ? { createContext: actionContextModule.createContext } : {}),` : "";
|
|
83
|
+
const manifestSource = [
|
|
84
|
+
"// Auto-generated by @agent-native/actions. Do not edit manually.",
|
|
85
|
+
'import { createActions } from "@agent-native/actions";',
|
|
86
|
+
...importLines,
|
|
87
|
+
...contextImport ? [contextImport] : [],
|
|
88
|
+
"",
|
|
89
|
+
"export const actions = createActions({",
|
|
90
|
+
" actions: {",
|
|
91
|
+
...entriesLines,
|
|
92
|
+
" },",
|
|
93
|
+
...createContextLine ? [createContextLine] : [],
|
|
94
|
+
"});",
|
|
95
|
+
"",
|
|
96
|
+
"export type AppActions = typeof actions;",
|
|
97
|
+
""
|
|
98
|
+
].join("\n");
|
|
99
|
+
const typeImportLines = scan.actions.map(
|
|
100
|
+
(action) => ` ${JSON.stringify(action.name)}: typeof import(${JSON.stringify(action.relativeImport)}).default;`
|
|
101
|
+
);
|
|
102
|
+
const typesSource = [
|
|
103
|
+
"// Auto-generated by @agent-native/actions. Do not edit manually.",
|
|
104
|
+
'import type { InferActionInputFromDef, InferActionReturn } from "@agent-native/actions";',
|
|
105
|
+
"",
|
|
106
|
+
"interface GeneratedActionDefinitions {",
|
|
107
|
+
...typeImportLines,
|
|
108
|
+
"}",
|
|
109
|
+
"",
|
|
110
|
+
'declare module "@agent-native/actions/client" {',
|
|
111
|
+
" interface ActionTypeRegistry {",
|
|
112
|
+
" actions: {",
|
|
113
|
+
" [K in keyof GeneratedActionDefinitions]: {",
|
|
114
|
+
" input: InferActionInputFromDef<GeneratedActionDefinitions[K]>;",
|
|
115
|
+
" output: InferActionReturn<GeneratedActionDefinitions[K]>;",
|
|
116
|
+
" };",
|
|
117
|
+
" };",
|
|
118
|
+
" }",
|
|
119
|
+
"}",
|
|
120
|
+
"",
|
|
121
|
+
"export {};",
|
|
122
|
+
""
|
|
123
|
+
].join("\n");
|
|
124
|
+
const manifestPath = path.join(generatedDir, "actions.ts");
|
|
125
|
+
const typesPath = path.join(generatedDir, "action-types.d.ts");
|
|
126
|
+
writeFileIfChanged(manifestPath, manifestSource);
|
|
127
|
+
writeFileIfChanged(typesPath, typesSource);
|
|
128
|
+
return {
|
|
129
|
+
manifestPath,
|
|
130
|
+
typesPath,
|
|
131
|
+
actionCount: scan.actions.length,
|
|
132
|
+
hasContextFile: Boolean(scan.contextFile)
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
function writeFileIfChanged(filePath, content) {
|
|
136
|
+
if (fs.existsSync(filePath)) {
|
|
137
|
+
const existing = fs.readFileSync(filePath, "utf8");
|
|
138
|
+
if (existing === content) return;
|
|
139
|
+
}
|
|
140
|
+
fs.writeFileSync(filePath, content, "utf8");
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export {
|
|
144
|
+
scanActionsDirectory,
|
|
145
|
+
generateActionArtifacts
|
|
146
|
+
};
|
|
147
|
+
//# sourceMappingURL=chunk-SXOEFWAM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/codegen.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\nconst SKIP_FILES = new Set([\n \"context\",\n \"helpers\",\n \"index\",\n \"registry\",\n \"run\",\n \"types\",\n \"utils\",\n]);\n\nconst ACTION_EXTENSIONS = new Set([\".ts\", \".tsx\", \".mts\", \".js\", \".mjs\"]);\n\nexport interface ScannedActionFile {\n name: string;\n filePath: string;\n relativeImport: string;\n identifier: string;\n}\n\nexport interface ScanActionsResult {\n actions: ScannedActionFile[];\n contextFile: string | null;\n}\n\nfunction toValidIdentifier(name: string, index: number): string {\n const cleaned = name.replace(/[^A-Za-z0-9_$]/g, \"_\");\n return `action_${index}_${cleaned}`;\n}\n\nfunction toPosixRelative(fromDir: string, targetFile: string): string {\n const withoutExt = targetFile.replace(/\\.(?:tsx?|mts|mjs|js)$/, \"\");\n const rel = path.relative(fromDir, withoutExt).split(path.sep).join(\"/\");\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\nexport function scanActionsDirectory(\n projectRoot: string,\n options: { actionsDir?: string; generatedDir?: string } = {},\n): ScanActionsResult {\n const actionsDir = path.resolve(projectRoot, options.actionsDir ?? \"actions\");\n const generatedDir = path.resolve(\n projectRoot,\n options.generatedDir ?? \".generated\",\n );\n\n if (!fs.existsSync(actionsDir)) {\n return { actions: [], contextFile: null };\n }\n\n let contextFile: string | null = null;\n const entries = fs\n .readdirSync(actionsDir, { withFileTypes: true })\n .filter((entry) => entry.isFile())\n .sort((a, b) => a.name.localeCompare(b.name));\n\n const seenNames = new Map<string, string>();\n const actions: ScannedActionFile[] = [];\n\n for (const entry of entries) {\n if (\n entry.name.endsWith(\".d.ts\") ||\n entry.name.includes(\".spec.\") ||\n entry.name.includes(\".test.\") ||\n entry.name.startsWith(\"_\") ||\n entry.name.startsWith(\".\")\n ) {\n continue;\n }\n\n const ext = path.extname(entry.name);\n if (!ACTION_EXTENSIONS.has(ext)) continue;\n\n const baseName = entry.name.slice(0, -ext.length);\n const fullPath = path.join(actionsDir, entry.name);\n\n if (baseName === \"context\") {\n contextFile = fullPath;\n continue;\n }\n\n if (SKIP_FILES.has(baseName)) continue;\n\n const existing = seenNames.get(baseName);\n if (existing) {\n throw new Error(\n `Duplicate action name \"${baseName}\" found in ${existing} and ${fullPath}.`,\n );\n }\n seenNames.set(baseName, fullPath);\n\n actions.push({\n name: baseName,\n filePath: fullPath,\n relativeImport: toPosixRelative(generatedDir, fullPath),\n identifier: toValidIdentifier(baseName, actions.length),\n });\n }\n\n return { actions, contextFile };\n}\n\nexport interface GenerateArtifactsOptions {\n projectRoot: string;\n actionsDir?: string;\n generatedDir?: string;\n}\n\nexport interface GenerateArtifactsResult {\n manifestPath: string;\n typesPath: string;\n actionCount: number;\n hasContextFile: boolean;\n}\n\n/**\n * Deterministically generate:\n * - `.generated/actions.ts`: static ES-import registry (`export const actions`, `export type AppActions`)\n * - `.generated/action-types.d.ts`: module augmentation for `ActionTypeRegistry`\n */\nexport function generateActionArtifacts(\n options: GenerateArtifactsOptions,\n): GenerateArtifactsResult {\n const generatedDir = path.resolve(\n options.projectRoot,\n options.generatedDir ?? \".generated\",\n );\n const scan = scanActionsDirectory(options.projectRoot, {\n ...(options.actionsDir ? { actionsDir: options.actionsDir } : {}),\n ...(options.generatedDir ? { generatedDir: options.generatedDir } : {}),\n });\n\n fs.mkdirSync(generatedDir, { recursive: true });\n\n const importLines = scan.actions.map(\n (action) =>\n `import ${action.identifier} from ${JSON.stringify(action.relativeImport)};`,\n );\n\n const contextImport = scan.contextFile\n ? `import * as actionContextModule from ${JSON.stringify(toPosixRelative(generatedDir, scan.contextFile))};`\n : \"\";\n\n const entriesLines = scan.actions.map(\n (action) => ` ${JSON.stringify(action.name)}: ${action.identifier},`,\n );\n\n const createContextLine = scan.contextFile\n ? ` ...(typeof actionContextModule.createContext === \"function\" ? { createContext: actionContextModule.createContext } : {}),`\n : \"\";\n\n const manifestSource = [\n \"// Auto-generated by @agent-native/actions. Do not edit manually.\",\n 'import { createActions } from \"@agent-native/actions\";',\n ...importLines,\n ...(contextImport ? [contextImport] : []),\n \"\",\n \"export const actions = createActions({\",\n \" actions: {\",\n ...entriesLines,\n \" },\",\n ...(createContextLine ? [createContextLine] : []),\n \"});\",\n \"\",\n \"export type AppActions = typeof actions;\",\n \"\",\n ].join(\"\\n\");\n\n const typeImportLines = scan.actions.map(\n (action) =>\n ` ${JSON.stringify(action.name)}: typeof import(${JSON.stringify(action.relativeImport)}).default;`,\n );\n\n const typesSource = [\n \"// Auto-generated by @agent-native/actions. Do not edit manually.\",\n 'import type { InferActionInputFromDef, InferActionReturn } from \"@agent-native/actions\";',\n \"\",\n \"interface GeneratedActionDefinitions {\",\n ...typeImportLines,\n \"}\",\n \"\",\n 'declare module \"@agent-native/actions/client\" {',\n \" interface ActionTypeRegistry {\",\n \" actions: {\",\n \" [K in keyof GeneratedActionDefinitions]: {\",\n \" input: InferActionInputFromDef<GeneratedActionDefinitions[K]>;\",\n \" output: InferActionReturn<GeneratedActionDefinitions[K]>;\",\n \" };\",\n \" };\",\n \" }\",\n \"}\",\n \"\",\n \"export {};\",\n \"\",\n ].join(\"\\n\");\n\n const manifestPath = path.join(generatedDir, \"actions.ts\");\n const typesPath = path.join(generatedDir, \"action-types.d.ts\");\n\n writeFileIfChanged(manifestPath, manifestSource);\n writeFileIfChanged(typesPath, typesSource);\n\n return {\n manifestPath,\n typesPath,\n actionCount: scan.actions.length,\n hasContextFile: Boolean(scan.contextFile),\n };\n}\n\nfunction writeFileIfChanged(filePath: string, content: string): void {\n if (fs.existsSync(filePath)) {\n const existing = fs.readFileSync(filePath, \"utf8\");\n if (existing === content) return;\n }\n fs.writeFileSync(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