feat(generator): add jQuery + fetch dual HTTP client support in template

Enhance defaultDeps with:
- validatePageContext: Checks hostname against expected_domain for page context validation
- queryData: Dual HTTP client with jQuery $.ajax as primary and fetch as fallback
  - jQuery preferred for internal pages that typically have it
  - Clear error message if neither client is available

🤖 Generated with [Qoder][https://qoder.com]
This commit is contained in:
木炎
2026-04-17 12:19:02 +08:00
parent b8d2eb9faa
commit d996b511f6

View File

@@ -347,18 +347,51 @@ function buildArtifact(args, rows) {{
}} }}
const defaultDeps = {{ const defaultDeps = {{
validatePageContext: async () => true, validatePageContext(args) {{
queryData: async (args) => {{ const host = (globalThis.location?.hostname || '').trim();
const expected = (args.expected_domain || '').trim();
if (!host) return {{ ok: false, reason: 'page_context_unavailable' }};
if (host !== expected) return {{ ok: false, reason: 'page_context_mismatch' }};
return {{ ok: true }};
}},
async queryData(args) {{
const endpoint = API_ENDPOINTS[0]; const endpoint = API_ENDPOINTS[0];
if (!endpoint) throw new Error('No API endpoint configured'); if (!endpoint) throw new Error('No API endpoint configured');
const request = buildRequest(args, endpoint); const request = buildRequest(args, endpoint);
const response = await fetch(request.url, {{
method: request.method, // Prefer jQuery (internal pages typically have it)
headers: request.headers, if (typeof $ !== 'undefined' && typeof $.ajax === 'function') {{
body: request.body return new Promise((resolve, reject) => {{
}}); $.ajax({{
if (!response.ok) throw new Error(`HTTP ${{response.status}}: ${{response.statusText}}`); url: request.url,
return response.json(); type: request.method,
data: request.body,
contentType: 'application/json',
dataType: 'json',
success: resolve,
error: (xhr, status, err) => reject(new Error(
`API failed (${{xhr.status}}): ${{err}} | body=${{(xhr.responseText || '').substring(0, 200)}}`
))
}});
}});
}}
// Fallback: fetch API
if (typeof fetch === 'function') {{
const response = await fetch(request.url, {{
method: request.method,
headers: request.headers,
body: request.method !== 'GET' ? request.body : undefined
}});
if (!response.ok) {{
const text = await response.text().catch(() => '');
throw new Error(`HTTP ${{response.status}}: ${{text.substring(0, 200)}}`);
}}
return response.json();
}}
throw new Error('No HTTP client available (need jQuery or fetch)');
}} }}
}}; }};