[Question]
  [
Given a ragged list of positive integers, where the maximum depth is \$d\_\text{max}\$, return the same list, except for every element \$e\$, its depth is \$d\_\text{max}+1-d\_e\$ (where \$d\_e\$ is the depth of that element).
Your output should contain the minimal number of brackets, and you can assume the same from your input. Or in other words, "],[" doesn't appear in the input, and shouldn't appear in the output. You can assume that nonempty inputs contain at least one element with depth 1.
# Test cases
```
[] <-> []
[[1,2],3,4] <-> [1,2,[3,4]]
[1,[2],1,[3],1] <-> [[1],2,[1],3,[1]]
[3,[2,[1],2],3] <-> [[[3],2],1,[2,[3]]]
[1,2,3,4] <-> [1,2,3,4]
[[[1]],10] <-> [1,[[10]]
```
  
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 83 bytes
```
+`],
,]
T`[]`][
+`,]
],
{`^(?!\[((\[)|(?<-2>])|\d|,)*(?(2)^)]$).*
[$&]
\[([][])]
$1
```
[Try it online!](https://tio.run/##LYuxDsIwDER3/wVSQXZrkJIwIjLyA2zOVUGCgYUBsZF/D1bLcrp3fn4/Ps/XrW/5UvtUoaSgazVUGE3VwadvnTlvijEXk8b5tI9nSCv3pjJy5iizYJDDSDbsQC4aDAIaQu8GMgsaoUmP3oOad8/k6Zyc1QIWY7nHv7mq698P "Retina 0.8.2 – Try It Online") Link include test cases. Explanation:
```
+`],
,]
T`[]`][
+`,]
],
```
Exchange `],` with `,[`, and also flip the leading `[`s and trailing `]`s.
```
{`
```
Repeat until the string has been rebalanced.
```
^(?!\[((\[)|(?<-2>])|\d|,)*(?(2)^)]$).*
[$&]
```
If it's unbalanced then wrap it in `[]`s.
```
\[([][])]
$1
```
Collapse unnecessary `[]` pairs.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage/wiki/Tutorial), ~~31~~ ~~30~~ 27 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page)
```
ŒJẈạṀ$‘Ø0jIr0Ṣ€Ṡị“[],”żFFḊṖ
```
I'm pretty rusty in Jelly, ~~so can probably be golfed a bit further~~. It indeed can:  
-3 bytes thanks to *@JonathanAllan*.
Input as a list; output as a string.
Port of [my 05AB1E answer](https://codegolf.stackexchange.com/a/242190/52210). The `Ø0jIr0Ṣ€Ṡị“[],”żFFḊṖ` is a slight modification from [*@xigoi*'s Jelly answer for the *Build a list from a depth map* challenge](https://codegolf.stackexchange.com/a/241653/52210).
[Try it online](https://tio.run/##AVEArv9qZWxsef//xZJK4bqI4bqh4bmAJOKAmMOYMGpJcjDhuaLigqzhuaDhu4vigJxbXSzigJ3FvEZG4biK4bmW////WzMsWzIsWzFdLDJdLDMsNF0) or [verify all test cases](https://tio.run/##y0rNyan8///oJK@Huzoe7lr4cGeDyqOGGYdnGGR5Fhk83LnoUdOahzsXPNzd/ahhTnSszqOGuUf3uLk93NH1cOc0oLaHO2foHG7PAkoq6NopAGU1I///jwYqVIiONtQxitUx1jEBcQx1ooEcIGkMJEECxkABnWggE6QGosIIphisGqQ0NlbHRMc0NhYA).
**Explanation:**
```
                 # Main link, taking the input-list as argument:
ŒJẈ              #  Determine the depth of each integer:
ŒJ               #   Get the multidimensional arguments
  Ẉ              #   Get the length of each inner list
   ạṀ$‘          #  Invert this depth-list:
     $           #   Apply the previous two links as monad:
    Ṁ            #    Get the maximum of this list of depths
   ạ             #    Calculate the absolute difference
      ‘          #   Increase each 0-based depth by 1
Ø0jIr0Ṣ€Ṡị“[],”  #  Create a string to zip with:
Ø0j              #   Surround the list with leading/trailing 0
   I             #   Forward-differences
    r0           #   Map each integer `n` to a list in the range [n,0]
      Ṣ€         #   Sort each range
        Ṡ        #   Signum (-1 if <0; 0 if 0; 1 if >0)
         ị“[],”  #   Index into "[]," ("[" if 1; "," if 0; "]" if -1)
ż                #  Zip/transpose, using the list above
 F               #  and the flattened input as arguments
  F              #  Then flatten the result
   ḊṖ            #  And remove the leading/trailing ","
                 #  (after which the result is output implicitly)
```
[Answer]
# [R](https://www.r-project.org/), 172 bytes
Or **[R](https://www.r-project.org/)>=4.1, 151 bytes** by replacing three `function` occurrences with `\`s.
```
function(l,`?`=unlist,g=function(l)"if"(is.list(l),1+?Map(g,l),0),h=function(v)"if"(any(v),{y[]=cumsum(c(T,y<-v<2)|y);Map(h,split(v-1,y))},v))relist(?l,h(max(g(l))-g(l)+1))
```
[Try it online!](https://tio.run/?fbclid=IwAR1LuUT8zKk_OaDLtmpg4YS-vE-DQlpYLwWbKDUBVzGBeBuScasDenpyqkI##jZHNboMwDMfve4qKU6yaaSm7tYwn6G03iFSEBkSCtCofKtr27MxOQQw0rXAwjuP8/Ld97VO/TxuT1PpsRIGn4OQ3ptBVjZk/xcHRqSN09cw3dES5DY7xRWRI/gtgPuW299zYdOTiZxcqP2nKqilFIt6xO7jtYQdfHez5fY7VpdC1aF2JHcA3tgDXD1skKDAXZXwTGdUDl@1WAvSpsNcA@ySuhbNx3zahioy7/CITGQeehnRrJO4APXydvaUghhRUjyGcah3L@A1himL0Goj9kZLB88hbwBRrkgwku7Y5GNVJbnLwFq2GpJKsR/YxdoBMVJ7eXCmT7kgeolqrdex7GsI4WJgr9ixY2iLeugX9td9/F9P/AA "R – Try It Online")
### Explanation outline
1. Compute the depths of elements using recursive function `g`.
2. Compute the target depths.
3. Compute the target structure of the list using a recursive function `h` just like here: [Build a list from a depth map](https://codegolf.stackexchange.com/a/242243/55372).
4. Use an obscure [R](https://www.r-project.org/) function `relist` to assign original values to the new structure (as [suggested by @Giuseppe](https://codegolf.stackexchange.com/questions/241633/build-a-list-from-a-depth-map?noredirect=1&lq=1#comment545828_242243)).
[Answer]
# Python3, 274 bytes:
```
from itertools import*
f=lambda x,c=0:[i for j in x for i in([(j,c)]if int==type(j)else f(j,c+1))]
g=lambda x,m:[j for a,b in groupby(x,key=lambda x:x[1]==m)for j in(lambda b:[u for u,_ in b]if a else[[*g(b,m-1)]])([*b])]
r=lambda x:g(l:=f(x),max(b for _,b in l))if x else x
```
[Try it online!](https://tio.run/##XY/RbsMgDEXf8xU82pknLc0epkh8CUJV6EJGFgqiRCJfnxLatepeLNuXey72a/xx5/bLh23TwVlm4hCic/OFGetdiHWl@dxb9d2zRCf@0QnDtAtsYubMUmlNbkHARCeURuchch5XP8CEw3wZmN6ltwZRVuOTZTsxFXtPameNwS1erZDod1gfz7okGsm5xb9MuCuqE0uxL3Tc7WqP7tkeKEQ9giL73qCUCKJWMkeHJ3OEueMaEpLtE6iCOd5@MSNmTiocljYf8jUQQEjE6jGIhg6SWvp82TYk8jbXNtcXpc0K5TuK65/ncOdsVw)
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 191 bytes
```
f=lambda a:(a*0==0)*[(0,a)]or[(d+1,x)for y in a for d,x in f(y)]
def g(a):
 s=",".join("["*(z:=max(f(a))[0]+1-n)+f"{x}"+z*"]"for n,x in f(a))
 for _ in s:s=s.replace("],[",",")
 return s or[]
```
[Try it online!](https://tio.run/##VY7RaoNAEEXf/YplnmZ1ErT2IQj7JctQJtFNLckqqwFN6bfbsdBCXy5zOZfDjOv8PsT6NKZtC@4m93MrRhqUvHSutLnHksTykDy2RUWLDUMyq@mjEbOfLS17CbhaztoumCuKbTIzOSA4fgx9RPCQ47Nxd1kwKLW@5KI6RFsE@Fy@oHjmwLDL4q9MR9mP/m3vUzO56Zi68SaXDoHJq5tAJ6mbH0kHRv/jbUx9nPGKviL/wqRZa7K6/kithHzFpLym139My/YN "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Python](https://www.python.org), 165 bytes
```
lambda x,i=0:x and[*eval(",".join((j-i)*"["+(i-(i:=j))*"],"+str(k)for j,k in d(x,-min(d(x))[0]))+i*"]")]
d=lambda x,c=0:x*-1and[(c,x)]or sum((d(y,c-1)for y in x),[])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU9LboMwEN1zCsurmWRAIekiikov4npBQ1CHgEGYVHCGHqGbSFV6p9ym45BWVb0Y-828j-fjq5uG19adP8vs-XIaynh7vdR581LkaiTOVrtR5a4wi8NbXoMmnVQtO4AqZlxoo5fAMfAuq1CgJb30Qw9HLNteVXRU7FQBI8WNaOSBaFYWccnC1WijIvuN2oeoRZyGMNjTiFYs_KkB0U20j9Ob5xQcRyRj8f7Znpuu7QflJx8FRh0YAhI_FOyS_pAXNbuDB9xFSg5TlTV5B2EfqhPf1TyAVo_xk9KIN0rXsxugIv4LS2CkEmTPaE4-X9-NvemMjYxJaW1pQw_3lkAyAcosJSMzqRup97lJbWCkQSNVWHLPjeDzwwqSWRvs7Oy2_pcT0Pynbw)
#### Old [Python](https://www.python.org), 169 bytes
```
lambda x,i=0:x and[*eval(",".join(((n:=j-min(d(x))[0])-i)*"["+(i-(i:=n))*"],"+str(k)for j,k in d(x))+i*"]")]
d=lambda x,c=0:x*-1and[(c,x)]or sum((d(y,c-1)for y in x),[])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU9LboMwEN1zCsurcTJGIekiQqUXcb2gIahDwCBwKjhDj9BNpKqVeqTcpmNIq6pejP1m3mf89tlN_rl1l_cye_w4-1Lvr1913jwVuRiRsk06itwVZnV8yWuQKOOqJQcALs0q3fCzgFEps7FKk1pJI9dAGijNnGJoUa4H38NJlW0vKjwJcmJWrImnUtmoyH7jDiFupZMQCAcclWXRcG6AQyY86GR2mYLHqNBYdVu4p6Zrey-GaYgCow4MBvHgC3Jxf8yLmtxxAJVGgg9hlTV5B-FPWMdDV5MHKe71g5BKzZSuJ-ehQvoLSyCFJVTMWZIv11djZ52xkTEJbi3u8O7WYogmQJ4laHjGdcf1NjeJDYwkaLgyi--lEXx-WEGyaIOdXdy2_3ICWnb6Bg)
#### Old [Python](https://www.python.org), 174 bytes
```
lambda x,i=0:x and[*eval(",".join(((n:=j-min(sum(d(x),())))-i)*"["+(i-(i:=n))*"],"+str(k)for j,k in d(x))+i*"]")]
d=lambda x,c=0:x*-1and[(c,x)]or sum((d(y,c-1)for y in x),[])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU9LTsMwEN3nFJZX43YckZYFiggXMV6EphGTJk6UpCg5A0dgUwnBkvv0Nsw0BSFmMfabeR_77bObx-c2nN7L7PHjOJb27vxV581TkasJKbtJJ5WHwq32L3kNGnVctRQAIKRZZRu-DscGCpgMguGyZFba6TWQBUqzYBh61Oth7OFgyrZXFR4UBSUSsybeauOjIvvN3EnmyiaSCjucjGeRhHDKjDubXFxm8eBQ58311T01XduPapiHSBi1MBjEw1hQiPt9XtQU9gOYNFJchFXW5B3Ix7COh66mEbS6tw9KG3OhdD2FESqkv7AEMlhCxZwl-XR-df6icz5yLsGNxy3eXkcM0QnkXYKOd9y33K97l3hhJKLhziw-l4H4_LBEsmjFzi9um385gpY3fQM)
#### Old [Python](https://www.python.org), 178 bytes
```
lambda x,i=0:x and eval("["+",".join(((n:=j-min(sum(d(x),())))-i)*"["+(i-(i:=n))*"],"+str(k)for j,k in d(x))+-~i*"]")
d=lambda x,c=0:x*-1and[(c,x)]or sum((d(y,c-1)for y in x),[])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU9LTsMwEN3nFJZX43YckZYFiggXMV6EphGTJk6UpCjZcAGOwKYSggNwm96GmTawYBZjv5n3sd-_unl8bsPpo8weP49jae_O33XePBW5mpCym3RSeSjU_iWvQTu91qjjqqUAACHNKtvwdTg2UMBkEAyXJbMSJpAFSrNgGHrU62Hs4WDKtlcVHhQFJRKztq_Ee22iIvvL3Unuyiac7GCHk_GskhSOmXFnk4vNLCac6rxZXv5MTdf2oxrmIRJGLQwG8TAWFOJ-nxc1hf0AJo0UF2GVNXkH8jus46GraQSt7u2D0sZcKF1PYYQqirAEMtwqg7Tknc5vzl_YzkfOJbjxuMXbZcQQnUDeJeh4x33Lfdm7xAsjEQ13ZvF5HYjPL0skV63Y-avb5l-OoOubfgA)
Based on [this](https://codegolf.stackexchange.com/a/241637/107561) answer to a related challenge.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~75~~ 72 bytes
```
If[v@#,#/.l->List,#0[##&@@@SequenceReplace[#,{a__}?v:>!l@a]]]&
v=VectorQ
```
[Try it online!](https://tio.run/##LYq9CsIwFEb3vIUEOt2q/VFBaM0qOKgFlxAkhBQLbdUau1zSV48JdTl83@F00jx0J02jpKsLd6z5yCjQ1bKNy1PzMUDXnNKIMVbp91f3Sl/1q5VKcwoo73d7GPflomVSCBGRsbhpZZ7DxZ2HpjecxmXNqIimSsl@QoIWCGICqYUM8nASQH88M88gMi8A/QzNXKT/eK4hJDngBnBrrYWdB7HuBw "Wolfram Language (Mathematica) – Try It Online")
-9 bytes if lower levels can have non-`List` heads: [Try it online!](https://tio.run/##LYrLCsIwFET3@QsJdHUF@1BBaM3WnVpwE0IJ4RYLbdUSu7mkvx4TKgOHmeEM2j5x0LYz2relv7RyFhxCdpLzRAhR4@eLo8E7vnttUHIg3TTuPJ@qTS@0Uiphc/lAY1/TzV@nbrSSb6tWcJUstdHjQowcMKIUMgc5FHGkQGEE5oHxyMMBFGp0ViP7y6sNUSmA9kAH5xwcA5jzPw "Wolfram Language (Mathematica) – Try It Online")
```
                           SequenceReplace[#,{a__}        ]     group consecutive
                                                  ?v              non-List elements
                                                    :> l@a        by wrapping with l
                     ##&@@@                           !         flatten out Lists
                  #0[                                      ]    recurse
If[v@#,          ,                                          ]     until no Lists left
       #/.l->List                                               turn l into List
```
---
### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~76~~ 74 bytes
```
#/.{{__d}:>#0/@d/@SplitBy[D@@@#,Head],{__}:>#0[d/@#]}&
d@{a__}=d@a:{__d}=a
```
[Try it online!](https://tio.run/##LctNC4JAEAbg@/6NBU9T5kcFgrJEh46BRxEZ3CQhJWIvMYx/fZvVLi8z7zwzoXs@JnRjj34ovY73RF1nuaj0ITY2NvX7NbrLt7kaYzTcHmhbELGCRu665UhZQyhdaQ0W63uJ/v4ZZ9foXTWIiZa6x3khRQyKKIGUIYM8LAmQLJKZZCgyKYBkDGYT6R9vGgLJgY5AJ2aGs4Ri/wM "Wolfram Language (Mathematica) – Try It Online")
```
main function:
#/.                                   {__}:>#0[d/@#]    get depths
#/. {__d}:>                                             construct by:
               d/@SplitBy[D@@@#,Head]                     group this layer
           #0/@                                           recurse
                                                          (atoms are unchanged)
depth helper:
        d@a:{__d}=a     don't change lists that only have d[...]s
d@{a__}=          a     splat other lists
                        (stay unevaluated on atoms)
```
The first step of the main function wraps each value in a number of `d`s equal to their final depth. Then the final structure is constructed recursively in a manner similar to [this answer](https://codegolf.stackexchange.com/a/241678/81203).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 44 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
_"Ddië®δ.V>"©.V˜ZαU˜εXNèF…[ÿ]]',ý…[ÿ]…],[',:
```
I knew this approach would be pretty long, but not sure what a good alternative would be..
Input as a list; output as a string.
[Try it online](https://tio.run/##yy9OTMpM/f8/XsklJfPw6kPrzm3RC7NTOrRSL@z0nKhzG0NPzzm3NcLv8Aq3Rw3Log/vj41V1zm8F8oGUrE60eo6Vv//RxvrRBvpRBvG6hjF6hjHAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/3gll5TMw6sPrTu3RS/MTunQSr2w03Oizm0MPT3n3NYIv8Mr3B41LIs@vD@2tlZd5/BeKAdIxepEq@tY/df5Hx0dq6MQHW2oYxSrY6xjAuIY6kQDOUDSGEiCBIyBAjrRQCZIDUSFEUwxWDVIaWysjomOaWwsAA).
**Explanation:**
In pseudo-code I do the following steps:
1. Determine the (0-based) depth of each integer in the nested input-list (`_"Ddië®δ.V>"©.V˜Zα` - [try it online](https://tio.run/##ATEAzv9vc2FiaWX//18iRGRpw6vCrs60LlY@IsKpLlbLnFrOsf//WzMsWzIsWzFdLDJdLDNd)).
2. Flatten the input-list (`˜`).
3. Use a minor modification of [my 05AB1E answer for the *Build a list from a depth map* challenge](https://codegolf.stackexchange.com/a/241695/52210) with the list of step 1 to mold the flattened input-list (as string..) (`εXNèF…[ÿ]}}',ý…[ÿ]…],[',:`).
As for the actual code:
```
_           # Transform each integer in the (implicit) input to 0
 "..."      # Push the recursive string explained below
      ©     # Store it in variable `®` (without popping)
       .V   # Evaluate and execute it as 05AB1E code
  D         # Duplicate the current list
   dië      # If it's not an integer (so it's a list):
       δ    #  Map over each item:
      ® .V  #   Do a recursive call
      >     #  Then increase each integer in this list by 1
˜           # Flatten the result
 Z          # Push the maximum depth (without popping the list)
  α         # Pop and push the absolute difference
   U        # Pop and store this list in variable `X`
˜           # Flatten the (implicit) input-list
 ε          # Map over each integer:
  XNè       #  Get the depth from `X` at the same index
     F      #  Loop that many times:
      …[ÿ]  #   Wrap it in square blocks
 ]          # Close both the inner loop and outer map
  ',ý      '# Join everything by "," delimiter
     …[ÿ]   # Wrap the entire string in square blocks as well
  …],[',:  '# Replace all "],[" with ","
            # (after which the string is output implicitly as result)
```
[Answer]
# JavaScript (ES6), 156 bytes
```
f=(a,i=d=+(m=b=[]))=>a.map?a.map(v=>f(v,i+1))|i||eval('b='+[...b,[f,'b']].map(g=a=>d^([v,x]=a,v+=~m)?d-->v?"["+g(a):"],"+g(a,d+=2):x)):b.push([i<m?i:m=i,a])
```
[Try it online!](https://tio.run/##bY7NboMwEITvfYqIC7a8OIL0hLrwICtXMuGnriCg0lg5oLw69RL1N/VhZM1@M7uv1tv5@Oam9@Q01s26tigsOKxRiQErJCMlFlYPdio3FR6LVnhwKpVyccvSeNuLuMJYkda6AmohrmJjNrhDi0X9LMjDxaAFr/A6yLJOksKXEUWqE1bmkYHtB7XCTOYXKfNKT@f5RZB7GkqXD@jAGrkex9M89o3ux060gm/b/Xr7/Y7Mwx@KUsgMHODxE2cqeEDs3eEpUMCDHoJyhHFKDQdS7gl6FwrubcybvkJcceviZea/XdnPw75PY3P9AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 27 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Is there something shorter than the `¬ȦƇẈƊ` this uses?
```
ŒṖṚ¬ȦƇẈƊÞṪḢ’$Ȧ¡€
ŒJẈÇŒṪ¿ṁ@F
```
A monadic Link accepting a ragged list that yields a ragged list.
**[Try it online!](https://tio.run/##y0rNyan8///opIc7pz3cOevQmhPLjrU/3NVxrOvwvIc7Vz3csehRw0yVE8sOLXzUtIbr6CQvoNzhdpDyVYf2P9zZ6OD2H8Kd8f9/dHS0QWysDpAyjAXSRrEA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///opIc7pz3cOevQmhPLjrU/3NVxrOvwvIc7Vz3csehRw0yVE8sOLXzUtIbr6CQvoNzhdpDyVYf2P9zZ6OD2XwfCnwFU8HDHfCD5qHFb1qOGOQq6dgqPGuZqRv7/Hx0dqxMdbahjFKtjrGMCZBvqRAPZQNIYSAL5xkA@UDQWrAIsbwRWGQsA "Jelly – Try It Online").
### How?
Firstly, get the depths of the items.
While there are any non-zero integers at any depth group together as many zeros, and lists that are only zeros at all depths, as possible and decrease all the other integers by one.
Lastly, mould a flattened version of the input like that ragged list.
```
ŒJẈÇŒṪ¿ṁ@F - Main Link: ragged list, A
ŒJ         - multidimensional indices of A
  Ẉ        - length of each -> flat list of depths
      ¿    - while...
    ŒṪ     - ...condition: truthy multidimensional indices
   Ç       - ...do: call the helper link
         F - flatten A
        @  - with swapped arguments:
       ṁ   -   mould like
ŒṖṚ¬ȦƇẈƊÞṪḢ’$Ȧ¡€ - Helper link: ragged list, Current State
ŒṖ               - all partitions of the Current State
  Ṛ              - reverse (to have longest last rather than first)
        Þ        - sort by:
       Ɗ         -   last three links as a monad:
   ¬             -     logical NOT (vectorises)
     Ƈ           -     filter keep those for which:
    Ȧ            -       any and all?
      Ẉ          -     length of each
         Ṫ       - tail
               € - for each:
              ¡  -   repeat...
             Ȧ   -   ...times: any and all?
            $    -   ...action: last two links as a monad:
          Ḣ      -     head
           ’     -     decrement
```
---
Alternative helper, same byte count:
```
ŒṖṚŒṪƇẈ$ÞḢḢ’$Ȧ¡€
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 137 bytes
```
x=>(y=JSON.stringify(x).replace(/,\[|],/g,t=>t>'['?(b+=']]',',['):(a+='[[','],'),a=b=''),g=t=>t?t.map?t[1]?t:g(t[0]):[t]:[])(eval(a+y+b))
```
[Try it online!](https://tio.run/##bU7LboMwELz3K3KzrWyhJD0hGe49tIcet3sw1FhEFBBYUZD673RXUR9J6sNYOzuzMwd3dHM9tWO874d3vzZ2PdlCL/bp9eU5mePU9qFtFn0yyeTHztVep/CGnwRpgGiLWChUpa62VhEpUIDK5NrxiMgjgTLgbGUV/8GKoYzJhxvLiBmVMQ864gOZHCPlSEb7o@vYvmwrY9Z66Oeh80k3BN1oXpvNxUvTDdLdlQoz2BHs4fFbLirmAIW7kWeALGfcM4pF5NxNDJncYbwxMXteS9KPSU6cb0kY/Ze1@1vst5qQ6xc "JavaScript (Node.js) – Try It Online")
First with lots of outer brackets then clean some
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~122~~ 120 bytes
```
≔＆θ⁰η≔⟦η⟧ζＦζＦιＦ⁼κ⁺⟦⟧κ«ＵＭκ⊖μ⊞ζκ»⊞υθ⊞υηＦυＦιＦ⁼κ⁺⟦⟧κ⊞υκＦ⮌υ«≔⟦⟧ζＷι⊞ζ⊟ιＦ⮌ζ¿⁺⟦⟧κＦκ⊞ιλ⊞ικ»≔⮌θθ≔⁰ζＦ⁻η⊖⌊η«Ｆ⁻ζι]→Ｆ⁻ιζ[Ｉ⊟θ≔ιζ»Ｆζ]ＵＢ,
```
[Try it online!](https://tio.run/##jVFNj4IwED3Lr2g4tUlNXL2tJ3X3aGLcY8OhwWonFBBKNWHjb2cHaAne9tTOzJv30aZa1mkpTdftrIVbQffQPMGqXXGhFScrxolm28gPhU44abG@ljWhLSPDCf78rpw0lmacnIyzVCA2Y4yR32hxlPdDmecSWXH8pdJa5apo1IXmDOkWJ2c1bXv8NnpFQ@U4qbAKdx1U3T9Vw2IWFs/qoWqrkGCwFCL5RIunBqMG2mDmVN6x7Gdv@y3uw5XQudxoJfO7wIlhW6KMVVNjTOZFA1XFxpC@vZo97hEKpNfvj4VNyF1ONfPvOoOiYehj11A0NE7i3vexfCj6eYabbqYYIxp6qQktBvRYHKRtaB@9YkN27w1Gb6/p6@dCP6rZyzS71aXDH4459rpOiA0Xay4@Er5O@CZJuuXD/AE "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Not an easy problem to solve without access to recursion.
```
≔＆θ⁰η
```
Make a deep clone of the input and set all of the integers in that clone to zero. (`BitwiseAnd` fully vectorises, unlike, say, `Times`.)
```
≔⟦η⟧ζＦζＦιＦ⁼κ⁺⟦⟧κ«ＵＭκ⊖μ⊞ζκ»
```
Perform a breadth-first search over the clone and decrement each sublist. (Again, it is fortunate that `Decremented` fully vectorises, although I still have to `MapCommand` it because I need to modify each sublist in-place.) The resulting list ends up with values appropriate to their depth.
```
⊞υθ⊞υηＦυＦιＦ⁼κ⁺⟦⟧κ⊞υκＦ⮌υ«≔⟦⟧ζＷι⊞ζ⊟ιＦ⮌ζ¿⁺⟦⟧κＦκ⊞ιλ⊞ικ»
```
Flatten both the input and the depth clone in-place.
```
≔⮌θθ≔⁰ζＦ⁻η⊖⌊η«Ｆ⁻ζι]→Ｆ⁻ιζ[Ｉ⊟θ≔ιζ»Ｆζ]ＵＢ,
```
Adjust the depth list so that the minimum depth is 1, and use that to build the desired output list from the depth list and the flattened input list. (See my answer to [Build a list from a depth map](https://codegolf.stackexchange.com/questions/241633/) for more detail.)
]