export interface TemplateOptions {
serverUrl: string;
projectPath?: string;
logMessage: string;
variables?: string[];
level?: 'info' | 'error' | 'debug' | 'warn';
}
export interface TemplateResult {
code: string;
language: string;
description: string;
usageInstructions: string;
}
export class TemplateGenerator {
/**
* Generate debug code template for browser environment
*/
generateBrowserTemplate(options: TemplateOptions): TemplateResult {
const { serverUrl, projectPath, logMessage, variables = [], level = 'info' } = options;
const varsObject = variables.length > 0
? `{ ${variables.join(', ')} }`
: '{}';
const code = `// ==================== DEBUG CODE START ====================
// ⚠️ DO NOT REPLACE WITH console.log()
// This code sends logs via HTTP POST to the debug server at ${serverUrl}
// Logs are stored in: ${projectPath || 'project'}/.debug/debug.log
// ==================== DEBUG CODE START ====================
fetch('${serverUrl}', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
projectPath: '${projectPath || ''}',
timestamp: new Date().toISOString(),
level: '${level}',
message: '${logMessage}',
data: ${varsObject}
})
}).catch(err => console.error('[Debug Log Failed]', err));
// ==================== DEBUG CODE END ====================`;
return {
code,
language: 'javascript',
description: 'Browser debug template using fetch API',
usageInstructions: 'Paste this code in your browser JavaScript code at the location you want to debug. ⚠️ This is NOT console.log() - it sends logs via HTTP POST to the debug server.'
};
}
/**
* Generate debug code template for Node.js environment
*/
generateNodeTemplate(options: TemplateOptions): TemplateResult {
const { serverUrl, projectPath, logMessage, variables = [], level = 'info' } = options;
const varsObject = variables.length > 0
? `{ ${variables.join(', ')} }`
: '{}';
const code = `// ==================== DEBUG CODE START ====================
// ⚠️ DO NOT REPLACE WITH console.log()
// This code sends logs via HTTP POST to the debug server at ${serverUrl}
// Logs are stored in: ${projectPath || 'project'}/.debug/debug.log
// ==================== DEBUG CODE START ====================
fetch('${serverUrl}', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
projectPath: '${projectPath || ''}',
timestamp: new Date().toISOString(),
level: '${level}',
message: '${logMessage}',
data: ${varsObject}
})
}).catch(err => console.error('[Debug Log Failed]', err));
// ==================== DEBUG CODE END ====================`;
return {
code,
language: 'javascript',
description: 'Node.js debug template using fetch API (Node 18+)',
usageInstructions: 'Paste this code in your Node.js code at the location you want to debug. Requires Node.js 18 or later. ⚠️ This is NOT console.log() - it sends logs via HTTP POST to the debug server.'
};
}
/**
* Generate debug code template for Python environment
*/
generatePythonTemplate(options: TemplateOptions): TemplateResult {
const { serverUrl, projectPath, logMessage, variables = [], level = 'info' } = options;
const varsDict = variables.length > 0
? variables.map(v => `'${v}': ${v}`).join(', ')
: '';
const projectPathStr = projectPath || '';
const code = `# ==================== DEBUG CODE START ====================
# ⚠️ DO NOT REPLACE WITH print()
# This code sends logs via HTTP POST to the debug server at ${serverUrl}
# Logs are stored in: ${projectPathStr}/.debug/debug.log
# ==================== DEBUG CODE START ====================
import requests
from datetime import datetime
try:
requests.post(
'${serverUrl}',
json={
'projectPath': '${projectPathStr}',
'timestamp': datetime.now().isoformat(),
'level': '${level}',
'message': '${logMessage}',
'data': {${varsDict}}
},
timeout=0.1
)
except Exception as e:
pass # Silent fail to not break main logic
# ==================== DEBUG CODE END ====================`;
return {
code,
language: 'python',
description: 'Python debug template using requests library',
usageInstructions: 'Requires requests library. Install with: pip install requests. ⚠️ This is NOT print() - it sends logs via HTTP POST to the debug server.'
};
}
/**
* Generate debug code template for PHP environment
*/
generatePHPTemplate(options: TemplateOptions): TemplateResult {
const { serverUrl, projectPath, logMessage, variables = [], level = 'info' } = options;
const varsArray = variables.length > 0
? variables.map(v => `'${v}' => $${v}`).join(', ')
: '';
const projectPathStr = projectPath || '';
const code = `// ==================== DEBUG CODE START ====================
// ⚠️ DO NOT REPLACE WITH echo() or var_dump()
// This code sends logs via HTTP POST to the debug server at ${serverUrl}
// Logs are stored in: ${projectPathStr}/.debug/debug.log
// ==================== DEBUG CODE START ====================
$logData = json_encode([
'projectPath' => '${projectPathStr}',
'timestamp' => date('c'),
'level' => '${level}',
'message' => '${logMessage}',
'data' => [${varsArray}]
]);
$ch = curl_init('${serverUrl}');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $logData);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 100);
curl_exec($ch);
curl_close($ch);
// ==================== DEBUG CODE END ====================`;
return {
code,
language: 'php',
description: 'PHP debug template using curl',
usageInstructions: 'Paste this code in your PHP file at the location you want to debug. ⚠️ This is NOT echo() - it sends logs via HTTP POST to the debug server.'
};
}
/**
* Generate debug code template for React Native
*/
generateReactNativeTemplate(options: TemplateOptions): TemplateResult {
const { serverUrl, projectPath, logMessage, variables = [], level = 'info' } = options;
const varsObject = variables.length > 0
? `{ ${variables.join(', ')} }`
: '{}';
const code = `// ==================== DEBUG CODE START ====================
// ⚠️ DO NOT REPLACE WITH console.log()
// This code sends logs via HTTP POST to the debug server at ${serverUrl}
// Logs are stored in: ${projectPath || 'project'}/.debug/debug.log
// ==================== DEBUG CODE START ====================
fetch('${serverUrl}', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
projectPath: '${projectPath || ''}',
timestamp: new Date().toISOString(),
level: '${level}',
message: '${logMessage}',
data: ${varsObject}
})
}).catch(err => console.error('[Debug Log Failed]', err));
// ==================== DEBUG CODE END ====================`;
return {
code,
language: 'javascript',
description: 'React Native debug template using fetch',
usageInstructions: 'For production, replace localhost with your actual server IP address. ⚠️ This is NOT console.log() - it sends logs via HTTP POST to the debug server.'
};
}
/**
* Generate debug code template for WeChat Mini Program
*/
generateWeChatMiniTemplate(options: TemplateOptions): TemplateResult {
const { serverUrl, projectPath, logMessage, variables = [], level = 'info' } = options;
const varsObject = variables.length > 0
? `{ ${variables.join(', ')} }`
: '{}';
const code = `// ==================== DEBUG CODE START ====================
// ⚠️ DO NOT REPLACE WITH console.log()
// This code sends logs via HTTP POST to the debug server at ${serverUrl}
// Logs are stored in: ${projectPath || 'project'}/.debug/debug.log
// ==================== DEBUG CODE START ====================
wx.request({
url: '${serverUrl}',
method: 'POST',
data: {
projectPath: '${projectPath || ''}',
timestamp: new Date().toISOString(),
level: '${level}',
message: '${logMessage}',
data: ${varsObject}
},
fail: (err) => console.error('[Debug Log Failed]', err)
});
// ==================== DEBUG CODE END ====================`;
return {
code,
language: 'javascript',
description: 'WeChat Mini Program debug template using wx.request',
usageInstructions: 'For production, add server domain to mini program whitelist. ⚠️ This is NOT console.log() - it sends logs via HTTP POST to the debug server.'
};
}
/**
* Generate debug code template for Java environment
*/
generateJavaTemplate(options: TemplateOptions): TemplateResult {
const { serverUrl, projectPath, logMessage, variables = [], level = 'info' } = options;
const varsMap = variables.length > 0
? `new java.util.HashMap<String, Object>() {{
${variables.map(v => `put("${v}", ${v});`).join('\n ')}
}}`
: 'new java.util.HashMap<String, Object>()';
const code = `// ==================== DEBUG CODE START ====================
// ⚠️ DO NOT REPLACE WITH System.out.println()
// This code sends logs via HTTP POST to the debug server at ${serverUrl}
// Logs are stored in: ${projectPath || 'project'}/.debug/debug.log
// ==================== DEBUG CODE START ====================
try {
DebugHttpClient.sendLog(
"${serverUrl}",
"${logMessage.replace(/"/g, '\\"')}",
${varsMap},
"${level}"
);
} catch (Exception e) {
// Silent fail - do not interrupt main logic
}
// ==================== DEBUG CODE END ====================`;
return {
code,
language: 'java',
description: 'Java server-side debug template using DebugHttpClient',
usageInstructions: '⚠️ IMPORTANT: Before using this code, add DebugHttpClient.java to your project. The tool library template will be provided separately. This is NOT System.out.println() - it sends logs via HTTP POST to the debug server.'
};
}
/**
* Generate debug code template for Android environment
*/
generateAndroidTemplate(options: TemplateOptions): TemplateResult {
const { serverUrl, projectPath, logMessage, variables = [], level = 'info' } = options;
const varsMap = variables.length > 0
? `new java.util.HashMap<String, Object>() {{
${variables.map(v => `put("${v}", ${v});`).join('\n ')}
}}`
: 'new java.util.HashMap<String, Object>()';
const code = `// ==================== DEBUG CODE START ====================
// ⚠️ DO NOT REPLACE WITH Log.d() or System.out.println()
// This code sends logs via HTTP POST to the debug server at ${serverUrl}
// Logs are stored in: ${projectPath || 'project'}/.debug/debug.log
// ⚠️ Android: Network requests must be executed in a background thread
// ==================== DEBUG CODE START ====================
// Android: Network requests must be executed in a background thread
if (android.os.Looper.getMainLooper().getThread() == Thread.currentThread()) {
// We are on the main thread, execute in background thread
new Thread(() -> {
try {
DebugHttpClient.sendLog(
"${serverUrl}",
"${logMessage.replace(/"/g, '\\"')}",
${varsMap},
"${level}"
);
} catch (Exception e) {
// Silent fail - do not interrupt main logic
}
}).start();
} else {
// Already in background thread, execute directly
try {
DebugHttpClient.sendLog(
"${serverUrl}",
"${logMessage.replace(/"/g, '\\"')}",
${varsMap},
"${level}"
);
} catch (Exception e) {
// Silent fail - do not interrupt main logic
}
}
// ==================== DEBUG CODE END ====================`;
return {
code,
language: 'java',
description: 'Android debug template using DebugHttpClient with thread safety',
usageInstructions: '⚠️ IMPORTANT: Before using this code, add DebugHttpClient.java to your project. The tool library template will be provided separately. Android requires network requests to run in background threads. This is NOT Log.d() - it sends logs via HTTP POST to the debug server.'
};
}
/**
* Generate debug code template for Kotlin environment
*/
generateKotlinTemplate(options: TemplateOptions): TemplateResult {
const { serverUrl, projectPath, logMessage, variables = [], level = 'info' } = options;
const varsMap = variables.length > 0
? `mapOf(${variables.map(v => `"${v}" to ${v}`).join(', ')})`
: 'emptyMap<String, Any>()';
const code = `// ==================== DEBUG CODE START ====================
// ⚠️ DO NOT REPLACE WITH println() or Log.d()
// This code sends logs via HTTP POST to the debug server at ${serverUrl}
// Logs are stored in: ${projectPath || 'project'}/.debug/debug.log
// ==================== DEBUG CODE START ====================
// Kotlin: Use coroutines for async network requests (Android) or direct call (Java)
try {
// For Android: Use coroutine scope
// CoroutineScope(Dispatchers.IO).launch {
// DebugHttpClient.sendLog(...)
// }
// For standard Java: Direct call
DebugHttpClient.sendLog(
"${serverUrl}",
"${logMessage.replace(/"/g, '\\"')}",
${varsMap},
"${level}"
)
} catch (e: Exception) {
// Silent fail - do not interrupt main logic
}
// ==================== DEBUG CODE END ====================`;
return {
code,
language: 'kotlin',
description: 'Kotlin debug template using DebugHttpClient with coroutine support',
usageInstructions: '⚠️ IMPORTANT: Before using this code, add DebugHttpClient.java to your project. The tool library template will be provided separately. For Android, uncomment the coroutine code. This is NOT println() - it sends logs via HTTP POST to the debug server.'
};
}
/**
* Generate debug code template for Objective-C environment
*/
generateObjectiveCTemplate(options: TemplateOptions): TemplateResult {
const { serverUrl, projectPath, logMessage, variables = [], level = 'info' } = options;
const varsDict = variables.length > 0
? `@{${variables.map(v => `@"${v}": ${v}`).join(', ')}}`
: '@{}';
const code = `// ==================== DEBUG CODE START ====================
// ⚠️ DO NOT REPLACE WITH NSLog() or print()
// This code sends logs via HTTP POST to the debug server at ${serverUrl}
// Logs are stored in: ${projectPath || 'project'}/.debug/debug.log
// ==================== DEBUG CODE START ====================
NSURL *url = [NSURL URLWithString:@"${serverUrl}"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setTimeoutInterval:0.1];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
NSString *timestamp = [formatter stringFromDate:[NSDate date]];
NSDictionary *logData = @{
@"timestamp": timestamp,
@"level": @"${level}",
@"message": @"${logMessage.replace(/"/g, '\\"')}",
@"data": ${varsDict}
};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:logData options:0 error:&error];
if (jsonData) {
[request setHTTPBody:jsonData];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Silent fail - do not interrupt main logic
}];
[task resume];
}
// ==================== DEBUG CODE END ====================`;
return {
code,
language: 'objective-c',
description: 'Objective-C debug template using NSURLSession (iOS/macOS)',
usageInstructions: 'Paste this code in your Objective-C file at the location you want to debug. Works for both iOS and macOS. ⚠️ This is NOT NSLog() - it sends logs via HTTP POST to the debug server.'
};
}
/**
* Get template by environment name
*/
getTemplate(environment: string, options: TemplateOptions): TemplateResult {
switch (environment.toLowerCase()) {
case 'browser':
case 'web':
case 'javascript':
return this.generateBrowserTemplate(options);
case 'node':
case 'nodejs':
return this.generateNodeTemplate(options);
case 'python':
case 'py':
return this.generatePythonTemplate(options);
case 'php':
return this.generatePHPTemplate(options);
case 'react-native':
case 'reactnative':
case 'rn':
return this.generateReactNativeTemplate(options);
case 'wechat':
case 'miniprogram':
case 'weixin':
return this.generateWeChatMiniTemplate(options);
case 'java':
return this.generateJavaTemplate(options);
case 'android':
return this.generateAndroidTemplate(options);
case 'kotlin':
case 'kt':
return this.generateKotlinTemplate(options);
case 'objective-c':
case 'objectivec':
case 'objc':
case 'ios':
case 'macos':
return this.generateObjectiveCTemplate(options);
default:
return this.generateBrowserTemplate(options);
}
}
/**
* Get list of supported environments
*/
getSupportedEnvironments(): string[] {
return [
'browser',
'node',
'python',
'php',
'react-native',
'wechat',
'java',
'android',
'kotlin',
'objective-c'
];
}
}