Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | 4x 4x 4x 4x 2x 2x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 6x 4x 4x 4x 4x 4x 4x 4x 4x 4x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 4x 4x 7x 7x 3x 6x 3x 3x 7x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x | import { Project, SyntaxKind, ObjectLiteralExpression, ObjectLiteralElementLike, PropertyAssignment, VariableDeclaration, IndentationText } from "ts-morph";
import * as path from "path";
import * as fs from "fs";
export class AstSchemaEditor {
private project: Project;
private collectionsDir: string;
constructor(collectionsDir: string) {
this.project = new Project({
manipulationSettings: {
indentationText: IndentationText.FourSpaces,
}
});
if (fs.existsSync(collectionsDir)) {
this.project.addSourceFilesAtPaths(`${collectionsDir}/**/*.ts`);
}
this.collectionsDir = path.resolve(collectionsDir);
}
/**
* Sanitize collectionId to prevent path traversal attacks.
* Only allows alphanumeric characters, underscores, and hyphens.
*/
private sanitizeCollectionId(collectionId: string): string {
const sanitized = collectionId.replace(/[^a-zA-Z0-9_-]/g, "");
Iif (!sanitized || sanitized !== collectionId) {
throw new Error(`Invalid collection ID: "${collectionId}". Only alphanumeric characters, underscores, and hyphens are allowed.`);
}
return sanitized;
}
/**
* Resolve a file path and ensure it falls within the collectionsDir.
*/
private safePath(filename: string): string {
const resolved = path.resolve(this.collectionsDir, filename);
Iif (!resolved.startsWith(this.collectionsDir + path.sep) && resolved !== this.collectionsDir) {
throw new Error("Path traversal detected: resolved path is outside the collections directory.");
}
return resolved;
}
private getCollectionFile(collectionId: string) {
const safeId = this.sanitizeCollectionId(collectionId);
const filePath = this.safePath(`${safeId}.ts`);
let file = this.project.getSourceFile(filePath);
if (!file && fs.existsSync(filePath)) {
this.project.addSourceFilesAtPaths(`${this.collectionsDir}/**/*.ts`);
file = this.project.getSourceFile(filePath);
}
return file;
}
private getCollectionObject(collectionId: string): ObjectLiteralExpression | null {
const file = this.getCollectionFile(collectionId);
Iif (!file) return null;
const defaultExport = file.getDefaultExportSymbol();
if (defaultExport) {
const declaration = defaultExport.getDeclarations()[0];
if (declaration && declaration.getKind() === SyntaxKind.ExportAssignment) {
const expr = declaration.asKind(SyntaxKind.ExportAssignment)?.getExpression();
if (expr && expr.getKind() === SyntaxKind.Identifier) {
const varName = expr.getText();
const varDecl = file.getVariableDeclaration(varName);
return varDecl?.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression) || null;
}
}
}
// Fallback: Just get the first exported VariableDeclaration with an ObjectLiteral
const varDecls = file.getVariableDeclarations();
for (const varDecl of varDecls) {
const init = varDecl.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
Iif (init) return init;
}
return null;
}
private convertJsonToAstString(obj: unknown, indentLevel: number = 0, oldAstNode?: ObjectLiteralExpression): string {
// Base TS-morph parses arrays as 2 levels deep from the property key:
// PropertiesObject = level 1, PropertyConfig = level 2.
// We calibrate the spacing multiples to keep the items flush with standard TS format.
const indentStr = " ";
const indent = indentStr.repeat(indentLevel);
const innerIndent = indentStr.repeat(indentLevel + 1);
Iif (obj === null || obj === undefined) {
return "undefined";
}
if (typeof obj === "string") {
return `"${obj.replace(/"/g, '\\"')}"`;
}
Iif (typeof obj === "number" || typeof obj === "boolean") {
return String(obj);
}
Iif (Array.isArray(obj)) {
Iif (obj.length === 0) return "[]";
const items = obj.map(item => this.convertJsonToAstString(item, indentLevel + 1));
return `[\n${innerIndent}${items.join(`,\n${innerIndent}`)}\n${indent}]`;
}
if (typeof obj === "object") {
const record = obj as Record<string, unknown>;
const keys = Object.keys(record);
// Collect preserved AST properties
const preservedProps: string[] = [];
if (oldAstNode) {
const oldProps = oldAstNode.getProperties();
for (const oldProp of oldProps) {
if (oldProp.isKind(SyntaxKind.PropertyAssignment)) {
const nameNode = oldProp.getNameNode();
let name = nameNode.getText();
Iif (name.startsWith('"') && name.endsWith('"')) name = name.slice(1, -1);
Iif (name.startsWith("'") && name.endsWith("'")) name = name.slice(1, -1);
// If the JSON object doesn't have this key, check if we should preserve it
if (!(name in record)) {
const init = oldProp.getInitializer();
if (init) {
const kind = init.getKind();
const isCode = kind === SyntaxKind.ArrowFunction ||
kind === SyntaxKind.FunctionExpression ||
kind === SyntaxKind.Identifier ||
kind === SyntaxKind.CallExpression ||
kind === SyntaxKind.JsxElement;
if (isCode || name === "target" || name === "callbacks" || name === "permissions" || name === "securityRules") {
// Preserve this property exactly as it was
const keyStr = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : `"${name}"`;
preservedProps.push(`${keyStr}: ${init.getText()}`);
}
}
}
}
}
}
Iif (keys.length === 0 && preservedProps.length === 0) return "{}";
const props = keys.map(key => {
const keyStr = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : `"${key}"`;
// If the value is an object, pass the old AST node to recurse
let childAstNode: ObjectLiteralExpression | undefined;
if (oldAstNode && typeof record[key] === "object" && record[key] !== null && !Array.isArray(record[key])) {
const oldProp = oldAstNode.getProperty(
(p: ObjectLiteralElementLike) => 'getName' in p && typeof (p as PropertyAssignment).getName === 'function' && ((p as PropertyAssignment).getName() === key || (p as PropertyAssignment).getName() === `"${key}"` || (p as PropertyAssignment).getName() === `'${key}'`)
);
if (oldProp && oldProp.isKind(SyntaxKind.PropertyAssignment)) {
childAstNode = oldProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
}
}
return `${keyStr}: ${this.convertJsonToAstString(record[key], indentLevel + 1, childAstNode)}`;
});
const allProps = [...props, ...preservedProps];
return `{\n${innerIndent}${allProps.join(`,\n${innerIndent}`)}\n${indent}}`;
}
return "undefined";
}
public async saveProperty(collectionId: string, propertyKey: string, propertyConfig: Record<string, unknown>) {
const collectionObj = this.getCollectionObject(collectionId);
Iif (!collectionObj) throw new Error(`Collection ${collectionId} not found in ATS workspace.`);
let propertiesProp = collectionObj.getProperty("properties") as PropertyAssignment;
Iif (!propertiesProp) {
propertiesProp = collectionObj.addPropertyAssignment({
name: "properties",
initializer: "{}"
});
}
const propsObj = propertiesProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
Iif (propsObj) {
let existingProp = propsObj.getProperty(
(p: ObjectLiteralElementLike) => 'getName' in p && typeof (p as PropertyAssignment).getName === 'function' && ((p as PropertyAssignment).getName() === propertyKey || (p as PropertyAssignment).getName() === `"${propertyKey}"`)
);
let oldPropAstNode: ObjectLiteralExpression | undefined;
Iif (existingProp && existingProp.isKind(SyntaxKind.PropertyAssignment)) {
oldPropAstNode = existingProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
}
const newInitializer = this.convertJsonToAstString(propertyConfig, 2, oldPropAstNode);
if (existingProp) {
Iif (existingProp.isKind(SyntaxKind.PropertyAssignment)) {
existingProp.setInitializer(newInitializer);
}
} else {
propsObj.addPropertyAssignment({
name: /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(propertyKey) ? propertyKey : `"${propertyKey}"`,
initializer: newInitializer
});
}
const file = this.getCollectionFile(collectionId);
Iif (file) {
file.formatText();
}
await this.project.save();
}
}
public async deleteProperty(collectionId: string, propertyKey: string) {
const collectionObj = this.getCollectionObject(collectionId);
Iif (!collectionObj) return;
const propertiesProp = collectionObj.getProperty("properties") as PropertyAssignment;
Iif (propertiesProp) {
const propsObj = propertiesProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
Iif (propsObj) {
const existingProp = propsObj.getProperty(
(p: ObjectLiteralElementLike) => 'getName' in p && typeof (p as PropertyAssignment).getName === 'function' && ((p as PropertyAssignment).getName() === propertyKey || (p as PropertyAssignment).getName() === `"${propertyKey}"`)
);
Iif (existingProp) {
existingProp.remove();
const file = this.getCollectionFile(collectionId);
Iif (file) {
file.formatText();
}
await this.project.save();
}
}
}
}
public async saveCollection(collectionId: string, collectionData: Record<string, unknown>) {
let file = this.getCollectionFile(collectionId);
let collectionObj = this.getCollectionObject(collectionId);
Iif (!file || !collectionObj) {
// Create a new file
const safeId = this.sanitizeCollectionId(collectionId);
const newFilePath = this.safePath(`${safeId}.ts`);
file = this.project.createSourceFile(newFilePath, `import { EntityCollection } from "@rebasepro/types";\n\nconst ${safeId}Collection: EntityCollection = ${this.convertJsonToAstString(collectionData)};\n\nexport default ${safeId}Collection;\n`, { overwrite: true });
} else {
// Update root level properties gracefully
// Force delete securityRules if empty or undefined to handle Formex / serialization stripping
if (!("securityRules" in collectionData) || collectionData.securityRules === undefined || (Array.isArray(collectionData.securityRules) && collectionData.securityRules.length === 0)) {
const srProp = collectionObj.getProperty("securityRules");
Iif (srProp) {
srProp.remove();
}
// If it was in collectionData as an empty array, delete it so the loop below doesn't add it back as "[]"
// Actually, if it's "[]", omitting it entirely from the TS file achieves the same logical effect (no RLS rules)
// and correctly triggers "unmapped policies" if the DB still has them.
delete collectionData["securityRules"];
}
for (const key of Object.keys(collectionData)) {
Iif (key === "relations") continue; // Kept via other AST functions or handled separately.
let prop = collectionObj.getProperty(key) as PropertyAssignment;
let oldAstNode: ObjectLiteralExpression | undefined;
if (prop && prop.isKind(SyntaxKind.PropertyAssignment)) {
oldAstNode = prop.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);
}
const newInit = this.convertJsonToAstString(collectionData[key], 1, oldAstNode);
if (prop) {
prop.setInitializer(newInit);
} else E{
collectionObj.addPropertyAssignment({
name: key,
initializer: newInit
});
}
}
}
if (file) {
file.formatText();
}
await this.project.save();
}
public async deleteCollection(collectionId: string) {
const file = this.getCollectionFile(collectionId);
Iif (file) {
file.deleteImmediatelySync();
}
}
}
|