Q:

What happens to resources stored in a building that I demolish?

When demolishing a building, what happens to the resources (input/output storage) inside? Are they lost? If not, are they transported to the docks? Further, do they somehow count towards export tasks?

A:

When a building containing resources is destroyed, all of the stored resources (both input and output goods) are teleported to the dock. Since you get credit for exports at the time the resources are loaded onto the ship, they will count towards export tasks.
Thanks to SCIENCE!, I can confirm that when a mine or rum factory is destroyed, both the input goods and output goods are immediately teleported to the nearest dock.
I played a buggy scenario where, instead of making deposits bigger, the scenario creator layered a large number of small deposits on top of each other. Since Borehole Mines exploit all deposits simultaneously, this meant that a single shift of mine-work was generating 26,000 resources! I demolished the mine when it had ~20,000 resources in it, and the closest dock immediately had ~20,000 more resources stored in it. I repeated this with a full Rum Factory (~1000 input goods, ~1000 output goods), and confirmed that the nearest dock's supply jumped up by over 2000 when the factory was demolished.
(Not tested: demolishing a factory when its input goods are in demand elsewhere, such as food at canneries or when you have another building of the same type somewhere else. I'm not sure if your teamsters will remove the input-goods from the dock to take them to your other factory.)

