"""Correct locked-generator edge cases for the asset-lock query before publishing. Keep these patches local to the new messages (and their merge-capable scalar submessages), rather than changing every existing API's generated conversions. Every replacement checks the locked generator's shape and fails before build.sh replaces clients/ if that shape changes. Wire regressions live in asset-lock.spec.js. """ import re import sys from pathlib import Path def replace_once(source, old, new): if source.count(old) != 1: raise ValueError(f'expected one generated occurrence of {old!r}') return source.replace(old, new, 1) def merge_decoder(source, name): """Allow asset-lock callers to decode repeated submessages into an existing one.""" pattern = rf'\b{name}\.decode = function decode\(reader, length\) \{{.*?\n[ \t]*\}};' matches = list(re.finditer(pattern, source, re.DOTALL)) if len(matches) != 1: raise ValueError(f'expected one {name} decoder') match = matches[0] block = replace_once(match.group(), 'function decode(reader, length)', 'function decode(reader, length, message)') pattern = r'(?m)^([ \t]*)var end = (.*), message = new (.*)\(\);$' block, count = re.subn(pattern, r'\1var end = \2;\n\1message = message || new \3();', block) if count != 1: raise ValueError(f'expected one {name} decoder initialization') return source[:match.start()] + block + source[match.end():] def patch_shared_pbjs_dictionaries(source, type_name, next_type_name): start = source.index(type_name) end = next_type_name if isinstance(next_type_name, int) else source.index(next_type_name, start) block = source[start:end] block = block.replace('message.hasOwnProperty(', 'Object.prototype.hasOwnProperty.call(message, ') return source[:start] + block + source[end:] def patch_pbjs(source): start = source.index('v0.GetAssetLockOutpointInfoRequest = (function() {') end = source.index('return GetAssetLockOutpointInfoResponse;', start) block = source[start:end] block = block.replace('message.hasOwnProperty(', 'Object.prototype.hasOwnProperty.call(message, ') block = block.replace('Object.hasOwnProperty.call(', 'Object.prototype.hasOwnProperty.call(') block = replace_once( block, '(message.remainingCredits = $util.Long.fromValue(object.remainingCredits)).unsigned = true;', 'message.remainingCredits = $util.Long.fromValue(object.remainingCredits, true);') # Defaults must not manufacture presence for this proto3 optional field. block, count = re.subn( r'(?m)^[ \t]*if \(\$util.Long\) \{\n[ \t]*var long = new \$util.Long\(0, 0, true\);\n' r'[ \t]*object.remainingCredits = .*;\n[ \t]*\} else\n[ \t]*object.remainingCredits = .*;\n', '', block) if count != 1: raise ValueError('expected one remainingCredits defaults block') block, count = re.subn( r'(?m)^([ \t]*)switch \(object.status\) \{', lambda m: (m.group() + '\n' + m[1] + 'default:\n' + m[1] + ' if (typeof object.status === "number")\n' + m[1] + ' message.status = object.status;\n' + m[1] + ' break;'), block) if count != 1: raise ValueError('expected one status conversion switch') enum = '$root.org.dash.platform.dapi.v0.GetAssetLockOutpointInfoResponse.Status[message.status]' block = replace_once(block, f'options.enums === String ? {enum} : message.status;', f'options.enums === String && {enum} !== undefined ? {enum} : message.status;') for field, sibling in (('assetLockOutpointInfo', 'proof'), ('proof', 'assetLockOutpointInfo')): # Clear only when a different member is read, not when metadata is read. block, count = re.subn( rf'(?m)^([ \t]*)(message\.{field} = .*\.decode\(reader, reader\.uint32\(\)\);)$', rf'\1delete message.{sibling};\n\1\2', block) if count != 1: raise ValueError(f'expected one {field} decode branch') for field in ('v0', 'assetLockOutpointInfo', 'proof', 'metadata'): block, count = re.subn( rf'(message\.{field} = .*\.decode\(reader, reader.uint32\(\))\);', rf'\1, message.{field});', block) expected = 2 if field == 'v0' else 1 if count != expected: raise ValueError(f'expected {expected} {field} submessage decodes') source = source[:start] + block + source[end:] for name in ('GetAssetLockOutpointInfoRequestV0', 'GetAssetLockOutpointInfoResponseV0', 'AssetLockOutpointInfo', 'Proof', 'ResponseMetadata'): source = merge_decoder(source, name) source = patch_shared_pbjs_dictionaries( source, 'v0.Proof = (function()', '\n v0.ResponseMetadata = (function()') metadata_start = source.index('v0.ResponseMetadata = (function()') metadata_end = source.index('\n v0.', metadata_start + 10) source = patch_shared_pbjs_dictionaries( source, 'v0.ResponseMetadata = (function()', metadata_end) return source def patch_jspb(source): def merge_jspb_fields_in_decoder(source, decoder, fields): marker = f'{decoder} = function(msg, reader) {{' start = source.index(marker) end = source.index('\n};', start) + 3 block = source[start:end] for field, type_name in fields: old = (f' var value = new {type_name};\n' f' reader.readMessage(value,{type_name}.deserializeBinaryFromReader);\n' f' msg.set{field}(value);') new = (f' var value = msg.get{field}() || new {type_name};\n' f' reader.readMessage(value,{type_name}.deserializeBinaryFromReader);\n' f' msg.set{field}(value);') block = replace_once(block, old, new) return source[:start] + block + source[end:] source = replace_once( source, 'remainingCredits: jspb.Message.getFieldWithDefault(msg, 2, "0")', 'remainingCredits: msg.hasRemainingCredits() ? msg.getRemainingCredits() : undefined') source = merge_jspb_fields_in_decoder( source, 'proto.org.dash.platform.dapi.v0.GetAssetLockOutpointInfoRequest.deserializeBinaryFromReader', [('V0', 'proto.org.dash.platform.dapi.v0.GetAssetLockOutpointInfoRequest.GetAssetLockOutpointInfoRequestV0')], ) source = merge_jspb_fields_in_decoder( source, 'proto.org.dash.platform.dapi.v0.GetAssetLockOutpointInfoResponse.deserializeBinaryFromReader', [('V0', 'proto.org.dash.platform.dapi.v0.GetAssetLockOutpointInfoResponse.GetAssetLockOutpointInfoResponseV0')], ) source = merge_jspb_fields_in_decoder( source, 'proto.org.dash.platform.dapi.v0.GetAssetLockOutpointInfoResponse.GetAssetLockOutpointInfoResponseV0.deserializeBinaryFromReader', [ ('AssetLockOutpointInfo', 'proto.org.dash.platform.dapi.v0.GetAssetLockOutpointInfoResponse.AssetLockOutpointInfo'), ('Proof', 'proto.org.dash.platform.dapi.v0.Proof'), ('Metadata', 'proto.org.dash.platform.dapi.v0.ResponseMetadata'), ], ) for setter in ('setAssetLockOutpointInfo', 'setProof'): name = ('proto.org.dash.platform.dapi.v0.GetAssetLockOutpointInfoResponse.' f'GetAssetLockOutpointInfoResponseV0.prototype.{setter}') pattern = re.escape(name) + r' = function\(value\) \{.*?\n\};' matches = list(re.finditer(pattern, source, re.DOTALL)) if len(matches) != 1: raise ValueError(f'expected one {setter} setter') match = matches[0] block = replace_once(match.group(), ', value);', ', value == null ? undefined : value);') source = source[:match.start()] + block + source[match.end():] return source def patch_dts(source): return replace_once(source, ' remainingCredits: string,', ' remainingCredits?: string,') def main(): clients = Path(sys.argv[1]) for service in ('platform', 'drive'): path = clients / service / 'v0/nodejs' / f'{service}_pbjs.js' path.write_text(patch_pbjs(path.read_text())) for folder, name in (('nodejs', 'platform_protoc.js'), ('web', 'platform_pb.js')): path = clients / 'platform/v0' / folder / name path.write_text(patch_jspb(path.read_text())) dts = clients / 'platform/v0/web/platform_pb.d.ts' dts.write_text(patch_dts(dts.read_text())) if __name__ == '__main__': main()