@wix/mcp 1.0.82 → 1.0.84
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 +3 -1
- package/build/bin-standalone.js +836 -2
- package/build/cjs/index.cjs +1468 -173
- package/build/cjs/toolkit.cjs +838 -2
- package/build/dts/bin.d.ts +1 -1
- package/build/dts/bin.js +13 -1
- package/build/dts/config/default-config.d.ts +1 -0
- package/build/dts/config/default-config.js +28 -1
- package/build/dts/config/param-descriptions.d.ts +21 -0
- package/build/dts/config/param-descriptions.js +21 -0
- package/build/dts/docs/get-to-know.js +17 -1
- package/build/dts/graphql/constants.d.ts +8 -0
- package/build/dts/graphql/constants.js +11 -0
- package/build/dts/graphql/index.d.ts +30 -0
- package/build/dts/graphql/index.js +259 -0
- package/build/dts/graphql/introspection.d.ts +106 -0
- package/build/dts/graphql/introspection.js +282 -0
- package/build/dts/graphql/search.d.ts +25 -0
- package/build/dts/graphql/search.js +277 -0
- package/build/dts/index.d.ts +2 -1
- package/build/dts/index.js +3 -1
- package/build/dts/site-widget-tools/suggested-domain-tool/index.js +21 -8
- package/build/dts/toolkit-entry.d.cts +12 -0
- package/build/dts/toolkit-entry.d.ts +12 -0
- package/build/dts/toolkit-entry.js +4 -0
- package/build/dts/toolkit.js +14 -0
- package/build/dts/wixel/wixel-session-tools.d.ts +43 -0
- package/build/dts/wixel/wixel-session-tools.js +701 -198
- package/build/esm/index.js +1460 -173
- package/build/esm/toolkit.js +833 -2
- package/package.json +2 -2
package/build/esm/toolkit.js
CHANGED
|
@@ -12909,6 +12909,32 @@ function buildToolDescriptions(includeReadme, includeImageUploadGuidance = true)
|
|
|
12909
12909
|
|
|
12910
12910
|
Call this when the user provides a specific template by \`metaSiteId\` or \`templateId\`. Use this only when the user gives a valid \`metaSiteId\` or \`templateId\` directly. To browse or choose a template first, call \`SearchSiteTemplates\`.
|
|
12911
12911
|
|
|
12912
|
+
`,
|
|
12913
|
+
SearchWixGraphQLOperations: dedent_default`
|
|
12914
|
+
Discover Wix GraphQL operations by intent (ranked keyword search over the root fields). Wix exposes ONE GraphQL schema over all Wix public APIs (Developer Preview) at POST https://www.wixapis.com/graphql/alpha: about 100 query roots and 580 mutation roots named <app><Service><Version><Verb/Entity>, e.g. \`storesProductsV3V3Products\`, \`crmContactsV4Contacts\`, \`crmContactsV4CreateContact\`, \`ecomOrdersV1SearchOrders\`.
|
|
12915
|
+
|
|
12916
|
+
GraphQL flow (3 steps, keep to it): SearchWixGraphQLOperations (find the operation) -> InspectWixGraphQLSchema (read its exact input and return types) -> ExecuteWixGraphQL (run it). Never write an operation or field name you did not see in one of these results.
|
|
12917
|
+
|
|
12918
|
+
When to prefer GraphQL over the REST tools:
|
|
12919
|
+
- Reading several related entities in ONE round-trip: related entities are resolved fields (product -> inventoryItems / collections, order -> fulfillments, booking -> contact), and independent root fields (products + contacts + orders) can share one request.
|
|
12920
|
+
- Picking exactly the fields you need, so responses stay small.
|
|
12921
|
+
- Answering "how many / list / show" questions: a query root plus \`pageInfo\` (\`hasNext\`, and \`total\` where the API provides it).
|
|
12922
|
+
Prefer the REST tools when a recipe or code example already gives you the exact REST call, for uploads/media, or when the GraphQL schema has no matching operation.
|
|
12923
|
+
|
|
12924
|
+
Conventions: query roots take \`queryInput\`; list roots (plural names) take \`queryInput: { query: { paging | cursorPaging, filter, sort } }\` and return \`{ items, pageInfo }\`; singular roots take the entity id. \`filter\`/\`sort\` are a JSON scalar in REST filter syntax (e.g. {"info.name.first": {"$eq": "Ada"}}) — pass them as variables. Mutations take \`input\`; a few read operations (search/list) are exposed as mutations, so search kind "all" unless you are sure.
|
|
12925
|
+
Results list \`kind name(arg: InputType): ReturnType\` plus a one-line description; pass the chosen name to InspectWixGraphQLSchema next.
|
|
12926
|
+
`,
|
|
12927
|
+
InspectWixGraphQLSchema: dedent_default`
|
|
12928
|
+
Read the exact Wix GraphQL schema for an operation and its types, as compact SDL with field descriptions. Pass \`operation\` (a root query/mutation name from SearchWixGraphQLOperations) to get its arguments, input type and return type expanded \`depth\` levels (default 2). Types that were referenced but not expanded are listed at the end — pass the ones you need in \`typeNames\` (optionally together with \`operation\`) instead of raising depth for everything.
|
|
12929
|
+
Use it before every ExecuteWixGraphQL call that introduces a new operation or new fields: read the INPUT type before writing a mutation or filter, and the RETURN type before writing the selection set. GraphQL rejects unknown fields and arguments, and every object-typed field needs its own selection set. \`JSON\` scalar fields (filter, sort, free-form data) accept any JSON — pass them as variables. Never guess a type or field name; if a validation error names a field, come back here.
|
|
12930
|
+
`,
|
|
12931
|
+
ExecuteWixGraphQL: dedent_default`
|
|
12932
|
+
Execute a GraphQL query or mutation against the Wix GraphQL API (POST https://www.wixapis.com/graphql/alpha) with the user's credentials. Authentication is injected — never add Authorization or site/account headers.
|
|
12933
|
+
Site targeting: site-level operations (anything that reads or writes inside a site: products, inventory, orders, contacts, bookings, CMS data, blog, members ...) require \`siteId\`; resolve it with GetSiteContext or ListWixSites first. Use \`scope: "account"\` only for account-level operations.
|
|
12934
|
+
Grounding: every root field, argument and selected field must come from SearchWixGraphQLOperations / InspectWixGraphQLSchema results in this conversation — never from memory. If the response says "Cannot query field" or "Unknown argument", re-inspect the schema and fix the name; do not retry with another guess.
|
|
12935
|
+
Compose: put independent reads in one document as several root fields, and use related-entity fields (e.g. \`inventoryItems\`, \`collections\`, \`fulfillments\`) instead of extra round-trips. Select only the fields you need; every object field needs a selection set. Variables: use them for \`JSON\` scalars (filter, sort) and plain scalars (String, Int, ID), declared in the document (e.g. \`query Q($f: JSON) { ... filter: $f ... }\`). Write mutation inputs and any object that contains an enum INLINE as GraphQL literals with enum values unquoted (e.g. \`input: { product: { name: "Mug", productType: PHYSICAL } }\`) — this endpoint fails with 503 when an enum value arrives inside an object-typed variable. For lists page with \`cursorPaging\` or \`paging\` exactly as the input type declares (never the other one), and request \`pageInfo { hasNext total }\`; \`total\` is only populated with offset \`paging\`, so for a cursor-paged list count by walking pages or use a count operation.
|
|
12936
|
+
Results: each root field fails independently — \`errors[].path\` names the failing field and \`errors[].extensions.message\` the cause (e.g. PERMISSION_DENIED); \`data\` still holds the fields that succeeded. Mutations return the created/updated entity — read the IDs from it and do not re-query to verify. Large results are truncated: narrow the selection or page size instead of re-running.
|
|
12937
|
+
Set \`hasMutations: true\` for any document containing a mutation root field.
|
|
12912
12938
|
`,
|
|
12913
12939
|
CreateWixBusinessGuide: dedent_default`
|
|
12914
12940
|
Provides comprehensive documentation for creating a new Wix business (site, app, etc.).
|
|
@@ -13028,7 +13054,8 @@ function mergeConfig(base, overrides) {
|
|
|
13028
13054
|
dynamicContextEnabled: overrides.dynamicContextEnabled ?? base.dynamicContextEnabled,
|
|
13029
13055
|
partnerContextEnabled: overrides.partnerContextEnabled ?? base.partnerContextEnabled,
|
|
13030
13056
|
usePlatformizedSearch: overrides.usePlatformizedSearch ?? base.usePlatformizedSearch,
|
|
13031
|
-
skillsPrOverrideEnabled: overrides.skillsPrOverrideEnabled ?? base.skillsPrOverrideEnabled
|
|
13057
|
+
skillsPrOverrideEnabled: overrides.skillsPrOverrideEnabled ?? base.skillsPrOverrideEnabled,
|
|
13058
|
+
graphqlEnabled: overrides.graphqlEnabled ?? base.graphqlEnabled
|
|
13032
13059
|
};
|
|
13033
13060
|
}
|
|
13034
13061
|
var defaultConfig = {
|
|
@@ -13634,6 +13661,27 @@ var paramDescriptions = {
|
|
|
13634
13661
|
mimeType: 'MIME type of the image (e.g. "image/jpeg", "image/png", "image/webp"). Required when imageBase64 does not include a data URL prefix.',
|
|
13635
13662
|
displayName: "Optional display name for the file in Media Manager. If not provided, uses the original filename."
|
|
13636
13663
|
},
|
|
13664
|
+
SearchWixGraphQLOperations: {
|
|
13665
|
+
query: 'Free-text intent or entity, e.g. "products with inventory", "create contact", "orders", "blog posts", "booking services". Operation names encode app + service + version + verb/entity (e.g. storesProductsV3V3Products, crmContactsV4CreateContact), so a noun plus a verb (query/get/create/update/delete) ranks best. You may also pass an exact operation name.',
|
|
13666
|
+
kind: 'Restrict to "query" (reads), "mutation" (writes \u2014 note a few reads such as search/list calls are exposed as mutations), or "all" (default).',
|
|
13667
|
+
maxResults: "Maximum number of operations to return (default 10, max 50).",
|
|
13668
|
+
reason: "One sentence describing the original user request and why you are looking for a GraphQL operation."
|
|
13669
|
+
},
|
|
13670
|
+
InspectWixGraphQLSchema: {
|
|
13671
|
+
operation: 'Exact root query or mutation name from SearchWixGraphQLOperations (e.g. "crmContactsV4Contacts"). Returns its arguments, input type and return type as compact SDL, expanded `depth` levels.',
|
|
13672
|
+
typeNames: 'Type names to expand, e.g. ones listed as "Not expanded" in a previous result, or a nested input/object/enum type you need before writing the request. Can be combined with `operation`.',
|
|
13673
|
+
depth: "How many levels of referenced types to expand (1-4, default 2). Level 1 is the given types, level 2 the types their fields reference, and so on. Keep it small and expand specific types with typeNames instead of dumping everything.",
|
|
13674
|
+
reason: "One sentence describing the original user request and why you need this part of the GraphQL schema."
|
|
13675
|
+
},
|
|
13676
|
+
ExecuteWixGraphQL: {
|
|
13677
|
+
query: "The GraphQL document (a query or a mutation). Every root field, argument and selected field MUST come from SearchWixGraphQLOperations / InspectWixGraphQLSchema results in this conversation, never from memory. Declare variables for filters, sort and large inputs, e.g. `query Q($f: JSON) { crmContactsV4Contacts(queryInput: { query: { filter: $f, paging: { limit: 50 } } }) { items { id } pageInfo { hasNext } } }`. Object-typed fields need a selection set. You can put several independent root fields in one document.",
|
|
13678
|
+
variables: 'Variables object for the document, as a JSON object (not a string). Use it for JSON-scalar filters/sort (REST filter syntax, e.g. {"info.name.first": {"$eq": "Ada"}}) and plain scalars. Do NOT pass object inputs that contain enum values (product types, statuses, registration types ...) through variables \u2014 write those inline in the document with the enum unquoted; the endpoint returns 503 otherwise.',
|
|
13679
|
+
operationName: "Operation to run when the document defines more than one named operation.",
|
|
13680
|
+
siteId: "The Wix site to run against. Required for site-level operations (anything reading or writing inside a site \u2014 products, orders, contacts, bookings, CMS, blog, members ...). Resolve it with GetSiteContext or ListWixSites; never pass a guessed value.",
|
|
13681
|
+
scope: '"site" (default when siteId is given) runs with a site-scoped credential; "account" runs account-level operations (sites, account settings) and ignores siteId.',
|
|
13682
|
+
hasMutations: "Whether this document creates, updates, deletes or otherwise mutates Wix data. True for any mutation root field (in any operation of the document) even when the intent is inspection; false only for pure queries. This flag alone decides whether a transient server error may be retried, so never mark a document that writes as false.",
|
|
13683
|
+
reason: "One sentence explaining the original user request and why you are running this GraphQL operation to complete it."
|
|
13684
|
+
},
|
|
13637
13685
|
RunWixCliCommand: {
|
|
13638
13686
|
appPath: "The full path to the Wix CLI app to run the command on.",
|
|
13639
13687
|
extensionType: "The type of extension to generate. You MUST provide this for commands that generate extensions.",
|
|
@@ -13868,7 +13916,16 @@ ${skillsContent}`
|
|
|
13868
13916
|
] : await Promise.all(
|
|
13869
13917
|
baseDocs.filter((doc) => doc.url === RECIPES_INDEX_URL).map(fetchDoc)
|
|
13870
13918
|
);
|
|
13871
|
-
const
|
|
13919
|
+
const recipeNotes = !skillsContent?.includes("Dashboard Navigation") ? [] : [
|
|
13920
|
+
await fetchDoc({
|
|
13921
|
+
action: "text",
|
|
13922
|
+
title: "Recipe Notes",
|
|
13923
|
+
content: dedent_default`
|
|
13924
|
+
- **Navigation recipes** (the *Dashboard Navigation* family) build direct manage.wix.com URLs. If your environment provides dedicated navigation tools, use those to perform the actual navigation — opening a recipe-built URL forces a full page refresh. Use the recipe URLs for composing a link to hand the user, or for navigating when no dedicated tool exists.
|
|
13925
|
+
`
|
|
13926
|
+
})
|
|
13927
|
+
];
|
|
13928
|
+
const contents = [...baseContents, ...recipesContents, ...recipeNotes];
|
|
13872
13929
|
const dynamicContext = await dynamicContextPromise;
|
|
13873
13930
|
const parts = [
|
|
13874
13931
|
...contents.filter(
|
|
@@ -15620,6 +15677,761 @@ function truncateResponse(content, maxChars = DEFAULT_MAX_CHARS) {
|
|
|
15620
15677
|
Response was ~${estimatedTokens.toLocaleString()} tokens (limit: ${limitTokens.toLocaleString()}). Refine your code to return less data.`;
|
|
15621
15678
|
}
|
|
15622
15679
|
|
|
15680
|
+
// src/graphql/constants.ts
|
|
15681
|
+
var WIX_GRAPHQL_ENDPOINT = "https://www.wixapis.com/graphql/alpha";
|
|
15682
|
+
var SEARCH_GRAPHQL_TOOL_NAME = "SearchWixGraphQLOperations";
|
|
15683
|
+
var INSPECT_GRAPHQL_TOOL_NAME = "InspectWixGraphQLSchema";
|
|
15684
|
+
var EXECUTE_GRAPHQL_TOOL_NAME = "ExecuteWixGraphQL";
|
|
15685
|
+
var GRAPHQL_TOOL_NAMES = [
|
|
15686
|
+
SEARCH_GRAPHQL_TOOL_NAME,
|
|
15687
|
+
INSPECT_GRAPHQL_TOOL_NAME,
|
|
15688
|
+
EXECUTE_GRAPHQL_TOOL_NAME
|
|
15689
|
+
];
|
|
15690
|
+
|
|
15691
|
+
// src/graphql/introspection.ts
|
|
15692
|
+
var TYPE_REF_FRAGMENT = `
|
|
15693
|
+
fragment TR on __Type { kind name ofType { kind name ofType { kind name ofType { kind name } } } }`;
|
|
15694
|
+
var ROOT_OPERATIONS_QUERY = `{
|
|
15695
|
+
__schema {
|
|
15696
|
+
queryType { fields { name description args { name type { ...TR } } type { ...TR } } }
|
|
15697
|
+
mutationType { fields { name description args { name type { ...TR } } type { ...TR } } }
|
|
15698
|
+
}
|
|
15699
|
+
}${TYPE_REF_FRAGMENT}`;
|
|
15700
|
+
var TYPE_DETAILS_FRAGMENT = `
|
|
15701
|
+
fragment TD on __Type {
|
|
15702
|
+
kind name description
|
|
15703
|
+
fields { name description type { ...TR } args { name type { ...TR } } }
|
|
15704
|
+
inputFields { name description type { ...TR } defaultValue }
|
|
15705
|
+
enumValues { name description }
|
|
15706
|
+
possibleTypes { name }
|
|
15707
|
+
}`;
|
|
15708
|
+
var ROOT_CACHE_TTL_MS = 6 * 60 * 60 * 1e3;
|
|
15709
|
+
var rootCache;
|
|
15710
|
+
var typeCache = /* @__PURE__ */ new Map();
|
|
15711
|
+
var RETRY_DELAYS_MS = [800, 2e3, 4e3];
|
|
15712
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
15713
|
+
async function fetchWithRetry(fetchImpl, url, init, delays = RETRY_DELAYS_MS) {
|
|
15714
|
+
let attempt = 0;
|
|
15715
|
+
for (; ; ) {
|
|
15716
|
+
const resp = await fetchImpl(url, init);
|
|
15717
|
+
if (resp.status < 500 || attempt >= delays.length) return resp;
|
|
15718
|
+
await sleep(delays[attempt++]);
|
|
15719
|
+
}
|
|
15720
|
+
}
|
|
15721
|
+
async function postIntrospection(query, options) {
|
|
15722
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
15723
|
+
const endpoint = options.endpoint ?? WIX_GRAPHQL_ENDPOINT;
|
|
15724
|
+
const resp = await fetchWithRetry(
|
|
15725
|
+
fetchImpl,
|
|
15726
|
+
endpoint,
|
|
15727
|
+
{
|
|
15728
|
+
method: "POST",
|
|
15729
|
+
headers: {
|
|
15730
|
+
"Content-Type": "application/json",
|
|
15731
|
+
Accept: "application/json"
|
|
15732
|
+
},
|
|
15733
|
+
body: JSON.stringify({ query })
|
|
15734
|
+
},
|
|
15735
|
+
options.retryDelaysMs
|
|
15736
|
+
);
|
|
15737
|
+
const text = await resp.text();
|
|
15738
|
+
if (!resp.ok) {
|
|
15739
|
+
const body = /^\s*<(!doctype|html)/i.test(text) ? "(HTML error page \u2014 the endpoint is temporarily unavailable; try again in a moment)" : text.slice(0, 500);
|
|
15740
|
+
throw new Error(
|
|
15741
|
+
`GraphQL introspection failed (${resp.status} ${resp.statusText}): ${body}`
|
|
15742
|
+
);
|
|
15743
|
+
}
|
|
15744
|
+
const json = JSON.parse(text);
|
|
15745
|
+
if (json.errors?.length && !json.data) {
|
|
15746
|
+
throw new Error(
|
|
15747
|
+
`GraphQL introspection returned errors: ${JSON.stringify(json.errors).slice(0, 500)}`
|
|
15748
|
+
);
|
|
15749
|
+
}
|
|
15750
|
+
return json.data;
|
|
15751
|
+
}
|
|
15752
|
+
function getRootOperations(options = {}) {
|
|
15753
|
+
const now = Date.now();
|
|
15754
|
+
if (rootCache && now - rootCache.fetchedAt < ROOT_CACHE_TTL_MS) {
|
|
15755
|
+
return rootCache.promise;
|
|
15756
|
+
}
|
|
15757
|
+
const promise = postIntrospection(ROOT_OPERATIONS_QUERY, options).then(
|
|
15758
|
+
(data) => {
|
|
15759
|
+
const toOps = (fields, kind) => (fields ?? []).map((f) => ({
|
|
15760
|
+
kind,
|
|
15761
|
+
name: f.name,
|
|
15762
|
+
description: f.description ?? "",
|
|
15763
|
+
args: f.args ?? [],
|
|
15764
|
+
type: f.type
|
|
15765
|
+
}));
|
|
15766
|
+
return [
|
|
15767
|
+
...toOps(data?.__schema?.queryType?.fields, "query"),
|
|
15768
|
+
...toOps(data?.__schema?.mutationType?.fields, "mutation")
|
|
15769
|
+
];
|
|
15770
|
+
}
|
|
15771
|
+
);
|
|
15772
|
+
promise.catch(() => {
|
|
15773
|
+
if (rootCache?.promise === promise) rootCache = void 0;
|
|
15774
|
+
});
|
|
15775
|
+
rootCache = { promise, fetchedAt: now };
|
|
15776
|
+
return promise;
|
|
15777
|
+
}
|
|
15778
|
+
var GRAPHQL_NAME = /^[_A-Za-z][_0-9A-Za-z]*$/;
|
|
15779
|
+
var TYPE_BATCH_SIZE = 10;
|
|
15780
|
+
async function getTypes(names, options = {}) {
|
|
15781
|
+
const unique = [...new Set(names)].filter((n) => GRAPHQL_NAME.test(n));
|
|
15782
|
+
const missing = unique.filter((n) => !typeCache.has(n));
|
|
15783
|
+
for (let start = 0; start < missing.length; start += TYPE_BATCH_SIZE) {
|
|
15784
|
+
const chunk = missing.slice(start, start + TYPE_BATCH_SIZE);
|
|
15785
|
+
const selections = chunk.map((n, i) => `t${i}: __type(name: "${n}") { ...TD }`).join("\n");
|
|
15786
|
+
const query = `{
|
|
15787
|
+
${selections}
|
|
15788
|
+
}${TYPE_DETAILS_FRAGMENT}${TYPE_REF_FRAGMENT}`;
|
|
15789
|
+
const batch = postIntrospection(query, options);
|
|
15790
|
+
chunk.forEach((n, i) => {
|
|
15791
|
+
const p = batch.then(
|
|
15792
|
+
(data) => data?.[`t${i}`] ?? null
|
|
15793
|
+
);
|
|
15794
|
+
p.catch(() => {
|
|
15795
|
+
if (typeCache.get(n) === p) typeCache.delete(n);
|
|
15796
|
+
});
|
|
15797
|
+
typeCache.set(n, p);
|
|
15798
|
+
});
|
|
15799
|
+
await batch.catch(() => void 0);
|
|
15800
|
+
}
|
|
15801
|
+
const result = /* @__PURE__ */ new Map();
|
|
15802
|
+
await Promise.all(
|
|
15803
|
+
unique.map(async (n) => {
|
|
15804
|
+
result.set(n, await typeCache.get(n));
|
|
15805
|
+
})
|
|
15806
|
+
);
|
|
15807
|
+
return result;
|
|
15808
|
+
}
|
|
15809
|
+
function renderTypeRef(ref) {
|
|
15810
|
+
if (!ref) return "Unknown";
|
|
15811
|
+
if (ref.kind === "NON_NULL") return `${renderTypeRef(ref.ofType)}!`;
|
|
15812
|
+
if (ref.kind === "LIST") return `[${renderTypeRef(ref.ofType)}]`;
|
|
15813
|
+
return ref.name ?? "Unknown";
|
|
15814
|
+
}
|
|
15815
|
+
function namedType(ref) {
|
|
15816
|
+
let cur = ref;
|
|
15817
|
+
while (cur && (cur.kind === "NON_NULL" || cur.kind === "LIST")) {
|
|
15818
|
+
cur = cur.ofType ?? null;
|
|
15819
|
+
}
|
|
15820
|
+
return cur?.name ?? null;
|
|
15821
|
+
}
|
|
15822
|
+
var BUILTIN_SCALARS = /* @__PURE__ */ new Set([
|
|
15823
|
+
"String",
|
|
15824
|
+
"Int",
|
|
15825
|
+
"Float",
|
|
15826
|
+
"Boolean",
|
|
15827
|
+
"ID",
|
|
15828
|
+
"JSON"
|
|
15829
|
+
]);
|
|
15830
|
+
function isBuiltinScalar(name) {
|
|
15831
|
+
return !!name && BUILTIN_SCALARS.has(name);
|
|
15832
|
+
}
|
|
15833
|
+
function oneLine(text, max) {
|
|
15834
|
+
if (!text) return "";
|
|
15835
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
15836
|
+
return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
|
|
15837
|
+
}
|
|
15838
|
+
function renderField(field, isInput) {
|
|
15839
|
+
const args = !isInput && field.args?.length ? `(${field.args.map((a) => `${a.name}: ${renderTypeRef(a.type)}`).join(", ")})` : "";
|
|
15840
|
+
const def = isInput && field.defaultValue != null ? ` = ${field.defaultValue}` : "";
|
|
15841
|
+
const comment = field.description ? ` # ${oneLine(field.description, 140)}` : "";
|
|
15842
|
+
return ` ${field.name}${args}: ${renderTypeRef(field.type)}${def}${comment}`;
|
|
15843
|
+
}
|
|
15844
|
+
function renderType(type) {
|
|
15845
|
+
const references = /* @__PURE__ */ new Set();
|
|
15846
|
+
const collect = (ref) => {
|
|
15847
|
+
const n = namedType(ref);
|
|
15848
|
+
if (n && !isBuiltinScalar(n) && n !== type.name) references.add(n);
|
|
15849
|
+
};
|
|
15850
|
+
const header = type.description ? `# ${oneLine(type.description, 200)}
|
|
15851
|
+
` : "";
|
|
15852
|
+
let body;
|
|
15853
|
+
switch (type.kind) {
|
|
15854
|
+
case "ENUM":
|
|
15855
|
+
body = `enum ${type.name} {
|
|
15856
|
+
${(type.enumValues ?? []).map(
|
|
15857
|
+
(v) => ` ${v.name}${v.description ? ` # ${oneLine(v.description, 100)}` : ""}`
|
|
15858
|
+
).join("\n")}
|
|
15859
|
+
}`;
|
|
15860
|
+
break;
|
|
15861
|
+
case "INPUT_OBJECT":
|
|
15862
|
+
(type.inputFields ?? []).forEach((f) => collect(f.type));
|
|
15863
|
+
body = `input ${type.name} {
|
|
15864
|
+
${(type.inputFields ?? []).map((f) => renderField(f, true)).join("\n")}
|
|
15865
|
+
}`;
|
|
15866
|
+
break;
|
|
15867
|
+
case "UNION":
|
|
15868
|
+
(type.possibleTypes ?? []).forEach((p) => references.add(p.name));
|
|
15869
|
+
body = `union ${type.name} = ${(type.possibleTypes ?? []).map((p) => p.name).join(" | ")}`;
|
|
15870
|
+
break;
|
|
15871
|
+
case "SCALAR":
|
|
15872
|
+
body = `scalar ${type.name}`;
|
|
15873
|
+
break;
|
|
15874
|
+
default: {
|
|
15875
|
+
(type.fields ?? []).forEach((f) => {
|
|
15876
|
+
collect(f.type);
|
|
15877
|
+
f.args?.forEach((a) => collect(a.type));
|
|
15878
|
+
});
|
|
15879
|
+
const keyword = type.kind === "INTERFACE" ? "interface" : "type";
|
|
15880
|
+
body = `${keyword} ${type.name} {
|
|
15881
|
+
${(type.fields ?? []).map((f) => renderField(f, false)).join("\n")}
|
|
15882
|
+
}`;
|
|
15883
|
+
}
|
|
15884
|
+
}
|
|
15885
|
+
return { text: header + body, references: [...references] };
|
|
15886
|
+
}
|
|
15887
|
+
function renderOperationSignature(op) {
|
|
15888
|
+
const args = op.args.map((a) => `${a.name}: ${renderTypeRef(a.type)}`).join(", ");
|
|
15889
|
+
return `${op.kind === "query" ? "Query" : "Mutation"}.${op.name}(${args}): ${renderTypeRef(op.type)}`;
|
|
15890
|
+
}
|
|
15891
|
+
async function expandTypes(rootTypeNames, options = {}) {
|
|
15892
|
+
const depth = Math.max(1, Math.min(options.depth ?? 2, 5));
|
|
15893
|
+
const maxTypes = options.maxTypes ?? 40;
|
|
15894
|
+
const rendered = [];
|
|
15895
|
+
const unknown = [];
|
|
15896
|
+
const seen = /* @__PURE__ */ new Set();
|
|
15897
|
+
let frontier = [...new Set(rootTypeNames)].filter((n) => !isBuiltinScalar(n));
|
|
15898
|
+
let level = 1;
|
|
15899
|
+
let overflow = [];
|
|
15900
|
+
while (frontier.length > 0 && level <= depth) {
|
|
15901
|
+
const room = maxTypes - seen.size;
|
|
15902
|
+
if (room <= 0) {
|
|
15903
|
+
overflow = frontier;
|
|
15904
|
+
break;
|
|
15905
|
+
}
|
|
15906
|
+
const batch = frontier.slice(0, room);
|
|
15907
|
+
overflow = frontier.slice(room);
|
|
15908
|
+
batch.forEach((n) => seen.add(n));
|
|
15909
|
+
const types = await getTypes(batch, options);
|
|
15910
|
+
const next = /* @__PURE__ */ new Set();
|
|
15911
|
+
for (const name of batch) {
|
|
15912
|
+
const type = types.get(name);
|
|
15913
|
+
if (!type) {
|
|
15914
|
+
unknown.push(name);
|
|
15915
|
+
continue;
|
|
15916
|
+
}
|
|
15917
|
+
const { text, references } = renderType(type);
|
|
15918
|
+
rendered.push(text);
|
|
15919
|
+
references.forEach((r) => {
|
|
15920
|
+
if (!seen.has(r)) next.add(r);
|
|
15921
|
+
});
|
|
15922
|
+
}
|
|
15923
|
+
frontier = [...next];
|
|
15924
|
+
level++;
|
|
15925
|
+
}
|
|
15926
|
+
const unexpanded = [.../* @__PURE__ */ new Set([...overflow, ...frontier])].filter(
|
|
15927
|
+
(n) => !seen.has(n) && !isBuiltinScalar(n)
|
|
15928
|
+
);
|
|
15929
|
+
return { rendered, unexpanded, unknown };
|
|
15930
|
+
}
|
|
15931
|
+
|
|
15932
|
+
// src/graphql/search.ts
|
|
15933
|
+
function tokenize(text) {
|
|
15934
|
+
return text.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/([a-zA-Z])([0-9])/g, "$1 $2").replace(/([0-9])([a-zA-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 0);
|
|
15935
|
+
}
|
|
15936
|
+
var STOP_WORDS = /* @__PURE__ */ new Set([
|
|
15937
|
+
"a",
|
|
15938
|
+
"an",
|
|
15939
|
+
"the",
|
|
15940
|
+
"of",
|
|
15941
|
+
"for",
|
|
15942
|
+
"to",
|
|
15943
|
+
"in",
|
|
15944
|
+
"on",
|
|
15945
|
+
"with",
|
|
15946
|
+
"and",
|
|
15947
|
+
"or",
|
|
15948
|
+
"by",
|
|
15949
|
+
"all",
|
|
15950
|
+
"my",
|
|
15951
|
+
"me",
|
|
15952
|
+
"i",
|
|
15953
|
+
"from",
|
|
15954
|
+
"is",
|
|
15955
|
+
"are",
|
|
15956
|
+
"be",
|
|
15957
|
+
"it",
|
|
15958
|
+
"this",
|
|
15959
|
+
"that",
|
|
15960
|
+
"wix",
|
|
15961
|
+
"api",
|
|
15962
|
+
"graphql"
|
|
15963
|
+
]);
|
|
15964
|
+
function stem(token) {
|
|
15965
|
+
if (token.length > 4 && token.endsWith("ies"))
|
|
15966
|
+
return `${token.slice(0, -3)}y`;
|
|
15967
|
+
if (token.length > 3 && token.endsWith("es") && !token.endsWith("ses"))
|
|
15968
|
+
return token.slice(0, -1);
|
|
15969
|
+
if (token.length > 3 && token.endsWith("s") && !token.endsWith("ss"))
|
|
15970
|
+
return token.slice(0, -1);
|
|
15971
|
+
return token;
|
|
15972
|
+
}
|
|
15973
|
+
var VERB_SYNONYMS = {
|
|
15974
|
+
list: ["query", "list", "search"],
|
|
15975
|
+
find: ["query", "search", "get"],
|
|
15976
|
+
fetch: ["get", "query"],
|
|
15977
|
+
read: ["get", "query"],
|
|
15978
|
+
show: ["get", "query"],
|
|
15979
|
+
count: ["count", "query"],
|
|
15980
|
+
add: ["create", "add"],
|
|
15981
|
+
new: ["create"],
|
|
15982
|
+
insert: ["create"],
|
|
15983
|
+
edit: ["update"],
|
|
15984
|
+
change: ["update"],
|
|
15985
|
+
modify: ["update"],
|
|
15986
|
+
set: ["update"],
|
|
15987
|
+
remove: ["delete", "remove"],
|
|
15988
|
+
destroy: ["delete"],
|
|
15989
|
+
cancel: ["cancel", "delete"],
|
|
15990
|
+
customer: ["contact", "member"],
|
|
15991
|
+
client: ["contact", "member"],
|
|
15992
|
+
item: ["product", "item"],
|
|
15993
|
+
inventory: ["inventory", "stock"],
|
|
15994
|
+
stock: ["inventory", "stock"],
|
|
15995
|
+
post: ["post", "blog"],
|
|
15996
|
+
article: ["post", "blog"],
|
|
15997
|
+
appointment: ["booking", "session"],
|
|
15998
|
+
collection: ["collection", "category", "data"],
|
|
15999
|
+
cms: ["data", "collection"],
|
|
16000
|
+
store: ["stores", "store"]
|
|
16001
|
+
};
|
|
16002
|
+
function expandQueryTokens(tokens) {
|
|
16003
|
+
const out = /* @__PURE__ */ new Set();
|
|
16004
|
+
for (const raw of tokens) {
|
|
16005
|
+
if (STOP_WORDS.has(raw)) continue;
|
|
16006
|
+
const s = stem(raw);
|
|
16007
|
+
out.add(s);
|
|
16008
|
+
for (const syn of VERB_SYNONYMS[raw] ?? VERB_SYNONYMS[s] ?? []) {
|
|
16009
|
+
out.add(stem(syn));
|
|
16010
|
+
}
|
|
16011
|
+
}
|
|
16012
|
+
return out;
|
|
16013
|
+
}
|
|
16014
|
+
var READ_VERBS = /* @__PURE__ */ new Set([
|
|
16015
|
+
"list",
|
|
16016
|
+
"get",
|
|
16017
|
+
"query",
|
|
16018
|
+
"find",
|
|
16019
|
+
"fetch",
|
|
16020
|
+
"read",
|
|
16021
|
+
"show",
|
|
16022
|
+
"retrieve",
|
|
16023
|
+
"search",
|
|
16024
|
+
"count",
|
|
16025
|
+
"view",
|
|
16026
|
+
"see"
|
|
16027
|
+
]);
|
|
16028
|
+
var WRITE_VERBS = /* @__PURE__ */ new Set([
|
|
16029
|
+
"create",
|
|
16030
|
+
"add",
|
|
16031
|
+
"new",
|
|
16032
|
+
"insert",
|
|
16033
|
+
"update",
|
|
16034
|
+
"edit",
|
|
16035
|
+
"change",
|
|
16036
|
+
"modify",
|
|
16037
|
+
"set",
|
|
16038
|
+
"delete",
|
|
16039
|
+
"remove",
|
|
16040
|
+
"destroy",
|
|
16041
|
+
"cancel",
|
|
16042
|
+
"bulk",
|
|
16043
|
+
"merge",
|
|
16044
|
+
"publish",
|
|
16045
|
+
"send"
|
|
16046
|
+
]);
|
|
16047
|
+
var isVersionToken = (t) => t === "v" || /^\d+$/.test(t);
|
|
16048
|
+
function stripMarkdown(text) {
|
|
16049
|
+
return text.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/[`*_]/g, "");
|
|
16050
|
+
}
|
|
16051
|
+
function firstSentence(text, max = 220) {
|
|
16052
|
+
const flat = stripMarkdown(text).replace(/\s+/g, " ").trim();
|
|
16053
|
+
const cut = flat.search(/(?<=[.!?])\s/);
|
|
16054
|
+
const sentence = cut > 0 ? flat.slice(0, cut) : flat;
|
|
16055
|
+
return sentence.length > max ? `${sentence.slice(0, max - 1)}\u2026` : sentence;
|
|
16056
|
+
}
|
|
16057
|
+
var indexCache = /* @__PURE__ */ new WeakMap();
|
|
16058
|
+
function indexOperations(ops) {
|
|
16059
|
+
let indexed = indexCache.get(ops);
|
|
16060
|
+
if (!indexed) {
|
|
16061
|
+
indexed = ops.map((op) => ({
|
|
16062
|
+
op,
|
|
16063
|
+
nameTokens: new Set(tokenize(op.name).map(stem)),
|
|
16064
|
+
descTokens: new Set(tokenize(op.description.slice(0, 600)).map(stem))
|
|
16065
|
+
}));
|
|
16066
|
+
indexCache.set(ops, indexed);
|
|
16067
|
+
}
|
|
16068
|
+
return indexed;
|
|
16069
|
+
}
|
|
16070
|
+
function searchOperations(ops, query, options = {}) {
|
|
16071
|
+
const { kind = "all", maxResults = 10 } = options;
|
|
16072
|
+
const rawTokens = tokenize(query);
|
|
16073
|
+
const terms = expandQueryTokens(rawTokens);
|
|
16074
|
+
const originalTerms = new Set(
|
|
16075
|
+
rawTokens.filter((t) => !STOP_WORDS.has(t)).map(stem)
|
|
16076
|
+
);
|
|
16077
|
+
const exactName = query.trim();
|
|
16078
|
+
const hasWriteVerb = rawTokens.some((t) => WRITE_VERBS.has(t));
|
|
16079
|
+
const nounTokens = rawTokens.filter(
|
|
16080
|
+
(t) => !STOP_WORDS.has(t) && !READ_VERBS.has(t) && !WRITE_VERBS.has(t)
|
|
16081
|
+
);
|
|
16082
|
+
const pluralIntent = nounTokens.length > 0 && nounTokens.some((t) => stem(t) !== t);
|
|
16083
|
+
const readIntent = !hasWriteVerb;
|
|
16084
|
+
const matches = [];
|
|
16085
|
+
for (const { op, nameTokens, descTokens } of indexOperations(ops)) {
|
|
16086
|
+
if (kind !== "all" && op.kind !== kind) continue;
|
|
16087
|
+
let score = 0;
|
|
16088
|
+
let originalHits = 0;
|
|
16089
|
+
const matchedNameTokens = /* @__PURE__ */ new Set();
|
|
16090
|
+
for (const term of terms) {
|
|
16091
|
+
const isOriginal = originalTerms.has(term);
|
|
16092
|
+
if (op.kind === "query" && readIntent && READ_VERBS.has(term)) {
|
|
16093
|
+
score += isOriginal ? 4 : 2;
|
|
16094
|
+
if (isOriginal) originalHits++;
|
|
16095
|
+
if (nameTokens.has(term)) matchedNameTokens.add(term);
|
|
16096
|
+
continue;
|
|
16097
|
+
}
|
|
16098
|
+
if (nameTokens.has(term)) {
|
|
16099
|
+
matchedNameTokens.add(term);
|
|
16100
|
+
score += isOriginal ? 4 : 2;
|
|
16101
|
+
if (isOriginal) originalHits++;
|
|
16102
|
+
continue;
|
|
16103
|
+
}
|
|
16104
|
+
let prefixHit = false;
|
|
16105
|
+
for (const nt of nameTokens) {
|
|
16106
|
+
if (term.length >= 3 && (nt.startsWith(term) || term.startsWith(nt))) {
|
|
16107
|
+
prefixHit = true;
|
|
16108
|
+
matchedNameTokens.add(nt);
|
|
16109
|
+
break;
|
|
16110
|
+
}
|
|
16111
|
+
}
|
|
16112
|
+
if (prefixHit) {
|
|
16113
|
+
score += isOriginal ? 2 : 1;
|
|
16114
|
+
if (isOriginal) originalHits++;
|
|
16115
|
+
continue;
|
|
16116
|
+
}
|
|
16117
|
+
if (descTokens.has(term)) {
|
|
16118
|
+
score += 1;
|
|
16119
|
+
if (isOriginal) originalHits++;
|
|
16120
|
+
}
|
|
16121
|
+
}
|
|
16122
|
+
if (score <= 0 && op.name !== exactName) continue;
|
|
16123
|
+
if (op.name === exactName) score += 100;
|
|
16124
|
+
if (originalTerms.size > 0 && originalHits === originalTerms.size) {
|
|
16125
|
+
score += 3;
|
|
16126
|
+
}
|
|
16127
|
+
const lastToken = tokenize(op.name).filter((t) => !isVersionToken(t)).pop();
|
|
16128
|
+
if (lastToken && nounTokens.length > 0) {
|
|
16129
|
+
const pluralOp = stem(lastToken) !== lastToken;
|
|
16130
|
+
score += pluralOp === pluralIntent ? 0.5 : -0.5;
|
|
16131
|
+
}
|
|
16132
|
+
if (/DoNotCall/i.test(op.name)) score -= 2;
|
|
16133
|
+
for (const nt of nameTokens) {
|
|
16134
|
+
if (!isVersionToken(nt) && !matchedNameTokens.has(nt)) score -= 0.3;
|
|
16135
|
+
}
|
|
16136
|
+
if (readIntent && op.kind === "mutation" && [...nameTokens].some((t) => WRITE_VERBS.has(t))) {
|
|
16137
|
+
score -= 6;
|
|
16138
|
+
}
|
|
16139
|
+
if (op.kind === "query" && readIntent) score += 1;
|
|
16140
|
+
const version = op.name.match(/V(\d+)/);
|
|
16141
|
+
if (version) score += Math.min(Number(version[1]), 5) * 0.1;
|
|
16142
|
+
if (!op.description) score -= 0.5;
|
|
16143
|
+
score -= op.name.length / 200;
|
|
16144
|
+
if (score <= 0) continue;
|
|
16145
|
+
matches.push({
|
|
16146
|
+
operation: op.name,
|
|
16147
|
+
kind: op.kind,
|
|
16148
|
+
signature: `${op.name}(${op.args.map((a) => `${a.name}: ${renderTypeRef(a.type)}`).join(", ")}): ${renderTypeRef(op.type)}`,
|
|
16149
|
+
description: firstSentence(op.description),
|
|
16150
|
+
inputType: op.args[0] ? namedType(op.args[0].type) : null,
|
|
16151
|
+
returnType: namedType(op.type),
|
|
16152
|
+
score: Math.round(score * 100) / 100
|
|
16153
|
+
});
|
|
16154
|
+
}
|
|
16155
|
+
matches.sort(
|
|
16156
|
+
(a, b) => b.score - a.score || a.operation.localeCompare(b.operation)
|
|
16157
|
+
);
|
|
16158
|
+
return matches.slice(0, Math.max(1, Math.min(maxResults, 50)));
|
|
16159
|
+
}
|
|
16160
|
+
|
|
16161
|
+
// src/graphql/index.ts
|
|
16162
|
+
var textResult = (text) => ({
|
|
16163
|
+
content: [{ type: "text", text }]
|
|
16164
|
+
});
|
|
16165
|
+
var errorResult = (text) => ({
|
|
16166
|
+
isError: true,
|
|
16167
|
+
content: [{ type: "text", text }]
|
|
16168
|
+
});
|
|
16169
|
+
var SCHEMA_MAX_RESPONSE_CHARS = 48e3;
|
|
16170
|
+
function addGraphqlTools(server, options = {}) {
|
|
16171
|
+
const { authStrategy, disableTools = [], toolDescriptions } = options;
|
|
16172
|
+
const getDescription = (name) => toolDescriptions?.[name] ?? defaultToolDescriptions[name];
|
|
16173
|
+
if (!disableTools.includes(SEARCH_GRAPHQL_TOOL_NAME)) {
|
|
16174
|
+
addSearchGraphqlTool(
|
|
16175
|
+
server,
|
|
16176
|
+
getDescription(SEARCH_GRAPHQL_TOOL_NAME),
|
|
16177
|
+
options
|
|
16178
|
+
);
|
|
16179
|
+
}
|
|
16180
|
+
if (!disableTools.includes(INSPECT_GRAPHQL_TOOL_NAME)) {
|
|
16181
|
+
addInspectGraphqlTool(
|
|
16182
|
+
server,
|
|
16183
|
+
getDescription(INSPECT_GRAPHQL_TOOL_NAME),
|
|
16184
|
+
options
|
|
16185
|
+
);
|
|
16186
|
+
}
|
|
16187
|
+
if (authStrategy && !disableTools.includes(EXECUTE_GRAPHQL_TOOL_NAME)) {
|
|
16188
|
+
addExecuteGraphqlTool(
|
|
16189
|
+
server,
|
|
16190
|
+
getDescription(EXECUTE_GRAPHQL_TOOL_NAME),
|
|
16191
|
+
authStrategy,
|
|
16192
|
+
options
|
|
16193
|
+
);
|
|
16194
|
+
}
|
|
16195
|
+
}
|
|
16196
|
+
function introspectionOptions(options) {
|
|
16197
|
+
return {
|
|
16198
|
+
endpoint: options.endpoint,
|
|
16199
|
+
fetchImpl: options.fetchImpl,
|
|
16200
|
+
retryDelaysMs: options.retryDelaysMs
|
|
16201
|
+
};
|
|
16202
|
+
}
|
|
16203
|
+
function addSearchGraphqlTool(server, description, options) {
|
|
16204
|
+
const d = desc("SearchWixGraphQLOperations");
|
|
16205
|
+
server.tool(
|
|
16206
|
+
SEARCH_GRAPHQL_TOOL_NAME,
|
|
16207
|
+
description,
|
|
16208
|
+
{
|
|
16209
|
+
query: external_exports.string().describe(d.query),
|
|
16210
|
+
kind: external_exports.enum(["query", "mutation", "all"]).optional().describe(d.kind),
|
|
16211
|
+
maxResults: external_exports.number().int().min(1).max(50).optional().describe(d.maxResults),
|
|
16212
|
+
reason: external_exports.string().describe(d.reason)
|
|
16213
|
+
},
|
|
16214
|
+
{ readOnlyHint: true, destructiveHint: false, openWorldHint: false },
|
|
16215
|
+
async ({ query, kind, maxResults, reason }) => {
|
|
16216
|
+
logger.log(
|
|
16217
|
+
`[${SEARCH_GRAPHQL_TOOL_NAME}] query="${query}" kind=${kind ?? "all"} reason="${reason}"`
|
|
16218
|
+
);
|
|
16219
|
+
try {
|
|
16220
|
+
const ops = await getRootOperations(introspectionOptions(options));
|
|
16221
|
+
const matches = searchOperations(ops, query, {
|
|
16222
|
+
kind: kind ?? "all",
|
|
16223
|
+
maxResults: maxResults ?? 10
|
|
16224
|
+
});
|
|
16225
|
+
if (matches.length === 0) {
|
|
16226
|
+
return textResult(
|
|
16227
|
+
`No GraphQL operations matched "${query}". Try other words for the entity (e.g. "contact" instead of "customer", "product" instead of "item") or the verb (query/get/create/update/delete), or search a single noun.`
|
|
16228
|
+
);
|
|
16229
|
+
}
|
|
16230
|
+
const lines = matches.map(
|
|
16231
|
+
(m, i) => `${i + 1}. ${m.kind} ${m.signature}
|
|
16232
|
+
${m.description || "(no description)"}`
|
|
16233
|
+
);
|
|
16234
|
+
const text = [
|
|
16235
|
+
`Top ${matches.length} of ${ops.length} Wix GraphQL root operations for "${query}":`,
|
|
16236
|
+
"",
|
|
16237
|
+
...lines,
|
|
16238
|
+
"",
|
|
16239
|
+
`Next: call ${INSPECT_GRAPHQL_TOOL_NAME} with \`operation\` set to the chosen name to read its exact input type and return type before writing the request.`
|
|
16240
|
+
].join("\n");
|
|
16241
|
+
return textResult(text);
|
|
16242
|
+
} catch (err) {
|
|
16243
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
16244
|
+
logger.log(`[${SEARCH_GRAPHQL_TOOL_NAME}] Error: ${message}`);
|
|
16245
|
+
return errorResult(`GraphQL schema search error: ${message}`);
|
|
16246
|
+
}
|
|
16247
|
+
}
|
|
16248
|
+
);
|
|
16249
|
+
}
|
|
16250
|
+
function addInspectGraphqlTool(server, description, options) {
|
|
16251
|
+
const d = desc("InspectWixGraphQLSchema");
|
|
16252
|
+
const maxChars = options.maxResponseSize ?? SCHEMA_MAX_RESPONSE_CHARS;
|
|
16253
|
+
server.tool(
|
|
16254
|
+
INSPECT_GRAPHQL_TOOL_NAME,
|
|
16255
|
+
description,
|
|
16256
|
+
{
|
|
16257
|
+
operation: external_exports.string().optional().describe(d.operation),
|
|
16258
|
+
typeNames: external_exports.array(external_exports.string()).optional().describe(d.typeNames),
|
|
16259
|
+
depth: external_exports.number().int().min(1).max(4).optional().describe(d.depth),
|
|
16260
|
+
reason: external_exports.string().describe(d.reason)
|
|
16261
|
+
},
|
|
16262
|
+
{ readOnlyHint: true, destructiveHint: false, openWorldHint: false },
|
|
16263
|
+
async ({ operation, typeNames, depth, reason }) => {
|
|
16264
|
+
logger.log(
|
|
16265
|
+
`[${INSPECT_GRAPHQL_TOOL_NAME}] operation=${operation ?? "-"} typeNames=${JSON.stringify(typeNames ?? [])} depth=${depth ?? 2} reason="${reason}"`
|
|
16266
|
+
);
|
|
16267
|
+
if (!operation && !(typeNames && typeNames.length > 0)) {
|
|
16268
|
+
return errorResult(
|
|
16269
|
+
"Pass `operation` (a root query/mutation name from SearchWixGraphQLOperations) and/or `typeNames` (type names to expand)."
|
|
16270
|
+
);
|
|
16271
|
+
}
|
|
16272
|
+
try {
|
|
16273
|
+
const io = introspectionOptions(options);
|
|
16274
|
+
const sections = [];
|
|
16275
|
+
const roots = [];
|
|
16276
|
+
if (operation) {
|
|
16277
|
+
const ops = await getRootOperations(io);
|
|
16278
|
+
const op = ops.find((o) => o.name === operation);
|
|
16279
|
+
if (!op) {
|
|
16280
|
+
const suggestions = searchOperations(ops, operation, {
|
|
16281
|
+
maxResults: 5
|
|
16282
|
+
});
|
|
16283
|
+
return errorResult(
|
|
16284
|
+
`No root operation named "${operation}". ${suggestions.length ? `Did you mean: ${suggestions.map((s) => `${s.kind} ${s.operation}`).join(", ")}? Use SearchWixGraphQLOperations to discover the exact name.` : "Use SearchWixGraphQLOperations to discover the exact name."}`
|
|
16285
|
+
);
|
|
16286
|
+
}
|
|
16287
|
+
sections.push(
|
|
16288
|
+
`# ${renderOperationSignature(op)}`,
|
|
16289
|
+
op.description ? op.description.trim().split("\n").map((l) => `# ${l}`).join("\n") : "# (no description)"
|
|
16290
|
+
);
|
|
16291
|
+
op.args.forEach((a) => {
|
|
16292
|
+
const n = namedType(a.type);
|
|
16293
|
+
if (n) roots.push(n);
|
|
16294
|
+
});
|
|
16295
|
+
const ret = namedType(op.type);
|
|
16296
|
+
if (ret) roots.push(ret);
|
|
16297
|
+
}
|
|
16298
|
+
if (typeNames?.length) roots.push(...typeNames);
|
|
16299
|
+
const { rendered, unexpanded, unknown } = await expandTypes(roots, {
|
|
16300
|
+
...io,
|
|
16301
|
+
depth: depth ?? 2
|
|
16302
|
+
});
|
|
16303
|
+
sections.push(...rendered);
|
|
16304
|
+
if (unknown.length) {
|
|
16305
|
+
sections.push(
|
|
16306
|
+
`# Unknown type names (not in the schema): ${unknown.join(", ")}`
|
|
16307
|
+
);
|
|
16308
|
+
}
|
|
16309
|
+
if (unexpanded.length) {
|
|
16310
|
+
sections.push(
|
|
16311
|
+
`# Not expanded (pass any of these in \`typeNames\` to read them): ${unexpanded.join(", ")}`
|
|
16312
|
+
);
|
|
16313
|
+
}
|
|
16314
|
+
sections.push(
|
|
16315
|
+
"# Notes: `JSON` scalar fields (filter, sort, free-form data) take any JSON \u2014 pass them as variables. Every object-typed field in a selection needs its own { ... } selection set. Only fields listed above exist. Paging: use exactly the paging style the input type declares \u2014 `paging` (offset) or `cursorPaging` (cursor) \u2014 never the other one. `pageInfo.total` is only populated with offset paging; with cursor paging, count by walking pages (`pageInfo.hasNext` + cursor) or use a dedicated count operation if one exists."
|
|
16316
|
+
);
|
|
16317
|
+
return textResult(truncateResponse(sections.join("\n\n"), maxChars));
|
|
16318
|
+
} catch (err) {
|
|
16319
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
16320
|
+
logger.log(`[${INSPECT_GRAPHQL_TOOL_NAME}] Error: ${message}`);
|
|
16321
|
+
return errorResult(`GraphQL schema inspection error: ${message}`);
|
|
16322
|
+
}
|
|
16323
|
+
}
|
|
16324
|
+
);
|
|
16325
|
+
}
|
|
16326
|
+
function addExecuteGraphqlTool(server, description, authStrategy, options) {
|
|
16327
|
+
const d = desc("ExecuteWixGraphQL");
|
|
16328
|
+
const endpoint = options.endpoint ?? WIX_GRAPHQL_ENDPOINT;
|
|
16329
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
16330
|
+
server.tool(
|
|
16331
|
+
EXECUTE_GRAPHQL_TOOL_NAME,
|
|
16332
|
+
description,
|
|
16333
|
+
{
|
|
16334
|
+
query: external_exports.string().describe(d.query),
|
|
16335
|
+
variables: external_exports.record(external_exports.unknown()).optional().describe(d.variables),
|
|
16336
|
+
operationName: external_exports.string().optional().describe(d.operationName),
|
|
16337
|
+
siteId: external_exports.string().optional().describe(d.siteId),
|
|
16338
|
+
scope: external_exports.enum(["site", "account"]).optional().describe(d.scope),
|
|
16339
|
+
hasMutations: external_exports.boolean().describe(d.hasMutations),
|
|
16340
|
+
reason: external_exports.string().describe(d.reason)
|
|
16341
|
+
},
|
|
16342
|
+
{ readOnlyHint: false, destructiveHint: true, openWorldHint: false },
|
|
16343
|
+
async ({ query, variables, operationName, siteId, scope, hasMutations, reason }, extra) => {
|
|
16344
|
+
const effectiveScope = scope ?? (siteId ? "site" : "account");
|
|
16345
|
+
logger.log(
|
|
16346
|
+
`[${EXECUTE_GRAPHQL_TOOL_NAME}] scope=${effectiveScope} siteId=${siteId ?? "none"} hasMutations=${hasMutations} operationName=${operationName ?? "-"} reason="${reason}"`
|
|
16347
|
+
);
|
|
16348
|
+
if (effectiveScope === "site" && !siteId) {
|
|
16349
|
+
return errorResult(
|
|
16350
|
+
'A `siteId` is required for site-level GraphQL operations (anything that reads or writes inside a site). Resolve it with GetSiteContext or ListWixSites, or set scope: "account" for account-level operations.'
|
|
16351
|
+
);
|
|
16352
|
+
}
|
|
16353
|
+
if (!query.trim()) {
|
|
16354
|
+
return errorResult("`query` must be a non-empty GraphQL document.");
|
|
16355
|
+
}
|
|
16356
|
+
const authHeaders = effectiveScope === "site" ? await authStrategy.getSiteAuthHeaders(siteId) : await authStrategy.getAccountAuthHeaders();
|
|
16357
|
+
try {
|
|
16358
|
+
const init = {
|
|
16359
|
+
method: "POST",
|
|
16360
|
+
headers: {
|
|
16361
|
+
"Content-Type": "application/json",
|
|
16362
|
+
Accept: "application/json",
|
|
16363
|
+
...authHeaders
|
|
16364
|
+
},
|
|
16365
|
+
body: JSON.stringify({
|
|
16366
|
+
query,
|
|
16367
|
+
...variables ? { variables } : {},
|
|
16368
|
+
...operationName ? { operationName } : {}
|
|
16369
|
+
})
|
|
16370
|
+
};
|
|
16371
|
+
const resp = hasMutations ? await fetchImpl(endpoint, init) : await fetchWithRetry(
|
|
16372
|
+
fetchImpl,
|
|
16373
|
+
endpoint,
|
|
16374
|
+
init,
|
|
16375
|
+
options.retryDelaysMs
|
|
16376
|
+
);
|
|
16377
|
+
const requestId = resp.headers?.get("x-wix-request-id") ?? void 0;
|
|
16378
|
+
extra?.setToolBiParams?.({ siteId, requestId });
|
|
16379
|
+
const text = await resp.text();
|
|
16380
|
+
if (!resp.ok) {
|
|
16381
|
+
await authStrategy.enforceValidWixToken?.({
|
|
16382
|
+
status: resp.status,
|
|
16383
|
+
response: { status: resp.status }
|
|
16384
|
+
});
|
|
16385
|
+
const body2 = /^\s*<(!doctype|html)/i.test(text) ? "(HTML error page)" : text.slice(0, 2e3);
|
|
16386
|
+
const hasObjectVariables = !!variables && Object.values(variables).some(
|
|
16387
|
+
(v) => v !== null && typeof v === "object"
|
|
16388
|
+
);
|
|
16389
|
+
const hint = resp.status >= 500 ? hasObjectVariables ? ` The Wix GraphQL endpoint (Developer Preview) returns 503 when an object-typed variable carries an enum value. Rewrite the document with the input INLINE as a GraphQL literal (enum values unquoted, e.g. productType: PHYSICAL), keep variables only for JSON scalars and plain scalars, and retry once. If it still fails and REST tools (ExecuteWixAPI / CallWixSiteAPI) are available, use the equivalent REST method.` : ` The Wix GraphQL endpoint (Developer Preview) failed for this operation. Do not retry the same document more than once. If REST tools (ExecuteWixAPI / CallWixSiteAPI) are available, complete the task through the equivalent REST method instead; otherwise report the failure with the request id.` : "";
|
|
16390
|
+
return errorResult(
|
|
16391
|
+
`Wix GraphQL request failed: ${resp.status} ${resp.statusText}.${requestId ? ` request id: ${requestId}.` : ""}${hint}
|
|
16392
|
+
${body2}`
|
|
16393
|
+
);
|
|
16394
|
+
}
|
|
16395
|
+
let json;
|
|
16396
|
+
try {
|
|
16397
|
+
json = JSON.parse(text);
|
|
16398
|
+
} catch {
|
|
16399
|
+
return errorResult(
|
|
16400
|
+
`Wix GraphQL returned a non-JSON body:
|
|
16401
|
+
${text.slice(0, 2e3)}`
|
|
16402
|
+
);
|
|
16403
|
+
}
|
|
16404
|
+
const hasData = json.data != null && Object.values(json.data).some((v) => v !== null && v !== void 0);
|
|
16405
|
+
const errors = json.errors ?? [];
|
|
16406
|
+
if (!hasData && errors.length > 0) {
|
|
16407
|
+
const permissionDenied = errors.some(
|
|
16408
|
+
(e) => e.extensions?.message === "PERMISSION_DENIED"
|
|
16409
|
+
);
|
|
16410
|
+
return errorResult(
|
|
16411
|
+
[
|
|
16412
|
+
`Wix GraphQL returned errors and no data${requestId ? ` (request id: ${requestId})` : ""}:`,
|
|
16413
|
+
JSON.stringify(errors, null, 2).slice(0, 4e3),
|
|
16414
|
+
permissionDenied ? "PERMISSION_DENIED usually means the operation is site-level and was called without the right `siteId`, the app behind it is not installed on the site, or the credential lacks that permission scope." : 'Validation errors ("Cannot query field ...", "Unknown argument ...") mean a name was guessed \u2014 re-read the exact fields with InspectWixGraphQLSchema and retry.'
|
|
16415
|
+
].join("\n")
|
|
16416
|
+
);
|
|
16417
|
+
}
|
|
16418
|
+
const body = { data: json.data };
|
|
16419
|
+
if (errors.length > 0) {
|
|
16420
|
+
body.errors = errors;
|
|
16421
|
+
body.note = "Partial result: some root fields failed (see errors[].path). Fields present in data succeeded.";
|
|
16422
|
+
}
|
|
16423
|
+
return textResult(truncateResponse(body, options.maxResponseSize));
|
|
16424
|
+
} catch (err) {
|
|
16425
|
+
rethrowIfUnauthorized(err);
|
|
16426
|
+
await authStrategy.enforceValidWixToken?.(err);
|
|
16427
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
16428
|
+
logger.log(`[${EXECUTE_GRAPHQL_TOOL_NAME}] Error: ${message}`);
|
|
16429
|
+
return errorResult(`Wix GraphQL execution error: ${message}`);
|
|
16430
|
+
}
|
|
16431
|
+
}
|
|
16432
|
+
);
|
|
16433
|
+
}
|
|
16434
|
+
|
|
15623
16435
|
// src/code-mode/validation.ts
|
|
15624
16436
|
var EXECUTE_FUNCTION_EXPRESSION_HINT = 'ExecuteWixAPI code must be a function expression, not a script body. Pass code like: async () => { const response = await wix.request({ scope: "site", method: "GET", url: "https://www.wixapis.com/..." }); return response.data; }. Do not write top-level const/await/return outside the function and do not invoke the function yourself.';
|
|
15625
16437
|
function validateExecuteCode(code) {
|
|
@@ -17940,6 +18752,20 @@ function createWixToolkit(options) {
|
|
|
17940
18752
|
maxResponseSize
|
|
17941
18753
|
});
|
|
17942
18754
|
}
|
|
18755
|
+
const requestedGraphqlTools = GRAPHQL_TOOL_NAMES.filter(
|
|
18756
|
+
(name) => requestedTools.has(name)
|
|
18757
|
+
);
|
|
18758
|
+
if (requestedGraphqlTools.length > 0) {
|
|
18759
|
+
addGraphqlTools(server, {
|
|
18760
|
+
authStrategy,
|
|
18761
|
+
disableTools: [
|
|
18762
|
+
...disableTools ?? [],
|
|
18763
|
+
...GRAPHQL_TOOL_NAMES.filter((n) => !requestedTools.has(n))
|
|
18764
|
+
],
|
|
18765
|
+
toolDescriptions: effectiveToolDescriptions,
|
|
18766
|
+
maxResponseSize
|
|
18767
|
+
});
|
|
18768
|
+
}
|
|
17943
18769
|
} else {
|
|
17944
18770
|
addApiCallTool(
|
|
17945
18771
|
server,
|
|
@@ -18121,10 +18947,15 @@ function createWixToolkit(options) {
|
|
|
18121
18947
|
}
|
|
18122
18948
|
export {
|
|
18123
18949
|
EXECUTE_FUNCTION_EXPRESSION_HINT,
|
|
18950
|
+
EXECUTE_GRAPHQL_TOOL_NAME,
|
|
18951
|
+
GRAPHQL_TOOL_NAMES,
|
|
18952
|
+
INSPECT_GRAPHQL_TOOL_NAME,
|
|
18124
18953
|
RECIPES_INDEX_URL,
|
|
18954
|
+
SEARCH_GRAPHQL_TOOL_NAME,
|
|
18125
18955
|
SYSTEM_REMINDER,
|
|
18126
18956
|
SYSTEM_REMINDER_GUIDELINES,
|
|
18127
18957
|
UNAUTHORIZED_ERROR_NAME,
|
|
18958
|
+
WIX_GRAPHQL_ENDPOINT,
|
|
18128
18959
|
WixFetchError,
|
|
18129
18960
|
attachConsoleLogger,
|
|
18130
18961
|
createWixToolkit,
|