'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const auth_ic = require('./auth.ic-0657d0c4.js');
require('./index-ef56c8c9.js');

const idlFactory$2 = ({IDL}) => {
  const BucketId = IDL.Principal;
  const DeckId = IDL.Text;
  return IDL.Service({
    deckEntries: IDL.Func([], [IDL.Vec(BucketId)], ['query']),
    delDeck: IDL.Func([DeckId], [IDL.Bool], []),
    delStorage: IDL.Func([], [IDL.Bool], []),
    deleteDecksAdmin: IDL.Func([IDL.Principal], [], []),
    deleteStorageAdmin: IDL.Func([IDL.Principal], [], []),
    getDeck: IDL.Func([DeckId], [IDL.Opt(BucketId)], ['query']),
    getStorage: IDL.Func([], [IDL.Opt(BucketId)], ['query']),
    initDeck: IDL.Func([DeckId], [BucketId], []),
    initStorage: IDL.Func([], [BucketId], [])
  });
};

const idlFactory$1 = ({IDL}) => {
  const SlideId__1 = IDL.Text;
  const Time = IDL.Int;
  const DeckId = IDL.Text;
  const Deck = IDL.Record({
    updated_at: Time,
    data: IDL.Vec(IDL.Nat8),
    deckId: DeckId,
    created_at: Time
  });
  const SlideId = IDL.Text;
  const Slide = IDL.Record({
    updated_at: Time,
    data: IDL.Vec(IDL.Nat8),
    created_at: Time,
    slideId: SlideId
  });
  const DeckBucket = IDL.Service({
    delSlide: IDL.Func([SlideId__1], [IDL.Bool], []),
    get: IDL.Func([], [Deck], ['query']),
    getSlide: IDL.Func([SlideId__1], [Slide], ['query']),
    set: IDL.Func([Deck], [], []),
    setSlide: IDL.Func([Slide], [], []),
    transferCycles: IDL.Func([], [], [])
  });
  return DeckBucket;
};

const idlFactory = ({IDL}) => {
  const AssetKey = IDL.Record({
    token: IDL.Text,
    name: IDL.Text,
    fullPath: IDL.Text,
    folder: IDL.Text
  });
  const Chunk = IDL.Record({
    content: IDL.Vec(IDL.Nat8),
    batchId: IDL.Nat
  });
  const HeaderField = IDL.Tuple(IDL.Text, IDL.Text);
  const HttpRequest = IDL.Record({
    url: IDL.Text,
    method: IDL.Text,
    body: IDL.Vec(IDL.Nat8),
    headers: IDL.Vec(HeaderField)
  });
  const StreamingCallbackToken__1 = IDL.Record({
    token: IDL.Text,
    fullPath: IDL.Text,
    index: IDL.Nat,
    contentEncoding: IDL.Text
  });
  const StreamingStrategy = IDL.Variant({
    Callback: IDL.Record({
      token: StreamingCallbackToken__1,
      callback: IDL.Func([], [], [])
    })
  });
  const HttpResponse = IDL.Record({
    body: IDL.Vec(IDL.Nat8),
    headers: IDL.Vec(HeaderField),
    streaming_strategy: IDL.Opt(StreamingStrategy),
    status_code: IDL.Nat16
  });
  const StreamingCallbackToken = IDL.Record({
    token: IDL.Text,
    fullPath: IDL.Text,
    index: IDL.Nat,
    contentEncoding: IDL.Text
  });
  const StreamingCallbackHttpResponse = IDL.Record({
    token: IDL.Opt(StreamingCallbackToken__1),
    body: IDL.Vec(IDL.Nat8)
  });
  const StorageBucket = IDL.Service({
    commit_batch: IDL.Func(
      [
        IDL.Record({
          contentType: IDL.Text,
          chunkIds: IDL.Vec(IDL.Nat),
          batchId: IDL.Nat
        })
      ],
      [],
      []
    ),
    create_batch: IDL.Func([AssetKey], [IDL.Record({batchId: IDL.Nat})], []),
    create_chunk: IDL.Func([Chunk], [IDL.Record({chunkId: IDL.Nat})], []),
    del: IDL.Func([IDL.Record({token: IDL.Text, fullPath: IDL.Text})], [], []),
    http_request: IDL.Func([HttpRequest], [HttpResponse], ['query']),
    http_request_streaming_callback: IDL.Func([StreamingCallbackToken], [StreamingCallbackHttpResponse], ['query']),
    list: IDL.Func([IDL.Opt(IDL.Text)], [IDL.Vec(AssetKey)], ['query']),
    transferCycles: IDL.Func([], [], [])
  });
  return StorageBucket;
};

const createManagerActor = ({ identity, host }) => {
  return auth_ic.createActor({ canisterId: "jkpvl-ziaaa-aaaai-aaafq-cai", idlFactory: idlFactory$2, identity, host });
};
const createDeckBucketActor = ({ identity, bucket, host }) => {
  return auth_ic.createActor({ canisterId: bucket, idlFactory: idlFactory$1, identity, host });
};
const createStorageBucketActor = ({ identity, bucket, host }) => {
  return auth_ic.createActor({ canisterId: bucket, idlFactory: idlFactory, identity, host });
};
const initDeckBucket = async ({ managerActor, deckId }) => {
  const existingBucket = auth_ic.fromNullable(await managerActor.getDeck(deckId));
  if (!existingBucket) {
    return await managerActor.initDeck(deckId);
  }
  return existingBucket;
};
const initStorageBucket = async ({ managerActor }) => {
  const existingBucket = auth_ic.fromNullable(await managerActor.getStorage());
  if (!existingBucket) {
    return await managerActor.initStorage();
  }
  return existingBucket;
};

const deckEntries = async (_userId) => {
  const identity = auth_ic.getIdentity();
  if (!identity) {
    return [];
  }
  const managerActor = await createManagerActor({ identity });
  console.log('Deck IC about to request entries');
  const buckets = await managerActor.deckEntries();
  console.log('Deck IC entries done.', buckets);
  const promises = buckets.map((bucket) => getDeckIc({ bucket, identity }));
  const decksIc = await Promise.all(promises);
  console.log('Deck IC decks done.', decksIc);
  const decksPromises = decksIc === null || decksIc === void 0 ? void 0 : decksIc.filter((deck) => deck !== undefined).map((deck) => fromDeck({ deck, identity }));
  const decks = await Promise.all(decksPromises);
  return decks;
};
const getDeckIc = async ({ bucket, identity }) => {
  try {
    const deckBucket = await createDeckBucketActor({ identity, bucket });
    return await deckBucket.get();
  }
  catch (err) {
    console.error('Deck cannot be found.', bucket);
    return undefined;
  }
};
const fromDeck = async ({ deck, identity }) => {
  const data = await auth_ic.fromArray(deck.data);
  return {
    id: deck.deckId,
    data: Object.assign(Object.assign({}, data), { owner_id: identity.getPrincipal().toText(), created_at: auth_ic.fromTimestamp(deck.created_at), updated_at: auth_ic.fromTimestamp(deck.updated_at) })
  };
};
const deleteDeck = async (deckId) => {
  if (!deckId) {
    return;
  }
  const identity = auth_ic.getIdentity();
  if (!identity) {
    return;
  }
  // We delete the all canister of the related deckId
  const managerActor = await createManagerActor({ identity });
  console.log('Deck IC about to delete deck and its slides');
  await managerActor.delDeck(deckId);
  console.log('Deck IC delete');
};

const getSlide$1 = (deckId, slideId) => {
  return new Promise(async (resolve, reject) => {
    const identity = auth_ic.getIdentity();
    if (!identity) {
      reject('No internet identity.');
      return;
    }
    try {
      const managerActor = await createManagerActor({ identity });
      const bucket = await initDeckBucket({ managerActor, deckId });
      const deckBucket = await createDeckBucketActor({ identity, bucket });
      const slide = await deckBucket.getSlide(slideId);
      const data = await auth_ic.fromArray(slide.data);
      resolve({
        id: slideId,
        data: Object.assign(Object.assign({}, data), { created_at: auth_ic.fromTimestamp(slide.created_at), updated_at: auth_ic.fromTimestamp(slide.updated_at) })
      });
    }
    catch (err) {
      reject(err);
    }
  });
};

var rngBrowser = auth_ic.createCommonjsModule(function (module) {
// Unique ID creation requires a high quality random # generator.  In the
// browser this is a little complicated due to unknown quality of Math.random()
// and inconsistent support for the `crypto` API.  We do the best we can via
// feature-detection

// getRandomValues needs to be invoked in a context where "this" is a Crypto
// implementation. Also, find the complete implementation of crypto on IE11.
var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
                      (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));

if (getRandomValues) {
  // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
  var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef

  module.exports = function whatwgRNG() {
    getRandomValues(rnds8);
    return rnds8;
  };
} else {
  // Math.random()-based (RNG)
  //
  // If all else fails, use Math.random().  It's fast, but is of unspecified
  // quality.
  var rnds = new Array(16);

  module.exports = function mathRNG() {
    for (var i = 0, r; i < 16; i++) {
      if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
      rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
    }

    return rnds;
  };
}
});

/**
 * Convert array of 16 byte values to UUID string format of the form:
 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
 */
var byteToHex = [];
for (var i = 0; i < 256; ++i) {
  byteToHex[i] = (i + 0x100).toString(16).substr(1);
}

function bytesToUuid(buf, offset) {
  var i = offset || 0;
  var bth = byteToHex;
  // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
  return ([
    bth[buf[i++]], bth[buf[i++]],
    bth[buf[i++]], bth[buf[i++]], '-',
    bth[buf[i++]], bth[buf[i++]], '-',
    bth[buf[i++]], bth[buf[i++]], '-',
    bth[buf[i++]], bth[buf[i++]], '-',
    bth[buf[i++]], bth[buf[i++]],
    bth[buf[i++]], bth[buf[i++]],
    bth[buf[i++]], bth[buf[i++]]
  ]).join('');
}

var bytesToUuid_1 = bytesToUuid;

// **`v1()` - Generate time-based UUID**
//
// Inspired by https://github.com/LiosK/UUID.js
// and http://docs.python.org/library/uuid.html

var _nodeId;
var _clockseq;

// Previous uuid creation time
var _lastMSecs = 0;
var _lastNSecs = 0;

// See https://github.com/uuidjs/uuid for API details
function v1(options, buf, offset) {
  var i = buf && offset || 0;
  var b = buf || [];

  options = options || {};
  var node = options.node || _nodeId;
  var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;

  // node and clockseq need to be initialized to random values if they're not
  // specified.  We do this lazily to minimize issues related to insufficient
  // system entropy.  See #189
  if (node == null || clockseq == null) {
    var seedBytes = rngBrowser();
    if (node == null) {
      // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
      node = _nodeId = [
        seedBytes[0] | 0x01,
        seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
      ];
    }
    if (clockseq == null) {
      // Per 4.2.2, randomize (14 bit) clockseq
      clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
    }
  }

  // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  // (1582-10-15 00:00).  JSNumbers aren't precise enough for this, so
  // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();

  // Per 4.2.1.2, use count of uuid's generated during the current clock
  // cycle to simulate higher resolution clock
  var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;

  // Time since last uuid creation (in msecs)
  var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;

  // Per 4.2.1.2, Bump clockseq on clock regression
  if (dt < 0 && options.clockseq === undefined) {
    clockseq = clockseq + 1 & 0x3fff;
  }

  // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  // time interval
  if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
    nsecs = 0;
  }

  // Per 4.2.1.2 Throw error if too many uuids are requested
  if (nsecs >= 10000) {
    throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
  }

  _lastMSecs = msecs;
  _lastNSecs = nsecs;
  _clockseq = clockseq;

  // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  msecs += 12219292800000;

  // `time_low`
  var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  b[i++] = tl >>> 24 & 0xff;
  b[i++] = tl >>> 16 & 0xff;
  b[i++] = tl >>> 8 & 0xff;
  b[i++] = tl & 0xff;

  // `time_mid`
  var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
  b[i++] = tmh >>> 8 & 0xff;
  b[i++] = tmh & 0xff;

  // `time_high_and_version`
  b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  b[i++] = tmh >>> 16 & 0xff;

  // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  b[i++] = clockseq >>> 8 | 0x80;

  // `clock_seq_low`
  b[i++] = clockseq & 0xff;

  // `node`
  for (var n = 0; n < 6; ++n) {
    b[i + n] = node[n];
  }

  return buf ? buf : bytesToUuid_1(b);
}

var v1_1 = v1;

function v4(options, buf, offset) {
  var i = buf && offset || 0;

  if (typeof(options) == 'string') {
    buf = options === 'binary' ? new Array(16) : null;
    options = null;
  }
  options = options || {};

  var rnds = options.random || (options.rng || rngBrowser)();

  // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  rnds[6] = (rnds[6] & 0x0f) | 0x40;
  rnds[8] = (rnds[8] & 0x3f) | 0x80;

  // Copy bytes to buffer, if provided
  if (buf) {
    for (var ii = 0; ii < 16; ++ii) {
      buf[i + ii] = rnds[ii];
    }
  }

  return buf || bytesToUuid_1(rnds);
}

var v4_1 = v4;

var uuid = v4_1;
uuid.v1 = v1_1;
uuid.v4 = v4_1;

var uuid_1 = uuid;

const uploadFile = async ({ data, folder, maxSize }) => {
  const identity = auth_ic.getIdentity();
  return uploadFileIC({ data, folder, maxSize, identity });
};
const uploadFileIC = async ({ data, maxSize, host, folder, identity }) => {
  if (!data || !data.name) {
    throw new Error('File not valid.');
  }
  if (data.size > maxSize) {
    throw new Error(`File is too big (max. ${maxSize / 1048576} Mb)`);
  }
  const { bucket, actor } = await getStorageBucket({ host, identity });
  const { fullPath, filename, token } = await upload({
    data,
    folder,
    storageBucket: actor
  });
  return {
    downloadUrl: `https://${bucket.toText()}.raw.ic0.app/${fullPath}?token=${token}`,
    fullPath,
    name: filename
  };
};
const getStorageBucket = async ({ host, identity }) => {
  if (!identity) {
    throw new Error('Invalid identity.');
  }
  const managerActor = await createManagerActor({ identity, host });
  const bucket = await initStorageBucket({ managerActor });
  const actor = await createStorageBucketActor({ identity, bucket, host });
  return {
    bucket,
    actor
  };
};
const uploadChunk = async ({ batchId, chunk, storageBucket }) => storageBucket.create_chunk({
  batchId,
  content: [...new Uint8Array(await chunk.arrayBuffer())]
});
const upload = async ({ data, folder, storageBucket }) => {
  const filename = encodeURI(data.name);
  const fullPath = `${folder}/${filename}`;
  const token = uuid_1.v4();
  console.log('About to upload to the IC');
  const t0 = performance.now();
  const { batchId } = await storageBucket.create_batch({ name: filename, fullPath, token, folder });
  const t1 = performance.now();
  console.log('Upload create_batch', t1 - t0);
  const promises = [];
  const chunkSize = 700000;
  for (let start = 0; start < data.size; start += chunkSize) {
    const chunk = data.slice(start, start + chunkSize);
    promises.push(uploadChunk({
      batchId,
      chunk,
      storageBucket
    }));
  }
  const chunkIds = await Promise.all(promises);
  const t2 = performance.now();
  console.log('Upload upload chunks', t2 - t1);
  await storageBucket.commit_batch({
    batchId,
    chunkIds: chunkIds.map(({ chunkId }) => chunkId),
    contentType: data.type
  });
  const t3 = performance.now();
  console.log('Upload commit_batch', t3 - t2);
  console.log('Data uploaded', t3 - t0);
  return {
    fullPath,
    filename,
    token
  };
};
const getFiles = async ({ folder }) => {
  const identity = auth_ic.getIdentity();
  const { bucket, actor } = await getStorageBucket({ identity });
  const assets = await actor.list(auth_ic.toNullable(folder));
  const host = `https://${bucket.toText()}.raw.ic0.app`;
  return {
    items: assets.map(({ name, fullPath, token }) => ({
      downloadUrl: `${host}/${fullPath}?token=${token}`,
      fullPath,
      name
    })),
    nextPageToken: null
  };
};

/**
 * Work around Safari 14 IndexedDB open bug.
 *
 * Safari has a horrible bug where IDB requests can hang while the browser is starting up. https://bugs.webkit.org/show_bug.cgi?id=226547
 * The only solution is to keep nudging it until it's awake.
 */
function idbReady() {
    var isSafari = !navigator.userAgentData &&
        /Safari\//.test(navigator.userAgent) &&
        !/Chrom(e|ium)\//.test(navigator.userAgent);
    // No point putting other browsers or older versions of Safari through this mess.
    if (!isSafari || !indexedDB.databases)
        return Promise.resolve();
    var intervalId;
    return new Promise(function (resolve) {
        var tryIdb = function () { return indexedDB.databases().finally(resolve); };
        intervalId = setInterval(tryIdb, 100);
        tryIdb();
    }).finally(function () { return clearInterval(intervalId); });
}

function promisifyRequest(request) {
  return new Promise(function (resolve, reject) {
    // @ts-ignore - file size hacks
    request.oncomplete = request.onsuccess = function () {
      return resolve(request.result);
    }; // @ts-ignore - file size hacks


    request.onabort = request.onerror = function () {
      return reject(request.error);
    };
  });
}

function createStore(dbName, storeName) {
  var dbp = idbReady().then(function () {
    var request = indexedDB.open(dbName);

    request.onupgradeneeded = function () {
      return request.result.createObjectStore(storeName);
    };

    return promisifyRequest(request);
  });
  return function (txMode, callback) {
    return dbp.then(function (db) {
      return callback(db.transaction(storeName, txMode).objectStore(storeName));
    });
  };
}

var defaultGetStoreFunc;

function defaultGetStore() {
  if (!defaultGetStoreFunc) {
    defaultGetStoreFunc = createStore('keyval-store', 'keyval');
  }

  return defaultGetStoreFunc;
}
/**
 * Get a value by its key.
 *
 * @param key
 * @param customStore Method to get a custom store. Use with caution (see the docs).
 */


function get(key) {
  var customStore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultGetStore();
  return customStore('readonly', function (store) {
    return promisifyRequest(store.get(key));
  });
}
/**
 * Set a value with a key.
 *
 * @param key
 * @param value
 * @param customStore Method to get a custom store. Use with caution (see the docs).
 */


function set(key, value) {
  var customStore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultGetStore();
  return customStore('readwrite', function (store) {
    store.put(value, key);
    return promisifyRequest(store.transaction);
  });
}

const updateDeckBackground = ({ deck, storageFile, imgSrc }) => {
  if (!storageFile || !imgSrc) {
    return Object.assign({}, deck);
  }
  return {
    id: deck.id,
    data: Object.assign(Object.assign({}, deck.data), { updated_at: new Date(), background: updateImgSrcAlt({ data: deck.data.background, imgSrc, storageFile }) })
  };
};
const updateSlideImages = ({ slide, images }) => {
  if (!images) {
    return Object.assign({}, slide);
  }
  const validImages = images.filter(({ src, storageFile }) => src !== undefined && storageFile !== undefined);
  let { content } = slide.data;
  validImages.forEach(({ src, storageFile }) => {
    content = updateImgSrcAlt({ data: content, storageFile, imgSrc: src });
  });
  return {
    id: slide.id,
    data: Object.assign(Object.assign({}, slide.data), { updated_at: new Date(), content })
  };
};
const updateSlideChart = ({ slide, chart }) => {
  if (!chart) {
    return Object.assign({}, slide);
  }
  const { src, storageFile } = chart;
  if (!src || !storageFile) {
    return Object.assign({}, slide);
  }
  const { attributes } = slide.data;
  if (!attributes) {
    return Object.assign({}, slide);
  }
  const { downloadUrl } = storageFile;
  return {
    id: slide.id,
    data: Object.assign(Object.assign({}, slide.data), { updated_at: new Date(), attributes: Object.assign(Object.assign({}, attributes), { src: downloadUrl }) })
  };
};
const updateImgSrcAlt = ({ data, storageFile, imgSrc }) => {
  const { downloadUrl, name } = storageFile;
  let updateData = data.replaceAll(`img-src="${imgSrc}"`, `img-src="${downloadUrl}"`);
  updateData = updateData.replaceAll(`img-alt="${imgSrc}"`, `img-alt="${name}"`);
  return updateData;
};

const syncDeckBackground = async (data) => {
  // 1. We update the deck in the DOM
  updateDeckDOM(data);
  // 2. We replicate the same changes to the slides in the DOM
  await updateSlidesDOM(data);
  // 3. We update the indexedDB stored deck with the new downloadUrl.
  await updateDeckIDB(data);
};
const syncSlideImage = async (data) => {
  const { slideId } = data;
  if (!slideId) {
    return;
  }
  // 1. We update the slide in the DOM
  await updateSlideImagesDOM(data);
  // 2. We update the indexedDB stored slide with the new downloadUrl.
  await updateSlideImagesIDB(data);
};
const syncSlideChart = async (data) => {
  const { slideId } = data;
  if (!slideId) {
    return;
  }
  // 1. We update the slide in the DOM
  updateSlideChartDOM(data);
  // 2. We update the indexedDB stored slide with the new downloadUrl.
  await updateSlideChartIDB(data);
};
const updateDeckDOM = ({ storageFile }) => {
  const backgroundElement = document.querySelector(`${auth_ic.u} > *[slot="background"]`);
  const img = backgroundElement === null || backgroundElement === void 0 ? void 0 : backgroundElement.querySelector('deckgo-lazy-img');
  if (!img) {
    return;
  }
  const { downloadUrl, name } = storageFile;
  img.imgSrc = downloadUrl;
  img.imgAlt = name;
};
const updateSlideImagesDOM = async ({ slideId, storageFile, src }) => {
  const slideElement = document.querySelector(`${auth_ic.u} > *[slide_id="${slideId}"]`);
  const images = slideElement === null || slideElement === void 0 ? void 0 : slideElement.querySelectorAll('deckgo-lazy-img');
  await updateImagesDOM({ images, storageFile, src });
};
const updateSlideChartDOM = ({ slideId, storageFile }) => {
  const slideElement = document.querySelector(`${auth_ic.u} > *[slide_id="${slideId}"]`);
  if (!slideElement || !slideElement.nodeName || slideElement.nodeName.toLowerCase() !== 'deckgo-slide-chart') {
    return;
  }
  const { downloadUrl } = storageFile;
  slideElement.src = downloadUrl;
};
const updateSlidesDOM = async ({ storageFile, src }) => {
  const images = document.querySelectorAll(`${auth_ic.u} .deckgo-slide-container:not([custom-background]) *[slot="background"] deckgo-lazy-img`);
  await updateImagesDOM({ images, storageFile, src });
};
const updateImagesDOM = async ({ storageFile, images, src }) => {
  if (!images || images.length <= 0) {
    return;
  }
  const matchingImages = Array.from(images).filter((img) => img.imgSrc === src);
  if (!matchingImages || matchingImages.length <= 0) {
    return;
  }
  const updateImage = async (img) => {
    const { downloadUrl, name } = storageFile;
    img.imgSrc = downloadUrl;
    img.imgAlt = name;
  };
  const promises = Array.from(matchingImages).map((img) => updateImage(img));
  await Promise.all(promises);
};
const updateDeckIDB = async ({ storageFile, src, deckId }) => {
  const deck = await get(`/decks/${deckId}`);
  if (!deck) {
    throw new Error('Deck not found and that is really weird here.');
  }
  const updateDeck = updateDeckBackground({ deck, imgSrc: src, storageFile });
  await set(`/decks/${deck.id}`, updateDeck);
};
const updateSlideImagesIDB = async ({ storageFile, src, slideId, deckId }) => {
  const slide = await getSlide({ deckId, slideId });
  const updateSlide = updateSlideImages({
    slide,
    images: [
      {
        src,
        storageFile
      }
    ]
  });
  await setSlide({ deckId, slideId, slide: updateSlide });
};
const updateSlideChartIDB = async ({ storageFile, src, slideId, deckId }) => {
  const slide = await getSlide({ deckId, slideId });
  const updateSlide = updateSlideChart({
    slide,
    chart: {
      src,
      storageFile
    }
  });
  await setSlide({ deckId, slideId, slide: updateSlide });
};
const getSlide = async ({ deckId, slideId }) => {
  const slide = await get(`/decks/${deckId}/slides/${slideId}`);
  if (!slide) {
    throw new Error('Slide not found and that is really weird here.');
  }
  return slide;
};
const setSlide = async ({ deckId, slideId, slide }) => set(`/decks/${deckId}/slides/${slideId}`, slide);

const workerPromise = Promise.resolve().then(function () { return require('./sync.ic.worker-e18cfb4f.js'); }).then(m => m.worker);
const uploadWorker = /*@__PURE__*/auth_ic.createWorkerProxy(workerPromise, 'stencil.sync.ic.worker', 'uploadWorker');

// - we cannot use postmessage because of CORS
// - we have to path the function separately for serialisation reason
const syncWindow = async ({ msg, data }) => {
  if (msg === 'deckdeckgo_sync_deck_background') {
    await syncDeckBackground(data);
  }
  if (msg === 'deckdeckgo_sync_slide_image') {
    await syncSlideImage(data);
  }
  if (msg === 'deckdeckgo_sync_slide_chart') {
    await syncSlideChart(data);
  }
};
const sync = async ({ syncData, clean }) => {
  const identity = auth_ic.getIdentity();
  if (!identity) {
    throw new Error('No internet identity to sync data');
  }
  const internetIdentity = await auth_ic.internetIdentityAuth();
  await uploadWorker({
    internetIdentity,
    syncData,
    host: `${window.location}`
  }, syncWindow);
  await clean(syncData);
};

exports.deleteAuth = auth_ic.deleteAuth;
exports.deleteUser = auth_ic.deleteUser;
exports.getIdentity = auth_ic.getIdentity;
exports.initAuth = auth_ic.initAuth;
exports.signIn = auth_ic.signIn;
exports.signOut = auth_ic.signOut;
exports.updateUser = auth_ic.updateUser;
exports.deckEntries = deckEntries;
exports.deleteDeck = deleteDeck;
exports.getFiles = getFiles;
exports.getSlide = getSlide$1;
exports.sync = sync;
exports.uploadFile = uploadFile;
exports.uploadFileIC = uploadFileIC;
