veza/apps/web/scripts/wrap_msw_handlers.py

106 lines
4.1 KiB
Python

#!/usr/bin/env python3
"""
Script to wrap MSW handler responses in the correct API format.
Converts: HttpResponse.json({ data })
To: HttpResponse.json({ success: true, data: { data } })
"""
import re
import sys
def wrap_handler_response(content):
"""
Find and wrap MSW handler responses that aren't already wrapped.
"""
# Pattern to match http.get/post/etc handlers
# This matches: http.METHOD('pattern', (...) => { return HttpResponse.json({ ... }); })
lines = content.split('\n')
result = []
i = 0
while i < len(lines):
line = lines[i]
# Check if this is a handler definition
if re.match(r'\s*http\.(get|post|put|delete|patch|all)\(', line):
# Find the return HttpResponse.json statement
handler_start = i
brace_count = 0
in_handler = False
for j in range(i, min(i + 100, len(lines))): # Look ahead up to 100 lines
current_line = lines[j]
# Track braces to know when we're inside the handler
brace_count += current_line.count('{') - current_line.count('}')
# Look for HttpResponse.json(
if 'HttpResponse.json(' in current_line:
# Check if already wrapped (has 'success: true')
# Look ahead a few lines to see if success: true exists
is_wrapped = False
for k in range(j, min(j + 5, len(lines))):
if 'success:' in lines[k] or 'success :' in lines[k]:
is_wrapped = True
break
if not is_wrapped and 'message:' not in current_line:
# This needs wrapping
# Find the opening brace after HttpResponse.json(
indent = len(current_line) - len(current_line.lstrip())
# Add the wrapper
result.append(current_line.replace(
'HttpResponse.json({',
'HttpResponse.json({\n' + ' ' * (indent + 2) + 'success: true,\n' + ' ' * (indent + 2) + 'data: {'
))
# Now we need to find the closing brace and add an extra }
json_brace_count = 1
for k in range(j + 1, len(lines)):
check_line = lines[k]
json_brace_count += check_line.count('{') - check_line.count('}')
if json_brace_count == 0:
# This is the closing brace
# Add extra closing brace before this one
result.append(' ' * (indent + 2) + '}')
result.append(check_line)
i = k + 1
break
else:
result.append(check_line)
break
else:
# Already wrapped or special case, just copy
result.append(current_line)
i = j + 1
break
elif j == i + 99 or (j > i and brace_count == 0):
# Didn't find HttpResponse.json, just copy the line
result.append(line)
i += 1
break
else:
result.append(line)
i += 1
return '\n'.join(result)
if __name__ == '__main__':
if len(sys.argv) != 2:
print("Usage: python wrap_msw_handlers.py <handlers_file>")
sys.exit(1)
filepath = sys.argv[1]
with open(filepath, 'r') as f:
content = f.read()
wrapped_content = wrap_handler_response(content)
with open(filepath, 'w') as f:
f.write(wrapped_content)
print(f"✅ Wrapped MSW handlers in {filepath}")