I’m not what all you’re looking for, but whatever you want to do is probably do-able. This just expands on what you have a little to maybe give you some ideas. I think I’d position the rectangle with an expression, so I’ve included how to do that. Anyway, I hope it’s helpful.
function addShapeOnTop(){
var comp = app.project.activeItem;
if (comp == null || ! (comp instanceof CompItem)){
alert("No comp active.");
return;
}
if (comp.selectedLayers.length == 0){
alert("No layer selected.");
return;
}
var margin = 10;
var textLayer = comp.selectedLayers[0];
var shapeLayer = comp.layers.addShape();
shapeLayer.name = "Shape on top";
var shapeLayerContents = shapeLayer.property("ADBE Root Vectors Group");
var rectangleGroup = shapeLayerContents.addProperty("ADBE Vector Group");
rectangleGroup.name = "Rectangle 1";
var rectangleContents = rectangleGroup.property("ADBE Vectors Group");
var pathGroup = rectangleContents.addProperty("ADBE Vector Shape - Rect");
var sourceRect = textLayer.sourceRectAtTime(0,false);
pathGroup.property("ADBE Vector Rect Size").setValue([sourceRect.width + margin*2,sourceRect.height + margin*2]);
var pathStroke = rectangleContents.addProperty("ADBE Vector Graphic - Stroke");
var pathFill = rectangleContents.addProperty("ADBE Vector Graphic - Fill");
var expr = 'L = thisComp.layer("' + textLayer.name + '");\r' +
'r = L.sourceRectAtTime(time,false);\r' +
'L.toComp([r.left+r.width/2,r.top+r.height/2])';
shapeLayer.property("Position").expression = expr;
shapeLayer.moveAfter(textLayer);
}
addShapeOnTop();